blob: c7797168be32ada7347da59bbbbb4f53b45e5766 [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 Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(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
Andy Hungdae27702016-10-31 14:01:16 -0700853void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
855 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700856 acquireWakeLock_l();
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");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800872 case MMAP:
873 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800874 default:
875 ALOG_ASSERT(false);
876 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100877 }
878}
879
Andy Hungdae27702016-10-31 14:01:16 -0700880void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800881{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800882 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800883 if (mPowerManager != 0) {
884 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700885 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
886 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700887 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100888 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700889 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700890 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800891 if (status == NO_ERROR) {
892 mWakeLockToken = binder;
893 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800894 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800895 }
Wei Jia3f273d12015-11-24 09:06:49 -0800896
Andy Hung3f0c9022016-01-15 17:49:46 -0800897 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800898 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
899 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800900}
901
902void AudioFlinger::ThreadBase::releaseWakeLock()
903{
904 Mutex::Autolock _l(mLock);
905 releaseWakeLock_l();
906}
907
908void AudioFlinger::ThreadBase::releaseWakeLock_l()
909{
Andy Hung3f0c9022016-01-15 17:49:46 -0800910 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800911 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800912 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700914 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
915 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 }
917 mWakeLockToken.clear();
918 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800919}
920
921void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700922 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 // use checkService() to avoid blocking if power service is not up yet
924 sp<IBinder> binder =
925 defaultServiceManager()->checkService(String16("power"));
926 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800928 } else {
929 mPowerManager = interface_cast<IPowerManager>(binder);
930 binder->linkToDeath(mDeathRecipient);
931 }
932 }
933}
934
Andy Hungd01b0f12016-11-07 16:10:30 -0800935void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800936 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700937
938#if !LOG_NDEBUG
939 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800940 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700941 s << uid << " ";
942 }
943 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
944#endif
945
Andy Hung438e7572015-12-14 15:51:17 -0800946 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
947 if (mSystemReady) {
948 ALOGE("no wake lock to update, but system ready!");
949 } else {
950 ALOGW("no wake lock to update, system not ready yet");
951 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 return;
953 }
954 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800955 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
956 status_t status = mPowerManager->updateWakeLockUids(
957 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
958 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800959 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800960 }
961}
962
Eric Laurent81784c32012-11-19 14:55:58 -0800963void AudioFlinger::ThreadBase::clearPowerManager()
964{
965 Mutex::Autolock _l(mLock);
966 releaseWakeLock_l();
967 mPowerManager.clear();
968}
969
Glenn Kasten0f11b512014-01-31 16:18:54 -0800970void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800971{
972 sp<ThreadBase> thread = mThread.promote();
973 if (thread != 0) {
974 thread->clearPowerManager();
975 }
976 ALOGW("power manager service died !!!");
977}
978
979void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800980 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800981{
982 Mutex::Autolock _l(mLock);
983 setEffectSuspended_l(type, suspend, sessionId);
984}
985
986void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800987 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800988{
989 sp<EffectChain> chain = getEffectChain_l(sessionId);
990 if (chain != 0) {
991 if (type != NULL) {
992 chain->setEffectSuspended_l(type, suspend);
993 } else {
994 chain->setEffectSuspendedAll_l(suspend);
995 }
996 }
997
998 updateSuspendedSessions_l(type, suspend, sessionId);
999}
1000
1001void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1002{
1003 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1004 if (index < 0) {
1005 return;
1006 }
1007
1008 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1009 mSuspendedSessions.valueAt(index);
1010
1011 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001012 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001013 for (int j = 0; j < desc->mRefCount; j++) {
1014 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1015 chain->setEffectSuspendedAll_l(true);
1016 } else {
1017 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1018 desc->mType.timeLow);
1019 chain->setEffectSuspended_l(&desc->mType, true);
1020 }
1021 }
1022 }
1023}
1024
1025void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1026 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001027 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001028{
1029 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1030
1031 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1032
1033 if (suspend) {
1034 if (index >= 0) {
1035 sessionEffects = mSuspendedSessions.valueAt(index);
1036 } else {
1037 mSuspendedSessions.add(sessionId, sessionEffects);
1038 }
1039 } else {
1040 if (index < 0) {
1041 return;
1042 }
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 }
1045
1046
1047 int key = EffectChain::kKeyForSuspendAll;
1048 if (type != NULL) {
1049 key = type->timeLow;
1050 }
1051 index = sessionEffects.indexOfKey(key);
1052
1053 sp<SuspendedSessionDesc> desc;
1054 if (suspend) {
1055 if (index >= 0) {
1056 desc = sessionEffects.valueAt(index);
1057 } else {
1058 desc = new SuspendedSessionDesc();
1059 if (type != NULL) {
1060 desc->mType = *type;
1061 }
1062 sessionEffects.add(key, desc);
1063 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1064 }
1065 desc->mRefCount++;
1066 } else {
1067 if (index < 0) {
1068 return;
1069 }
1070 desc = sessionEffects.valueAt(index);
1071 if (--desc->mRefCount == 0) {
1072 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1073 sessionEffects.removeItemsAt(index);
1074 if (sessionEffects.isEmpty()) {
1075 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1076 sessionId);
1077 mSuspendedSessions.removeItem(sessionId);
1078 }
1079 }
1080 }
1081 if (!sessionEffects.isEmpty()) {
1082 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1083 }
1084}
1085
1086void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1087 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001088 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001089{
1090 Mutex::Autolock _l(mLock);
1091 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 if (mType != RECORD) {
1099 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1100 // another session. This gives the priority to well behaved effect control panels
1101 // and applications not using global effects.
1102 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1103 // global effects
1104 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1105 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1106 }
1107 }
1108
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 if (chain != 0) {
1111 chain->checkSuspendOnEffectEnabled(effect, enabled);
1112 }
1113}
1114
Eric Laurent4c415062016-06-17 16:14:16 -07001115// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1116status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1117 const effect_descriptor_t *desc, audio_session_t sessionId)
1118{
1119 // No global effect sessions on record threads
1120 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1121 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1122 desc->name, mThreadName);
1123 return BAD_VALUE;
1124 }
1125 // only pre processing effects on record thread
1126 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1127 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1128 desc->name, mThreadName);
1129 return BAD_VALUE;
1130 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001131
1132 // always allow effects without processing load or latency
1133 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1134 return NO_ERROR;
1135 }
1136
Eric Laurent4c415062016-06-17 16:14:16 -07001137 audio_input_flags_t flags = mInput->flags;
1138 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1139 if (flags & AUDIO_INPUT_FLAG_RAW) {
1140 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1141 desc->name, mThreadName);
1142 return BAD_VALUE;
1143 }
1144 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1145 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1146 desc->name, mThreadName);
1147 return BAD_VALUE;
1148 }
1149 }
1150 return NO_ERROR;
1151}
1152
1153// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1154status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1155 const effect_descriptor_t *desc, audio_session_t sessionId)
1156{
1157 // no preprocessing on playback threads
1158 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1159 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1160 " thread %s", desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163
1164 switch (mType) {
1165 case MIXER: {
1166 // Reject any effect on mixer multichannel sinks.
1167 // TODO: fix both format and multichannel issues with effects.
1168 if (mChannelCount != FCC_2) {
1169 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1170 " thread %s", desc->name, mChannelCount, mThreadName);
1171 return BAD_VALUE;
1172 }
1173 audio_output_flags_t flags = mOutput->flags;
1174 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1175 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1176 // global effects are applied only to non fast tracks if they are SW
1177 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1178 break;
1179 }
1180 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1181 // only post processing on output stage session
1182 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1183 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1184 " on output stage session", desc->name);
1185 return BAD_VALUE;
1186 }
1187 } else {
1188 // no restriction on effects applied on non fast tracks
1189 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1190 break;
1191 }
1192 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001193
1194 // always allow effects without processing load or latency
1195 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1196 break;
1197 }
Eric Laurent4c415062016-06-17 16:14:16 -07001198 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1199 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1200 desc->name);
1201 return BAD_VALUE;
1202 }
1203 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1204 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1205 " in fast mode", desc->name);
1206 return BAD_VALUE;
1207 }
1208 }
1209 } break;
1210 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001211 // nothing actionable on offload threads, if the effect:
1212 // - is offloadable: the effect can be created
1213 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1214 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001215 break;
1216 case DIRECT:
1217 // Reject any effect on Direct output threads for now, since the format of
1218 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1219 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1220 desc->name, mThreadName);
1221 return BAD_VALUE;
1222 case DUPLICATING:
1223 // Reject any effect on mixer multichannel sinks.
1224 // TODO: fix both format and multichannel issues with effects.
1225 if (mChannelCount != FCC_2) {
1226 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1227 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1228 return BAD_VALUE;
1229 }
1230 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1231 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1232 " thread %s", desc->name, mThreadName);
1233 return BAD_VALUE;
1234 }
1235 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1236 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1237 " DUPLICATING thread %s", desc->name, mThreadName);
1238 return BAD_VALUE;
1239 }
1240 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1241 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1242 " DUPLICATING thread %s", desc->name, mThreadName);
1243 return BAD_VALUE;
1244 }
1245 break;
1246 default:
1247 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1248 }
1249
1250 return NO_ERROR;
1251}
1252
Eric Laurent81784c32012-11-19 14:55:58 -08001253// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1254sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1255 const sp<AudioFlinger::Client>& client,
1256 const sp<IEffectClient>& effectClient,
1257 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001258 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001259 effect_descriptor_t *desc,
1260 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001261 status_t *status,
1262 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001263{
1264 sp<EffectModule> effect;
1265 sp<EffectHandle> handle;
1266 status_t lStatus;
1267 sp<EffectChain> chain;
1268 bool chainCreated = false;
1269 bool effectCreated = false;
1270 bool effectRegistered = false;
1271
1272 lStatus = initCheck();
1273 if (lStatus != NO_ERROR) {
1274 ALOGW("createEffect_l() Audio driver not initialized.");
1275 goto Exit;
1276 }
1277
Eric Laurent81784c32012-11-19 14:55:58 -08001278 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1279
1280 { // scope for mLock
1281 Mutex::Autolock _l(mLock);
1282
Eric Laurent4c415062016-06-17 16:14:16 -07001283 lStatus = checkEffectCompatibility_l(desc, sessionId);
1284 if (lStatus != NO_ERROR) {
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // check for existing effect chain with the requested audio session
1289 chain = getEffectChain_l(sessionId);
1290 if (chain == 0) {
1291 // create a new chain for this session
1292 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1293 chain = new EffectChain(this, sessionId);
1294 addEffectChain_l(chain);
1295 chain->setStrategy(getStrategyForSession_l(sessionId));
1296 chainCreated = true;
1297 } else {
1298 effect = chain->getEffectFromDesc_l(desc);
1299 }
1300
1301 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1302
1303 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001304 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // Check CPU and memory usage
1306 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1307 if (lStatus != NO_ERROR) {
1308 goto Exit;
1309 }
1310 effectRegistered = true;
1311 // create a new effect module if none present in the chain
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001312 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001313 if (lStatus != NO_ERROR) {
1314 goto Exit;
1315 }
1316 effectCreated = true;
1317
1318 effect->setDevice(mOutDevice);
1319 effect->setDevice(mInDevice);
1320 effect->setMode(mAudioFlinger->getMode());
1321 effect->setAudioSource(mAudioSource);
1322 }
1323 // create effect handle and connect it to effect module
1324 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001325 lStatus = handle->initCheck();
1326 if (lStatus == OK) {
1327 lStatus = effect->addHandle(handle.get());
1328 }
Eric Laurent81784c32012-11-19 14:55:58 -08001329 if (enabled != NULL) {
1330 *enabled = (int)effect->isEnabled();
1331 }
1332 }
1333
1334Exit:
1335 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1336 Mutex::Autolock _l(mLock);
1337 if (effectCreated) {
1338 chain->removeEffect_l(effect);
1339 }
1340 if (effectRegistered) {
1341 AudioSystem::unregisterEffect(effect->id());
1342 }
1343 if (chainCreated) {
1344 removeEffectChain_l(chain);
1345 }
1346 handle.clear();
1347 }
1348
Glenn Kasten9156ef32013-08-06 15:39:08 -07001349 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001350 return handle;
1351}
1352
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001353void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1354 bool unpinIfLast)
1355{
1356 bool remove = false;
1357 sp<EffectModule> effect;
1358 {
1359 Mutex::Autolock _l(mLock);
1360
1361 effect = handle->effect().promote();
1362 if (effect == 0) {
1363 return;
1364 }
1365 // restore suspended effects if the disconnected handle was enabled and the last one.
1366 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1367 if (remove) {
1368 removeEffect_l(effect, true);
1369 }
1370 }
1371 if (remove) {
1372 mAudioFlinger->updateOrphanEffectChains(effect);
1373 AudioSystem::unregisterEffect(effect->id());
1374 if (handle->enabled()) {
1375 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1376 }
1377 }
1378}
1379
Glenn Kastend848eb42016-03-08 13:42:11 -08001380sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1381 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001382{
1383 Mutex::Autolock _l(mLock);
1384 return getEffect_l(sessionId, effectId);
1385}
1386
Glenn Kastend848eb42016-03-08 13:42:11 -08001387sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1388 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001389{
1390 sp<EffectChain> chain = getEffectChain_l(sessionId);
1391 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1392}
1393
1394// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1395// PlaybackThread::mLock held
1396status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1397{
1398 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001399 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001400 sp<EffectChain> chain = getEffectChain_l(sessionId);
1401 bool chainCreated = false;
1402
Eric Laurent5baf2af2013-09-12 17:37:00 -07001403 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1404 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1405 this, effect->desc().name, effect->desc().flags);
1406
Eric Laurent81784c32012-11-19 14:55:58 -08001407 if (chain == 0) {
1408 // create a new chain for this session
1409 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1410 chain = new EffectChain(this, sessionId);
1411 addEffectChain_l(chain);
1412 chain->setStrategy(getStrategyForSession_l(sessionId));
1413 chainCreated = true;
1414 }
1415 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1416
1417 if (chain->getEffectFromId_l(effect->id()) != 0) {
1418 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1419 this, effect->desc().name, chain.get());
1420 return BAD_VALUE;
1421 }
1422
Eric Laurent5baf2af2013-09-12 17:37:00 -07001423 effect->setOffloaded(mType == OFFLOAD, mId);
1424
Eric Laurent81784c32012-11-19 14:55:58 -08001425 status_t status = chain->addEffect_l(effect);
1426 if (status != NO_ERROR) {
1427 if (chainCreated) {
1428 removeEffectChain_l(chain);
1429 }
1430 return status;
1431 }
1432
1433 effect->setDevice(mOutDevice);
1434 effect->setDevice(mInDevice);
1435 effect->setMode(mAudioFlinger->getMode());
1436 effect->setAudioSource(mAudioSource);
1437 return NO_ERROR;
1438}
1439
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001440void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001441
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001442 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001443 effect_descriptor_t desc = effect->desc();
1444 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1445 detachAuxEffect_l(effect->id());
1446 }
1447
1448 sp<EffectChain> chain = effect->chain().promote();
1449 if (chain != 0) {
1450 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001451 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001452 removeEffectChain_l(chain);
1453 }
1454 } else {
1455 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1456 }
1457}
1458
1459void AudioFlinger::ThreadBase::lockEffectChains_l(
1460 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1461{
1462 effectChains = mEffectChains;
1463 for (size_t i = 0; i < mEffectChains.size(); i++) {
1464 mEffectChains[i]->lock();
1465 }
1466}
1467
1468void AudioFlinger::ThreadBase::unlockEffectChains(
1469 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1470{
1471 for (size_t i = 0; i < effectChains.size(); i++) {
1472 effectChains[i]->unlock();
1473 }
1474}
1475
Glenn Kastend848eb42016-03-08 13:42:11 -08001476sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001477{
1478 Mutex::Autolock _l(mLock);
1479 return getEffectChain_l(sessionId);
1480}
1481
Glenn Kastend848eb42016-03-08 13:42:11 -08001482sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1483 const
Eric Laurent81784c32012-11-19 14:55:58 -08001484{
1485 size_t size = mEffectChains.size();
1486 for (size_t i = 0; i < size; i++) {
1487 if (mEffectChains[i]->sessionId() == sessionId) {
1488 return mEffectChains[i];
1489 }
1490 }
1491 return 0;
1492}
1493
1494void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1495{
1496 Mutex::Autolock _l(mLock);
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 mEffectChains[i]->setMode_l(mode);
1500 }
1501}
1502
Eric Laurent83b88082014-06-20 18:31:16 -07001503void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1504{
1505 config->type = AUDIO_PORT_TYPE_MIX;
1506 config->ext.mix.handle = mId;
1507 config->sample_rate = mSampleRate;
1508 config->format = mFormat;
1509 config->channel_mask = mChannelMask;
1510 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1511 AUDIO_PORT_CONFIG_FORMAT;
1512}
1513
Eric Laurent72e3f392015-05-20 14:43:50 -07001514void AudioFlinger::ThreadBase::systemReady()
1515{
1516 Mutex::Autolock _l(mLock);
1517 if (mSystemReady) {
1518 return;
1519 }
1520 mSystemReady = true;
1521
1522 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1523 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1524 }
1525 mPendingConfigEvents.clear();
1526}
1527
Andy Hungdae27702016-10-31 14:01:16 -07001528template <typename T>
1529ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1530 ssize_t index = mActiveTracks.indexOf(track);
1531 if (index >= 0) {
1532 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1533 return index;
1534 }
1535 mActiveTracksGeneration++;
1536 mLatestActiveTrack = track;
1537 ++mBatteryCounter[track->uid()].second;
1538 return mActiveTracks.add(track);
1539}
1540
1541template <typename T>
1542ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1543 ssize_t index = mActiveTracks.remove(track);
1544 if (index < 0) {
1545 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1546 return index;
1547 }
1548 mActiveTracksGeneration++;
1549 --mBatteryCounter[track->uid()].second;
1550 // mLatestActiveTrack is not cleared even if is the same as track.
1551 return index;
1552}
1553
1554template <typename T>
1555void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1556 for (const sp<T> &track : mActiveTracks) {
1557 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1558 }
1559 mLastActiveTracksGeneration = mActiveTracksGeneration;
1560 mActiveTracks.clear();
1561 mLatestActiveTrack.clear();
1562 mBatteryCounter.clear();
1563}
1564
1565template <typename T>
1566void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1567 sp<ThreadBase> thread, bool force) {
1568 // Updates ActiveTracks client uids to the thread wakelock.
1569 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1570 thread->updateWakeLockUids_l(getWakeLockUids());
1571 mLastActiveTracksGeneration = mActiveTracksGeneration;
1572 }
1573
1574 // Updates BatteryNotifier uids
1575 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1576 const uid_t uid = it->first;
1577 ssize_t &previous = it->second.first;
1578 ssize_t &current = it->second.second;
1579 if (current > 0) {
1580 if (previous == 0) {
1581 BatteryNotifier::getInstance().noteStartAudio(uid);
1582 }
1583 previous = current;
1584 ++it;
1585 } else if (current == 0) {
1586 if (previous > 0) {
1587 BatteryNotifier::getInstance().noteStopAudio(uid);
1588 }
1589 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1590 } else /* (current < 0) */ {
1591 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1592 }
1593 }
1594}
Eric Laurent83b88082014-06-20 18:31:16 -07001595
Eric Laurent6acd1d42017-01-04 14:23:29 -08001596void AudioFlinger::ThreadBase::broadcast_l()
1597{
1598 // Thread could be blocked waiting for async
1599 // so signal it to handle state changes immediately
1600 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1601 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1602 mSignalPending = true;
1603 mWaitWorkCV.broadcast();
1604}
1605
Eric Laurent81784c32012-11-19 14:55:58 -08001606// ----------------------------------------------------------------------------
1607// Playback
1608// ----------------------------------------------------------------------------
1609
1610AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1611 AudioStreamOut* output,
1612 audio_io_handle_t id,
1613 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001614 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001615 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001616 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001617 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001618 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001619 mMixerBuffer(NULL),
1620 mMixerBufferSize(0),
1621 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1622 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001623 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001624 mEffectBuffer(NULL),
1625 mEffectBufferSize(0),
1626 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1627 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001628 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001629 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001630 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001631 // mStreamTypes[] initialized in constructor body
1632 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001633 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001634 mMixerStatus(MIXER_IDLE),
1635 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001636 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001637 mBytesRemaining(0),
1638 mCurrentWriteLength(0),
1639 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001640 mWriteAckSequence(0),
1641 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001642 mScreenState(AudioFlinger::mScreenState),
1643 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001644 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001645 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001646{
Glenn Kastend7dca052015-03-05 16:05:54 -08001647 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1648 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001649
1650 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1651 // it would be safer to explicitly pass initial masterVolume/masterMute as
1652 // parameter.
1653 //
1654 // If the HAL we are using has support for master volume or master mute,
1655 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1656 // and the mute set to false).
1657 mMasterVolume = audioFlinger->masterVolume_l();
1658 mMasterMute = audioFlinger->masterMute_l();
1659 if (mOutput && mOutput->audioHwDev) {
1660 if (mOutput->audioHwDev->canSetMasterVolume()) {
1661 mMasterVolume = 1.0;
1662 }
1663
1664 if (mOutput->audioHwDev->canSetMasterMute()) {
1665 mMasterMute = false;
1666 }
1667 }
1668
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001669 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001670
Eric Laurent223fd5c2014-11-11 13:43:36 -08001671 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001672 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001673 stream = (audio_stream_type_t) (stream + 1)) {
1674 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1675 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1676 }
Eric Laurent81784c32012-11-19 14:55:58 -08001677}
1678
1679AudioFlinger::PlaybackThread::~PlaybackThread()
1680{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001681 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001682 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001683 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001684 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001685}
1686
1687void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1688{
1689 dumpInternals(fd, args);
1690 dumpTracks(fd, args);
1691 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001692 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001693}
1694
Glenn Kasten0f11b512014-01-31 16:18:54 -08001695void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001696{
1697 const size_t SIZE = 256;
1698 char buffer[SIZE];
1699 String8 result;
1700
Marco Nelissenb2208842014-02-07 14:00:50 -08001701 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001702 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1703 const stream_type_t *st = &mStreamTypes[i];
1704 if (i > 0) {
1705 result.appendFormat(", ");
1706 }
1707 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1708 if (st->mute) {
1709 result.append("M");
1710 }
1711 }
1712 result.append("\n");
1713 write(fd, result.string(), result.length());
1714 result.clear();
1715
Eric Laurent81784c32012-11-19 14:55:58 -08001716 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1717 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001718 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001719 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001720
1721 size_t numtracks = mTracks.size();
1722 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001723 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001724 size_t numactiveseen = 0;
1725 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001726 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001727 Track::appendDumpHeader(result);
1728 for (size_t i = 0; i < numtracks; ++i) {
1729 sp<Track> track = mTracks[i];
1730 if (track != 0) {
1731 bool active = mActiveTracks.indexOf(track) >= 0;
1732 if (active) {
1733 numactiveseen++;
1734 }
1735 track->dump(buffer, SIZE, active);
1736 result.append(buffer);
1737 }
1738 }
1739 } else {
1740 result.append("\n");
1741 }
1742 if (numactiveseen != numactive) {
1743 // some tracks in the active list were not in the tracks list
1744 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1745 " not in the track list\n");
1746 result.append(buffer);
1747 Track::appendDumpHeader(result);
1748 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001749 sp<Track> track = mActiveTracks[i];
1750 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001751 track->dump(buffer, SIZE, true);
1752 result.append(buffer);
1753 }
1754 }
1755 }
1756
1757 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001758}
1759
1760void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1761{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001762 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001763
1764 dumpBase(fd, args);
1765
Elliott Hughes87cebad2014-05-22 10:14:43 -07001766 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001767 dprintf(fd, " Last write occurred (msecs): %llu\n",
1768 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001769 dprintf(fd, " Total writes: %d\n", mNumWrites);
1770 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1771 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1772 dprintf(fd, " Suspend count: %d\n", mSuspended);
1773 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1774 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1775 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1776 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001777 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001778 AudioStreamOut *output = mOutput;
1779 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001780 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1781 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001782 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1783 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1784 if (mPipeSink.get() != nullptr) {
1785 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1786 }
1787 if (output != nullptr) {
1788 dprintf(fd, " Hal stream dump:\n");
1789 (void)output->stream->dump(fd);
1790 }
Eric Laurent81784c32012-11-19 14:55:58 -08001791}
1792
1793// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001794
1795void AudioFlinger::PlaybackThread::onFirstRef()
1796{
Glenn Kastend7dca052015-03-05 16:05:54 -08001797 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001798}
1799
1800// ThreadBase virtuals
1801void AudioFlinger::PlaybackThread::preExit()
1802{
1803 ALOGV(" preExit()");
1804 // FIXME this is using hard-coded strings but in the future, this functionality will be
1805 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001806 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1807 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001808}
1809
1810// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1811sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1812 const sp<AudioFlinger::Client>& client,
1813 audio_stream_type_t streamType,
1814 uint32_t sampleRate,
1815 audio_format_t format,
1816 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001817 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001818 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001819 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001820 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001821 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001822 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001823 status_t *status,
1824 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001825{
Glenn Kasten74935e42013-12-19 08:56:45 -08001826 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001827 sp<Track> track;
1828 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001829 audio_output_flags_t outputFlags = mOutput->flags;
1830
1831 // special case for FAST flag considered OK if fast mixer is present
1832 if (hasFastMixer()) {
1833 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1834 }
1835
1836 // Check if requested flags are compatible with output stream flags
1837 if ((*flags & outputFlags) != *flags) {
1838 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1839 *flags, outputFlags);
1840 *flags = (audio_output_flags_t)(*flags & outputFlags);
1841 }
Eric Laurent81784c32012-11-19 14:55:58 -08001842
Eric Laurent81784c32012-11-19 14:55:58 -08001843 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001844 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001845 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001846 // PCM data
1847 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001848 // TODO: extract as a data library function that checks that a computationally
1849 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001850 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001851 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1852 (channelMask == AUDIO_CHANNEL_OUT_MONO
1853 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001854 // hardware sample rate
1855 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001856 // normal mixer has an associated fast mixer
1857 hasFastMixer() &&
1858 // there are sufficient fast track slots available
1859 (mFastTrackAvailMask != 0)
1860 // FIXME test that MixerThread for this fast track has a capable output HAL
1861 // FIXME add a permission test also?
1862 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001863 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1864 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001865 // read the fast track multiplier property the first time it is needed
1866 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1867 if (ok != 0) {
1868 ALOGE("%s pthread_once failed: %d", __func__, ok);
1869 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001870 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001871 }
Eric Laurent4c415062016-06-17 16:14:16 -07001872
1873 // check compatibility with audio effects.
1874 { // scope for mLock
1875 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001876 for (audio_session_t session : {
1877 AUDIO_SESSION_OUTPUT_STAGE,
1878 AUDIO_SESSION_OUTPUT_MIX,
1879 sessionId,
1880 }) {
1881 sp<EffectChain> chain = getEffectChain_l(session);
1882 if (chain.get() != nullptr) {
1883 audio_output_flags_t old = *flags;
1884 chain->checkOutputFlagCompatibility(flags);
1885 if (old != *flags) {
1886 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1887 (int)session, (int)old, (int)*flags);
1888 }
Eric Laurent4c415062016-06-17 16:14:16 -07001889 }
1890 }
1891 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001892 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001893 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1894 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001895 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001896 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1897 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001898 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001899 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001900 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001901 audio_is_linear_pcm(format),
1902 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001903 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001904 }
1905 }
1906 // For normal PCM streaming tracks, update minimum frame count.
1907 // For compatibility with AudioTrack calculation, buffer depth is forced
1908 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1909 // This is probably too conservative, but legacy application code may depend on it.
1910 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001911 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001912 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001913 // this must match AudioTrack.cpp calculateMinFrameCount().
1914 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001915 uint32_t latencyMs = 0;
1916 lStatus = mOutput->stream->getLatency(&latencyMs);
1917 if (lStatus != OK) {
1918 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1919 goto Exit;
1920 }
Eric Laurent81784c32012-11-19 14:55:58 -08001921 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1922 if (minBufCount < 2) {
1923 minBufCount = 2;
1924 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001925 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1926 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001927 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001928 minBufCount * sourceFramesNeededWithTimestretch(
1929 sampleRate, mNormalFrameCount,
1930 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001931 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001932 frameCount = minFrameCount;
1933 }
Eric Laurent81784c32012-11-19 14:55:58 -08001934 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001935 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001936
Glenn Kastenc3df8382014-03-13 15:05:25 -07001937 switch (mType) {
1938
1939 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001940 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001941 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001942 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1943 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001944 sampleRate, format, channelMask, mOutput, mFormat);
1945 lStatus = BAD_VALUE;
1946 goto Exit;
1947 }
1948 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001949 break;
1950
1951 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001953 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1954 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001955 sampleRate, format, channelMask, mOutput, mFormat);
1956 lStatus = BAD_VALUE;
1957 goto Exit;
1958 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001959 break;
1960
1961 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001962 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001963 ALOGE("createTrack_l() Bad parameter: format %#x \""
1964 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965 format, mOutput, mFormat);
1966 lStatus = BAD_VALUE;
1967 goto Exit;
1968 }
Andy Hungcd044842014-08-07 11:04:34 -07001969 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001970 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1971 lStatus = BAD_VALUE;
1972 goto Exit;
1973 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001974 break;
1975
Eric Laurent81784c32012-11-19 14:55:58 -08001976 }
1977
1978 lStatus = initCheck();
1979 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001980 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001981 goto Exit;
1982 }
1983
1984 { // scope for mLock
1985 Mutex::Autolock _l(mLock);
1986
1987 // all tracks in same audio session must share the same routing strategy otherwise
1988 // conflicts will happen when tracks are moved from one output to another by audio policy
1989 // manager
1990 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1991 for (size_t i = 0; i < mTracks.size(); ++i) {
1992 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001993 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001994 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1995 if (sessionId == t->sessionId() && strategy != actual) {
1996 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1997 strategy, actual);
1998 lStatus = BAD_VALUE;
1999 goto Exit;
2000 }
2001 }
2002 }
2003
Glenn Kastend79072e2016-01-06 08:41:20 -08002004 track = new Track(this, client, streamType, sampleRate, format,
2005 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002006 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002007
Glenn Kasten03003332013-08-06 15:40:54 -07002008 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2009 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002010 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002011 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002012 goto Exit;
2013 }
2014 mTracks.add(track);
2015
2016 sp<EffectChain> chain = getEffectChain_l(sessionId);
2017 if (chain != 0) {
2018 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2019 track->setMainBuffer(chain->inBuffer());
2020 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2021 chain->incTrackCnt();
2022 }
2023
Eric Laurent05067782016-06-01 18:27:28 -07002024 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002025 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2026 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2027 // so ask activity manager to do this on our behalf
2028 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2029 }
2030 }
2031
2032 lStatus = NO_ERROR;
2033
2034Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002035 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002036 return track;
2037}
2038
2039uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2040{
2041 return latency;
2042}
2043
2044uint32_t AudioFlinger::PlaybackThread::latency() const
2045{
2046 Mutex::Autolock _l(mLock);
2047 return latency_l();
2048}
2049uint32_t AudioFlinger::PlaybackThread::latency_l() const
2050{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002051 uint32_t latency;
2052 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2053 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002054 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002055 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002056}
2057
2058void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2059{
2060 Mutex::Autolock _l(mLock);
2061 // Don't apply master volume in SW if our HAL can do it for us.
2062 if (mOutput && mOutput->audioHwDev &&
2063 mOutput->audioHwDev->canSetMasterVolume()) {
2064 mMasterVolume = 1.0;
2065 } else {
2066 mMasterVolume = value;
2067 }
2068}
2069
2070void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2071{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002072 if (isDuplicating()) {
2073 return;
2074 }
Eric Laurent81784c32012-11-19 14:55:58 -08002075 Mutex::Autolock _l(mLock);
2076 // Don't apply master mute in SW if our HAL can do it for us.
2077 if (mOutput && mOutput->audioHwDev &&
2078 mOutput->audioHwDev->canSetMasterMute()) {
2079 mMasterMute = false;
2080 } else {
2081 mMasterMute = muted;
2082 }
2083}
2084
2085void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2086{
2087 Mutex::Autolock _l(mLock);
2088 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002089 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002090}
2091
2092void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2093{
2094 Mutex::Autolock _l(mLock);
2095 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002096 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002097}
2098
2099float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2100{
2101 Mutex::Autolock _l(mLock);
2102 return mStreamTypes[stream].volume;
2103}
2104
2105// addTrack_l() must be called with ThreadBase::mLock held
2106status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2107{
2108 status_t status = ALREADY_EXISTS;
2109
Eric Laurent81784c32012-11-19 14:55:58 -08002110 if (mActiveTracks.indexOf(track) < 0) {
2111 // the track is newly added, make sure it fills up all its
2112 // buffers before playing. This is to ensure the client will
2113 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002114 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115 TrackBase::track_state state = track->mState;
2116 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002117 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002118 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119 mLock.lock();
2120 // abort track was stopped/paused while we released the lock
2121 if (state != track->mState) {
2122 if (status == NO_ERROR) {
2123 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002124 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002125 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002126 mLock.lock();
2127 }
2128 return INVALID_OPERATION;
2129 }
2130 // abort if start is rejected by audio policy manager
2131 if (status != NO_ERROR) {
2132 return PERMISSION_DENIED;
2133 }
2134#ifdef ADD_BATTERY_DATA
2135 // to track the speaker usage
2136 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2137#endif
2138 }
2139
Eric Laurent51716182016-02-29 18:00:56 -08002140 // set retry count for buffer fill
2141 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002142 if (track->isStopping_1()) {
2143 track->mRetryCount = kMaxTrackStopRetriesOffload;
2144 } else {
2145 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2146 }
2147 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002148 } else {
2149 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002150 track->mFillingUpStatus =
2151 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002152 }
2153
Eric Laurent81784c32012-11-19 14:55:58 -08002154 track->mResetDone = false;
2155 track->mPresentationCompleteFrames = 0;
2156 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002157 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2158 if (chain != 0) {
2159 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2160 track->sessionId());
2161 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002162 }
2163
Andy Hung2148bf02016-11-28 19:01:02 -08002164 char buffer[256];
2165 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2166 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2167
Eric Laurent81784c32012-11-19 14:55:58 -08002168 status = NO_ERROR;
2169 }
2170
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002171 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002172 return status;
2173}
2174
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002176{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002178 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002179 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2180 track->mState = TrackBase::STOPPED;
2181 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002182 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002183 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002185 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186
2187 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002188}
2189
2190void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2191{
2192 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002193
2194 char buffer[256];
2195 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2196 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2197
Eric Laurent81784c32012-11-19 14:55:58 -08002198 mTracks.remove(track);
2199 deleteTrackName_l(track->name());
2200 // redundant as track is about to be destroyed, for dumpsys only
2201 track->mName = -1;
2202 if (track->isFastTrack()) {
2203 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002204 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002205 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2206 mFastTrackAvailMask |= 1 << index;
2207 // redundant as track is about to be destroyed, for dumpsys only
2208 track->mFastIndex = -1;
2209 }
2210 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2211 if (chain != 0) {
2212 chain->decTrackCnt();
2213 }
2214}
2215
2216String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2217{
Eric Laurent81784c32012-11-19 14:55:58 -08002218 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002219 String8 out_s8;
2220 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2221 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002222 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002223 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002224}
2225
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002226void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002227 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2228 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002229
Eric Laurent73e26b62015-04-27 16:55:58 -07002230 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002231
2232 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002233 case AUDIO_OUTPUT_OPENED:
2234 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002235 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002236 desc->mChannelMask = mChannelMask;
2237 desc->mSamplingRate = mSampleRate;
2238 desc->mFormat = mFormat;
2239 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002240 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002241 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002242 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002243 break;
2244
Eric Laurent73e26b62015-04-27 16:55:58 -07002245 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002246 default:
2247 break;
2248 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002249 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002252void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255}
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002259 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260}
2261
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002263{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002264 mCallbackThread->setAsyncError();
2265}
2266
Eric Laurent3b4529e2013-09-05 18:09:19 -07002267void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268{
2269 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002270 // reject out of sequence requests
2271 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2272 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 mWaitWorkCV.signal();
2274 }
2275}
2276
Eric Laurent3b4529e2013-09-05 18:09:19 -07002277void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278{
2279 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002280 // reject out of sequence requests
2281 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2282 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 mWaitWorkCV.signal();
2284 }
2285}
2286
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002287void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002288{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002289 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002290 mSampleRate = mOutput->getSampleRate();
2291 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002292 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002293 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002294 }
Andy Hung9a592762014-07-21 21:56:01 -07002295 if ((mType == MIXER || mType == DUPLICATING)
2296 && !isValidPcmSinkChannelMask(mChannelMask)) {
2297 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2298 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002299 }
Andy Hunge5412692014-05-16 11:25:07 -07002300 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002301
2302 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002303 status_t result = mOutput->stream->getFormat(&mHALFormat);
2304 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002305 // Get format from the shim, which will be different than the HAL format
2306 // if playing compressed audio over HDMI passthrough.
2307 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002308 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002309 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002310 }
Andy Hung6146c082014-03-18 11:56:15 -07002311 if ((mType == MIXER || mType == DUPLICATING)
2312 && !isValidPcmSinkFormat(mFormat)) {
2313 LOG_FATAL("HAL format %#x not supported for mixed output",
2314 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Phil Burk062e67a2015-02-11 13:40:50 -08002316 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002317 result = mOutput->stream->getBufferSize(&mBufferSize);
2318 LOG_ALWAYS_FATAL_IF(result != OK,
2319 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002320 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002321 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002322 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002323 mFrameCount);
2324 }
2325
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002326 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2327 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002329 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 }
2331 }
2332
Eric Laurentd1f69b02014-12-15 14:33:13 -08002333 mHwSupportsPause = false;
2334 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002335 bool supportsPause = false, supportsResume = false;
2336 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2337 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002339 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002340 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002341 } else if (supportsResume) {
2342 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002344 }
2345 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002346 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2347 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2348 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349
Andy Hungfbfc3952015-01-15 13:33:51 -08002350 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2351 // For best precision, we use float instead of the associated output
2352 // device format (typically PCM 16 bit).
2353
2354 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2355 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2356 mBufferSize = mFrameSize * mFrameCount;
2357
2358 // TODO: We currently use the associated output device channel mask and sample rate.
2359 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2360 // (if a valid mask) to avoid premature downmix.
2361 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2362 // instead of the output device sample rate to avoid loss of high frequency information.
2363 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2364 }
2365
Andy Hung09a50072014-02-27 14:30:47 -08002366 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002367 double multiplier = 1.0;
2368 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2369 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002370 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2371 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002372
Eric Laurent81784c32012-11-19 14:55:58 -08002373 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2374 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2375 maxNormalFrameCount = maxNormalFrameCount & ~15;
2376 if (maxNormalFrameCount < minNormalFrameCount) {
2377 maxNormalFrameCount = minNormalFrameCount;
2378 }
2379 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2380 if (multiplier <= 1.0) {
2381 multiplier = 1.0;
2382 } else if (multiplier <= 2.0) {
2383 if (2 * mFrameCount <= maxNormalFrameCount) {
2384 multiplier = 2.0;
2385 } else {
2386 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2387 }
2388 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002389 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002390 }
2391 }
2392 mNormalFrameCount = multiplier * mFrameCount;
2393 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002394 if (mType == MIXER || mType == DUPLICATING) {
2395 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2396 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002397 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002398 mNormalFrameCount);
2399
Andy Hung08fb1742015-05-31 23:22:10 -07002400 // Check if we want to throttle the processing to no more than 2x normal rate
2401 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002402 mThreadThrottleTimeMs = 0;
2403 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002404 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2405
Andy Hung010a1a12014-03-13 13:57:33 -07002406 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2407 // Originally this was int16_t[] array, need to remove legacy implications.
2408 free(mSinkBuffer);
2409 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002410 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2411 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2412 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002413 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002414
Andy Hung69aed5f2014-02-25 17:24:40 -08002415 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2416 // drives the output.
2417 free(mMixerBuffer);
2418 mMixerBuffer = NULL;
2419 if (mMixerBufferEnabled) {
2420 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2421 mMixerBufferSize = mNormalFrameCount * mChannelCount
2422 * audio_bytes_per_sample(mMixerBufferFormat);
2423 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2424 }
Andy Hung98ef9782014-03-04 14:46:50 -08002425 free(mEffectBuffer);
2426 mEffectBuffer = NULL;
2427 if (mEffectBufferEnabled) {
2428 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2429 mEffectBufferSize = mNormalFrameCount * mChannelCount
2430 * audio_bytes_per_sample(mEffectBufferFormat);
2431 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2432 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // force reconfiguration of effect chains and engines to take new buffer size and audio
2435 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002436 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2438 // matter.
2439 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2440 Vector< sp<EffectChain> > effectChains = mEffectChains;
2441 for (size_t i = 0; i < effectChains.size(); i ++) {
2442 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2443 }
2444}
2445
2446
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002447status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002448{
2449 if (halFrames == NULL || dspFrames == NULL) {
2450 return BAD_VALUE;
2451 }
2452 Mutex::Autolock _l(mLock);
2453 if (initCheck() != NO_ERROR) {
2454 return INVALID_OPERATION;
2455 }
Andy Hung818e7a32016-02-16 18:08:07 -08002456 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002457 *halFrames = framesWritten;
2458
2459 if (isSuspended()) {
2460 // return an estimation of rendered frames when the output is suspended
2461 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002462 *dspFrames = (uint32_t)
2463 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002464 return NO_ERROR;
2465 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002466 status_t status;
2467 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002468 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002469 *dspFrames = (size_t)frames;
2470 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002471 }
2472}
2473
Eric Laurent4c415062016-06-17 16:14:16 -07002474// hasAudioSession_l() must be called with ThreadBase::mLock held
2475uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002476{
Eric Laurent81784c32012-11-19 14:55:58 -08002477 uint32_t result = 0;
2478 if (getEffectChain_l(sessionId) != 0) {
2479 result = EFFECT_SESSION;
2480 }
2481
2482 for (size_t i = 0; i < mTracks.size(); ++i) {
2483 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002484 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002485 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002486 if (track->isFastTrack()) {
2487 result |= FAST_SESSION;
2488 }
Eric Laurent81784c32012-11-19 14:55:58 -08002489 break;
2490 }
2491 }
2492
2493 return result;
2494}
2495
Glenn Kastend848eb42016-03-08 13:42:11 -08002496uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002497{
2498 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2499 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2500 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2501 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2502 }
2503 for (size_t i = 0; i < mTracks.size(); i++) {
2504 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002505 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002506 return AudioSystem::getStrategyForStream(track->streamType());
2507 }
2508 }
2509 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2510}
2511
2512
Phil Burk062e67a2015-02-11 13:40:50 -08002513AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002514{
2515 Mutex::Autolock _l(mLock);
2516 return mOutput;
2517}
2518
Phil Burk062e67a2015-02-11 13:40:50 -08002519AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002520{
2521 Mutex::Autolock _l(mLock);
2522 AudioStreamOut *output = mOutput;
2523 mOutput = NULL;
2524 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2525 // must push a NULL and wait for ack
2526 mOutputSink.clear();
2527 mPipeSink.clear();
2528 mNormalSink.clear();
2529 return output;
2530}
2531
2532// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002533sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002534{
2535 if (mOutput == NULL) {
2536 return NULL;
2537 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002538 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002539}
2540
2541uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2542{
2543 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2544}
2545
2546status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2547{
2548 if (!isValidSyncEvent(event)) {
2549 return BAD_VALUE;
2550 }
2551
2552 Mutex::Autolock _l(mLock);
2553
2554 for (size_t i = 0; i < mTracks.size(); ++i) {
2555 sp<Track> track = mTracks[i];
2556 if (event->triggerSession() == track->sessionId()) {
2557 (void) track->setSyncEvent(event);
2558 return NO_ERROR;
2559 }
2560 }
2561
2562 return NAME_NOT_FOUND;
2563}
2564
2565bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2566{
2567 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2568}
2569
2570void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2571 const Vector< sp<Track> >& tracksToRemove)
2572{
2573 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002574 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002575 for (size_t i = 0 ; i < count ; i++) {
2576 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002577 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002578 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002579 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580#ifdef ADD_BATTERY_DATA
2581 // to track the speaker usage
2582 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2583#endif
2584 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002585 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002586 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 }
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
2589 }
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591}
2592
2593void AudioFlinger::PlaybackThread::checkSilentMode_l()
2594{
2595 if (!mMasterMute) {
2596 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002597 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2598 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2599 return;
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601 if (property_get("ro.audio.silent", value, "0") > 0) {
2602 char *endptr;
2603 unsigned long ul = strtoul(value, &endptr, 0);
2604 if (*endptr == '\0' && ul != 0) {
2605 ALOGD("Silence is golden");
2606 // The setprop command will not allow a property to be changed after
2607 // the first time it is set, so we don't have to worry about un-muting.
2608 setMasterMute_l(true);
2609 }
2610 }
2611 }
2612}
2613
2614// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002616{
Eric Laurent81784c32012-11-19 14:55:58 -08002617 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002619 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002620
2621 // If an NBAIO sink is present, use it to write the normal mixer's submix
2622 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002623
Andy Hung010a1a12014-03-13 13:57:33 -07002624 const size_t count = mBytesRemaining / mFrameSize;
2625
Simon Wilson2d590962012-11-29 15:18:50 -08002626 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002627 // update the setpoint when AudioFlinger::mScreenState changes
2628 uint32_t screenState = AudioFlinger::mScreenState;
2629 if (screenState != mScreenState) {
2630 mScreenState = screenState;
2631 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2632 if (pipe != NULL) {
2633 pipe->setAvgFrames((mScreenState & 1) ?
2634 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2635 }
2636 }
Andy Hung010a1a12014-03-13 13:57:33 -07002637 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002638 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002639 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002640 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002641 } else {
2642 bytesWritten = framesWritten;
2643 }
2644 // otherwise use the HAL / AudioStreamOut directly
2645 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002647
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002649 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2650 mWriteAckSequence += 2;
2651 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002653 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002655 // FIXME We should have an implementation of timestamps for direct output threads.
2656 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002657 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002658
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 if (mUseAsyncWrite &&
2660 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2661 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002662 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002664 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
Eric Laurent81784c32012-11-19 14:55:58 -08002668 mNumWrites++;
2669 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002670 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 return bytesWritten;
2672}
2673
2674void AudioFlinger::PlaybackThread::threadLoop_drain()
2675{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002676 bool supportsDrain = false;
2677 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2679 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002680 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2681 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002683 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002685 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002686 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 }
2688}
2689
2690void AudioFlinger::PlaybackThread::threadLoop_exit()
2691{
Eric Laurent275e8e92014-11-30 15:14:47 -08002692 {
2693 Mutex::Autolock _l(mLock);
2694 for (size_t i = 0; i < mTracks.size(); i++) {
2695 sp<Track> track = mTracks[i];
2696 track->invalidate();
2697 }
Andy Hungdae27702016-10-31 14:01:16 -07002698 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2699 // After we exit there are no more track changes sent to BatteryNotifier
2700 // because that requires an active threadLoop.
2701 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2702 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 }
Eric Laurent81784c32012-11-19 14:55:58 -08002704}
2705
2706/*
2707The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002708 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002709 - mActiveSleepTimeUs from activeSleepTimeUs()
2710 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002711 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2712 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002713 - maxPeriod from frame count and sample rate (MIXER only)
2714
2715The parameters that affect these derived values are:
2716 - frame count
2717 - frame size
2718 - sample rate
2719 - device type: A2DP or not
2720 - device latency
2721 - format: PCM or not
2722 - active sleep time
2723 - idle sleep time
2724*/
2725
2726void AudioFlinger::PlaybackThread::cacheParameters_l()
2727{
Andy Hung25c2dac2014-02-27 14:56:00 -08002728 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002729 mActiveSleepTimeUs = activeSleepTimeUs();
2730 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002731
2732 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2733 // truncating audio when going to standby.
2734 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2735 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2736 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2737 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2738 }
2739 }
Eric Laurent81784c32012-11-19 14:55:58 -08002740}
2741
Eric Laurent13084622016-05-17 10:51:49 -07002742bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002743{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002744 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002745 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002746 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002747 size_t size = mTracks.size();
2748 for (size_t i = 0; i < size; i++) {
2749 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002750 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002751 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002752 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002753 }
2754 }
Eric Laurent13084622016-05-17 10:51:49 -07002755 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002756}
2757
Haynes Mathew George05317d22016-05-03 16:34:26 -07002758void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2759{
2760 Mutex::Autolock _l(mLock);
2761 invalidateTracks_l(streamType);
2762}
2763
Eric Laurent81784c32012-11-19 14:55:58 -08002764status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2765{
Glenn Kastend848eb42016-03-08 13:42:11 -08002766 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002767 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2768 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002769 bool ownsBuffer = false;
2770
2771 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002772 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002773 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002774 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002775 if (mType != DIRECT) {
2776 size_t numSamples = mNormalFrameCount * mChannelCount;
2777 buffer = new int16_t[numSamples];
2778 memset(buffer, 0, numSamples * sizeof(int16_t));
2779 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2780 ownsBuffer = true;
2781 }
2782
2783 // Attach all tracks with same session ID to this chain.
2784 for (size_t i = 0; i < mTracks.size(); ++i) {
2785 sp<Track> track = mTracks[i];
2786 if (session == track->sessionId()) {
2787 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2788 buffer);
2789 track->setMainBuffer(buffer);
2790 chain->incTrackCnt();
2791 }
2792 }
2793
2794 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002795 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002796 if (session == track->sessionId()) {
2797 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2798 chain->incActiveTrackCnt();
2799 }
2800 }
2801 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002802 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002803 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002804 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2805 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002807 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2809 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002810 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002812 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002813 // Effect chain for other sessions are inserted at beginning of effect
2814 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002815 // sessions is not important.
2816 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2817 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2818 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002819 size_t size = mEffectChains.size();
2820 size_t i = 0;
2821 for (i = 0; i < size; i++) {
2822 if (mEffectChains[i]->sessionId() < session) {
2823 break;
2824 }
2825 }
2826 mEffectChains.insertAt(chain, i);
2827 checkSuspendOnAddEffectChain_l(chain);
2828
2829 return NO_ERROR;
2830}
2831
2832size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2833{
Glenn Kastend848eb42016-03-08 13:42:11 -08002834 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002835
2836 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2837
2838 for (size_t i = 0; i < mEffectChains.size(); i++) {
2839 if (chain == mEffectChains[i]) {
2840 mEffectChains.removeAt(i);
2841 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002842 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002843 if (session == track->sessionId()) {
2844 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2845 chain.get(), session);
2846 chain->decActiveTrackCnt();
2847 }
2848 }
2849
2850 // detach all tracks with same session ID from this chain
2851 for (size_t i = 0; i < mTracks.size(); ++i) {
2852 sp<Track> track = mTracks[i];
2853 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002854 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002855 chain->decTrackCnt();
2856 }
2857 }
2858 break;
2859 }
2860 }
2861 return mEffectChains.size();
2862}
2863
2864status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002865 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002866{
2867 Mutex::Autolock _l(mLock);
2868 return attachAuxEffect_l(track, EffectId);
2869}
2870
2871status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002872 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002873{
2874 status_t status = NO_ERROR;
2875
2876 if (EffectId == 0) {
2877 track->setAuxBuffer(0, NULL);
2878 } else {
2879 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2880 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2881 if (effect != 0) {
2882 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2883 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2884 } else {
2885 status = INVALID_OPERATION;
2886 }
2887 } else {
2888 status = BAD_VALUE;
2889 }
2890 }
2891 return status;
2892}
2893
2894void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2895{
2896 for (size_t i = 0; i < mTracks.size(); ++i) {
2897 sp<Track> track = mTracks[i];
2898 if (track->auxEffectId() == effectId) {
2899 attachAuxEffect_l(track, 0);
2900 }
2901 }
2902}
2903
2904bool AudioFlinger::PlaybackThread::threadLoop()
2905{
2906 Vector< sp<Track> > tracksToRemove;
2907
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002908 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002909 nsecs_t lastWriteFinished = -1; // time last server write completed
2910 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002911
2912 // MIXER
2913 nsecs_t lastWarning = 0;
2914
2915 // DUPLICATING
2916 // FIXME could this be made local to while loop?
2917 writeFrames = 0;
2918
2919 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002920 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002921
2922 if (mType == MIXER) {
2923 sleepTimeShift = 0;
2924 }
2925
2926 CpuStats cpuStats;
2927 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2928
2929 acquireWakeLock();
2930
Glenn Kasten9e58b552013-01-18 15:09:48 -08002931 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2932 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2933 // and then that string will be logged at the next convenient opportunity.
2934 const char *logString = NULL;
2935
Eric Laurent664539d2013-09-23 18:24:31 -07002936 checkSilentMode_l();
2937
Eric Laurent81784c32012-11-19 14:55:58 -08002938 while (!exitPending())
2939 {
2940 cpuStats.sample(myName);
2941
2942 Vector< sp<EffectChain> > effectChains;
2943
Eric Laurent81784c32012-11-19 14:55:58 -08002944 { // scope for mLock
2945
2946 Mutex::Autolock _l(mLock);
2947
Eric Laurent021cf962014-05-13 10:18:14 -07002948 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002949
Glenn Kasten9e58b552013-01-18 15:09:48 -08002950 if (logString != NULL) {
2951 mNBLogWriter->logTimestamp();
2952 mNBLogWriter->log(logString);
2953 logString = NULL;
2954 }
2955
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002956 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002957 // and associate with the sink frames written out. We need
2958 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002959 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002960 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002961 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002962 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002963 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002964 ExtendedTimestamp timestamp; // use private copy to fetch
2965 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002966
2967 // We keep track of the last valid kernel position in case we are in underrun
2968 // and the normal mixer period is the same as the fast mixer period, or there
2969 // is some error from the HAL.
2970 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2971 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2972 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2973 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2974 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2975
2976 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2977 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2978 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2979 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002980 }
2981
2982 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2983 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002984 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002985 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002986 }
2987
Andy Hung818e7a32016-02-16 18:08:07 -08002988 // copy over kernel info
2989 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002990 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2991 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002992 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2993 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002994 }
2995 // mFramesWritten for non-offloaded tracks are contiguous
2996 // even after standby() is called. This is useful for the track frame
2997 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002998 bool serverLocationUpdate = false;
2999 if (mFramesWritten != lastFramesWritten) {
3000 serverLocationUpdate = true;
3001 lastFramesWritten = mFramesWritten;
3002 }
3003 // Only update timestamps if there is a meaningful change.
3004 // Either the kernel timestamp must be valid or we have written something.
3005 if (kernelLocationUpdate || serverLocationUpdate) {
3006 if (serverLocationUpdate) {
3007 // use the time before we called the HAL write - it is a bit more accurate
3008 // to when the server last read data than the current time here.
3009 //
3010 // If we haven't written anything, mLastWriteTime will be -1
3011 // and we use systemTime().
3012 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3013 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3014 ? systemTime() : mLastWriteTime;
3015 }
Andy Hungdae27702016-10-31 14:01:16 -07003016
3017 for (const sp<Track> &t : mActiveTracks) {
3018 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003019 t->updateTrackFrameInfo(
3020 t->mAudioTrackServerProxy->framesReleased(),
3021 mFramesWritten,
3022 mTimestamp);
3023 }
Andy Hunge10393e2015-06-12 13:59:33 -07003024 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003025 }
3026
Eric Laurent81784c32012-11-19 14:55:58 -08003027 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 if (mSignalPending) {
3029 // A signal was raised while we were unlocked
3030 mSignalPending = false;
3031 } else if (waitingAsyncCallback_l()) {
3032 if (exitPending()) {
3033 break;
3034 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003035 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003036 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003037 releaseWakeLock_l();
3038 released = true;
3039 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 ALOGV("wait async completion");
3041 mWaitWorkCV.wait(mLock);
3042 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003043 if (released) {
3044 acquireWakeLock_l();
3045 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003046 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3047 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003048
3049 continue;
3050 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 isSuspended()) {
3053 // put audio hardware into standby after short delay
3054 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003055
3056 threadLoop_standby();
3057
3058 mStandby = true;
3059 }
3060
3061 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3062 // we're about to wait, flush the binder command buffer
3063 IPCThreadState::self()->flushCommands();
3064
3065 clearOutputTracks();
3066
3067 if (exitPending()) {
3068 break;
3069 }
3070
3071 releaseWakeLock_l();
3072 // wait until we have something to do...
3073 ALOGV("%s going to sleep", myName.string());
3074 mWaitWorkCV.wait(mLock);
3075 ALOGV("%s waking up", myName.string());
3076 acquireWakeLock_l();
3077
3078 mMixerStatus = MIXER_IDLE;
3079 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3080 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003082 checkSilentMode_l();
3083
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003084 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3085 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003086 if (mType == MIXER) {
3087 sleepTimeShift = 0;
3088 }
3089
3090 continue;
3091 }
3092 }
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // mMixerStatusIgnoringFastTracks is also updated internally
3094 mMixerStatus = prepareTracks_l(&tracksToRemove);
3095
Andy Hungdae27702016-10-31 14:01:16 -07003096 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003097
Eric Laurent81784c32012-11-19 14:55:58 -08003098 // prevent any changes in effect chain list and in each effect chain
3099 // during mixing and effect process as the audio buffers could be deleted
3100 // or modified if an effect is created or deleted
3101 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003102 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003103
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 if (mBytesRemaining == 0) {
3105 mCurrentWriteLength = 0;
3106 if (mMixerStatus == MIXER_TRACKS_READY) {
3107 // threadLoop_mix() sets mCurrentWriteLength
3108 threadLoop_mix();
3109 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3110 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 // must be written to HAL
3113 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003115 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 }
3117 }
Andy Hung98ef9782014-03-04 14:46:50 -08003118 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003119 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003120 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3121 // or mSinkBuffer (if there are no effects).
3122 //
3123 // This is done pre-effects computation; if effects change to
3124 // support higher precision, this needs to move.
3125 //
3126 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003127 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003128 if (mMixerBufferValid) {
3129 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3130 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3131
Andy Hung2ddee192015-12-18 17:34:44 -08003132 // mono blend occurs for mixer threads only (not direct or offloaded)
3133 // and is handled here if we're going directly to the sink.
3134 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003135 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3136 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003137 }
3138
Andy Hung98ef9782014-03-04 14:46:50 -08003139 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3140 mNormalFrameCount * mChannelCount);
3141 }
3142
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 mBytesRemaining = mCurrentWriteLength;
3144 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003145 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3146 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3147 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3148 mBytesWritten += mBytesRemaining;
3149 mFramesWritten += framesRemaining;
3150 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 mBytesRemaining = 0;
3152 }
Eric Laurent81784c32012-11-19 14:55:58 -08003153
Eric Laurentbfb1b832013-01-07 09:53:42 -08003154 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003155 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 for (size_t i = 0; i < effectChains.size(); i ++) {
3157 effectChains[i]->process_l();
3158 }
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003161 // Process effect chains for offloaded thread even if no audio
3162 // was read from audio track: process only updates effect state
3163 // and thus does have to be synchronized with audio writes but may have
3164 // to be called while waiting for async write callback
3165 if (mType == OFFLOAD) {
3166 for (size_t i = 0; i < effectChains.size(); i ++) {
3167 effectChains[i]->process_l();
3168 }
3169 }
Eric Laurent81784c32012-11-19 14:55:58 -08003170
Andy Hung98ef9782014-03-04 14:46:50 -08003171 // Only if the Effects buffer is enabled and there is data in the
3172 // Effects buffer (buffer valid), we need to
3173 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003174 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003175 if (mEffectBufferValid) {
3176 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003177
3178 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003179 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3180 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003181 }
3182
Andy Hung98ef9782014-03-04 14:46:50 -08003183 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3184 mNormalFrameCount * mChannelCount);
3185 }
3186
Eric Laurent81784c32012-11-19 14:55:58 -08003187 // enable changes in effect chain
3188 unlockEffectChains(effectChains);
3189
Eric Laurentbfb1b832013-01-07 09:53:42 -08003190 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003191 // mSleepTimeUs == 0 means we must write to audio hardware
3192 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003193 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003194 // We save lastWriteFinished here, as previousLastWriteFinished,
3195 // for throttling. On thread start, previousLastWriteFinished will be
3196 // set to -1, which properly results in no throttling after the first write.
3197 nsecs_t previousLastWriteFinished = lastWriteFinished;
3198 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003200 // FIXME rewrite to reduce number of system calls
3201 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003202 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003203 lastWriteFinished = systemTime();
3204 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 if (ret < 0) {
3206 mBytesRemaining = 0;
3207 } else {
3208 mBytesWritten += ret;
3209 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003210 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003211 }
3212 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3213 (mMixerStatus == MIXER_DRAIN_ALL)) {
3214 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003215 }
Andy Hung08fb1742015-05-31 23:22:10 -07003216 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003217 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003218 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003219 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003220 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003221 ATRACE_NAME("underrun");
3222 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003223 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003224 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003225 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 }
Andy Hung08fb1742015-05-31 23:22:10 -07003227
3228 if (mThreadThrottle
3229 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3230 && ret > 0) { // we wrote something
3231 // Limit MixerThread data processing to no more than twice the
3232 // expected processing rate.
3233 //
3234 // This helps prevent underruns with NuPlayer and other applications
3235 // which may set up buffers that are close to the minimum size, or use
3236 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3237 //
3238 // The throttle smooths out sudden large data drains from the device,
3239 // e.g. when it comes out of standby, which often causes problems with
3240 // (1) mixer threads without a fast mixer (which has its own warm-up)
3241 // (2) minimum buffer sized tracks (even if the track is full,
3242 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003243 //
3244 // Total time spent in last processing cycle equals time spent in
3245 // 1. threadLoop_write, as well as time spent in
3246 // 2. threadLoop_mix (significant for heavy mixing, especially
3247 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003248
Andy Hung69488c42016-05-16 18:43:33 -07003249 // it's OK if deltaMs is an overestimate.
3250 const int32_t deltaMs =
3251 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003252 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3253 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3254 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003255 // notify of throttle start on verbose log
3256 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3257 "mixer(%p) throttle begin:"
3258 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003259 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003260 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003261 // Throttle must be attributed to the previous mixer loop's write time
3262 // to allow back-to-back throttling.
3263 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003264 } else {
3265 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3266 if (diff > 0) {
3267 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003268 // but prevent spamming for bluetooth
3269 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3270 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003271 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3272 }
Andy Hung08fb1742015-05-31 23:22:10 -07003273 }
3274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 }
Eric Laurent81784c32012-11-19 14:55:58 -08003276
Eric Laurentbfb1b832013-01-07 09:53:42 -08003277 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003278 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003279 Mutex::Autolock _l(mLock);
3280 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3281 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003282 }
Glenn Kastene7754022014-10-31 12:11:26 -07003283 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285 }
3286
3287 // Finally let go of removed track(s), without the lock held
3288 // since we can't guarantee the destructors won't acquire that
3289 // same lock. This will also mutate and push a new fast mixer state.
3290 threadLoop_removeTracks(tracksToRemove);
3291 tracksToRemove.clear();
3292
3293 // FIXME I don't understand the need for this here;
3294 // it was in the original code but maybe the
3295 // assignment in saveOutputTracks() makes this unnecessary?
3296 clearOutputTracks();
3297
3298 // Effect chains will be actually deleted here if they were removed from
3299 // mEffectChains list during mixing or effects processing
3300 effectChains.clear();
3301
3302 // FIXME Note that the above .clear() is no longer necessary since effectChains
3303 // is now local to this block, but will keep it for now (at least until merge done).
3304 }
3305
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 threadLoop_exit();
3307
Eric Laurentcf817a22014-08-04 20:36:31 -07003308 if (!mStandby) {
3309 threadLoop_standby();
3310 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003311 }
3312
3313 releaseWakeLock();
3314
3315 ALOGV("Thread %p type %d exiting", this, mType);
3316 return false;
3317}
3318
Eric Laurentbfb1b832013-01-07 09:53:42 -08003319// removeTracks_l() must be called with ThreadBase::mLock held
3320void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3321{
3322 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003323 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003324 for (size_t i=0 ; i<count ; i++) {
3325 const sp<Track>& track = tracksToRemove.itemAt(i);
3326 mActiveTracks.remove(track);
3327 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3328 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3329 if (chain != 0) {
3330 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3331 track->sessionId());
3332 chain->decActiveTrackCnt();
3333 }
3334 if (track->isTerminated()) {
3335 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003336 } else { // inactive but not terminated
3337 char buffer[256];
3338 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3339 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 }
3341 }
3342 }
3343
3344}
Eric Laurent81784c32012-11-19 14:55:58 -08003345
Eric Laurentaccc1472013-09-20 09:36:34 -07003346status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3347{
3348 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003349 ExtendedTimestamp ets;
3350 status_t status = mNormalSink->getTimestamp(ets);
3351 if (status == NO_ERROR) {
3352 status = ets.getBestTimestamp(&timestamp);
3353 }
3354 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003355 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003356 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003357 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003358 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003359 timestamp.mPosition = (uint32_t)position64;
3360 return NO_ERROR;
3361 }
3362 }
3363 return INVALID_OPERATION;
3364}
Eric Laurent1c333e22014-05-20 10:48:17 -07003365
Eric Laurent054d9d32015-04-24 08:48:48 -07003366status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3367 audio_patch_handle_t *handle)
3368{
Andy Hungf60abce2016-08-26 11:37:54 -07003369 status_t status;
3370 if (property_get_bool("af.patch_park", false /* default_value */)) {
3371 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3372 // or if HAL does not properly lock against access.
3373 AutoPark<FastMixer> park(mFastMixer);
3374 status = PlaybackThread::createAudioPatch_l(patch, handle);
3375 } else {
3376 status = PlaybackThread::createAudioPatch_l(patch, handle);
3377 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003378 return status;
3379}
3380
Eric Laurent1c333e22014-05-20 10:48:17 -07003381status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3382 audio_patch_handle_t *handle)
3383{
3384 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003385
3386 // store new device and send to effects
3387 audio_devices_t type = AUDIO_DEVICE_NONE;
3388 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3389 type |= patch->sinks[i].ext.device.type;
3390 }
3391
3392#ifdef ADD_BATTERY_DATA
3393 // when changing the audio output device, call addBatteryData to notify
3394 // the change
3395 if (mOutDevice != type) {
3396 uint32_t params = 0;
3397 // check whether speaker is on
3398 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3399 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003400 }
3401
Eric Laurent054d9d32015-04-24 08:48:48 -07003402 audio_devices_t deviceWithoutSpeaker
3403 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3404 // check if any other device (except speaker) is on
3405 if (type & deviceWithoutSpeaker) {
3406 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3407 }
3408
3409 if (params != 0) {
3410 addBatteryData(params);
3411 }
3412 }
3413#endif
3414
3415 for (size_t i = 0; i < mEffectChains.size(); i++) {
3416 mEffectChains[i]->setDevice_l(type);
3417 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003418
3419 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3420 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3421 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003422 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003423 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003424
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003425 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003426 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3427 status = hwDevice->createAudioPatch(patch->num_sources,
3428 patch->sources,
3429 patch->num_sinks,
3430 patch->sinks,
3431 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003432 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003433 char *address;
3434 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3435 //FIXME: we only support address on first sink with HAL version < 3.0
3436 address = audio_device_address_to_parameter(
3437 patch->sinks[0].ext.device.type,
3438 patch->sinks[0].ext.device.address);
3439 } else {
3440 address = (char *)calloc(1, 1);
3441 }
3442 AudioParameter param = AudioParameter(String8(address));
3443 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003444 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003445 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003446 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003447 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003448 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003449 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003450 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3451 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003452 return status;
3453}
3454
Eric Laurent054d9d32015-04-24 08:48:48 -07003455status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3456{
Andy Hungf60abce2016-08-26 11:37:54 -07003457 status_t status;
3458 if (property_get_bool("af.patch_park", false /* default_value */)) {
3459 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3460 // or if HAL does not properly lock against access.
3461 AutoPark<FastMixer> park(mFastMixer);
3462 status = PlaybackThread::releaseAudioPatch_l(handle);
3463 } else {
3464 status = PlaybackThread::releaseAudioPatch_l(handle);
3465 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003466 return status;
3467}
3468
Eric Laurent1c333e22014-05-20 10:48:17 -07003469status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3470{
3471 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003472
3473 mOutDevice = AUDIO_DEVICE_NONE;
3474
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003475 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003476 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3477 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003478 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003479 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003480 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003481 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003482 }
3483 return status;
3484}
3485
Eric Laurent83b88082014-06-20 18:31:16 -07003486void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3487{
3488 Mutex::Autolock _l(mLock);
3489 mTracks.add(track);
3490}
3491
3492void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3493{
3494 Mutex::Autolock _l(mLock);
3495 destroyTrack_l(track);
3496}
3497
3498void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3499{
3500 ThreadBase::getAudioPortConfig(config);
3501 config->role = AUDIO_PORT_ROLE_SOURCE;
3502 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3503 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3504}
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506// ----------------------------------------------------------------------------
3507
3508AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003509 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3510 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003511 // mAudioMixer below
3512 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003513 mFastMixerFutex(0),
3514 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003515 // mOutputSink below
3516 // mPipeSink below
3517 // mNormalSink below
3518{
3519 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003520 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3521 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003522 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3523 mNormalFrameCount);
3524 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3525
Andy Hungfbfc3952015-01-15 13:33:51 -08003526 if (type == DUPLICATING) {
3527 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3528 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3529 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3530 return;
3531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003533 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003534 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003535 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003536#if !LOG_NDEBUG
3537 ssize_t index =
3538#else
3539 (void)
3540#endif
3541 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003542 ALOG_ASSERT(index == 0);
3543
3544 // initialize fast mixer depending on configuration
3545 bool initFastMixer;
3546 switch (kUseFastMixer) {
3547 case FastMixer_Never:
3548 initFastMixer = false;
3549 break;
3550 case FastMixer_Always:
3551 initFastMixer = true;
3552 break;
3553 case FastMixer_Static:
3554 case FastMixer_Dynamic:
3555 initFastMixer = mFrameCount < mNormalFrameCount;
3556 break;
3557 }
3558 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003559 audio_format_t fastMixerFormat;
3560 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3561 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3562 } else {
3563 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3564 }
3565 if (mFormat != fastMixerFormat) {
3566 // change our Sink format to accept our intermediate precision
3567 mFormat = fastMixerFormat;
3568 free(mSinkBuffer);
3569 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3570 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3571 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3572 }
Eric Laurent81784c32012-11-19 14:55:58 -08003573
3574 // create a MonoPipe to connect our submix to FastMixer
3575 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003576#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003577 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003578#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003579 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003580 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003581 format.mFormat = fastMixerFormat;
3582 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3583
Eric Laurent81784c32012-11-19 14:55:58 -08003584 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3585 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3586 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3587 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3588 const NBAIO_Format offers[1] = {format};
3589 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003590#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003591 ssize_t index =
3592#else
3593 (void)
3594#endif
3595 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003596 ALOG_ASSERT(index == 0);
3597 monoPipe->setAvgFrames((mScreenState & 1) ?
3598 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3599 mPipeSink = monoPipe;
3600
Glenn Kasten46909e72013-02-26 09:20:22 -08003601#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003602 if (mTeeSinkOutputEnabled) {
3603 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003604 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3605 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003606 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003607 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003608 ALOG_ASSERT(index == 0);
3609 mTeeSink = teeSink;
3610 PipeReader *teeSource = new PipeReader(*teeSink);
3611 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003612 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003613 ALOG_ASSERT(index == 0);
3614 mTeeSource = teeSource;
3615 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003616#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003617
3618 // create fast mixer and configure it initially with just one fast track for our submix
3619 mFastMixer = new FastMixer();
3620 FastMixerStateQueue *sq = mFastMixer->sq();
3621#ifdef STATE_QUEUE_DUMP
3622 sq->setObserverDump(&mStateQueueObserverDump);
3623 sq->setMutatorDump(&mStateQueueMutatorDump);
3624#endif
3625 FastMixerState *state = sq->begin();
3626 FastTrack *fastTrack = &state->mFastTracks[0];
3627 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3628 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3629 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003630 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3631 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003632 fastTrack->mGeneration++;
3633 state->mFastTracksGen++;
3634 state->mTrackMask = 1;
3635 // fast mixer will use the HAL output sink
3636 state->mOutputSink = mOutputSink.get();
3637 state->mOutputSinkGen++;
3638 state->mFrameCount = mFrameCount;
3639 state->mCommand = FastMixerState::COLD_IDLE;
3640 // already done in constructor initialization list
3641 //mFastMixerFutex = 0;
3642 state->mColdFutexAddr = &mFastMixerFutex;
3643 state->mColdGen++;
3644 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003645#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003646 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003647#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003648 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3649 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003650 sq->end();
3651 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3652
3653 // start the fast mixer
3654 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3655 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003656 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003657
3658#ifdef AUDIO_WATCHDOG
3659 // create and start the watchdog
3660 mAudioWatchdog = new AudioWatchdog();
3661 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3662 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3663 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003664 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003665#endif
3666
Eric Laurent81784c32012-11-19 14:55:58 -08003667 }
3668
3669 switch (kUseFastMixer) {
3670 case FastMixer_Never:
3671 case FastMixer_Dynamic:
3672 mNormalSink = mOutputSink;
3673 break;
3674 case FastMixer_Always:
3675 mNormalSink = mPipeSink;
3676 break;
3677 case FastMixer_Static:
3678 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3679 break;
3680 }
3681}
3682
3683AudioFlinger::MixerThread::~MixerThread()
3684{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003685 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003686 FastMixerStateQueue *sq = mFastMixer->sq();
3687 FastMixerState *state = sq->begin();
3688 if (state->mCommand == FastMixerState::COLD_IDLE) {
3689 int32_t old = android_atomic_inc(&mFastMixerFutex);
3690 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003691 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003692 }
3693 }
3694 state->mCommand = FastMixerState::EXIT;
3695 sq->end();
3696 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3697 mFastMixer->join();
3698 // Though the fast mixer thread has exited, it's state queue is still valid.
3699 // We'll use that extract the final state which contains one remaining fast track
3700 // corresponding to our sub-mix.
3701 state = sq->begin();
3702 ALOG_ASSERT(state->mTrackMask == 1);
3703 FastTrack *fastTrack = &state->mFastTracks[0];
3704 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3705 delete fastTrack->mBufferProvider;
3706 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003707 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003708#ifdef AUDIO_WATCHDOG
3709 if (mAudioWatchdog != 0) {
3710 mAudioWatchdog->requestExit();
3711 mAudioWatchdog->requestExitAndWait();
3712 mAudioWatchdog.clear();
3713 }
3714#endif
3715 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003716 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003717 delete mAudioMixer;
3718}
3719
3720
3721uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3722{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003723 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003724 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3725 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3726 }
3727 return latency;
3728}
3729
3730
3731void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3732{
3733 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3734}
3735
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003737{
3738 // FIXME we should only do one push per cycle; confirm this is true
3739 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003740 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003741 FastMixerStateQueue *sq = mFastMixer->sq();
3742 FastMixerState *state = sq->begin();
3743 if (state->mCommand != FastMixerState::MIX_WRITE &&
3744 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3745 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003746
3747 // FIXME workaround for first HAL write being CPU bound on some devices
3748 ATRACE_BEGIN("write");
3749 mOutput->write((char *)mSinkBuffer, 0);
3750 ATRACE_END();
3751
Eric Laurent81784c32012-11-19 14:55:58 -08003752 int32_t old = android_atomic_inc(&mFastMixerFutex);
3753 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003754 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003755 }
3756#ifdef AUDIO_WATCHDOG
3757 if (mAudioWatchdog != 0) {
3758 mAudioWatchdog->resume();
3759 }
3760#endif
3761 }
3762 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003763#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003764 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003765 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003766#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003767 sq->end();
3768 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3769 if (kUseFastMixer == FastMixer_Dynamic) {
3770 mNormalSink = mPipeSink;
3771 }
3772 } else {
3773 sq->end(false /*didModify*/);
3774 }
3775 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003776 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003777}
3778
3779void AudioFlinger::MixerThread::threadLoop_standby()
3780{
3781 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003782 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003783 FastMixerStateQueue *sq = mFastMixer->sq();
3784 FastMixerState *state = sq->begin();
3785 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003786 // Report any frames trapped in the Monopipe
3787 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3788 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3789 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3790 "monoPipeWritten:%lld monoPipeLeft:%lld",
3791 (long long)mFramesWritten, (long long)mSuspendedFrames,
3792 (long long)mPipeSink->framesWritten(), pipeFrames);
3793 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3794
Eric Laurent81784c32012-11-19 14:55:58 -08003795 state->mCommand = FastMixerState::COLD_IDLE;
3796 state->mColdFutexAddr = &mFastMixerFutex;
3797 state->mColdGen++;
3798 mFastMixerFutex = 0;
3799 sq->end();
3800 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3801 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3802 if (kUseFastMixer == FastMixer_Dynamic) {
3803 mNormalSink = mOutputSink;
3804 }
3805#ifdef AUDIO_WATCHDOG
3806 if (mAudioWatchdog != 0) {
3807 mAudioWatchdog->pause();
3808 }
3809#endif
3810 } else {
3811 sq->end(false /*didModify*/);
3812 }
3813 }
3814 PlaybackThread::threadLoop_standby();
3815}
3816
Eric Laurentbfb1b832013-01-07 09:53:42 -08003817bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3818{
3819 return false;
3820}
3821
3822bool AudioFlinger::PlaybackThread::shouldStandby_l()
3823{
3824 return !mStandby;
3825}
3826
3827bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3828{
3829 Mutex::Autolock _l(mLock);
3830 return waitingAsyncCallback_l();
3831}
3832
Eric Laurent81784c32012-11-19 14:55:58 -08003833// shared by MIXER and DIRECT, overridden by DUPLICATING
3834void AudioFlinger::PlaybackThread::threadLoop_standby()
3835{
3836 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003837 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003839 // discard any pending drain or write ack by incrementing sequence
3840 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3841 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003842 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003843 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3844 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003846 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003847}
3848
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003849void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3850{
3851 ALOGV("signal playback thread");
3852 broadcast_l();
3853}
3854
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003855void AudioFlinger::PlaybackThread::onAsyncError()
3856{
3857 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3858 invalidateTracks((audio_stream_type_t)i);
3859 }
3860}
3861
Eric Laurent81784c32012-11-19 14:55:58 -08003862void AudioFlinger::MixerThread::threadLoop_mix()
3863{
Eric Laurent81784c32012-11-19 14:55:58 -08003864 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003865 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003866 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003867 // increase sleep time progressively when application underrun condition clears.
3868 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3869 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3870 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003871 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003872 sleepTimeShift--;
3873 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003874 mSleepTimeUs = 0;
3875 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003876 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003877
Eric Laurent81784c32012-11-19 14:55:58 -08003878}
3879
3880void AudioFlinger::MixerThread::threadLoop_sleepTime()
3881{
3882 // If no tracks are ready, sleep once for the duration of an output
3883 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003884 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003885 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003886 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3887 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3888 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003889 }
3890 // reduce sleep time in case of consecutive application underruns to avoid
3891 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3892 // duration we would end up writing less data than needed by the audio HAL if
3893 // the condition persists.
3894 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3895 sleepTimeShift++;
3896 }
3897 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003898 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003899 }
3900 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003901 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3902 // before effects processing or output.
3903 if (mMixerBufferValid) {
3904 memset(mMixerBuffer, 0, mMixerBufferSize);
3905 } else {
3906 memset(mSinkBuffer, 0, mSinkBufferSize);
3907 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003908 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003909 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3910 "anticipated start");
3911 }
3912 // TODO add standby time extension fct of effect tail
3913}
3914
3915// prepareTracks_l() must be called with ThreadBase::mLock held
3916AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3917 Vector< sp<Track> > *tracksToRemove)
3918{
3919
3920 mixer_state mixerStatus = MIXER_IDLE;
3921 // find out which tracks need to be processed
3922 size_t count = mActiveTracks.size();
3923 size_t mixedTracks = 0;
3924 size_t tracksWithEffect = 0;
3925 // counts only _active_ fast tracks
3926 size_t fastTracks = 0;
3927 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3928
3929 float masterVolume = mMasterVolume;
3930 bool masterMute = mMasterMute;
3931
3932 if (masterMute) {
3933 masterVolume = 0;
3934 }
3935 // Delegate master volume control to effect in output mix effect chain if needed
3936 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3937 if (chain != 0) {
3938 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3939 chain->setVolume_l(&v, &v);
3940 masterVolume = (float)((v + (1 << 23)) >> 24);
3941 chain.clear();
3942 }
3943
3944 // prepare a new state to push
3945 FastMixerStateQueue *sq = NULL;
3946 FastMixerState *state = NULL;
3947 bool didModify = false;
3948 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003949 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003950 sq = mFastMixer->sq();
3951 state = sq->begin();
3952 }
3953
Andy Hung69aed5f2014-02-25 17:24:40 -08003954 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003955 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003956
Eric Laurent81784c32012-11-19 14:55:58 -08003957 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003958 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003959
3960 // this const just means the local variable doesn't change
3961 Track* const track = t.get();
3962
3963 // process fast tracks
3964 if (track->isFastTrack()) {
3965
3966 // It's theoretically possible (though unlikely) for a fast track to be created
3967 // and then removed within the same normal mix cycle. This is not a problem, as
3968 // the track never becomes active so it's fast mixer slot is never touched.
3969 // The converse, of removing an (active) track and then creating a new track
3970 // at the identical fast mixer slot within the same normal mix cycle,
3971 // is impossible because the slot isn't marked available until the end of each cycle.
3972 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003973 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003974 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3975 FastTrack *fastTrack = &state->mFastTracks[j];
3976
3977 // Determine whether the track is currently in underrun condition,
3978 // and whether it had a recent underrun.
3979 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3980 FastTrackUnderruns underruns = ftDump->mUnderruns;
3981 uint32_t recentFull = (underruns.mBitFields.mFull -
3982 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3983 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3984 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3985 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3986 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3987 uint32_t recentUnderruns = recentPartial + recentEmpty;
3988 track->mObservedUnderruns = underruns;
3989 // don't count underruns that occur while stopping or pausing
3990 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003991 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3992 recentUnderruns > 0) {
3993 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3994 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003995 } else {
3996 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003997 }
3998
3999 // This is similar to the state machine for normal tracks,
4000 // with a few modifications for fast tracks.
4001 bool isActive = true;
4002 switch (track->mState) {
4003 case TrackBase::STOPPING_1:
4004 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004006 track->mState = TrackBase::STOPPING_2;
4007 }
4008 break;
4009 case TrackBase::PAUSING:
4010 // ramp down is not yet implemented
4011 track->setPaused();
4012 break;
4013 case TrackBase::RESUMING:
4014 // ramp up is not yet implemented
4015 track->mState = TrackBase::ACTIVE;
4016 break;
4017 case TrackBase::ACTIVE:
4018 if (recentFull > 0 || recentPartial > 0) {
4019 // track has provided at least some frames recently: reset retry count
4020 track->mRetryCount = kMaxTrackRetries;
4021 }
4022 if (recentUnderruns == 0) {
4023 // no recent underruns: stay active
4024 break;
4025 }
4026 // there has recently been an underrun of some kind
4027 if (track->sharedBuffer() == 0) {
4028 // were any of the recent underruns "empty" (no frames available)?
4029 if (recentEmpty == 0) {
4030 // no, then ignore the partial underruns as they are allowed indefinitely
4031 break;
4032 }
4033 // there has recently been an "empty" underrun: decrement the retry counter
4034 if (--(track->mRetryCount) > 0) {
4035 break;
4036 }
4037 // indicate to client process that the track was disabled because of underrun;
4038 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004039 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004040 // remove from active list, but state remains ACTIVE [confusing but true]
4041 isActive = false;
4042 break;
4043 }
4044 // fall through
4045 case TrackBase::STOPPING_2:
4046 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004047 case TrackBase::STOPPED:
4048 case TrackBase::FLUSHED: // flush() while active
4049 // Check for presentation complete if track is inactive
4050 // We have consumed all the buffers of this track.
4051 // This would be incomplete if we auto-paused on underrun
4052 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004053 uint32_t latency = 0;
4054 status_t result = mOutput->stream->getLatency(&latency);
4055 ALOGE_IF(result != OK,
4056 "Error when retrieving output stream latency: %d", result);
4057 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004058 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004059 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4060 // track stays in active list until presentation is complete
4061 break;
4062 }
4063 }
4064 if (track->isStopping_2()) {
4065 track->mState = TrackBase::STOPPED;
4066 }
4067 if (track->isStopped()) {
4068 // Can't reset directly, as fast mixer is still polling this track
4069 // track->reset();
4070 // So instead mark this track as needing to be reset after push with ack
4071 resetMask |= 1 << i;
4072 }
4073 isActive = false;
4074 break;
4075 case TrackBase::IDLE:
4076 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004077 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079
4080 if (isActive) {
4081 // was it previously inactive?
4082 if (!(state->mTrackMask & (1 << j))) {
4083 ExtendedAudioBufferProvider *eabp = track;
4084 VolumeProvider *vp = track;
4085 fastTrack->mBufferProvider = eabp;
4086 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004087 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004088 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004089 fastTrack->mGeneration++;
4090 state->mTrackMask |= 1 << j;
4091 didModify = true;
4092 // no acknowledgement required for newly active tracks
4093 }
4094 // cache the combined master volume and stream type volume for fast mixer; this
4095 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004096 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004097 ++fastTracks;
4098 } else {
4099 // was it previously active?
4100 if (state->mTrackMask & (1 << j)) {
4101 fastTrack->mBufferProvider = NULL;
4102 fastTrack->mGeneration++;
4103 state->mTrackMask &= ~(1 << j);
4104 didModify = true;
4105 // If any fast tracks were removed, we must wait for acknowledgement
4106 // because we're about to decrement the last sp<> on those tracks.
4107 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4108 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004109 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4110 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4111 j, track->mState, state->mTrackMask, recentUnderruns,
4112 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004113 }
4114 tracksToRemove->add(track);
4115 // Avoids a misleading display in dumpsys
4116 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4117 }
4118 continue;
4119 }
4120
4121 { // local variable scope to avoid goto warning
4122
4123 audio_track_cblk_t* cblk = track->cblk();
4124
4125 // The first time a track is added we wait
4126 // for all its buffers to be filled before processing it
4127 int name = track->name();
4128 // make sure that we have enough frames to mix one full buffer.
4129 // enforce this condition only once to enable draining the buffer in case the client
4130 // app does not call stop() and relies on underrun to stop:
4131 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4132 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004133 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004134 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004135 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004136
4137 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004138 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004139 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4140 // add frames already consumed but not yet released by the resampler
4141 // because mAudioTrackServerProxy->framesReady() will include these frames
4142 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4143
Eric Laurent81784c32012-11-19 14:55:58 -08004144 uint32_t minFrames = 1;
4145 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4146 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004147 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004148 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004149
4150 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004151 if (ATRACE_ENABLED()) {
4152 // I wish we had formatted trace names
4153 char traceName[16];
4154 strcpy(traceName, "nRdy");
4155 int name = track->name();
4156 if (AudioMixer::TRACK0 <= name &&
4157 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4158 name -= AudioMixer::TRACK0;
4159 traceName[4] = (name / 10) + '0';
4160 traceName[5] = (name % 10) + '0';
4161 } else {
4162 traceName[4] = '?';
4163 traceName[5] = '?';
4164 }
4165 traceName[6] = '\0';
4166 ATRACE_INT(traceName, framesReady);
4167 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004168 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004169 !track->isPaused() && !track->isTerminated())
4170 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004171 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004172
4173 mixedTracks++;
4174
Andy Hung69aed5f2014-02-25 17:24:40 -08004175 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4176 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004177 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004178 if (track->mainBuffer() != mSinkBuffer &&
4179 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004180 if (mEffectBufferEnabled) {
4181 mEffectBufferValid = true; // Later can set directly.
4182 }
Eric Laurent81784c32012-11-19 14:55:58 -08004183 chain = getEffectChain_l(track->sessionId());
4184 // Delegate volume control to effect in track effect chain if needed
4185 if (chain != 0) {
4186 tracksWithEffect++;
4187 } else {
4188 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4189 "session %d",
4190 name, track->sessionId());
4191 }
4192 }
4193
4194
4195 int param = AudioMixer::VOLUME;
4196 if (track->mFillingUpStatus == Track::FS_FILLED) {
4197 // no ramp for the first volume setting
4198 track->mFillingUpStatus = Track::FS_ACTIVE;
4199 if (track->mState == TrackBase::RESUMING) {
4200 track->mState = TrackBase::ACTIVE;
4201 param = AudioMixer::RAMP_VOLUME;
4202 }
4203 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004204 // FIXME should not make a decision based on mServer
4205 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004206 // If the track is stopped before the first frame was mixed,
4207 // do not apply ramp
4208 param = AudioMixer::RAMP_VOLUME;
4209 }
4210
4211 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004212 uint32_t vl, vr; // in U8.24 integer format
4213 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004214 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004215 vl = vr = 0;
4216 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004217 if (track->isPausing()) {
4218 track->setPaused();
4219 }
4220 } else {
4221
4222 // read original volumes with volume control
4223 float typeVolume = mStreamTypes[track->streamType()].volume;
4224 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004225 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004226 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004227 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4228 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004229 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004230 if (vlf > GAIN_FLOAT_UNITY) {
4231 ALOGV("Track left volume out of range: %.3g", vlf);
4232 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004233 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004234 if (vrf > GAIN_FLOAT_UNITY) {
4235 ALOGV("Track right volume out of range: %.3g", vrf);
4236 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004237 }
4238 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004239 vlf *= v;
4240 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004241 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004242 // then derive vl and vr as U8.24 versions for the effect chain
4243 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4244 vl = (uint32_t) (scaleto8_24 * vlf);
4245 vr = (uint32_t) (scaleto8_24 * vrf);
4246 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004247 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004248 // send level comes from shared memory and so may be corrupt
4249 if (sendLevel > MAX_GAIN_INT) {
4250 ALOGV("Track send level out of range: %04X", sendLevel);
4251 sendLevel = MAX_GAIN_INT;
4252 }
Andy Hung6be49402014-05-30 10:42:03 -07004253 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4254 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004255 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004256
Eric Laurent81784c32012-11-19 14:55:58 -08004257 // Delegate volume control to effect in track effect chain if needed
4258 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4259 // Do not ramp volume if volume is controlled by effect
4260 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004261 // Update remaining floating point volume levels
4262 vlf = (float)vl / (1 << 24);
4263 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004264 track->mHasVolumeController = true;
4265 } else {
4266 // force no volume ramp when volume controller was just disabled or removed
4267 // from effect chain to avoid volume spike
4268 if (track->mHasVolumeController) {
4269 param = AudioMixer::VOLUME;
4270 }
4271 track->mHasVolumeController = false;
4272 }
4273
Eric Laurent81784c32012-11-19 14:55:58 -08004274 // XXX: these things DON'T need to be done each time
4275 mAudioMixer->setBufferProvider(name, track);
4276 mAudioMixer->enable(name);
4277
Andy Hung6be49402014-05-30 10:42:03 -07004278 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4279 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4280 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004281 mAudioMixer->setParameter(
4282 name,
4283 AudioMixer::TRACK,
4284 AudioMixer::FORMAT, (void *)track->format());
4285 mAudioMixer->setParameter(
4286 name,
4287 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004288 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004289 mAudioMixer->setParameter(
4290 name,
4291 AudioMixer::TRACK,
4292 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004293 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004294 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004295 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004296 if (reqSampleRate == 0) {
4297 reqSampleRate = mSampleRate;
4298 } else if (reqSampleRate > maxSampleRate) {
4299 reqSampleRate = maxSampleRate;
4300 }
Eric Laurent81784c32012-11-19 14:55:58 -08004301 mAudioMixer->setParameter(
4302 name,
4303 AudioMixer::RESAMPLE,
4304 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004305 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004306
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004307 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004308 mAudioMixer->setParameter(
4309 name,
4310 AudioMixer::TIMESTRETCH,
4311 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004312 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004313
Andy Hung69aed5f2014-02-25 17:24:40 -08004314 /*
4315 * Select the appropriate output buffer for the track.
4316 *
Andy Hung98ef9782014-03-04 14:46:50 -08004317 * Tracks with effects go into their own effects chain buffer
4318 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004319 *
4320 * Other tracks can use mMixerBuffer for higher precision
4321 * channel accumulation. If this buffer is enabled
4322 * (mMixerBufferEnabled true), then selected tracks will accumulate
4323 * into it.
4324 *
4325 */
4326 if (mMixerBufferEnabled
4327 && (track->mainBuffer() == mSinkBuffer
4328 || track->mainBuffer() == mMixerBuffer)) {
4329 mAudioMixer->setParameter(
4330 name,
4331 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004332 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004333 mAudioMixer->setParameter(
4334 name,
4335 AudioMixer::TRACK,
4336 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4337 // TODO: override track->mainBuffer()?
4338 mMixerBufferValid = true;
4339 } else {
4340 mAudioMixer->setParameter(
4341 name,
4342 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004343 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004344 mAudioMixer->setParameter(
4345 name,
4346 AudioMixer::TRACK,
4347 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4348 }
Eric Laurent81784c32012-11-19 14:55:58 -08004349 mAudioMixer->setParameter(
4350 name,
4351 AudioMixer::TRACK,
4352 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4353
4354 // reset retry count
4355 track->mRetryCount = kMaxTrackRetries;
4356
4357 // If one track is ready, set the mixer ready if:
4358 // - the mixer was not ready during previous round OR
4359 // - no other track is not ready
4360 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4361 mixerStatus != MIXER_TRACKS_ENABLED) {
4362 mixerStatus = MIXER_TRACKS_READY;
4363 }
4364 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004365 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004366 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4367 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004368 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004369 } else {
4370 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004371 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004372
Eric Laurent81784c32012-11-19 14:55:58 -08004373 // clear effect chain input buffer if an active track underruns to avoid sending
4374 // previous audio buffer again to effects
4375 chain = getEffectChain_l(track->sessionId());
4376 if (chain != 0) {
4377 chain->clearInputBuffer();
4378 }
4379
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004380 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004381 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4382 track->isStopped() || track->isPaused()) {
4383 // We have consumed all the buffers of this track.
4384 // Remove it from the list of active tracks.
4385 // TODO: use actual buffer filling status instead of latency when available from
4386 // audio HAL
4387 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004388 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004389 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4390 if (track->isStopped()) {
4391 track->reset();
4392 }
4393 tracksToRemove->add(track);
4394 }
4395 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004396 // No buffers for this track. Give it a few chances to
4397 // fill a buffer, then remove it from active list.
4398 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004399 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004400 tracksToRemove->add(track);
4401 // indicate to client process that the track was disabled because of underrun;
4402 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004403 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004404 // If one track is not ready, mark the mixer also not ready if:
4405 // - the mixer was ready during previous round OR
4406 // - no other track is ready
4407 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4408 mixerStatus != MIXER_TRACKS_READY) {
4409 mixerStatus = MIXER_TRACKS_ENABLED;
4410 }
4411 }
4412 mAudioMixer->disable(name);
4413 }
4414
4415 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004416
4417 }
4418
4419 // Push the new FastMixer state if necessary
4420 bool pauseAudioWatchdog = false;
4421 if (didModify) {
4422 state->mFastTracksGen++;
4423 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4424 if (kUseFastMixer == FastMixer_Dynamic &&
4425 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4426 state->mCommand = FastMixerState::COLD_IDLE;
4427 state->mColdFutexAddr = &mFastMixerFutex;
4428 state->mColdGen++;
4429 mFastMixerFutex = 0;
4430 if (kUseFastMixer == FastMixer_Dynamic) {
4431 mNormalSink = mOutputSink;
4432 }
4433 // If we go into cold idle, need to wait for acknowledgement
4434 // so that fast mixer stops doing I/O.
4435 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4436 pauseAudioWatchdog = true;
4437 }
Eric Laurent81784c32012-11-19 14:55:58 -08004438 }
4439 if (sq != NULL) {
4440 sq->end(didModify);
4441 sq->push(block);
4442 }
4443#ifdef AUDIO_WATCHDOG
4444 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4445 mAudioWatchdog->pause();
4446 }
4447#endif
4448
4449 // Now perform the deferred reset on fast tracks that have stopped
4450 while (resetMask != 0) {
4451 size_t i = __builtin_ctz(resetMask);
4452 ALOG_ASSERT(i < count);
4453 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004454 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004455 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4456 track->reset();
4457 }
4458
4459 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004461
Eric Laurent97d547d2014-09-02 14:45:53 -07004462 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4463 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004464 }
4465
4466 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004467 // as long as there are effects we should clear the effects buffer, to avoid
4468 // passing a non-clean buffer to the effect chain
4469 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004470 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004471 // sink or mix buffer must be cleared if all tracks are connected to an
4472 // effect chain as in this case the mixer will not write to the sink or mix buffer
4473 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004474 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4475 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004476 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004477 if (mMixerBufferValid) {
4478 memset(mMixerBuffer, 0, mMixerBufferSize);
4479 // TODO: In testing, mSinkBuffer below need not be cleared because
4480 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4481 // after mixing.
4482 //
4483 // To enforce this guarantee:
4484 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4485 // (mixedTracks == 0 && fastTracks > 0))
4486 // must imply MIXER_TRACKS_READY.
4487 // Later, we may clear buffers regardless, and skip much of this logic.
4488 }
Andy Hung98ef9782014-03-04 14:46:50 -08004489 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004490 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004491 }
4492
4493 // if any fast tracks, then status is ready
4494 mMixerStatusIgnoringFastTracks = mixerStatus;
4495 if (fastTracks > 0) {
4496 mixerStatus = MIXER_TRACKS_READY;
4497 }
4498 return mixerStatus;
4499}
4500
Eric Laurentad7dd962016-09-22 12:38:37 -07004501// trackCountForUid_l() must be called with ThreadBase::mLock held
4502uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4503{
4504 uint32_t trackCount = 0;
4505 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004506 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004507 trackCount++;
4508 }
4509 }
4510 return trackCount;
4511}
4512
Eric Laurent81784c32012-11-19 14:55:58 -08004513// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004514int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004515 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004516{
Eric Laurentad7dd962016-09-22 12:38:37 -07004517 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4518 return -1;
4519 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004520 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004521}
4522
4523// deleteTrackName_l() must be called with ThreadBase::mLock held
4524void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4525{
4526 ALOGV("remove track (%d) and delete from mixer", name);
4527 mAudioMixer->deleteTrackName(name);
4528}
4529
Eric Laurent10351942014-05-08 18:49:52 -07004530// checkForNewParameter_l() must be called with ThreadBase::mLock held
4531bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4532 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004533{
Eric Laurent81784c32012-11-19 14:55:58 -08004534 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004535 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004536
Eric Laurent10351942014-05-08 18:49:52 -07004537 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004538
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004539 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004540
Eric Laurent10351942014-05-08 18:49:52 -07004541 AudioParameter param = AudioParameter(keyValuePair);
4542 int value;
4543 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4544 reconfig = true;
4545 }
4546 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004547 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004548 status = BAD_VALUE;
4549 } else {
4550 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004551 reconfig = true;
4552 }
Eric Laurent10351942014-05-08 18:49:52 -07004553 }
4554 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004555 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004556 status = BAD_VALUE;
4557 } else {
4558 // no need to save value, since it's constant
4559 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004560 }
Eric Laurent10351942014-05-08 18:49:52 -07004561 }
4562 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4563 // do not accept frame count changes if tracks are open as the track buffer
4564 // size depends on frame count and correct behavior would not be guaranteed
4565 // if frame count is changed after track creation
4566 if (!mTracks.isEmpty()) {
4567 status = INVALID_OPERATION;
4568 } else {
4569 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004570 }
Eric Laurent10351942014-05-08 18:49:52 -07004571 }
4572 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004573#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004574 // when changing the audio output device, call addBatteryData to notify
4575 // the change
4576 if (mOutDevice != value) {
4577 uint32_t params = 0;
4578 // check whether speaker is on
4579 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4580 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
Eric Laurent10351942014-05-08 18:49:52 -07004582
4583 audio_devices_t deviceWithoutSpeaker
4584 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4585 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004586 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004587 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4588 }
4589
4590 if (params != 0) {
4591 addBatteryData(params);
4592 }
4593 }
Eric Laurent81784c32012-11-19 14:55:58 -08004594#endif
4595
Eric Laurent10351942014-05-08 18:49:52 -07004596 // forward device change to effects that have requested to be
4597 // aware of attached audio device.
4598 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004599 a2dpDeviceChanged =
4600 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004601 mOutDevice = value;
4602 for (size_t i = 0; i < mEffectChains.size(); i++) {
4603 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004604 }
4605 }
Eric Laurent10351942014-05-08 18:49:52 -07004606 }
Eric Laurent81784c32012-11-19 14:55:58 -08004607
Eric Laurent10351942014-05-08 18:49:52 -07004608 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004609 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004610 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004611 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004612 mStandby = true;
4613 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004614 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004615 }
Eric Laurent10351942014-05-08 18:49:52 -07004616 if (status == NO_ERROR && reconfig) {
4617 readOutputParameters_l();
4618 delete mAudioMixer;
4619 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4620 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004621 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004622 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004623 if (name < 0) {
4624 break;
4625 }
4626 mTracks[i]->mName = name;
4627 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004628 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004629 }
Eric Laurent81784c32012-11-19 14:55:58 -08004630 }
4631
Eric Laurent42537be2016-01-08 17:16:42 -08004632 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004633}
4634
4635
4636void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4637{
Eric Laurent81784c32012-11-19 14:55:58 -08004638 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004639 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004640 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004641 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004642
4643 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004644 // while we are dumping it. It may be inconsistent, but it won't mutate!
4645 // This is a large object so we place it on the heap.
4646 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4647 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4648 copy->dump(fd);
4649 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004650
4651#ifdef STATE_QUEUE_DUMP
4652 // Similar for state queue
4653 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4654 observerCopy.dump(fd);
4655 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4656 mutatorCopy.dump(fd);
4657#endif
4658
Glenn Kasten46909e72013-02-26 09:20:22 -08004659#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004660 // Write the tee output to a .wav file
4661 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004662#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004663
4664#ifdef AUDIO_WATCHDOG
4665 if (mAudioWatchdog != 0) {
4666 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4667 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4668 wdCopy.dump(fd);
4669 }
4670#endif
4671}
4672
4673uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4674{
4675 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4676}
4677
4678uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4679{
4680 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4681}
4682
4683void AudioFlinger::MixerThread::cacheParameters_l()
4684{
4685 PlaybackThread::cacheParameters_l();
4686
4687 // FIXME: Relaxed timing because of a certain device that can't meet latency
4688 // Should be reduced to 2x after the vendor fixes the driver issue
4689 // increase threshold again due to low power audio mode. The way this warning
4690 // threshold is calculated and its usefulness should be reconsidered anyway.
4691 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4692}
4693
4694// ----------------------------------------------------------------------------
4695
4696AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004697 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4698 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004699 // mLeftVolFloat, mRightVolFloat
4700{
4701}
4702
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4704 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004705 ThreadBase::type_t type, bool systemReady)
4706 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707 // mLeftVolFloat, mRightVolFloat
4708{
4709}
4710
Eric Laurent81784c32012-11-19 14:55:58 -08004711AudioFlinger::DirectOutputThread::~DirectOutputThread()
4712{
4713}
4714
Eric Laurent5850c4c2016-11-10 13:04:31 -08004715void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717 float left, right;
4718
4719 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4720 left = right = 0;
4721 } else {
4722 float typeVolume = mStreamTypes[track->streamType()].volume;
4723 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004724 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004725 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4726 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4727 if (left > GAIN_FLOAT_UNITY) {
4728 left = GAIN_FLOAT_UNITY;
4729 }
4730 left *= v;
4731 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4732 if (right > GAIN_FLOAT_UNITY) {
4733 right = GAIN_FLOAT_UNITY;
4734 }
4735 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004736 }
4737
4738 if (lastTrack) {
4739 if (left != mLeftVolFloat || right != mRightVolFloat) {
4740 mLeftVolFloat = left;
4741 mRightVolFloat = right;
4742
4743 // Convert volumes from float to 8.24
4744 uint32_t vl = (uint32_t)(left * (1 << 24));
4745 uint32_t vr = (uint32_t)(right * (1 << 24));
4746
4747 // Delegate volume control to effect in track effect chain if needed
4748 // only one effect chain can be present on DirectOutputThread, so if
4749 // there is one, the track is connected to it
4750 if (!mEffectChains.isEmpty()) {
4751 mEffectChains[0]->setVolume_l(&vl, &vr);
4752 left = (float)vl / (1 << 24);
4753 right = (float)vr / (1 << 24);
4754 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004755 status_t result = mOutput->stream->setVolume(left, right);
4756 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757 }
4758 }
4759}
4760
Phil Burk43b4dcc2015-06-09 16:53:44 -07004761void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4762{
4763 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004764 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004765
Eric Laurent0f0631e2015-07-06 18:01:25 -07004766 if (previousTrack != 0 && latestTrack != 0) {
4767 if (mType == DIRECT) {
4768 if (previousTrack.get() != latestTrack.get()) {
4769 mFlushPending = true;
4770 }
4771 } else /* mType == OFFLOAD */ {
4772 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4773 mFlushPending = true;
4774 }
4775 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004776 }
4777 PlaybackThread::onAddNewTrack_l();
4778}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004779
Eric Laurent81784c32012-11-19 14:55:58 -08004780AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4781 Vector< sp<Track> > *tracksToRemove
4782)
4783{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004784 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004785 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004786 bool doHwPause = false;
4787 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004788
4789 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004790 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004791 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004792 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004793 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004794 continue;
4795 }
4796
Eric Laurent5850c4c2016-11-10 13:04:31 -08004797 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004798#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004799 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004800#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004801 // Only consider last track started for volume and mixer state control.
4802 // In theory an older track could underrun and restart after the new one starts
4803 // but as we only care about the transition phase between two tracks on a
4804 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004805 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004806 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004807
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004808 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004809 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004810 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004811 doHwPause = true;
4812 mHwPaused = true;
4813 }
4814 tracksToRemove->add(track);
4815 } else if (track->isFlushPending()) {
4816 track->flushAck();
4817 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004818 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004819 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004820 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004821 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004822 if (last) {
4823 mLeftVolFloat = mRightVolFloat = -1.0;
4824 if (mHwPaused) {
4825 doHwResume = true;
4826 mHwPaused = false;
4827 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004828 }
4829 }
4830
Eric Laurent81784c32012-11-19 14:55:58 -08004831 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004832 // for all its buffers to be filled before processing it.
4833 // Allow draining the buffer in case the client
4834 // app does not call stop() and relies on underrun to stop:
4835 // hence the test on (track->mRetryCount > 1).
4836 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004837 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004838 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004839 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004840 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004841 minFrames = mNormalFrameCount;
4842 } else {
4843 minFrames = 1;
4844 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845
Eric Laurentab5cdba2014-06-09 17:22:27 -07004846 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4847 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004848 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004849 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004850
4851 if (track->mFillingUpStatus == Track::FS_FILLED) {
4852 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004853 if (last) {
4854 // make sure processVolume_l() will apply new volume even if 0
4855 mLeftVolFloat = mRightVolFloat = -1.0;
4856 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857 if (!mHwSupportsPause) {
4858 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004859 }
4860 }
4861
4862 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863 processVolume_l(track, last);
4864 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004865 sp<Track> previousTrack = mPreviousTrack.promote();
4866 if (previousTrack != 0) {
4867 if (track != previousTrack.get()) {
4868 // Flush any data still being written from last track
4869 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004870 // Invalidate previous track to force a seek when resuming.
4871 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004872 }
4873 }
4874 mPreviousTrack = track;
4875
Eric Laurentd595b7c2013-04-03 17:27:56 -07004876 // reset retry count
4877 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004878 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004879 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004880 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004881 doHwResume = true;
4882 mHwPaused = false;
4883 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004884 }
Eric Laurent81784c32012-11-19 14:55:58 -08004885 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004886 // clear effect chain input buffer if the last active track started underruns
4887 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004888 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004889 mEffectChains[0]->clearInputBuffer();
4890 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004891 if (track->isStopping_1()) {
4892 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004893 if (last && mHwPaused) {
4894 doHwResume = true;
4895 mHwPaused = false;
4896 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004897 }
4898 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4899 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004900 // We have consumed all the buffers of this track.
4901 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004902 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004903 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004904 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4905 } else {
4906 audioHALFrames = 0;
4907 }
4908
Andy Hung818e7a32016-02-16 18:08:07 -08004909 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004910 if (mStandby || !last ||
4911 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004912 if (track->isStopping_2()) {
4913 track->mState = TrackBase::STOPPED;
4914 }
Eric Laurent81784c32012-11-19 14:55:58 -08004915 if (track->isStopped()) {
4916 track->reset();
4917 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004918 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004919 }
4920 } else {
4921 // No buffers for this track. Give it a few chances to
4922 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004923 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004924 if (--(track->mRetryCount) <= 0) {
4925 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004926 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004927 // indicate to client process that the track was disabled because of underrun;
4928 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004929 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004930 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004931 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4932 "minFrames = %u, mFormat = %#x",
4933 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004934 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004935 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004936 doHwPause = true;
4937 mHwPaused = true;
4938 }
Eric Laurent81784c32012-11-19 14:55:58 -08004939 }
4940 }
4941 }
4942 }
4943
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004945 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 for (size_t i = 0; i < mTracks.size(); i++) {
4947 if (mTracks[i]->isFlushPending()) {
4948 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004949 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004950 }
4951 }
4952 }
4953
4954 // make sure the pause/flush/resume sequence is executed in the right order.
4955 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4956 // before flush and then resume HW. This can happen in case of pause/flush/resume
4957 // if resume is received before pause is executed.
4958 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004959 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004960 status_t result = mOutput->stream->pause();
4961 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004962 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004963 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004964 flushHw_l();
4965 }
4966 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004967 status_t result = mOutput->stream->resume();
4968 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004969 }
Eric Laurent81784c32012-11-19 14:55:58 -08004970 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004971 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004972
4973 return mixerStatus;
4974}
4975
4976void AudioFlinger::DirectOutputThread::threadLoop_mix()
4977{
Eric Laurent81784c32012-11-19 14:55:58 -08004978 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004979 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004980 // output audio to hardware
4981 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004982 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004983 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004984 status_t status = mActiveTrack->getNextBuffer(&buffer);
4985 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004986 // no need to pad with 0 for compressed audio
4987 if (audio_has_proportional_frames(mFormat)) {
4988 memset(curBuf, 0, frameCount * mFrameSize);
4989 }
Eric Laurent81784c32012-11-19 14:55:58 -08004990 break;
4991 }
4992 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4993 frameCount -= buffer.frameCount;
4994 curBuf += buffer.frameCount * mFrameSize;
4995 mActiveTrack->releaseBuffer(&buffer);
4996 }
Andy Hung2098f272014-02-27 14:00:06 -08004997 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004998 mSleepTimeUs = 0;
4999 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005000 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005001}
5002
5003void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5004{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005006 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005007 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005008 return;
5009 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005010 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005011 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005012 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005013 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005014 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005015 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005016 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005017 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005018 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
5020}
5021
Eric Laurentd1f69b02014-12-15 14:33:13 -08005022void AudioFlinger::DirectOutputThread::threadLoop_exit()
5023{
5024 {
5025 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005026 for (size_t i = 0; i < mTracks.size(); i++) {
5027 if (mTracks[i]->isFlushPending()) {
5028 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005029 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005030 }
5031 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005032 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005033 flushHw_l();
5034 }
5035 }
5036 PlaybackThread::threadLoop_exit();
5037}
5038
5039// must be called with thread mutex locked
5040bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5041{
5042 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005043 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005044
vivek mehta9cd7ad12016-03-17 00:18:29 -07005045 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5046 return !mStandby;
5047 }
5048
Eric Laurentd1f69b02014-12-15 14:33:13 -08005049 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5050 // after a timeout and we will enter standby then.
5051 if (mTracks.size() > 0) {
5052 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005053 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5054 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 }
5056
Eric Laurent5cff4032015-05-26 13:49:58 -07005057 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005058}
5059
Eric Laurent81784c32012-11-19 14:55:58 -08005060// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005061int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005062 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005063{
Eric Laurentad7dd962016-09-22 12:38:37 -07005064 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5065 return -1;
5066 }
Eric Laurent81784c32012-11-19 14:55:58 -08005067 return 0;
5068}
5069
5070// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005071void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005072{
5073}
5074
Eric Laurent10351942014-05-08 18:49:52 -07005075// checkForNewParameter_l() must be called with ThreadBase::mLock held
5076bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5077 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005078{
5079 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005080 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005081
Eric Laurent10351942014-05-08 18:49:52 -07005082 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005083
Eric Laurent10351942014-05-08 18:49:52 -07005084 AudioParameter param = AudioParameter(keyValuePair);
5085 int value;
5086 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5087 // forward device change to effects that have requested to be
5088 // aware of attached audio device.
5089 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005090 a2dpDeviceChanged =
5091 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005092 mOutDevice = value;
5093 for (size_t i = 0; i < mEffectChains.size(); i++) {
5094 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005095 }
5096 }
Eric Laurent81784c32012-11-19 14:55:58 -08005097 }
Eric Laurent10351942014-05-08 18:49:52 -07005098 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5099 // do not accept frame count changes if tracks are open as the track buffer
5100 // size depends on frame count and correct behavior would not be garantied
5101 // if frame count is changed after track creation
5102 if (!mTracks.isEmpty()) {
5103 status = INVALID_OPERATION;
5104 } else {
5105 reconfig = true;
5106 }
5107 }
5108 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005109 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005110 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005111 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005112 mStandby = true;
5113 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005114 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005115 }
5116 if (status == NO_ERROR && reconfig) {
5117 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005118 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005119 }
5120 }
5121
Eric Laurent42537be2016-01-08 17:16:42 -08005122 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005123}
5124
5125uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5126{
5127 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005128 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005129 time = PlaybackThread::activeSleepTimeUs();
5130 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005131 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 }
5133 return time;
5134}
5135
5136uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5137{
5138 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005139 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005140 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5141 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005142 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005143 }
5144 return time;
5145}
5146
5147uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5148{
5149 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005150 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005151 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5152 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005153 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005154 }
5155 return time;
5156}
5157
5158void AudioFlinger::DirectOutputThread::cacheParameters_l()
5159{
5160 PlaybackThread::cacheParameters_l();
5161
5162 // use shorter standby delay as on normal output to release
5163 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005164 // no delay on outputs with HW A/V sync
5165 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005166 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005167 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005168 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005169 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005170 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005171 }
Eric Laurent81784c32012-11-19 14:55:58 -08005172}
5173
Eric Laurente659ef42014-09-29 13:06:46 -07005174void AudioFlinger::DirectOutputThread::flushHw_l()
5175{
Phil Burk062e67a2015-02-11 13:40:50 -08005176 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005177 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005178 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005179}
5180
Eric Laurent81784c32012-11-19 14:55:58 -08005181// ----------------------------------------------------------------------------
5182
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005184 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005186 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005187 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005188 mDrainSequence(0),
5189 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005190{
5191}
5192
5193AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5194{
5195}
5196
5197void AudioFlinger::AsyncCallbackThread::onFirstRef()
5198{
5199 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5200}
5201
5202bool AudioFlinger::AsyncCallbackThread::threadLoop()
5203{
5204 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005205 uint32_t writeAckSequence;
5206 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005207 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208
5209 {
5210 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005211 while (!((mWriteAckSequence & 1) ||
5212 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005213 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005214 exitPending())) {
5215 mWaitWorkCV.wait(mLock);
5216 }
5217
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 if (exitPending()) {
5219 break;
5220 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005221 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5222 mWriteAckSequence, mDrainSequence);
5223 writeAckSequence = mWriteAckSequence;
5224 mWriteAckSequence &= ~1;
5225 drainSequence = mDrainSequence;
5226 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005227 asyncError = mAsyncError;
5228 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005229 }
5230 {
Eric Laurent4de95592013-09-26 15:28:21 -07005231 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5232 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005233 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005234 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005236 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005237 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005239 if (asyncError) {
5240 playbackThread->onAsyncError();
5241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 }
5243 }
5244 }
5245 return false;
5246}
5247
5248void AudioFlinger::AsyncCallbackThread::exit()
5249{
5250 ALOGV("AsyncCallbackThread::exit");
5251 Mutex::Autolock _l(mLock);
5252 requestExit();
5253 mWaitWorkCV.broadcast();
5254}
5255
Eric Laurent3b4529e2013-09-05 18:09:19 -07005256void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257{
5258 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005259 // bit 0 is cleared
5260 mWriteAckSequence = sequence << 1;
5261}
5262
5263void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5264{
5265 Mutex::Autolock _l(mLock);
5266 // ignore unexpected callbacks
5267 if (mWriteAckSequence & 2) {
5268 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005269 mWaitWorkCV.signal();
5270 }
5271}
5272
Eric Laurent3b4529e2013-09-05 18:09:19 -07005273void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274{
5275 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005276 // bit 0 is cleared
5277 mDrainSequence = sequence << 1;
5278}
5279
5280void AudioFlinger::AsyncCallbackThread::resetDraining()
5281{
5282 Mutex::Autolock _l(mLock);
5283 // ignore unexpected callbacks
5284 if (mDrainSequence & 2) {
5285 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005286 mWaitWorkCV.signal();
5287 }
5288}
5289
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005290void AudioFlinger::AsyncCallbackThread::setAsyncError()
5291{
5292 Mutex::Autolock _l(mLock);
5293 mAsyncError = true;
5294 mWaitWorkCV.signal();
5295}
5296
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297
5298// ----------------------------------------------------------------------------
5299AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005300 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5301 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005302 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5303 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304{
Eric Laurentfd477972013-10-25 18:10:40 -07005305 //FIXME: mStandby should be set to true by ThreadBase constructor
5306 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005307 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308}
5309
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310void AudioFlinger::OffloadThread::threadLoop_exit()
5311{
5312 if (mFlushPending || mHwPaused) {
5313 // If a flush is pending or track was paused, just discard buffered data
5314 flushHw_l();
5315 } else {
5316 mMixerStatus = MIXER_DRAIN_ALL;
5317 threadLoop_drain();
5318 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005319 if (mUseAsyncWrite) {
5320 ALOG_ASSERT(mCallbackThread != 0);
5321 mCallbackThread->exit();
5322 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005323 PlaybackThread::threadLoop_exit();
5324}
5325
5326AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5327 Vector< sp<Track> > *tracksToRemove
5328)
5329{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005330 size_t count = mActiveTracks.size();
5331
5332 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005333 bool doHwPause = false;
5334 bool doHwResume = false;
5335
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005336 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005337
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005339 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005340 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005341#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005343#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005344 // Only consider last track started for volume and mixer state control.
5345 // In theory an older track could underrun and restart after the new one starts
5346 // but as we only care about the transition phase between two tracks on a
5347 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005348 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005349 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005350
Haynes Mathew George7844f672014-01-15 12:32:55 -08005351 if (track->isInvalid()) {
5352 ALOGW("An invalidated track shouldn't be in active list");
5353 tracksToRemove->add(track);
5354 continue;
5355 }
5356
5357 if (track->mState == TrackBase::IDLE) {
5358 ALOGW("An idle track shouldn't be in active list");
5359 continue;
5360 }
5361
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 if (track->isPausing()) {
5363 track->setPaused();
5364 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005365 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005366 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367 mHwPaused = true;
5368 }
5369 // If we were part way through writing the mixbuffer to
5370 // the HAL we must save this until we resume
5371 // BUG - this will be wrong if a different track is made active,
5372 // in that case we want to discard the pending data in the
5373 // mixbuffer and tell the client to present it again when the
5374 // track is resumed
5375 mPausedWriteLength = mCurrentWriteLength;
5376 mPausedBytesRemaining = mBytesRemaining;
5377 mBytesRemaining = 0; // stop writing
5378 }
5379 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005380 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005381 if (track->isStopping_1()) {
5382 track->mRetryCount = kMaxTrackStopRetriesOffload;
5383 } else {
5384 track->mRetryCount = kMaxTrackRetriesOffload;
5385 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005386 track->flushAck();
5387 if (last) {
5388 mFlushPending = true;
5389 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005390 } else if (track->isResumePending()){
5391 track->resumeAck();
5392 if (last) {
5393 if (mPausedBytesRemaining) {
5394 // Need to continue write that was interrupted
5395 mCurrentWriteLength = mPausedWriteLength;
5396 mBytesRemaining = mPausedBytesRemaining;
5397 mPausedBytesRemaining = 0;
5398 }
5399 if (mHwPaused) {
5400 doHwResume = true;
5401 mHwPaused = false;
5402 // threadLoop_mix() will handle the case that we need to
5403 // resume an interrupted write
5404 }
5405 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005406 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005407
Eric Laurent3df841a2016-07-15 15:15:40 -07005408 mLeftVolFloat = mRightVolFloat = -1.0;
5409
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005410 // Do not handle new data in this iteration even if track->framesReady()
5411 mixerStatus = MIXER_TRACKS_ENABLED;
5412 }
5413 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005414 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005415 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 if (track->mFillingUpStatus == Track::FS_FILLED) {
5417 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005418 if (last) {
5419 // make sure processVolume_l() will apply new volume even if 0
5420 mLeftVolFloat = mRightVolFloat = -1.0;
5421 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 }
5423
5424 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005425 sp<Track> previousTrack = mPreviousTrack.promote();
5426 if (previousTrack != 0) {
5427 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005428 // Flush any data still being written from last track
5429 mBytesRemaining = 0;
5430 if (mPausedBytesRemaining) {
5431 // Last track was paused so we also need to flush saved
5432 // mixbuffer state and invalidate track so that it will
5433 // re-submit that unwritten data when it is next resumed
5434 mPausedBytesRemaining = 0;
5435 // Invalidate is a bit drastic - would be more efficient
5436 // to have a flag to tell client that some of the
5437 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005438 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005439 }
5440 // flush data already sent to the DSP if changing audio session as audio
5441 // comes from a different source. Also invalidate previous track to force a
5442 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005443 if (previousTrack->sessionId() != track->sessionId()) {
5444 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005445 }
5446 }
5447 }
5448 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005449 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005450 if (track->isStopping_1()) {
5451 track->mRetryCount = kMaxTrackStopRetriesOffload;
5452 } else {
5453 track->mRetryCount = kMaxTrackRetriesOffload;
5454 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005455 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 mixerStatus = MIXER_TRACKS_READY;
5457 }
5458 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005459 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005461 if (--(track->mRetryCount) <= 0) {
5462 // Hardware buffer can hold a large amount of audio so we must
5463 // wait for all current track's data to drain before we say
5464 // that the track is stopped.
5465 if (mBytesRemaining == 0) {
5466 // Only start draining when all data in mixbuffer
5467 // has been written
5468 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5469 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5470 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5471 if (last && !mStandby) {
5472 // do not modify drain sequence if we are already draining. This happens
5473 // when resuming from pause after drain.
5474 if ((mDrainSequence & 1) == 0) {
5475 mSleepTimeUs = 0;
5476 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5477 mixerStatus = MIXER_DRAIN_TRACK;
5478 mDrainSequence += 2;
5479 }
5480 if (mHwPaused) {
5481 // It is possible to move from PAUSED to STOPPING_1 without
5482 // a resume so we must ensure hardware is running
5483 doHwResume = true;
5484 mHwPaused = false;
5485 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486 }
5487 }
Eric Laurente93cc032016-05-05 10:15:10 -07005488 } else if (last) {
5489 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5490 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005491 }
5492 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005493 // Drain has completed or we are in standby, signal presentation complete
5494 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005496 uint32_t latency = 0;
5497 status_t result = mOutput->stream->getLatency(&latency);
5498 ALOGE_IF(result != OK,
5499 "Error when retrieving output stream latency: %d", result);
5500 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005501 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005502 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005503 track->presentationComplete(framesWritten, audioHALFrames);
5504 track->reset();
5505 tracksToRemove->add(track);
5506 }
5507 } else {
5508 // No buffers for this track. Give it a few chances to
5509 // fill a buffer, then remove it from active list.
5510 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005511 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005512 uint64_t position = 0;
5513 struct timespec unused;
5514 // The running check restarts the retry counter at least once.
5515 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5516 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5517 running = true;
5518 mOffloadUnderrunPosition = position;
5519 }
5520 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005521 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5522 (long long)position, (long long)mOffloadUnderrunPosition);
5523 }
5524 if (running) { // still running, give us more time.
5525 track->mRetryCount = kMaxTrackRetriesOffload;
5526 } else {
5527 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5528 track->name());
5529 tracksToRemove->add(track);
5530 // indicate to client process that the track was disabled because of underrun;
5531 // it will then automatically call start() when data is available
5532 track->disable();
5533 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534 } else if (last){
5535 mixerStatus = MIXER_TRACKS_ENABLED;
5536 }
5537 }
5538 }
5539 // compute volume for this track
5540 processVolume_l(track, last);
5541 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005542
Eric Laurentea0fade2013-10-04 16:23:48 -07005543 // make sure the pause/flush/resume sequence is executed in the right order.
5544 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5545 // before flush and then resume HW. This can happen in case of pause/flush/resume
5546 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005547 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005548 status_t result = mOutput->stream->pause();
5549 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005550 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005551 if (mFlushPending) {
5552 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005553 }
Eric Laurentfd477972013-10-25 18:10:40 -07005554 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005555 status_t result = mOutput->stream->resume();
5556 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005557 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005558
Eric Laurentbfb1b832013-01-07 09:53:42 -08005559 // remove all the tracks that need to be...
5560 removeTracks_l(*tracksToRemove);
5561
5562 return mixerStatus;
5563}
5564
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565// must be called with thread mutex locked
5566bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5567{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005568 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5569 mWriteAckSequence, mDrainSequence);
5570 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571 return true;
5572 }
5573 return false;
5574}
5575
Eric Laurentbfb1b832013-01-07 09:53:42 -08005576bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5577{
5578 Mutex::Autolock _l(mLock);
5579 return waitingAsyncCallback_l();
5580}
5581
5582void AudioFlinger::OffloadThread::flushHw_l()
5583{
Eric Laurente659ef42014-09-29 13:06:46 -07005584 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005585 // Flush anything still waiting in the mixbuffer
5586 mCurrentWriteLength = 0;
5587 mBytesRemaining = 0;
5588 mPausedWriteLength = 0;
5589 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005590 // reset bytes written count to reflect that DSP buffers are empty after flush.
5591 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005592 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005593
Eric Laurentbfb1b832013-01-07 09:53:42 -08005594 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005595 // discard any pending drain or write ack by incrementing sequence
5596 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5597 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005598 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005599 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5600 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005601 }
5602}
5603
Haynes Mathew George05317d22016-05-03 16:34:26 -07005604void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5605{
5606 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005607 if (PlaybackThread::invalidateTracks_l(streamType)) {
5608 mFlushPending = true;
5609 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005610}
5611
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612// ----------------------------------------------------------------------------
5613
Eric Laurent81784c32012-11-19 14:55:58 -08005614AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005615 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005616 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005617 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005618 mWaitTimeMs(UINT_MAX)
5619{
5620 addOutputTrack(mainThread);
5621}
5622
5623AudioFlinger::DuplicatingThread::~DuplicatingThread()
5624{
5625 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5626 mOutputTracks[i]->destroy();
5627 }
5628}
5629
5630void AudioFlinger::DuplicatingThread::threadLoop_mix()
5631{
5632 // mix buffers...
5633 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005634 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005635 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005636 if (mMixerBufferValid) {
5637 memset(mMixerBuffer, 0, mMixerBufferSize);
5638 } else {
5639 memset(mSinkBuffer, 0, mSinkBufferSize);
5640 }
Eric Laurent81784c32012-11-19 14:55:58 -08005641 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005642 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005643 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005644 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005645 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005646}
5647
5648void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5649{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005650 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005651 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005652 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005653 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005654 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005655 }
5656 } else if (mBytesWritten != 0) {
5657 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5658 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005659 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005660 } else {
5661 // flush remaining overflow buffers in output tracks
5662 writeFrames = 0;
5663 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005664 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005665 }
5666}
5667
Eric Laurentbfb1b832013-01-07 09:53:42 -08005668ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005669{
5670 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005671 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005672 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005673 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005674 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005675}
5676
5677void AudioFlinger::DuplicatingThread::threadLoop_standby()
5678{
5679 // DuplicatingThread implements standby by stopping all tracks
5680 for (size_t i = 0; i < outputTracks.size(); i++) {
5681 outputTracks[i]->stop();
5682 }
5683}
5684
5685void AudioFlinger::DuplicatingThread::saveOutputTracks()
5686{
5687 outputTracks = mOutputTracks;
5688}
5689
5690void AudioFlinger::DuplicatingThread::clearOutputTracks()
5691{
5692 outputTracks.clear();
5693}
5694
5695void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5696{
5697 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005698 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5699 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5700 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5701 const size_t frameCount =
5702 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5703 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5704 // from different OutputTracks and their associated MixerThreads (e.g. one may
5705 // nearly empty and the other may be dropping data).
5706
5707 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005708 this,
5709 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005710 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005711 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005712 frameCount,
5713 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005714 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5715 if (status != NO_ERROR) {
5716 ALOGE("addOutputTrack() initCheck failed %d", status);
5717 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005718 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005719 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5720 mOutputTracks.add(outputTrack);
5721 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5722 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005723}
5724
5725void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5726{
5727 Mutex::Autolock _l(mLock);
5728 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5729 if (mOutputTracks[i]->thread() == thread) {
5730 mOutputTracks[i]->destroy();
5731 mOutputTracks.removeAt(i);
5732 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005733 if (thread->getOutput() == mOutput) {
5734 mOutput = NULL;
5735 }
Eric Laurent81784c32012-11-19 14:55:58 -08005736 return;
5737 }
5738 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005739 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005740}
5741
5742// caller must hold mLock
5743void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5744{
5745 mWaitTimeMs = UINT_MAX;
5746 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5747 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5748 if (strong != 0) {
5749 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5750 if (waitTimeMs < mWaitTimeMs) {
5751 mWaitTimeMs = waitTimeMs;
5752 }
5753 }
5754 }
5755}
5756
5757
5758bool AudioFlinger::DuplicatingThread::outputsReady(
5759 const SortedVector< sp<OutputTrack> > &outputTracks)
5760{
5761 for (size_t i = 0; i < outputTracks.size(); i++) {
5762 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5763 if (thread == 0) {
5764 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5765 outputTracks[i].get());
5766 return false;
5767 }
5768 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5769 // see note at standby() declaration
5770 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5771 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5772 thread.get());
5773 return false;
5774 }
5775 }
5776 return true;
5777}
5778
5779uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5780{
5781 return (mWaitTimeMs * 1000) / 2;
5782}
5783
5784void AudioFlinger::DuplicatingThread::cacheParameters_l()
5785{
5786 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5787 updateWaitTime_l();
5788
5789 MixerThread::cacheParameters_l();
5790}
5791
Eric Laurent6acd1d42017-01-04 14:23:29 -08005792
Eric Laurent81784c32012-11-19 14:55:58 -08005793// ----------------------------------------------------------------------------
5794// Record
5795// ----------------------------------------------------------------------------
5796
5797AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5798 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005799 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005800 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005801 audio_devices_t inDevice,
5802 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005803#ifdef TEE_SINK
5804 , const sp<NBAIO_Sink>& teeSink
5805#endif
5806 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005807 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005808 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005809 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005810 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005811#ifdef TEE_SINK
5812 , mTeeSink(teeSink)
5813#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005814 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5815 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005816 // mFastCapture below
5817 , mFastCaptureFutex(0)
5818 // mInputSource
5819 // mPipeSink
5820 // mPipeSource
5821 , mPipeFramesP2(0)
5822 // mPipeMemory
5823 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005824 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005825{
Glenn Kastend7dca052015-03-05 16:05:54 -08005826 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5827 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005828
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005829 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005830
5831 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005832 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 size_t numCounterOffers = 0;
5834 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005835#if !LOG_NDEBUG
5836 ssize_t index =
5837#else
5838 (void)
5839#endif
5840 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841 ALOG_ASSERT(index == 0);
5842
5843 // initialize fast capture depending on configuration
5844 bool initFastCapture;
5845 switch (kUseFastCapture) {
5846 case FastCapture_Never:
5847 initFastCapture = false;
5848 break;
5849 case FastCapture_Always:
5850 initFastCapture = true;
5851 break;
5852 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005853 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854 break;
5855 // case FastCapture_Dynamic:
5856 }
5857
5858 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005859 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005861 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5862 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005863 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5864 void *pipeBuffer;
5865 const sp<MemoryDealer> roHeap(readOnlyHeap());
5866 sp<IMemory> pipeMemory;
5867 if ((roHeap == 0) ||
5868 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5869 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5870 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5871 goto failed;
5872 }
5873 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5874 memset(pipeBuffer, 0, pipeSize);
5875 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5876 const NBAIO_Format offers[1] = {format};
5877 size_t numCounterOffers = 0;
5878 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5879 ALOG_ASSERT(index == 0);
5880 mPipeSink = pipe;
5881 PipeReader *pipeReader = new PipeReader(*pipe);
5882 numCounterOffers = 0;
5883 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5884 ALOG_ASSERT(index == 0);
5885 mPipeSource = pipeReader;
5886 mPipeFramesP2 = pipeFramesP2;
5887 mPipeMemory = pipeMemory;
5888
5889 // create fast capture
5890 mFastCapture = new FastCapture();
5891 FastCaptureStateQueue *sq = mFastCapture->sq();
5892#ifdef STATE_QUEUE_DUMP
5893 // FIXME
5894#endif
5895 FastCaptureState *state = sq->begin();
5896 state->mCblk = NULL;
5897 state->mInputSource = mInputSource.get();
5898 state->mInputSourceGen++;
5899 state->mPipeSink = pipe;
5900 state->mPipeSinkGen++;
5901 state->mFrameCount = mFrameCount;
5902 state->mCommand = FastCaptureState::COLD_IDLE;
5903 // already done in constructor initialization list
5904 //mFastCaptureFutex = 0;
5905 state->mColdFutexAddr = &mFastCaptureFutex;
5906 state->mColdGen++;
5907 state->mDumpState = &mFastCaptureDumpState;
5908#ifdef TEE_SINK
5909 // FIXME
5910#endif
5911 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5912 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5913 sq->end();
5914 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5915
5916 // start the fast capture
5917 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5918 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005919 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920#ifdef AUDIO_WATCHDOG
5921 // FIXME
5922#endif
5923
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005924 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005925 }
5926failed: ;
5927
5928 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005929}
5930
Eric Laurent81784c32012-11-19 14:55:58 -08005931AudioFlinger::RecordThread::~RecordThread()
5932{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005933 if (mFastCapture != 0) {
5934 FastCaptureStateQueue *sq = mFastCapture->sq();
5935 FastCaptureState *state = sq->begin();
5936 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5937 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5938 if (old == -1) {
5939 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5940 }
5941 }
5942 state->mCommand = FastCaptureState::EXIT;
5943 sq->end();
5944 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5945 mFastCapture->join();
5946 mFastCapture.clear();
5947 }
5948 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005949 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005950 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005951}
5952
5953void AudioFlinger::RecordThread::onFirstRef()
5954{
Glenn Kastend7dca052015-03-05 16:05:54 -08005955 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005956}
5957
Eric Laurent81784c32012-11-19 14:55:58 -08005958bool AudioFlinger::RecordThread::threadLoop()
5959{
Eric Laurent81784c32012-11-19 14:55:58 -08005960 nsecs_t lastWarning = 0;
5961
5962 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005963
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005964reacquire_wakelock:
5965 sp<RecordTrack> activeTrack;
5966 {
5967 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005968 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005969 }
5970
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005971 // used to request a deferred sleep, to be executed later while mutex is unlocked
5972 uint32_t sleepUs = 0;
5973
5974 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005975 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005976 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005977
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005978 // activeTracks accumulates a copy of a subset of mActiveTracks
5979 Vector< sp<RecordTrack> > activeTracks;
5980
Glenn Kasten735f45f2014-08-18 15:51:59 -07005981 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005982 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005983
Glenn Kasten735f45f2014-08-18 15:51:59 -07005984 // reference to a fast track which is about to be removed
5985 sp<RecordTrack> fastTrackToRemove;
5986
Eric Laurent81784c32012-11-19 14:55:58 -08005987 { // scope for mLock
5988 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005989
Eric Laurent021cf962014-05-13 10:18:14 -07005990 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005991
Eric Laurent000a4192014-01-29 15:17:32 -08005992 // check exitPending here because checkForNewParameters_l() and
5993 // checkForNewParameters_l() can temporarily release mLock
5994 if (exitPending()) {
5995 break;
5996 }
5997
Eric Laurent5c25d562016-07-13 17:17:45 -07005998 // sleep with mutex unlocked
5999 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006000 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006001 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6002 ATRACE_END();
6003 sleepUs = 0;
6004 continue;
6005 }
6006
Glenn Kasten2b806402013-11-20 16:37:38 -08006007 // if no active track(s), then standby and release wakelock
6008 size_t size = mActiveTracks.size();
6009 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006010 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006011 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006012 releaseWakeLock_l();
6013 ALOGV("RecordThread: loop stopping");
6014 // go to sleep
6015 mWaitWorkCV.wait(mLock);
6016 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006017 goto reacquire_wakelock;
6018 }
6019
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006020 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006021 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006022 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006024 activeTrack = mActiveTracks[i];
6025 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006026 if (activeTrack->isFastTrack()) {
6027 ALOG_ASSERT(fastTrackToRemove == 0);
6028 fastTrackToRemove = activeTrack;
6029 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006030 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006031 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006032 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006033 continue;
6034 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006035
6036 TrackBase::track_state activeTrackState = activeTrack->mState;
6037 switch (activeTrackState) {
6038
6039 case TrackBase::PAUSING:
6040 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 doBroadcast = true;
6042 size--;
6043 continue;
6044
6045 case TrackBase::STARTING_1:
6046 sleepUs = 10000;
6047 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006048 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006049 continue;
6050
6051 case TrackBase::STARTING_2:
6052 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006053 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006054 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006055 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 break;
6057
6058 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006059 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 break;
6061
6062 case TrackBase::IDLE:
6063 i++;
6064 continue;
6065
6066 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006067 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006068 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006069
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 activeTracks.add(activeTrack);
6071 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006072
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006073 if (activeTrack->isFastTrack()) {
6074 ALOG_ASSERT(!mFastTrackAvail);
6075 ALOG_ASSERT(fastTrack == 0);
6076 fastTrack = activeTrack;
6077 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006078 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006079
Andy Hungdae27702016-10-31 14:01:16 -07006080 mActiveTracks.updatePowerState(this);
6081
Eric Laurent5c25d562016-07-13 17:17:45 -07006082 if (allStopped) {
6083 standbyIfNotAlreadyInStandby();
6084 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 if (doBroadcast) {
6086 mStartStopCond.broadcast();
6087 }
6088
6089 // sleep if there are no active tracks to process
6090 if (activeTracks.size() == 0) {
6091 if (sleepUs == 0) {
6092 sleepUs = kRecordThreadSleepUs;
6093 }
6094 continue;
6095 }
6096 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006097
Eric Laurent81784c32012-11-19 14:55:58 -08006098 lockEffectChains_l(effectChains);
6099 }
6100
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006101 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006102
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 size_t size = effectChains.size();
6104 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006105 // thread mutex is not locked, but effect chain is locked
6106 effectChains[i]->process_l();
6107 }
6108
Glenn Kasten735f45f2014-08-18 15:51:59 -07006109 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006110 if (mFastCapture != 0) {
6111 FastCaptureStateQueue *sq = mFastCapture->sq();
6112 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006113 bool didModify = false;
6114 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6116 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6117 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6118 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6119 if (old == -1) {
6120 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6121 }
6122 }
6123 state->mCommand = FastCaptureState::READ_WRITE;
6124#if 0 // FIXME
6125 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006126 FastThreadDumpState::kSamplingNforLowRamDevice :
6127 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006128#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006129 didModify = true;
6130 }
6131 audio_track_cblk_t *cblkOld = state->mCblk;
6132 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6133 if (cblkNew != cblkOld) {
6134 state->mCblk = cblkNew;
6135 // block until acked if removing a fast track
6136 if (cblkOld != NULL) {
6137 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6138 }
6139 didModify = true;
6140 }
6141 sq->end(didModify);
6142 if (didModify) {
6143 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006144#if 0
6145 if (kUseFastCapture == FastCapture_Dynamic) {
6146 mNormalSource = mPipeSource;
6147 }
6148#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006149 }
6150 }
6151
Glenn Kasten735f45f2014-08-18 15:51:59 -07006152 // now run the fast track destructor with thread mutex unlocked
6153 fastTrackToRemove.clear();
6154
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6156 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6157 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6158 // If destination is non-contiguous, first read past the nominal end of buffer, then
6159 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006162 ssize_t framesRead;
6163
6164 // If an NBAIO source is present, use it to read the normal capture's data
6165 if (mPipeSource != 0) {
6166 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006167 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006168 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006169 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006170 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6171 // buffer size or at least for 20ms.
6172 size_t sleepFrames = max(
6173 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6174 if (framesRead <= (ssize_t) sleepFrames) {
6175 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6176 }
6177 if (framesRead < 0) {
6178 status_t status = (status_t) framesRead;
6179 switch (status) {
6180 case OVERRUN:
6181 ALOGW("overrun on read from pipe");
6182 framesRead = 0;
6183 break;
6184 case NEGOTIATE:
6185 ALOGE("re-negotiation is needed");
6186 framesRead = -1; // Will cause an attempt to recover.
6187 break;
6188 default:
6189 ALOGE("unknown error %d on read from pipe", status);
6190 break;
6191 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006192 }
6193 // otherwise use the HAL / AudioStreamIn directly
6194 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006195 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006196 size_t bytesRead;
6197 status_t result = mInput->stream->read(
6198 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006199 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006200 if (result < 0) {
6201 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006202 } else {
6203 framesRead = bytesRead / mFrameSize;
6204 }
6205 }
6206
Andy Hung3f0c9022016-01-15 17:49:46 -08006207 // Update server timestamp with server stats
6208 // systemTime() is optional if the hardware supports timestamps.
6209 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6210 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6211
6212 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006213 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006214 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006215 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006216 if (ret == NO_ERROR) {
6217 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6218 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6219 // Note: In general record buffers should tend to be empty in
6220 // a properly running pipeline.
6221 //
6222 // Also, it is not advantageous to call get_presentation_position during the read
6223 // as the read obtains a lock, preventing the timestamp call from executing.
6224 }
6225 }
6226 // Use this to track timestamp information
6227 // ALOGD("%s", mTimestamp.toString().c_str());
6228
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006229 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006230 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 // Force input into standby so that it tries to recover at next read attempt
6232 inputStandBy();
6233 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006234 }
6235 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006236 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006237 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006240 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006241 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 }
6243 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006244 {
6245 size_t part1 = mRsmpInFramesP2 - rear;
6246 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006247 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006248 (framesRead - part1) * mFrameSize);
6249 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006250 }
6251 rear = mRsmpInRear += framesRead;
6252
6253 size = activeTracks.size();
6254 // loop over each active track
6255 for (size_t i = 0; i < size; i++) {
6256 activeTrack = activeTracks[i];
6257
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006258 // skip fast tracks, as those are handled directly by FastCapture
6259 if (activeTrack->isFastTrack()) {
6260 continue;
6261 }
6262
Andy Hung73c02e42015-03-29 01:13:58 -07006263 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006264 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6265
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006266 enum {
6267 OVERRUN_UNKNOWN,
6268 OVERRUN_TRUE,
6269 OVERRUN_FALSE
6270 } overrun = OVERRUN_UNKNOWN;
6271
6272 // loop over getNextBuffer to handle circular sink
6273 for (;;) {
6274
6275 activeTrack->mSink.frameCount = ~0;
6276 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6277 size_t framesOut = activeTrack->mSink.frameCount;
6278 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6279
Andy Hung73c02e42015-03-29 01:13:58 -07006280 // check available frames and handle overrun conditions
6281 // if the record track isn't draining fast enough.
6282 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006283 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006284 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6285 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006286 overrun = OVERRUN_TRUE;
6287 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006288 if (framesOut == 0 || framesIn == 0) {
6289 break;
6290 }
6291
Andy Hung6770c6f2015-04-07 13:43:36 -07006292 // Don't allow framesOut to be larger than what is possible with resampling
6293 // from framesIn.
6294 // This isn't strictly necessary but helps limit buffer resizing in
6295 // RecordBufferConverter. TODO: remove when no longer needed.
6296 framesOut = min(framesOut,
6297 destinationFramesPossible(
6298 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006299 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6300 framesOut = activeTrack->mRecordBufferConverter->convert(
6301 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006302
6303 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6304 overrun = OVERRUN_FALSE;
6305 }
6306
6307 if (activeTrack->mFramesToDrop == 0) {
6308 if (framesOut > 0) {
6309 activeTrack->mSink.frameCount = framesOut;
6310 activeTrack->releaseBuffer(&activeTrack->mSink);
6311 }
6312 } else {
6313 // FIXME could do a partial drop of framesOut
6314 if (activeTrack->mFramesToDrop > 0) {
6315 activeTrack->mFramesToDrop -= framesOut;
6316 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006317 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006318 }
6319 } else {
6320 activeTrack->mFramesToDrop += framesOut;
6321 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6322 activeTrack->mSyncStartEvent->isCancelled()) {
6323 ALOGW("Synced record %s, session %d, trigger session %d",
6324 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6325 activeTrack->sessionId(),
6326 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006327 activeTrack->mSyncStartEvent->triggerSession() :
6328 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006329 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006330 }
6331 }
6332 }
6333
6334 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006336 }
6337 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338
6339 switch (overrun) {
6340 case OVERRUN_TRUE:
6341 // client isn't retrieving buffers fast enough
6342 if (!activeTrack->setOverflow()) {
6343 nsecs_t now = systemTime();
6344 // FIXME should lastWarning per track?
6345 if ((now - lastWarning) > kWarningThrottleNs) {
6346 ALOGW("RecordThread: buffer overflow");
6347 lastWarning = now;
6348 }
6349 }
6350 break;
6351 case OVERRUN_FALSE:
6352 activeTrack->clearOverflow();
6353 break;
6354 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006355 break;
6356 }
6357
Andy Hung3f0c9022016-01-15 17:49:46 -08006358 // update frame information and push timestamp out
6359 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006360 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006361 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6362 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006363 }
6364
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006365unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006366 // enable changes in effect chain
6367 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006368 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006369 }
6370
Glenn Kasten93e471f2013-08-19 08:40:07 -07006371 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006372
6373 {
6374 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006375 for (size_t i = 0; i < mTracks.size(); i++) {
6376 sp<RecordTrack> track = mTracks[i];
6377 track->invalidate();
6378 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006379 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006380 mStartStopCond.broadcast();
6381 }
6382
6383 releaseWakeLock();
6384
6385 ALOGV("RecordThread %p exiting", this);
6386 return false;
6387}
6388
Glenn Kasten93e471f2013-08-19 08:40:07 -07006389void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006390{
6391 if (!mStandby) {
6392 inputStandBy();
6393 mStandby = true;
6394 }
6395}
6396
6397void AudioFlinger::RecordThread::inputStandBy()
6398{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006399 // Idle the fast capture if it's currently running
6400 if (mFastCapture != 0) {
6401 FastCaptureStateQueue *sq = mFastCapture->sq();
6402 FastCaptureState *state = sq->begin();
6403 if (!(state->mCommand & FastCaptureState::IDLE)) {
6404 state->mCommand = FastCaptureState::COLD_IDLE;
6405 state->mColdFutexAddr = &mFastCaptureFutex;
6406 state->mColdGen++;
6407 mFastCaptureFutex = 0;
6408 sq->end();
6409 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6410 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6411#if 0
6412 if (kUseFastCapture == FastCapture_Dynamic) {
6413 // FIXME
6414 }
6415#endif
6416#ifdef AUDIO_WATCHDOG
6417 // FIXME
6418#endif
6419 } else {
6420 sq->end(false /*didModify*/);
6421 }
6422 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006423 status_t result = mInput->stream->standby();
6424 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006425
6426 // If going into standby, flush the pipe source.
6427 if (mPipeSource.get() != nullptr) {
6428 const ssize_t flushed = mPipeSource->flush();
6429 if (flushed > 0) {
6430 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6431 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6432 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6433 }
6434 }
Eric Laurent81784c32012-11-19 14:55:58 -08006435}
6436
Glenn Kasten05997e22014-03-13 15:08:33 -07006437// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006438sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006439 const sp<AudioFlinger::Client>& client,
6440 uint32_t sampleRate,
6441 audio_format_t format,
6442 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006443 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006444 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006445 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006446 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006447 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006448 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006449 status_t *status,
6450 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006451{
Glenn Kasten74935e42013-12-19 08:56:45 -08006452 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006453 sp<RecordTrack> track;
6454 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006455 audio_input_flags_t inputFlags = mInput->flags;
6456
6457 // special case for FAST flag considered OK if fast capture is present
6458 if (hasFastCapture()) {
6459 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6460 }
6461
6462 // Check if requested flags are compatible with output stream flags
6463 if ((*flags & inputFlags) != *flags) {
6464 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6465 " input flags (%08x)",
6466 *flags, inputFlags);
6467 *flags = (audio_input_flags_t)(*flags & inputFlags);
6468 }
Eric Laurent81784c32012-11-19 14:55:58 -08006469
Glenn Kasten90e58b12013-07-31 16:16:02 -07006470 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006471 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006472 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006473 // we formerly checked for a callback handler (non-0 tid),
6474 // but that is no longer required for TRANSFER_OBTAIN mode
6475 //
Glenn Kasten74105912014-07-03 12:28:53 -07006476 // frame count is not specified, or is exactly the pipe depth
6477 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006478 // PCM data
6479 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006480 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006481 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006482 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006483 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006484 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006485 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006486 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006487 hasFastCapture() &&
6488 // there are sufficient fast track slots available
6489 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006490 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006491 // check compatibility with audio effects.
6492 Mutex::Autolock _l(mLock);
6493 // Do not accept FAST flag if the session has software effects
6494 sp<EffectChain> chain = getEffectChain_l(sessionId);
6495 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006496 audio_input_flags_t old = *flags;
6497 chain->checkInputFlagCompatibility(flags);
6498 if (old != *flags) {
6499 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6500 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006501 }
6502 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006503 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006504 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6505 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006506 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006507 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006508 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006509 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006510 frameCount, mFrameCount, mPipeFramesP2,
6511 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6512 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006513 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006514 }
6515 }
6516
6517 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006518 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006519 // fast track: frame count is exactly the pipe depth
6520 frameCount = mPipeFramesP2;
6521 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6522 *notificationFrames = mFrameCount;
6523 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006524 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6525 // or 20 ms if there is a fast capture
6526 // TODO This could be a roundupRatio inline, and const
6527 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6528 * sampleRate + mSampleRate - 1) / mSampleRate;
6529 // minimum number of notification periods is at least kMinNotifications,
6530 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6531 static const size_t kMinNotifications = 3;
6532 static const uint32_t kMinMs = 30;
6533 // TODO This could be a roundupRatio inline
6534 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6535 // TODO This could be a roundupRatio inline
6536 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6537 maxNotificationFrames;
6538 const size_t minFrameCount = maxNotificationFrames *
6539 max(kMinNotifications, minNotificationsByMs);
6540 frameCount = max(frameCount, minFrameCount);
6541 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6542 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006543 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006544 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006545 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006546
Glenn Kasten15e57982013-09-24 11:52:37 -07006547 lStatus = initCheck();
6548 if (lStatus != NO_ERROR) {
6549 ALOGE("createRecordTrack_l() audio driver not initialized");
6550 goto Exit;
6551 }
Eric Laurent81784c32012-11-19 14:55:58 -08006552
6553 { // scope for mLock
6554 Mutex::Autolock _l(mLock);
6555
6556 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006557 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006558 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006559
Glenn Kasten03003332013-08-06 15:40:54 -07006560 lStatus = track->initCheck();
6561 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006562 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006563 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006564 goto Exit;
6565 }
6566 mTracks.add(track);
6567
6568 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6569 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6570 mAudioFlinger->btNrecIsOff();
6571 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6572 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006573
Eric Laurent05067782016-06-01 18:27:28 -07006574 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006575 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6576 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6577 // so ask activity manager to do this on our behalf
6578 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6579 }
Eric Laurent81784c32012-11-19 14:55:58 -08006580 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006581
Eric Laurent81784c32012-11-19 14:55:58 -08006582 lStatus = NO_ERROR;
6583
6584Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006585 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006586 return track;
6587}
6588
6589status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6590 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006591 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006592{
6593 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6594 sp<ThreadBase> strongMe = this;
6595 status_t status = NO_ERROR;
6596
6597 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006598 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006599 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006600 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006601 triggerSession,
6602 recordTrack->sessionId(),
6603 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006604 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006605 // Sync event can be cancelled by the trigger session if the track is not in a
6606 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006607 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006608 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006609 } else {
6610 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006611 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006612 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006613 }
6614 }
6615
6616 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006617 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006618 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006619 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6620 if (recordTrack->mState == TrackBase::PAUSING) {
6621 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006622 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006623 } else {
6624 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006625 }
6626 return status;
6627 }
6628
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006629 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6630 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6631 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006632 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006633 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006634 status_t status = NO_ERROR;
6635 if (recordTrack->isExternalTrack()) {
6636 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006637 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006638 mLock.lock();
6639 // FIXME should verify that recordTrack is still in mActiveTracks
6640 if (status != NO_ERROR) {
6641 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006642 recordTrack->clearSyncStartEvent();
6643 ALOGV("RecordThread::start error %d", status);
6644 return status;
6645 }
Eric Laurent81784c32012-11-19 14:55:58 -08006646 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006647 // Catch up with current buffer indices if thread is already running.
6648 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6649 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6650 // see previously buffered data before it called start(), but with greater risk of overrun.
6651
Andy Hung73c02e42015-03-29 01:13:58 -07006652 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006653 // clear any converter state as new data will be discontinuous
6654 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006655 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006656 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006657 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006658 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006659 ALOGV("Record failed to start");
6660 status = BAD_VALUE;
6661 goto startError;
6662 }
Eric Laurent81784c32012-11-19 14:55:58 -08006663 return status;
6664 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006665
Eric Laurent81784c32012-11-19 14:55:58 -08006666startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006667 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006668 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006669 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006670 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006671 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006672 return status;
6673}
6674
Eric Laurent81784c32012-11-19 14:55:58 -08006675void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6676{
6677 sp<SyncEvent> strongEvent = event.promote();
6678
6679 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006680 sp<RefBase> ptr = strongEvent->cookie().promote();
6681 if (ptr != 0) {
6682 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6683 recordTrack->handleSyncStartEvent(strongEvent);
6684 }
Eric Laurent81784c32012-11-19 14:55:58 -08006685 }
6686}
6687
Glenn Kastena8356f62013-07-25 14:37:52 -07006688bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006689 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006690 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006691 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006692 return false;
6693 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006694 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006695 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006696 // signal thread to stop
6697 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006698 // do not wait for mStartStopCond if exiting
6699 if (exitPending()) {
6700 return true;
6701 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006702 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006703 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006704 // if we have been restarted, recordTrack is in mActiveTracks here
6705 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006706 ALOGV("Record stopped OK");
6707 return true;
6708 }
6709 return false;
6710}
6711
Glenn Kasten0f11b512014-01-31 16:18:54 -08006712bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006713{
6714 return false;
6715}
6716
Glenn Kasten0f11b512014-01-31 16:18:54 -08006717status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006718{
6719#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6720 if (!isValidSyncEvent(event)) {
6721 return BAD_VALUE;
6722 }
6723
Glenn Kastend848eb42016-03-08 13:42:11 -08006724 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006725 status_t ret = NAME_NOT_FOUND;
6726
6727 Mutex::Autolock _l(mLock);
6728
6729 for (size_t i = 0; i < mTracks.size(); i++) {
6730 sp<RecordTrack> track = mTracks[i];
6731 if (eventSession == track->sessionId()) {
6732 (void) track->setSyncEvent(event);
6733 ret = NO_ERROR;
6734 }
6735 }
6736 return ret;
6737#else
6738 return BAD_VALUE;
6739#endif
6740}
6741
6742// destroyTrack_l() must be called with ThreadBase::mLock held
6743void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6744{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006745 track->terminate();
6746 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006747 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006748 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006749 removeTrack_l(track);
6750 }
6751}
6752
6753void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6754{
6755 mTracks.remove(track);
6756 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006757 if (track->isFastTrack()) {
6758 ALOG_ASSERT(!mFastTrackAvail);
6759 mFastTrackAvail = true;
6760 }
Eric Laurent81784c32012-11-19 14:55:58 -08006761}
6762
6763void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6764{
6765 dumpInternals(fd, args);
6766 dumpTracks(fd, args);
6767 dumpEffectChains(fd, args);
6768}
6769
6770void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6771{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006772 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006773
Glenn Kasten44182c22015-03-05 17:12:23 -08006774 dumpBase(fd, args);
6775
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006776 AudioStreamIn *input = mInput;
6777 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6778 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6779 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006780 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006781 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006782 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006783 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006784 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006785
Glenn Kasten2f90c512015-12-02 11:40:09 -08006786 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6787 // while we are dumping it. It may be inconsistent, but it won't mutate!
6788 // This is a large object so we place it on the heap.
6789 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6790 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6791 copy->dump(fd);
6792 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006793}
6794
Glenn Kasten0f11b512014-01-31 16:18:54 -08006795void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006796{
6797 const size_t SIZE = 256;
6798 char buffer[SIZE];
6799 String8 result;
6800
Marco Nelissenb2208842014-02-07 14:00:50 -08006801 size_t numtracks = mTracks.size();
6802 size_t numactive = mActiveTracks.size();
6803 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006804 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006805 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006806 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006807 RecordTrack::appendDumpHeader(result);
6808 for (size_t i = 0; i < numtracks ; ++i) {
6809 sp<RecordTrack> track = mTracks[i];
6810 if (track != 0) {
6811 bool active = mActiveTracks.indexOf(track) >= 0;
6812 if (active) {
6813 numactiveseen++;
6814 }
6815 track->dump(buffer, SIZE, active);
6816 result.append(buffer);
6817 }
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006819 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006820 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006821 }
6822
Marco Nelissenb2208842014-02-07 14:00:50 -08006823 if (numactiveseen != numactive) {
6824 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6825 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006826 result.append(buffer);
6827 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006828 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006829 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006830 if (mTracks.indexOf(track) < 0) {
6831 track->dump(buffer, SIZE, true);
6832 result.append(buffer);
6833 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006834 }
Eric Laurent81784c32012-11-19 14:55:58 -08006835
6836 }
6837 write(fd, result.string(), result.size());
6838}
6839
Andy Hung73c02e42015-03-29 01:13:58 -07006840
6841void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6842{
6843 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6844 RecordThread *recordThread = (RecordThread *) threadBase.get();
6845 mRsmpInFront = recordThread->mRsmpInRear;
6846 mRsmpInUnrel = 0;
6847}
6848
6849void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6850 size_t *framesAvailable, bool *hasOverrun)
6851{
6852 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6853 RecordThread *recordThread = (RecordThread *) threadBase.get();
6854 const int32_t rear = recordThread->mRsmpInRear;
6855 const int32_t front = mRsmpInFront;
6856 const ssize_t filled = rear - front;
6857
6858 size_t framesIn;
6859 bool overrun = false;
6860 if (filled < 0) {
6861 // should not happen, but treat like a massive overrun and re-sync
6862 framesIn = 0;
6863 mRsmpInFront = rear;
6864 overrun = true;
6865 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6866 framesIn = (size_t) filled;
6867 } else {
6868 // client is not keeping up with server, but give it latest data
6869 framesIn = recordThread->mRsmpInFrames;
6870 mRsmpInFront = /* front = */ rear - framesIn;
6871 overrun = true;
6872 }
6873 if (framesAvailable != NULL) {
6874 *framesAvailable = framesIn;
6875 }
6876 if (hasOverrun != NULL) {
6877 *hasOverrun = overrun;
6878 }
6879}
6880
Eric Laurent81784c32012-11-19 14:55:58 -08006881// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006882status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006883 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006884{
Andy Hung73c02e42015-03-29 01:13:58 -07006885 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006886 if (threadBase == 0) {
6887 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006888 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889 return NOT_ENOUGH_DATA;
6890 }
6891 RecordThread *recordThread = (RecordThread *) threadBase.get();
6892 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006893 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006894 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006895 // FIXME should not be P2 (don't want to increase latency)
6896 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006897 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006898 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006899 front &= recordThread->mRsmpInFramesP2 - 1;
6900 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006901 if (part1 > (size_t) filled) {
6902 part1 = filled;
6903 }
6904 size_t ask = buffer->frameCount;
6905 ALOG_ASSERT(ask > 0);
6906 if (part1 > ask) {
6907 part1 = ask;
6908 }
6909 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006910 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006911 buffer->raw = NULL;
6912 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006913 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006914 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006915 }
6916
Andy Hung57446612015-04-19 23:56:46 -07006917 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006918 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006919 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006920 return NO_ERROR;
6921}
6922
6923// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006924void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6925 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006926{
Glenn Kasten85948432013-08-19 12:09:05 -07006927 size_t stepCount = buffer->frameCount;
6928 if (stepCount == 0) {
6929 return;
6930 }
Andy Hung73c02e42015-03-29 01:13:58 -07006931 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6932 mRsmpInUnrel -= stepCount;
6933 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006934 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006935 buffer->frameCount = 0;
6936}
6937
Andy Hung97a893e2015-03-29 01:03:07 -07006938AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6939 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6940 uint32_t srcSampleRate,
6941 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6942 uint32_t dstSampleRate) :
6943 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6944 // mSrcFormat
6945 // mSrcSampleRate
6946 // mDstChannelMask
6947 // mDstFormat
6948 // mDstSampleRate
6949 // mSrcChannelCount
6950 // mDstChannelCount
6951 // mDstFrameSize
6952 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006953 mResampler(NULL),
6954 mIsLegacyDownmix(false),
6955 mIsLegacyUpmix(false),
6956 mRequiresFloat(false),
6957 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006958{
6959 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6960 dstChannelMask, dstFormat, dstSampleRate);
6961}
6962
6963AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6964 free(mBuf);
6965 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006966 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006967}
6968
6969size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6970 AudioBufferProvider *provider, size_t frames)
6971{
Andy Hungd330ee42015-04-20 13:23:41 -07006972 if (mInputConverterProvider != NULL) {
6973 mInputConverterProvider->setBufferProvider(provider);
6974 provider = mInputConverterProvider;
6975 }
6976
6977 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006978 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6979 mSrcSampleRate, mSrcFormat, mDstFormat);
6980
6981 AudioBufferProvider::Buffer buffer;
6982 for (size_t i = frames; i > 0; ) {
6983 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006984 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006985 if (status != OK || buffer.frameCount == 0) {
6986 frames -= i; // cannot fill request.
6987 break;
6988 }
Andy Hungd330ee42015-04-20 13:23:41 -07006989 // format convert to destination buffer
6990 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006991
6992 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6993 i -= buffer.frameCount;
6994 provider->releaseBuffer(&buffer);
6995 }
6996 } else {
6997 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6998 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6999
Andy Hungd330ee42015-04-20 13:23:41 -07007000 // reallocate buffer if needed
7001 if (mBufFrameSize != 0 && mBufFrames < frames) {
7002 free(mBuf);
7003 mBufFrames = frames;
7004 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7005 }
Andy Hung97a893e2015-03-29 01:03:07 -07007006 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007007 memset(mBuf, 0, frames * mBufFrameSize);
7008 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7009 // format convert to destination buffer
7010 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007011 }
7012 return frames;
7013}
7014
7015status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7016 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7017 uint32_t srcSampleRate,
7018 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7019 uint32_t dstSampleRate)
7020{
7021 // quick evaluation if there is any change.
7022 if (mSrcFormat == srcFormat
7023 && mSrcChannelMask == srcChannelMask
7024 && mSrcSampleRate == srcSampleRate
7025 && mDstFormat == dstFormat
7026 && mDstChannelMask == dstChannelMask
7027 && mDstSampleRate == dstSampleRate) {
7028 return NO_ERROR;
7029 }
7030
Andy Hungdb4c0312015-05-06 08:46:52 -07007031 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7032 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7033 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007034 const bool valid =
7035 audio_is_input_channel(srcChannelMask)
7036 && audio_is_input_channel(dstChannelMask)
7037 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7038 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7039 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7040 ; // no upsampling checks for now
7041 if (!valid) {
7042 return BAD_VALUE;
7043 }
7044
7045 mSrcFormat = srcFormat;
7046 mSrcChannelMask = srcChannelMask;
7047 mSrcSampleRate = srcSampleRate;
7048 mDstFormat = dstFormat;
7049 mDstChannelMask = dstChannelMask;
7050 mDstSampleRate = dstSampleRate;
7051
7052 // compute derived parameters
7053 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7054 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7055 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7056
Andy Hungd330ee42015-04-20 13:23:41 -07007057 // do we need to resample?
7058 delete mResampler;
7059 mResampler = NULL;
7060 if (mSrcSampleRate != mDstSampleRate) {
7061 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7062 mSrcChannelCount, mDstSampleRate);
7063 mResampler->setSampleRate(mSrcSampleRate);
7064 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7065 }
7066
7067 // are we running legacy channel conversion modes?
7068 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7069 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7070 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7071 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7072 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7073 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7074
7075 // do we need to process in float?
7076 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7077
7078 // do we need a staging buffer to convert for destination (we can still optimize this)?
7079 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7080 if (mResampler != NULL) {
7081 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7082 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007083 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007084 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7085 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007086 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7087 } else {
7088 mBufFrameSize = 0;
7089 }
7090 mBufFrames = 0; // force the buffer to be resized.
7091
Andy Hungd330ee42015-04-20 13:23:41 -07007092 // do we need an input converter buffer provider to give us float?
7093 delete mInputConverterProvider;
7094 mInputConverterProvider = NULL;
7095 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7096 mInputConverterProvider = new ReformatBufferProvider(
7097 audio_channel_count_from_in_mask(mSrcChannelMask),
7098 mSrcFormat,
7099 AUDIO_FORMAT_PCM_FLOAT,
7100 256 /* provider buffer frame count */);
7101 }
7102
7103 // do we need a remixer to do channel mask conversion
7104 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7105 (void) memcpy_by_index_array_initialization_from_channel_mask(
7106 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007107 }
7108 return NO_ERROR;
7109}
7110
Andy Hungd330ee42015-04-20 13:23:41 -07007111void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7112 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007113{
Andy Hungd330ee42015-04-20 13:23:41 -07007114 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007115 if (mBufFrameSize != 0 && mBufFrames < frames) {
7116 free(mBuf);
7117 mBufFrames = frames;
7118 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7119 }
Andy Hungd330ee42015-04-20 13:23:41 -07007120 // do we need to do legacy upmix and downmix?
7121 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007122 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007123 if (mIsLegacyUpmix) {
7124 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7125 (const float *)src, frames);
7126 } else /*mIsLegacyDownmix */ {
7127 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7128 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007129 }
Andy Hungd330ee42015-04-20 13:23:41 -07007130 if (mBuf != NULL) {
7131 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7132 frames * mDstChannelCount);
7133 }
7134 return;
7135 }
7136 // do we need to do channel mask conversion?
7137 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007138 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007139 memcpy_by_index_array(dstBuf, mDstChannelCount,
7140 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7141 if (dstBuf == dst) {
7142 return; // format is the same
7143 }
7144 }
7145 // convert to destination buffer
7146 const void *convertBuf = mBuf != NULL ? mBuf : src;
7147 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7148 frames * mDstChannelCount);
7149}
7150
7151void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7152 void *dst, /*not-a-const*/ void *src, size_t frames)
7153{
7154 // src buffer format is ALWAYS float when entering this routine
7155 if (mIsLegacyUpmix) {
7156 ; // mono to stereo already handled by resampler
7157 } else if (mIsLegacyDownmix
7158 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7159 // the resampler outputs stereo for mono input channel (a feature?)
7160 // must convert to mono
7161 downmix_to_mono_float_from_stereo_float((float *)src,
7162 (const float *)src, frames);
7163 } else if (mSrcChannelMask != mDstChannelMask) {
7164 // convert to mono channel again for channel mask conversion (could be skipped
7165 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007166 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007167 downmix_to_mono_float_from_stereo_float((float *)src,
7168 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007169 }
Andy Hungd330ee42015-04-20 13:23:41 -07007170 // convert to destination format (in place, OK as float is larger than other types)
7171 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7172 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7173 frames * mSrcChannelCount);
7174 }
7175 // channel convert and save to dst
7176 memcpy_by_index_array(dst, mDstChannelCount,
7177 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7178 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007179 }
Andy Hungd330ee42015-04-20 13:23:41 -07007180 // convert to destination format and save to dst
7181 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7182 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007183}
7184
Eric Laurent10351942014-05-08 18:49:52 -07007185bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7186 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007187{
7188 bool reconfig = false;
7189
Eric Laurent10351942014-05-08 18:49:52 -07007190 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007191
Eric Laurent10351942014-05-08 18:49:52 -07007192 audio_format_t reqFormat = mFormat;
7193 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007194 // 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 -07007195 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7196
7197 AudioParameter param = AudioParameter(keyValuePair);
7198 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007199
7200 // scope for AutoPark extends to end of method
7201 AutoPark<FastCapture> park(mFastCapture);
7202
Eric Laurent10351942014-05-08 18:49:52 -07007203 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7204 // channel count change can be requested. Do we mandate the first client defines the
7205 // HAL sampling rate and channel count or do we allow changes on the fly?
7206 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7207 samplingRate = value;
7208 reconfig = true;
7209 }
7210 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007211 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007212 status = BAD_VALUE;
7213 } else {
7214 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007215 reconfig = true;
7216 }
Eric Laurent10351942014-05-08 18:49:52 -07007217 }
7218 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7219 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007220 if (!audio_is_input_channel(mask) ||
7221 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007222 status = BAD_VALUE;
7223 } else {
7224 channelMask = mask;
7225 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
Eric Laurent10351942014-05-08 18:49:52 -07007227 }
7228 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7229 // do not accept frame count changes if tracks are open as the track buffer
7230 // size depends on frame count and correct behavior would not be guaranteed
7231 // if frame count is changed after track creation
7232 if (mActiveTracks.size() > 0) {
7233 status = INVALID_OPERATION;
7234 } else {
7235 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007236 }
Eric Laurent10351942014-05-08 18:49:52 -07007237 }
7238 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7239 // forward device change to effects that have requested to be
7240 // aware of attached audio device.
7241 for (size_t i = 0; i < mEffectChains.size(); i++) {
7242 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007243 }
Eric Laurent81784c32012-11-19 14:55:58 -08007244
Eric Laurent10351942014-05-08 18:49:52 -07007245 // store input device and output device but do not forward output device to audio HAL.
7246 // Note that status is ignored by the caller for output device
7247 // (see AudioFlinger::setParameters()
7248 if (audio_is_output_devices(value)) {
7249 mOutDevice = value;
7250 status = BAD_VALUE;
7251 } else {
7252 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007253 if (value != AUDIO_DEVICE_NONE) {
7254 mPrevInDevice = value;
7255 }
Eric Laurent10351942014-05-08 18:49:52 -07007256 // disable AEC and NS if the device is a BT SCO headset supporting those
7257 // pre processings
7258 if (mTracks.size() > 0) {
7259 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7260 mAudioFlinger->btNrecIsOff();
7261 for (size_t i = 0; i < mTracks.size(); i++) {
7262 sp<RecordTrack> track = mTracks[i];
7263 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7264 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007265 }
7266 }
7267 }
Eric Laurent10351942014-05-08 18:49:52 -07007268 }
7269 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7270 mAudioSource != (audio_source_t)value) {
7271 // forward device change to effects that have requested to be
7272 // aware of attached audio device.
7273 for (size_t i = 0; i < mEffectChains.size(); i++) {
7274 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007275 }
Eric Laurent10351942014-05-08 18:49:52 -07007276 mAudioSource = (audio_source_t)value;
7277 }
Glenn Kastene198c362013-08-13 09:13:36 -07007278
Eric Laurent10351942014-05-08 18:49:52 -07007279 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007280 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007281 if (status == INVALID_OPERATION) {
7282 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007283 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007284 }
7285 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007286 if (status == BAD_VALUE) {
7287 uint32_t sRate;
7288 audio_channel_mask_t channelMask;
7289 audio_format_t format;
7290 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7291 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7292 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7293 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7294 status = NO_ERROR;
7295 }
Eric Laurent81784c32012-11-19 14:55:58 -08007296 }
Eric Laurent10351942014-05-08 18:49:52 -07007297 if (status == NO_ERROR) {
7298 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007299 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007300 }
7301 }
Eric Laurent81784c32012-11-19 14:55:58 -08007302 }
Eric Laurent10351942014-05-08 18:49:52 -07007303
Eric Laurent81784c32012-11-19 14:55:58 -08007304 return reconfig;
7305}
7306
7307String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7308{
Eric Laurent81784c32012-11-19 14:55:58 -08007309 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007310 if (initCheck() == NO_ERROR) {
7311 String8 out_s8;
7312 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7313 return out_s8;
7314 }
Eric Laurent81784c32012-11-19 14:55:58 -08007315 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007316 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007317}
7318
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007319void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007320 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7321
7322 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007323
7324 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007325 case AUDIO_INPUT_OPENED:
7326 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007327 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007328 desc->mChannelMask = mChannelMask;
7329 desc->mSamplingRate = mSampleRate;
7330 desc->mFormat = mFormat;
7331 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007332 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007333 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007334 break;
7335
Eric Laurent73e26b62015-04-27 16:55:58 -07007336 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007337 default:
7338 break;
7339 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007340 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007341}
7342
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007343void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007344{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007345 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7346 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007347 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007348 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007349 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007350 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7351 result = mInput->stream->getFrameSize(&mFrameSize);
7352 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7353 result = mInput->stream->getBufferSize(&mBufferSize);
7354 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007355 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007356 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007357 // 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 -07007358 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007359 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007360 // A larger value should allow more old data to be read after a track calls start(),
7361 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007362 //
7363 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007364 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007365 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007366 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007367 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007368
7369 // TODO optimize audio capture buffer sizes ...
7370 // Here we calculate the size of the sliding buffer used as a source
7371 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7372 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7373 // be better to have it derived from the pipe depth in the long term.
7374 // The current value is higher than necessary. However it should not add to latency.
7375
Glenn Kasten85948432013-08-19 12:09:05 -07007376 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007377 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7378 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7379 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007380
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007381 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7382 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007383}
7384
Glenn Kasten5f972c02014-01-13 09:59:31 -08007385uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007386{
7387 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 uint32_t result;
7389 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7390 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007391 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007392 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007393}
7394
Eric Laurent4c415062016-06-17 16:14:16 -07007395// hasAudioSession_l() must be called with ThreadBase::mLock held
7396uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007397{
Eric Laurent81784c32012-11-19 14:55:58 -08007398 uint32_t result = 0;
7399 if (getEffectChain_l(sessionId) != 0) {
7400 result = EFFECT_SESSION;
7401 }
7402
7403 for (size_t i = 0; i < mTracks.size(); ++i) {
7404 if (sessionId == mTracks[i]->sessionId()) {
7405 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007406 if (mTracks[i]->isFastTrack()) {
7407 result |= FAST_SESSION;
7408 }
Eric Laurent81784c32012-11-19 14:55:58 -08007409 break;
7410 }
7411 }
7412
7413 return result;
7414}
7415
Glenn Kastend848eb42016-03-08 13:42:11 -08007416KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007417{
Glenn Kastend848eb42016-03-08 13:42:11 -08007418 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007419 Mutex::Autolock _l(mLock);
7420 for (size_t j = 0; j < mTracks.size(); ++j) {
7421 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007422 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007423 if (ids.indexOfKey(sessionId) < 0) {
7424 ids.add(sessionId, true);
7425 }
7426 }
7427 return ids;
7428}
7429
7430AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7431{
7432 Mutex::Autolock _l(mLock);
7433 AudioStreamIn *input = mInput;
7434 mInput = NULL;
7435 return input;
7436}
7437
7438// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007439sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007440{
7441 if (mInput == NULL) {
7442 return NULL;
7443 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007444 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007445}
7446
7447status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7448{
7449 // only one chain per input thread
7450 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007451 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007452 return INVALID_OPERATION;
7453 }
7454 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007455 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007456 chain->setInBuffer(NULL);
7457 chain->setOutBuffer(NULL);
7458
7459 checkSuspendOnAddEffectChain_l(chain);
7460
Eric Laurent1b928682014-10-02 19:41:47 -07007461 // make sure enabled pre processing effects state is communicated to the HAL as we
7462 // just moved them to a new input stream.
7463 chain->syncHalEffectsState();
7464
Eric Laurent81784c32012-11-19 14:55:58 -08007465 mEffectChains.add(chain);
7466
7467 return NO_ERROR;
7468}
7469
7470size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7471{
7472 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7473 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007474 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007475 chain.get(), mEffectChains.size(), this);
7476 if (mEffectChains.size() == 1) {
7477 mEffectChains.removeAt(0);
7478 }
7479 return 0;
7480}
7481
Eric Laurent1c333e22014-05-20 10:48:17 -07007482status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7483 audio_patch_handle_t *handle)
7484{
7485 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007486
7487 // store new device and send to effects
7488 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007489 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007490 for (size_t i = 0; i < mEffectChains.size(); i++) {
7491 mEffectChains[i]->setDevice_l(mInDevice);
7492 }
7493
7494 // disable AEC and NS if the device is a BT SCO headset supporting those
7495 // pre processings
7496 if (mTracks.size() > 0) {
7497 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7498 mAudioFlinger->btNrecIsOff();
7499 for (size_t i = 0; i < mTracks.size(); i++) {
7500 sp<RecordTrack> track = mTracks[i];
7501 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7502 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7503 }
7504 }
7505
7506 // store new source and send to effects
7507 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7508 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007509 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007510 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007511 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007512 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007513
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007514 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007515 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7516 status = hwDevice->createAudioPatch(patch->num_sources,
7517 patch->sources,
7518 patch->num_sinks,
7519 patch->sinks,
7520 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007521 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007522 char *address;
7523 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7524 address = audio_device_address_to_parameter(
7525 patch->sources[0].ext.device.type,
7526 patch->sources[0].ext.device.address);
7527 } else {
7528 address = (char *)calloc(1, 1);
7529 }
7530 AudioParameter param = AudioParameter(String8(address));
7531 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007532 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007533 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007534 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007535 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007536 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007537 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007538 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007539
Eric Laurente8726fe2015-06-26 09:39:24 -07007540 if (mInDevice != mPrevInDevice) {
7541 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7542 mPrevInDevice = mInDevice;
7543 }
Eric Laurent296fb132015-05-01 11:38:42 -07007544
Eric Laurent1c333e22014-05-20 10:48:17 -07007545 return status;
7546}
7547
7548status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7549{
7550 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007551
7552 mInDevice = AUDIO_DEVICE_NONE;
7553
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007554 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007555 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7556 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007558 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007559 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007560 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007561 }
7562 return status;
7563}
7564
Eric Laurent83b88082014-06-20 18:31:16 -07007565void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7566{
7567 Mutex::Autolock _l(mLock);
7568 mTracks.add(record);
7569}
7570
7571void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7572{
7573 Mutex::Autolock _l(mLock);
7574 destroyTrack_l(record);
7575}
7576
7577void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7578{
7579 ThreadBase::getAudioPortConfig(config);
7580 config->role = AUDIO_PORT_ROLE_SINK;
7581 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7582 config->ext.mix.usecase.source = mAudioSource;
7583}
Eric Laurent1c333e22014-05-20 10:48:17 -07007584
Eric Laurent6acd1d42017-01-04 14:23:29 -08007585// ----------------------------------------------------------------------------
7586// Mmap
7587// ----------------------------------------------------------------------------
7588
7589AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7590 : mThread(thread)
7591{
7592}
7593
7594AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7595{
7596 MmapThread *thread = mThread.get();
7597 // clear our strong reference before disconnecting the thread: the last strong reference
7598 // will be removed when closeInput/closeOutput is executed upono call from audio policy manager
7599 // and the thread removed from mMMapThreads list causing the thread destruction.
7600 mThread.clear();
7601 if (thread != nullptr) {
7602 thread->disconnect();
7603 }
7604}
7605
7606status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7607 struct audio_mmap_buffer_info *info)
7608{
7609 if (mThread == 0) {
7610 return NO_INIT;
7611 }
7612 return mThread->createMmapBuffer(minSizeFrames, info);
7613}
7614
7615status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7616{
7617 if (mThread == 0) {
7618 return NO_INIT;
7619 }
7620 return mThread->getMmapPosition(position);
7621}
7622
7623status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle)
7624
7625{
7626 if (mThread == 0) {
7627 return NO_INIT;
7628 }
7629 return mThread->start(client, handle);
7630}
7631
7632status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7633{
7634 if (mThread == 0) {
7635 return NO_INIT;
7636 }
7637 return mThread->stop(handle);
7638}
7639
7640
7641AudioFlinger::MmapThread::MmapThread(
7642 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7643 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7644 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7645 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7646 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7647{
7648 readHalParameters_l();
7649}
7650
7651AudioFlinger::MmapThread::~MmapThread()
7652{
7653}
7654
7655void AudioFlinger::MmapThread::onFirstRef()
7656{
7657 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7658}
7659
7660void AudioFlinger::MmapThread::disconnect()
7661{
7662 for (const sp<MmapTrack> &t : mActiveTracks) {
7663 stop(t->portId());
7664 }
7665 // this will cause the destruction of this thread.
7666 if (isOutput()) {
7667 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7668 } else {
7669 AudioSystem::releaseInput(mId, mSessionId);
7670 }
7671}
7672
7673
7674void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7675 audio_stream_type_t streamType __unused,
7676 audio_session_t sessionId,
7677 const sp<MmapStreamCallback>& callback,
7678 audio_port_handle_t portId)
7679{
7680 mAttr = *attr;
7681 mSessionId = sessionId;
7682 mCallback = callback;
7683 mPortId = portId;
7684}
7685
7686status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7687 struct audio_mmap_buffer_info *info)
7688{
7689 if (mHalStream == 0) {
7690 return NO_INIT;
7691 }
7692 return mHalStream->createMmapBuffer(minSizeFrames, info);
7693}
7694
7695status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7696{
7697 if (mHalStream == 0) {
7698 return NO_INIT;
7699 }
7700 return mHalStream->getMmapPosition(position);
7701}
7702
7703status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7704 audio_port_handle_t *handle)
7705{
7706 ALOGV("%s clientUid %d", __FUNCTION__, client.clientUid);
7707 if (mHalStream == 0) {
7708 return NO_INIT;
7709 }
7710
7711 status_t ret;
7712 audio_session_t sessionId;
7713 audio_port_handle_t portId;
7714
7715 if (mActiveTracks.size() == 0) {
7716 // for the first track, reuse portId and session allocated when the stream was opened
7717 mHalStream->start();
7718 portId = mPortId;
7719 sessionId = mSessionId;
7720 } else {
7721 // for other tracks than first one, get a new port ID from APM.
7722 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7723 audio_io_handle_t io;
7724 if (isOutput()) {
7725 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7726 config.sample_rate = mSampleRate;
7727 config.channel_mask = mChannelMask;
7728 config.format = mFormat;
7729 audio_stream_type_t stream = streamType();
7730 audio_output_flags_t flags =
7731 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7732 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7733 sessionId,
7734 &stream,
7735 client.clientUid,
7736 &config,
7737 flags,
7738 AUDIO_PORT_HANDLE_NONE,
7739 &portId);
7740 } else {
7741 audio_config_base_t config;
7742 config.sample_rate = mSampleRate;
7743 config.channel_mask = mChannelMask;
7744 config.format = mFormat;
7745 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7746 sessionId,
7747 client.clientPid,
7748 client.clientUid,
7749 &config,
7750 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7751 AUDIO_PORT_HANDLE_NONE,
7752 &portId);
7753 }
7754 // APM should not chose a different input or output stream for the same set of attributes
7755 // and audo configuration
7756 if (ret != NO_ERROR || io != mId) {
7757 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7758 __FUNCTION__, ret, io, mId);
7759 return BAD_VALUE;
7760 }
7761 }
7762
7763 if (isOutput()) {
7764 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7765 } else {
7766 ret = AudioSystem::startInput(mId, sessionId);
7767 }
7768
7769 // abort if start is rejected by audio policy manager
7770 if (ret != NO_ERROR) {
7771 if (mActiveTracks.size() != 0) {
7772 if (isOutput()) {
7773 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7774 } else {
7775 AudioSystem::releaseInput(mId, sessionId);
7776 }
7777 }
7778 return PERMISSION_DENIED;
7779 }
7780
7781 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7782 client.clientUid, portId);
7783
7784 mActiveTracks.add(track);
7785 sp<EffectChain> chain = getEffectChain_l(sessionId);
7786 if (chain != 0) {
7787 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7788 chain->incTrackCnt();
7789 chain->incActiveTrackCnt();
7790 }
7791
7792 *handle = portId;
7793
7794 broadcast_l();
7795
7796 ALOGV("%s DONE handle %d", __FUNCTION__, portId);
7797
7798 return NO_ERROR;
7799}
7800
7801status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7802{
7803
7804 ALOGV("%s handle %d", __FUNCTION__, handle);
7805
7806 if (mHalStream == 0) {
7807 return NO_INIT;
7808 }
7809
7810 sp<MmapTrack> track;
7811 for (const sp<MmapTrack> &t : mActiveTracks) {
7812 if (handle == t->portId()) {
7813 track = t;
7814 break;
7815 }
7816 }
7817 if (track == 0) {
7818 return BAD_VALUE;
7819 }
7820
7821 mActiveTracks.remove(track);
7822
7823 if (isOutput()) {
7824 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7825 if (mActiveTracks.size() != 0) {
7826 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7827 }
7828 } else {
7829 AudioSystem::stopInput(mId, track->sessionId());
7830 if (mActiveTracks.size() != 0) {
7831 AudioSystem::releaseInput(mId, track->sessionId());
7832 }
7833 }
7834
7835 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7836 if (chain != 0) {
7837 chain->decActiveTrackCnt();
7838 chain->decTrackCnt();
7839 }
7840
7841 broadcast_l();
7842
7843 if (mActiveTracks.size() == 0) {
7844 mHalStream->stop();
7845 }
7846 return NO_ERROR;
7847}
7848
7849
7850void AudioFlinger::MmapThread::readHalParameters_l()
7851{
7852 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7853 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7854 mFormat = mHALFormat;
7855 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7856 result = mHalStream->getFrameSize(&mFrameSize);
7857 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7858 result = mHalStream->getBufferSize(&mBufferSize);
7859 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7860 mFrameCount = mBufferSize / mFrameSize;
7861}
7862
7863bool AudioFlinger::MmapThread::threadLoop()
7864{
7865 acquireWakeLock();
7866
7867 checkSilentMode_l();
7868
7869 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7870
7871 while (!exitPending())
7872 {
7873 Mutex::Autolock _l(mLock);
7874 Vector< sp<EffectChain> > effectChains;
7875
7876 if (mSignalPending) {
7877 // A signal was raised while we were unlocked
7878 mSignalPending = false;
7879 } else {
7880 if (mConfigEvents.isEmpty()) {
7881 // we're about to wait, flush the binder command buffer
7882 IPCThreadState::self()->flushCommands();
7883
7884 if (exitPending()) {
7885 break;
7886 }
7887
7888 bool wakelockReleased = false;
7889 if (mActiveTracks.size() == 0) {
7890 releaseWakeLock_l();
7891 wakelockReleased = true;
7892 }
7893 // wait until we have something to do...
7894 ALOGV("%s going to sleep", myName.string());
7895 mWaitWorkCV.wait(mLock);
7896 ALOGV("%s waking up", myName.string());
7897 if (wakelockReleased) {
7898 acquireWakeLock_l();
7899 }
7900
7901 checkSilentMode_l();
7902
7903 continue;
7904 }
7905 }
7906
7907 processConfigEvents_l();
7908
7909 processVolume_l();
7910
7911 checkInvalidTracks_l();
7912
7913 mActiveTracks.updatePowerState(this);
7914
7915 lockEffectChains_l(effectChains);
7916 for (size_t i = 0; i < effectChains.size(); i ++) {
7917 effectChains[i]->process_l();
7918 }
7919 // enable changes in effect chain
7920 unlockEffectChains(effectChains);
7921 // Effect chains will be actually deleted here if they were removed from
7922 // mEffectChains list during mixing or effects processing
7923 }
7924
7925 threadLoop_exit();
7926
7927 if (!mStandby) {
7928 threadLoop_standby();
7929 mStandby = true;
7930 }
7931
7932 releaseWakeLock();
7933
7934 ALOGV("Thread %p type %d exiting", this, mType);
7935 return false;
7936}
7937
7938// checkForNewParameter_l() must be called with ThreadBase::mLock held
7939bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7940 status_t& status)
7941{
7942 AudioParameter param = AudioParameter(keyValuePair);
7943 int value;
7944 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7945 // forward device change to effects that have requested to be
7946 // aware of attached audio device.
7947 if (value != AUDIO_DEVICE_NONE) {
7948 mOutDevice = value;
7949 for (size_t i = 0; i < mEffectChains.size(); i++) {
7950 mEffectChains[i]->setDevice_l(mOutDevice);
7951 }
7952 }
7953 }
7954 status = mHalStream->setParameters(keyValuePair);
7955
7956 return false;
7957}
7958
7959String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7960{
7961 Mutex::Autolock _l(mLock);
7962 String8 out_s8;
7963 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7964 return out_s8;
7965 }
7966 return String8();
7967}
7968
7969void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7970 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7971
7972 desc->mIoHandle = mId;
7973
7974 switch (event) {
7975 case AUDIO_INPUT_OPENED:
7976 case AUDIO_INPUT_CONFIG_CHANGED:
7977 case AUDIO_OUTPUT_OPENED:
7978 case AUDIO_OUTPUT_CONFIG_CHANGED:
7979 desc->mPatch = mPatch;
7980 desc->mChannelMask = mChannelMask;
7981 desc->mSamplingRate = mSampleRate;
7982 desc->mFormat = mFormat;
7983 desc->mFrameCount = mFrameCount;
7984 desc->mFrameCountHAL = mFrameCount;
7985 desc->mLatency = 0;
7986 break;
7987
7988 case AUDIO_INPUT_CLOSED:
7989 case AUDIO_OUTPUT_CLOSED:
7990 default:
7991 break;
7992 }
7993 mAudioFlinger->ioConfigChanged(event, desc, pid);
7994}
7995
7996status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7997 audio_patch_handle_t *handle)
7998{
7999 status_t status = NO_ERROR;
8000
8001 // store new device and send to effects
8002 audio_devices_t type = AUDIO_DEVICE_NONE;
8003 audio_port_handle_t deviceId;
8004 if (isOutput()) {
8005 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8006 type |= patch->sinks[i].ext.device.type;
8007 }
8008 deviceId = patch->sinks[0].id;
8009 } else {
8010 type = patch->sources[0].ext.device.type;
8011 deviceId = patch->sources[0].id;
8012 }
8013
8014 for (size_t i = 0; i < mEffectChains.size(); i++) {
8015 mEffectChains[i]->setDevice_l(type);
8016 }
8017
8018 if (isOutput()) {
8019 mOutDevice = type;
8020 } else {
8021 mInDevice = type;
8022 // store new source and send to effects
8023 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8024 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8025 for (size_t i = 0; i < mEffectChains.size(); i++) {
8026 mEffectChains[i]->setAudioSource_l(mAudioSource);
8027 }
8028 }
8029 }
8030
8031 if (mAudioHwDev->supportsAudioPatches()) {
8032 status = mHalDevice->createAudioPatch(patch->num_sources,
8033 patch->sources,
8034 patch->num_sinks,
8035 patch->sinks,
8036 handle);
8037 } else {
8038 char *address;
8039 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8040 //FIXME: we only support address on first sink with HAL version < 3.0
8041 address = audio_device_address_to_parameter(
8042 patch->sinks[0].ext.device.type,
8043 patch->sinks[0].ext.device.address);
8044 } else {
8045 address = (char *)calloc(1, 1);
8046 }
8047 AudioParameter param = AudioParameter(String8(address));
8048 free(address);
8049 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8050 if (!isOutput()) {
8051 param.addInt(String8(AudioParameter::keyInputSource),
8052 (int)patch->sinks[0].ext.mix.usecase.source);
8053 }
8054 status = mHalStream->setParameters(param.toString());
8055 *handle = AUDIO_PATCH_HANDLE_NONE;
8056 }
8057
8058 if (isOutput() && mPrevOutDevice != mOutDevice) {
8059 mPrevOutDevice = type;
8060 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
8061 if (mCallback != 0) {
8062 mCallback->onRoutingChanged(deviceId);
8063 }
8064 }
8065 if (!isOutput() && mPrevInDevice != mInDevice) {
8066 mPrevInDevice = type;
8067 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8068 if (mCallback != 0) {
8069 mCallback->onRoutingChanged(deviceId);
8070 }
8071 }
8072 return status;
8073}
8074
8075status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8076{
8077 status_t status = NO_ERROR;
8078
8079 mInDevice = AUDIO_DEVICE_NONE;
8080
8081 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8082 supportsAudioPatches : false;
8083
8084 if (supportsAudioPatches) {
8085 status = mHalDevice->releaseAudioPatch(handle);
8086 } else {
8087 AudioParameter param;
8088 param.addInt(String8(AudioParameter::keyRouting), 0);
8089 status = mHalStream->setParameters(param.toString());
8090 }
8091 return status;
8092}
8093
8094void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8095{
8096 ThreadBase::getAudioPortConfig(config);
8097 if (isOutput()) {
8098 config->role = AUDIO_PORT_ROLE_SOURCE;
8099 config->ext.mix.hw_module = mAudioHwDev->handle();
8100 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8101 } else {
8102 config->role = AUDIO_PORT_ROLE_SINK;
8103 config->ext.mix.hw_module = mAudioHwDev->handle();
8104 config->ext.mix.usecase.source = mAudioSource;
8105 }
8106}
8107
8108status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8109{
8110 audio_session_t session = chain->sessionId();
8111
8112 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8113 // Attach all tracks with same session ID to this chain.
8114 // indicate all active tracks in the chain
8115 for (const sp<MmapTrack> &track : mActiveTracks) {
8116 if (session == track->sessionId()) {
8117 chain->incTrackCnt();
8118 chain->incActiveTrackCnt();
8119 }
8120 }
8121
8122 chain->setThread(this);
8123 chain->setInBuffer(nullptr);
8124 chain->setOutBuffer(nullptr);
8125 chain->syncHalEffectsState();
8126
8127 mEffectChains.add(chain);
8128 checkSuspendOnAddEffectChain_l(chain);
8129 return NO_ERROR;
8130}
8131
8132size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8133{
8134 audio_session_t session = chain->sessionId();
8135
8136 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8137
8138 for (size_t i = 0; i < mEffectChains.size(); i++) {
8139 if (chain == mEffectChains[i]) {
8140 mEffectChains.removeAt(i);
8141 // detach all active tracks from the chain
8142 // detach all tracks with same session ID from this chain
8143 for (const sp<MmapTrack> &track : mActiveTracks) {
8144 if (session == track->sessionId()) {
8145 chain->decActiveTrackCnt();
8146 chain->decTrackCnt();
8147 }
8148 }
8149 break;
8150 }
8151 }
8152 return mEffectChains.size();
8153}
8154
8155// hasAudioSession_l() must be called with ThreadBase::mLock held
8156uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8157{
8158 uint32_t result = 0;
8159 if (getEffectChain_l(sessionId) != 0) {
8160 result = EFFECT_SESSION;
8161 }
8162
8163 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8164 sp<MmapTrack> track = mActiveTracks[i];
8165 if (sessionId == track->sessionId()) {
8166 result |= TRACK_SESSION;
8167 if (track->isFastTrack()) {
8168 result |= FAST_SESSION;
8169 }
8170 break;
8171 }
8172 }
8173
8174 return result;
8175}
8176
8177void AudioFlinger::MmapThread::threadLoop_standby()
8178{
8179 mHalStream->standby();
8180}
8181
8182void AudioFlinger::MmapThread::threadLoop_exit()
8183{
8184 if (mCallback != 0) {
8185 mCallback->onTearDown();
8186 }
8187}
8188
8189status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8190{
8191 return BAD_VALUE;
8192}
8193
8194bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8195{
8196 return false;
8197}
8198
8199status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8200 const effect_descriptor_t *desc, audio_session_t sessionId)
8201{
8202 // No global effect sessions on mmap threads
8203 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8204 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8205 desc->name, mThreadName);
8206 return BAD_VALUE;
8207 }
8208
8209 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8210 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8211 desc->name);
8212 return BAD_VALUE;
8213 }
8214 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
8215 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap thread",
8216 desc->name);
8217 return BAD_VALUE;
8218 }
8219
8220 // Only allow effects without processing load or latency
8221 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8222 return BAD_VALUE;
8223 }
8224
8225 return NO_ERROR;
8226
8227}
8228
8229void AudioFlinger::MmapThread::checkInvalidTracks_l()
8230{
8231 for (const sp<MmapTrack> &track : mActiveTracks) {
8232 if (track->isInvalid()) {
8233 if (mCallback != 0) {
8234 mCallback->onTearDown();
8235 }
8236 break;
8237 }
8238 }
8239}
8240
8241void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8242{
8243 dumpInternals(fd, args);
8244 dumpTracks(fd, args);
8245 dumpEffectChains(fd, args);
8246}
8247
8248void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8249{
8250 dprintf(fd, "\nMmap thread %p:\n", this);
8251
8252 dumpBase(fd, args);
8253
8254 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8255 mAttr.content_type, mAttr.usage, mAttr.source);
8256 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8257 if (mActiveTracks.size() == 0) {
8258 dprintf(fd, " No active clients\n");
8259 }
8260}
8261
8262void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8263{
8264 const size_t SIZE = 256;
8265 char buffer[SIZE];
8266 String8 result;
8267
8268 size_t numtracks = mActiveTracks.size();
8269 dprintf(fd, " %zu Tracks", numtracks);
8270 if (numtracks) {
8271 MmapTrack::appendDumpHeader(result);
8272 for (size_t i = 0; i < numtracks ; ++i) {
8273 sp<MmapTrack> track = mActiveTracks[i];
8274 track->dump(buffer, SIZE);
8275 result.append(buffer);
8276 }
8277 } else {
8278 dprintf(fd, "\n");
8279 }
8280 write(fd, result.string(), result.size());
8281}
8282
8283AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8284 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8285 AudioHwDevice *hwDev, AudioStreamOut *output,
8286 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8287 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8288 mStreamType(AUDIO_STREAM_MUSIC),
8289 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8290{
8291 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8292 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8293 mMasterVolume = audioFlinger->masterVolume_l();
8294 mMasterMute = audioFlinger->masterMute_l();
8295 if (mAudioHwDev) {
8296 if (mAudioHwDev->canSetMasterVolume()) {
8297 mMasterVolume = 1.0;
8298 }
8299
8300 if (mAudioHwDev->canSetMasterMute()) {
8301 mMasterMute = false;
8302 }
8303 }
8304}
8305
8306void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8307 audio_stream_type_t streamType,
8308 audio_session_t sessionId,
8309 const sp<MmapStreamCallback>& callback,
8310 audio_port_handle_t portId)
8311{
8312 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8313 mStreamType = streamType;
8314}
8315
8316AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8317{
8318 Mutex::Autolock _l(mLock);
8319 AudioStreamOut *output = mOutput;
8320 mOutput = NULL;
8321 return output;
8322}
8323
8324void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8325{
8326 Mutex::Autolock _l(mLock);
8327 // Don't apply master volume in SW if our HAL can do it for us.
8328 if (mAudioHwDev &&
8329 mAudioHwDev->canSetMasterVolume()) {
8330 mMasterVolume = 1.0;
8331 } else {
8332 mMasterVolume = value;
8333 }
8334}
8335
8336void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8337{
8338 Mutex::Autolock _l(mLock);
8339 // Don't apply master mute in SW if our HAL can do it for us.
8340 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8341 mMasterMute = false;
8342 } else {
8343 mMasterMute = muted;
8344 }
8345}
8346
8347void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8348{
8349 Mutex::Autolock _l(mLock);
8350 if (stream == mStreamType) {
8351 mStreamVolume = value;
8352 broadcast_l();
8353 }
8354}
8355
8356float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8357{
8358 Mutex::Autolock _l(mLock);
8359 if (stream == mStreamType) {
8360 return mStreamVolume;
8361 }
8362 return 0.0f;
8363}
8364
8365void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8366{
8367 Mutex::Autolock _l(mLock);
8368 if (stream == mStreamType) {
8369 mStreamMute= muted;
8370 broadcast_l();
8371 }
8372}
8373
8374void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8375{
8376 Mutex::Autolock _l(mLock);
8377 if (streamType == mStreamType) {
8378 for (const sp<MmapTrack> &track : mActiveTracks) {
8379 track->invalidate();
8380 }
8381 broadcast_l();
8382 }
8383}
8384
8385void AudioFlinger::MmapPlaybackThread::processVolume_l()
8386{
8387 float volume;
8388
8389 if (mMasterMute || mStreamMute) {
8390 volume = 0;
8391 } else {
8392 volume = mMasterVolume * mStreamVolume;
8393 }
8394
8395 if (volume != mHalVolFloat) {
8396 mHalVolFloat = volume;
8397
8398 // Convert volumes from float to 8.24
8399 uint32_t vol = (uint32_t)(volume * (1 << 24));
8400
8401 // Delegate volume control to effect in track effect chain if needed
8402 // only one effect chain can be present on DirectOutputThread, so if
8403 // there is one, the track is connected to it
8404 if (!mEffectChains.isEmpty()) {
8405 mEffectChains[0]->setVolume_l(&vol, &vol);
8406 volume = (float)vol / (1 << 24);
8407 }
8408
8409 mOutput->stream->setVolume(volume, volume);
8410
8411 if (mCallback != 0) {
8412 int channelCount;
8413 if (isOutput()) {
8414 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8415 } else {
8416 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8417 }
8418 Vector<float> values;
8419 for (int i = 0; i < channelCount; i++) {
8420 values.add(volume);
8421 }
8422 mCallback->onVolumeChanged(mChannelMask, values);
8423 }
8424 }
8425}
8426
8427void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8428{
8429 if (!mMasterMute) {
8430 char value[PROPERTY_VALUE_MAX];
8431 if (property_get("ro.audio.silent", value, "0") > 0) {
8432 char *endptr;
8433 unsigned long ul = strtoul(value, &endptr, 0);
8434 if (*endptr == '\0' && ul != 0) {
8435 ALOGD("Silence is golden");
8436 // The setprop command will not allow a property to be changed after
8437 // the first time it is set, so we don't have to worry about un-muting.
8438 setMasterMute_l(true);
8439 }
8440 }
8441 }
8442}
8443
8444void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8445{
8446 MmapThread::dumpInternals(fd, args);
8447
8448 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n", mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
8449 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8450}
8451
8452AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8453 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8454 AudioHwDevice *hwDev, AudioStreamIn *input,
8455 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8456 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8457 mInput(input)
8458{
8459 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8460 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8461}
8462
8463AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8464{
8465 Mutex::Autolock _l(mLock);
8466 AudioStreamIn *input = mInput;
8467 mInput = NULL;
8468 return input;
8469}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008470} // namespace android