blob: a684c1e5fee3bed118733ba48086f8f52a30f270 [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>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Andy Hungd330ee42015-04-20 13:23:41 -070097#ifndef ARRAY_SIZE
98#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
99#endif
100
Eric Laurent81784c32012-11-19 14:55:58 -0800101namespace android {
102
103// retry counts for buffer fill timeout
104// 50 * ~20msecs = 1 second
105static const int8_t kMaxTrackRetries = 50;
106static const int8_t kMaxTrackStartupRetries = 50;
107// allow less retry attempts on direct output thread.
108// direct outputs can be a scarce resource in audio hardware and should
109// be released as quickly as possible.
110static const int8_t kMaxTrackRetriesDirect = 2;
111
112// don't warn about blocked writes or record buffer overflows more often than this
113static const nsecs_t kWarningThrottleNs = seconds(5);
114
115// RecordThread loop sleep time upon application overrun or audio HAL read error
116static const int kRecordThreadSleepUs = 5000;
117
Eric Laurent10351942014-05-08 18:49:52 -0700118// maximum time to wait in sendConfigEvent_l() for a status to be received
119static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// minimum sleep time for the mixer thread loop when tracks are active but in underrun
122static const uint32_t kMinThreadSleepTimeUs = 5000;
123// maximum divider applied to the active sleep time in the mixer thread loop
124static const uint32_t kMaxThreadSleepTimeShift = 2;
125
Andy Hung09a50072014-02-27 14:30:47 -0800126// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700127// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700132// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
133// FIXME This should be based on experimentally observed scheduling jitter
134static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
135
Eric Laurent972a1732013-09-04 09:42:59 -0700136// Offloaded output thread standby delay: allows track transition without going to standby
137static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
138
Eric Laurent81784c32012-11-19 14:55:58 -0800139// Whether to use fast mixer
140static const enum {
141 FastMixer_Never, // never initialize or use: for debugging only
142 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
143 // normal mixer multiplier is 1
144 FastMixer_Static, // initialize if needed, then use all the time if initialized,
145 // multiplier is calculated based on min & max normal mixer buffer size
146 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
147 // multiplier is calculated based on min & max normal mixer buffer size
148 // FIXME for FastMixer_Dynamic:
149 // Supporting this option will require fixing HALs that can't handle large writes.
150 // For example, one HAL implementation returns an error from a large write,
151 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
152 // We could either fix the HAL implementations, or provide a wrapper that breaks
153 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
154} kUseFastMixer = FastMixer_Static;
155
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700156// Whether to use fast capture
157static const enum {
158 FastCapture_Never, // never initialize or use: for debugging only
159 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
160 FastCapture_Static, // initialize if needed, then use all the time if initialized
161} kUseFastCapture = FastCapture_Static;
162
Eric Laurent81784c32012-11-19 14:55:58 -0800163// Priorities for requestPriority
164static const int kPriorityAudioApp = 2;
165static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700166static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800167
168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800170// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
171// So for now we just assume that client is double-buffered for fast tracks.
172// FIXME It would be better for client to tell AudioFlinger the value of N,
173// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800174// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700175
176// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800177static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800178
Glenn Kasten03490092014-05-27 12:30:54 -0700179// The minimum and maximum allowed values
180static const int kFastTrackMultiplierMin = 1;
181static const int kFastTrackMultiplierMax = 2;
182
183// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
184static int sFastTrackMultiplier = kFastTrackMultiplier;
185
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700186// See Thread::readOnlyHeap().
187// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
188// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
189// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700190static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700191
Eric Laurent81784c32012-11-19 14:55:58 -0800192// ----------------------------------------------------------------------------
193
Glenn Kasten03490092014-05-27 12:30:54 -0700194static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
195
196static void sFastTrackMultiplierInit()
197{
198 char value[PROPERTY_VALUE_MAX];
199 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
200 char *endptr;
201 unsigned long ul = strtoul(value, &endptr, 0);
202 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
203 sFastTrackMultiplier = (int) ul;
204 }
205 }
206}
207
208// ----------------------------------------------------------------------------
209
Eric Laurent81784c32012-11-19 14:55:58 -0800210#ifdef ADD_BATTERY_DATA
211// To collect the amplifier usage
212static void addBatteryData(uint32_t params) {
213 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
214 if (service == NULL) {
215 // it already logged
216 return;
217 }
218
219 service->addBatteryData(params);
220}
221#endif
222
Andy Hung3f0c9022016-01-15 17:49:46 -0800223// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
224struct {
225 // call when you acquire a partial wakelock
226 void acquire(const sp<IBinder> &wakeLockToken) {
227 pthread_mutex_lock(&mLock);
228 if (wakeLockToken.get() == nullptr) {
229 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
230 } else {
231 if (mCount == 0) {
232 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
233 }
234 ++mCount;
235 }
236 pthread_mutex_unlock(&mLock);
237 }
238
239 // call when you release a partial wakelock.
240 void release(const sp<IBinder> &wakeLockToken) {
241 if (wakeLockToken.get() == nullptr) {
242 return;
243 }
244 pthread_mutex_lock(&mLock);
245 if (--mCount < 0) {
246 ALOGE("negative wakelock count");
247 mCount = 0;
248 }
249 pthread_mutex_unlock(&mLock);
250 }
251
252 // retrieves the boottime timebase offset from monotonic.
253 int64_t getBoottimeOffset() {
254 pthread_mutex_lock(&mLock);
255 int64_t boottimeOffset = mBoottimeOffset;
256 pthread_mutex_unlock(&mLock);
257 return boottimeOffset;
258 }
259
260 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
261 // and the selected timebase.
262 // Currently only TIMEBASE_BOOTTIME is allowed.
263 //
264 // This only needs to be called upon acquiring the first partial wakelock
265 // after all other partial wakelocks are released.
266 //
267 // We do an empirical measurement of the offset rather than parsing
268 // /proc/timer_list since the latter is not a formal kernel ABI.
269 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
270 int clockbase;
271 switch (timebase) {
272 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
273 clockbase = SYSTEM_TIME_BOOTTIME;
274 break;
275 default:
276 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
277 break;
278 }
279 // try three times to get the clock offset, choose the one
280 // with the minimum gap in measurements.
281 const int tries = 3;
282 nsecs_t bestGap, measured;
283 for (int i = 0; i < tries; ++i) {
284 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
285 const nsecs_t tbase = systemTime(clockbase);
286 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
287 const nsecs_t gap = tmono2 - tmono;
288 if (i == 0 || gap < bestGap) {
289 bestGap = gap;
290 measured = tbase - ((tmono + tmono2) >> 1);
291 }
292 }
293
294 // to avoid micro-adjusting, we don't change the timebase
295 // unless it is significantly different.
296 //
297 // Assumption: It probably takes more than toleranceNs to
298 // suspend and resume the device.
299 static int64_t toleranceNs = 10000; // 10 us
300 if (llabs(*offset - measured) > toleranceNs) {
301 ALOGV("Adjusting timebase offset old: %lld new: %lld",
302 (long long)*offset, (long long)measured);
303 *offset = measured;
304 }
305 }
306
307 pthread_mutex_t mLock;
308 int32_t mCount;
309 int64_t mBoottimeOffset;
310} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800311
312// ----------------------------------------------------------------------------
313// CPU Stats
314// ----------------------------------------------------------------------------
315
316class CpuStats {
317public:
318 CpuStats();
319 void sample(const String8 &title);
320#ifdef DEBUG_CPU_USAGE
321private:
322 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
323 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
324
325 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
326
327 int mCpuNum; // thread's current CPU number
328 int mCpukHz; // frequency of thread's current CPU in kHz
329#endif
330};
331
332CpuStats::CpuStats()
333#ifdef DEBUG_CPU_USAGE
334 : mCpuNum(-1), mCpukHz(-1)
335#endif
336{
337}
338
Glenn Kasten0f11b512014-01-31 16:18:54 -0800339void CpuStats::sample(const String8 &title
340#ifndef DEBUG_CPU_USAGE
341 __unused
342#endif
343 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800344#ifdef DEBUG_CPU_USAGE
345 // get current thread's delta CPU time in wall clock ns
346 double wcNs;
347 bool valid = mCpuUsage.sampleAndEnable(wcNs);
348
349 // record sample for wall clock statistics
350 if (valid) {
351 mWcStats.sample(wcNs);
352 }
353
354 // get the current CPU number
355 int cpuNum = sched_getcpu();
356
357 // get the current CPU frequency in kHz
358 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
359
360 // check if either CPU number or frequency changed
361 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
362 mCpuNum = cpuNum;
363 mCpukHz = cpukHz;
364 // ignore sample for purposes of cycles
365 valid = false;
366 }
367
368 // if no change in CPU number or frequency, then record sample for cycle statistics
369 if (valid && mCpukHz > 0) {
370 double cycles = wcNs * cpukHz * 0.000001;
371 mHzStats.sample(cycles);
372 }
373
374 unsigned n = mWcStats.n();
375 // mCpuUsage.elapsed() is expensive, so don't call it every loop
376 if ((n & 127) == 1) {
377 long long elapsed = mCpuUsage.elapsed();
378 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
379 double perLoop = elapsed / (double) n;
380 double perLoop100 = perLoop * 0.01;
381 double perLoop1k = perLoop * 0.001;
382 double mean = mWcStats.mean();
383 double stddev = mWcStats.stddev();
384 double minimum = mWcStats.minimum();
385 double maximum = mWcStats.maximum();
386 double meanCycles = mHzStats.mean();
387 double stddevCycles = mHzStats.stddev();
388 double minCycles = mHzStats.minimum();
389 double maxCycles = mHzStats.maximum();
390 mCpuUsage.resetElapsed();
391 mWcStats.reset();
392 mHzStats.reset();
393 ALOGD("CPU usage for %s over past %.1f secs\n"
394 " (%u mixer loops at %.1f mean ms per loop):\n"
395 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
396 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
397 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
398 title.string(),
399 elapsed * .000000001, n, perLoop * .000001,
400 mean * .001,
401 stddev * .001,
402 minimum * .001,
403 maximum * .001,
404 mean / perLoop100,
405 stddev / perLoop100,
406 minimum / perLoop100,
407 maximum / perLoop100,
408 meanCycles / perLoop1k,
409 stddevCycles / perLoop1k,
410 minCycles / perLoop1k,
411 maxCycles / perLoop1k);
412
413 }
414 }
415#endif
416};
417
418// ----------------------------------------------------------------------------
419// ThreadBase
420// ----------------------------------------------------------------------------
421
Glenn Kasten97b7b752014-09-28 13:04:24 -0700422// static
423const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
424{
425 switch (type) {
426 case MIXER:
427 return "MIXER";
428 case DIRECT:
429 return "DIRECT";
430 case DUPLICATING:
431 return "DUPLICATING";
432 case RECORD:
433 return "RECORD";
434 case OFFLOAD:
435 return "OFFLOAD";
436 default:
437 return "unknown";
438 }
439}
440
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800441String8 devicesToString(audio_devices_t devices)
442{
443 static const struct mapping {
444 audio_devices_t mDevices;
445 const char * mString;
446 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800447 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
448 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
449 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
450 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
451 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
452 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
453 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
454 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
455 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
456 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
457 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
458 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
459 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
460 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
461 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
462 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
463 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
464 {AUDIO_DEVICE_OUT_LINE, "LINE"},
465 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
466 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
467 {AUDIO_DEVICE_OUT_FM, "FM"},
468 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
469 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
470 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800471 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800472 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800473 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800474 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
475 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
476 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
477 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
478 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
479 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
480 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
481 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
482 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
483 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
484 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
485 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
486 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
487 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
488 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
489 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
490 {AUDIO_DEVICE_IN_LINE, "LINE"},
491 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
492 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
493 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
494 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800495 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800496 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800497 };
498 String8 result;
499 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
500 const mapping *entry;
501 if (devices & AUDIO_DEVICE_BIT_IN) {
502 devices &= ~AUDIO_DEVICE_BIT_IN;
503 entry = mappingsIn;
504 } else {
505 entry = mappingsOut;
506 }
507 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
508 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
509 if (devices & entry->mDevices) {
510 if (!result.isEmpty()) {
511 result.append("|");
512 }
513 result.append(entry->mString);
514 }
515 }
516 if (devices & ~allDevices) {
517 if (!result.isEmpty()) {
518 result.append("|");
519 }
520 result.appendFormat("0x%X", devices & ~allDevices);
521 }
522 if (result.isEmpty()) {
523 result.append(entry->mString);
524 }
525 return result;
526}
527
528String8 inputFlagsToString(audio_input_flags_t flags)
529{
530 static const struct mapping {
531 audio_input_flags_t mFlag;
532 const char * mString;
533 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800534 {AUDIO_INPUT_FLAG_FAST, "FAST"},
535 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
536 {AUDIO_INPUT_FLAG_RAW, "RAW"},
537 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
538 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800539 };
540 String8 result;
541 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
542 const mapping *entry;
543 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
544 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
545 if (flags & entry->mFlag) {
546 if (!result.isEmpty()) {
547 result.append("|");
548 }
549 result.append(entry->mString);
550 }
551 }
552 if (flags & ~allFlags) {
553 if (!result.isEmpty()) {
554 result.append("|");
555 }
556 result.appendFormat("0x%X", flags & ~allFlags);
557 }
558 if (result.isEmpty()) {
559 result.append(entry->mString);
560 }
561 return result;
562}
563
564String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700565{
566 static const struct mapping {
567 audio_output_flags_t mFlag;
568 const char * mString;
569 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800570 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
571 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
572 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
573 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
574 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
575 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
576 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
577 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
578 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
579 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
580 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700581 };
582 String8 result;
583 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
584 const mapping *entry;
585 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
586 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
587 if (flags & entry->mFlag) {
588 if (!result.isEmpty()) {
589 result.append("|");
590 }
591 result.append(entry->mString);
592 }
593 }
594 if (flags & ~allFlags) {
595 if (!result.isEmpty()) {
596 result.append("|");
597 }
598 result.appendFormat("0x%X", flags & ~allFlags);
599 }
600 if (result.isEmpty()) {
601 result.append(entry->mString);
602 }
603 return result;
604}
605
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800606const char *sourceToString(audio_source_t source)
607{
608 switch (source) {
609 case AUDIO_SOURCE_DEFAULT: return "default";
610 case AUDIO_SOURCE_MIC: return "mic";
611 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
612 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
613 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
614 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
615 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
616 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
617 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800618 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800619 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
620 case AUDIO_SOURCE_HOTWORD: return "hotword";
621 default: return "unknown";
622 }
623}
624
Eric Laurent81784c32012-11-19 14:55:58 -0800625AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700626 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800627 : Thread(false /*canCallJava*/),
628 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700629 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700630 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800631 // are set by PlaybackThread::readOutputParameters_l() or
632 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700633 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800634 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700635 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
636 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800637 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700638 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800639 mSystemReady(systemReady),
640 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800641{
Eric Laurent296fb132015-05-01 11:38:42 -0700642 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800643}
644
645AudioFlinger::ThreadBase::~ThreadBase()
646{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700647 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700648 mConfigEvents.clear();
649
Eric Laurent81784c32012-11-19 14:55:58 -0800650 // do not lock the mutex in destructor
651 releaseWakeLock_l();
652 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800653 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800654 binder->unlinkToDeath(mDeathRecipient);
655 }
656}
657
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700658status_t AudioFlinger::ThreadBase::readyToRun()
659{
660 status_t status = initCheck();
661 if (status == NO_ERROR) {
662 ALOGI("AudioFlinger's thread %p ready to run", this);
663 } else {
664 ALOGE("No working audio driver found.");
665 }
666 return status;
667}
668
Eric Laurent81784c32012-11-19 14:55:58 -0800669void AudioFlinger::ThreadBase::exit()
670{
671 ALOGV("ThreadBase::exit");
672 // do any cleanup required for exit to succeed
673 preExit();
674 {
675 // This lock prevents the following race in thread (uniprocessor for illustration):
676 // if (!exitPending()) {
677 // // context switch from here to exit()
678 // // exit() calls requestExit(), what exitPending() observes
679 // // exit() calls signal(), which is dropped since no waiters
680 // // context switch back from exit() to here
681 // mWaitWorkCV.wait(...);
682 // // now thread is hung
683 // }
684 AutoMutex lock(mLock);
685 requestExit();
686 mWaitWorkCV.broadcast();
687 }
688 // When Thread::requestExitAndWait is made virtual and this method is renamed to
689 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
690 requestExitAndWait();
691}
692
693status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
694{
695 status_t status;
696
697 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
698 Mutex::Autolock _l(mLock);
699
Eric Laurent10351942014-05-08 18:49:52 -0700700 return sendSetParameterConfigEvent_l(keyValuePairs);
701}
702
703// sendConfigEvent_l() must be called with ThreadBase::mLock held
704// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
705status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
706{
707 status_t status = NO_ERROR;
708
Eric Laurent72e3f392015-05-20 14:43:50 -0700709 if (event->mRequiresSystemReady && !mSystemReady) {
710 event->mWaitStatus = false;
711 mPendingConfigEvents.add(event);
712 return status;
713 }
Eric Laurent10351942014-05-08 18:49:52 -0700714 mConfigEvents.add(event);
715 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800716 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700717 mLock.unlock();
718 {
719 Mutex::Autolock _l(event->mLock);
720 while (event->mWaitStatus) {
721 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
722 event->mStatus = TIMED_OUT;
723 event->mWaitStatus = false;
724 }
725 }
726 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800729 return status;
730}
731
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700732void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800733{
734 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700735 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800736}
737
738// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700739void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800740{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700741 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700742 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800743}
744
Eric Laurent72e3f392015-05-20 14:43:50 -0700745void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
746{
747 Mutex::Autolock _l(mLock);
748 sendPrioConfigEvent_l(pid, tid, prio);
749}
750
Eric Laurent81784c32012-11-19 14:55:58 -0800751// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
752void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
753{
Eric Laurent10351942014-05-08 18:49:52 -0700754 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
755 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800756}
757
Eric Laurent10351942014-05-08 18:49:52 -0700758// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
759status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800760{
Andy Hung2ddee192015-12-18 17:34:44 -0800761 sp<ConfigEvent> configEvent;
762 AudioParameter param(keyValuePair);
763 int value;
764 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
765 setMasterMono_l(value != 0);
766 if (param.size() == 1) {
767 return NO_ERROR; // should be a solo parameter - we don't pass down
768 }
769 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
770 configEvent = new SetParameterConfigEvent(param.toString());
771 } else {
772 configEvent = new SetParameterConfigEvent(keyValuePair);
773 }
Eric Laurent10351942014-05-08 18:49:52 -0700774 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700775}
776
Eric Laurent1c333e22014-05-20 10:48:17 -0700777status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
778 const struct audio_patch *patch,
779 audio_patch_handle_t *handle)
780{
781 Mutex::Autolock _l(mLock);
782 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
783 status_t status = sendConfigEvent_l(configEvent);
784 if (status == NO_ERROR) {
785 CreateAudioPatchConfigEventData *data =
786 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
787 *handle = data->mHandle;
788 }
789 return status;
790}
791
792status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
793 const audio_patch_handle_t handle)
794{
795 Mutex::Autolock _l(mLock);
796 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
797 return sendConfigEvent_l(configEvent);
798}
799
800
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700801// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700802void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700803{
Eric Laurent10351942014-05-08 18:49:52 -0700804 bool configChanged = false;
805
Eric Laurent81784c32012-11-19 14:55:58 -0800806 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700807 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
808 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800809 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700810 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700811 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700812 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
813 // FIXME Need to understand why this has to be done asynchronously
814 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700815 true /*asynchronous*/);
816 if (err != 0) {
817 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700818 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700819 }
820 } break;
821 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700822 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700823 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700824 } break;
825 case CFG_EVENT_SET_PARAMETER: {
826 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
827 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
828 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700829 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700831 case CFG_EVENT_CREATE_AUDIO_PATCH: {
832 CreateAudioPatchConfigEventData *data =
833 (CreateAudioPatchConfigEventData *)event->mData.get();
834 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
835 } break;
836 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
837 ReleaseAudioPatchConfigEventData *data =
838 (ReleaseAudioPatchConfigEventData *)event->mData.get();
839 event->mStatus = releaseAudioPatch_l(data->mHandle);
840 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700841 default:
Eric Laurent10351942014-05-08 18:49:52 -0700842 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700843 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800844 }
Eric Laurent10351942014-05-08 18:49:52 -0700845 {
846 Mutex::Autolock _l(event->mLock);
847 if (event->mWaitStatus) {
848 event->mWaitStatus = false;
849 event->mCond.signal();
850 }
851 }
852 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
853 }
854
855 if (configChanged) {
856 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
Eric Laurent81784c32012-11-19 14:55:58 -0800858}
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
861 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700862 const audio_channel_representation_t representation =
863 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700864
865 switch (representation) {
866 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
867 if (output) {
868 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
869 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
870 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
871 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
872 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
873 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
874 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
875 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
876 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
878 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
879 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
880 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
881 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
885 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
886 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
887 } else {
888 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
889 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
890 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
891 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
892 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
893 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
894 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
895 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
896 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
897 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
898 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
899 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
900 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
901 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
902 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
903 }
904 const int len = s.length();
905 if (len > 2) {
906 char *str = s.lockBuffer(len); // needed?
907 s.unlockBuffer(len - 2); // remove trailing ", "
908 }
909 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800910 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700911 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
912 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
913 return s;
914 default:
915 s.appendFormat("unknown mask, representation:%d bits:%#x",
916 representation, audio_channel_mask_get_bits(mask));
917 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800918 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800919}
920
Glenn Kasten0f11b512014-01-31 16:18:54 -0800921void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800922{
923 const size_t SIZE = 256;
924 char buffer[SIZE];
925 String8 result;
926
927 bool locked = AudioFlinger::dumpTryLock(mLock);
928 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700929 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
931
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800932 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700933 dprintf(fd, " I/O handle: %d\n", mId);
934 dprintf(fd, " TID: %d\n", getTid());
935 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700936 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700937 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700938 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700939 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700940 dprintf(fd, " Channel count: %u\n", mChannelCount);
941 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800942 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700943 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
944 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700945 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 size_t numConfig = mConfigEvents.size();
947 if (numConfig) {
948 for (size_t i = 0; i < numConfig; i++) {
949 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800953 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800955 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800956 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
957 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
958 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800959
960 if (locked) {
961 mLock.unlock();
962 }
963}
964
965void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
966{
967 const size_t SIZE = 256;
968 char buffer[SIZE];
969 String8 result;
970
Marco Nelissenb2208842014-02-07 14:00:50 -0800971 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000972 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800973 write(fd, buffer, strlen(buffer));
974
Marco Nelissenb2208842014-02-07 14:00:50 -0800975 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800976 sp<EffectChain> chain = mEffectChains[i];
977 if (chain != 0) {
978 chain->dump(fd, args);
979 }
980 }
981}
982
Marco Nelissene14a5d62013-10-03 08:51:24 -0700983void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
985 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700986 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800987}
988
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100989String16 AudioFlinger::ThreadBase::getWakeLockTag()
990{
991 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800992 case MIXER:
993 return String16("AudioMix");
994 case DIRECT:
995 return String16("AudioDirectOut");
996 case DUPLICATING:
997 return String16("AudioDup");
998 case RECORD:
999 return String16("AudioIn");
1000 case OFFLOAD:
1001 return String16("AudioOffload");
1002 default:
1003 ALOG_ASSERT(false);
1004 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001005 }
1006}
1007
Marco Nelissene14a5d62013-10-03 08:51:24 -07001008void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001009{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001010 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001011 if (mPowerManager != 0) {
1012 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001013 status_t status;
1014 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001015 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001016 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001017 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001018 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001019 uid,
1020 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001021 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001022 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001024 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001025 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001026 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001027 }
Eric Laurent81784c32012-11-19 14:55:58 -08001028 if (status == NO_ERROR) {
1029 mWakeLockToken = binder;
1030 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001031 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001032 }
Wei Jia3f273d12015-11-24 09:06:49 -08001033
1034 if (!mNotifiedBatteryStart) {
1035 BatteryNotifier::getInstance().noteStartAudio();
1036 mNotifiedBatteryStart = true;
1037 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001038 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001039 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1040 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001041}
1042
1043void AudioFlinger::ThreadBase::releaseWakeLock()
1044{
1045 Mutex::Autolock _l(mLock);
1046 releaseWakeLock_l();
1047}
1048
1049void AudioFlinger::ThreadBase::releaseWakeLock_l()
1050{
Andy Hung3f0c9022016-01-15 17:49:46 -08001051 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001052 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001053 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001054 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001055 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1056 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001057 }
1058 mWakeLockToken.clear();
1059 }
Wei Jia3f273d12015-11-24 09:06:49 -08001060
1061 if (mNotifiedBatteryStart) {
1062 BatteryNotifier::getInstance().noteStopAudio();
1063 mNotifiedBatteryStart = false;
1064 }
Eric Laurent81784c32012-11-19 14:55:58 -08001065}
1066
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001067void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1068 Mutex::Autolock _l(mLock);
1069 updateWakeLockUids_l(uids);
1070}
1071
1072void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001073 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001074 // use checkService() to avoid blocking if power service is not up yet
1075 sp<IBinder> binder =
1076 defaultServiceManager()->checkService(String16("power"));
1077 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001078 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001079 } else {
1080 mPowerManager = interface_cast<IPowerManager>(binder);
1081 binder->linkToDeath(mDeathRecipient);
1082 }
1083 }
1084}
1085
1086void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001087 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001088 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1089 if (mSystemReady) {
1090 ALOGE("no wake lock to update, but system ready!");
1091 } else {
1092 ALOGW("no wake lock to update, system not ready yet");
1093 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 return;
1095 }
1096 if (mPowerManager != 0) {
1097 sp<IBinder> binder = new BBinder();
1098 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001099 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1100 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -08001101 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 }
1103}
1104
Eric Laurent81784c32012-11-19 14:55:58 -08001105void AudioFlinger::ThreadBase::clearPowerManager()
1106{
1107 Mutex::Autolock _l(mLock);
1108 releaseWakeLock_l();
1109 mPowerManager.clear();
1110}
1111
Glenn Kasten0f11b512014-01-31 16:18:54 -08001112void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001113{
1114 sp<ThreadBase> thread = mThread.promote();
1115 if (thread != 0) {
1116 thread->clearPowerManager();
1117 }
1118 ALOGW("power manager service died !!!");
1119}
1120
1121void AudioFlinger::ThreadBase::setEffectSuspended(
1122 const effect_uuid_t *type, bool suspend, int sessionId)
1123{
1124 Mutex::Autolock _l(mLock);
1125 setEffectSuspended_l(type, suspend, sessionId);
1126}
1127
1128void AudioFlinger::ThreadBase::setEffectSuspended_l(
1129 const effect_uuid_t *type, bool suspend, int sessionId)
1130{
1131 sp<EffectChain> chain = getEffectChain_l(sessionId);
1132 if (chain != 0) {
1133 if (type != NULL) {
1134 chain->setEffectSuspended_l(type, suspend);
1135 } else {
1136 chain->setEffectSuspendedAll_l(suspend);
1137 }
1138 }
1139
1140 updateSuspendedSessions_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1144{
1145 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1146 if (index < 0) {
1147 return;
1148 }
1149
1150 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1151 mSuspendedSessions.valueAt(index);
1152
1153 for (size_t i = 0; i < sessionEffects.size(); i++) {
1154 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1155 for (int j = 0; j < desc->mRefCount; j++) {
1156 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1157 chain->setEffectSuspendedAll_l(true);
1158 } else {
1159 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1160 desc->mType.timeLow);
1161 chain->setEffectSuspended_l(&desc->mType, true);
1162 }
1163 }
1164 }
1165}
1166
1167void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1168 bool suspend,
1169 int sessionId)
1170{
1171 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1172
1173 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1174
1175 if (suspend) {
1176 if (index >= 0) {
1177 sessionEffects = mSuspendedSessions.valueAt(index);
1178 } else {
1179 mSuspendedSessions.add(sessionId, sessionEffects);
1180 }
1181 } else {
1182 if (index < 0) {
1183 return;
1184 }
1185 sessionEffects = mSuspendedSessions.valueAt(index);
1186 }
1187
1188
1189 int key = EffectChain::kKeyForSuspendAll;
1190 if (type != NULL) {
1191 key = type->timeLow;
1192 }
1193 index = sessionEffects.indexOfKey(key);
1194
1195 sp<SuspendedSessionDesc> desc;
1196 if (suspend) {
1197 if (index >= 0) {
1198 desc = sessionEffects.valueAt(index);
1199 } else {
1200 desc = new SuspendedSessionDesc();
1201 if (type != NULL) {
1202 desc->mType = *type;
1203 }
1204 sessionEffects.add(key, desc);
1205 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1206 }
1207 desc->mRefCount++;
1208 } else {
1209 if (index < 0) {
1210 return;
1211 }
1212 desc = sessionEffects.valueAt(index);
1213 if (--desc->mRefCount == 0) {
1214 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1215 sessionEffects.removeItemsAt(index);
1216 if (sessionEffects.isEmpty()) {
1217 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1218 sessionId);
1219 mSuspendedSessions.removeItem(sessionId);
1220 }
1221 }
1222 }
1223 if (!sessionEffects.isEmpty()) {
1224 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1225 }
1226}
1227
1228void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1229 bool enabled,
1230 int sessionId)
1231{
1232 Mutex::Autolock _l(mLock);
1233 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1234}
1235
1236void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1237 bool enabled,
1238 int sessionId)
1239{
1240 if (mType != RECORD) {
1241 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1242 // another session. This gives the priority to well behaved effect control panels
1243 // and applications not using global effects.
1244 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1245 // global effects
1246 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1247 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1248 }
1249 }
1250
1251 sp<EffectChain> chain = getEffectChain_l(sessionId);
1252 if (chain != 0) {
1253 chain->checkSuspendOnEffectEnabled(effect, enabled);
1254 }
1255}
1256
1257// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1258sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1259 const sp<AudioFlinger::Client>& client,
1260 const sp<IEffectClient>& effectClient,
1261 int32_t priority,
1262 int sessionId,
1263 effect_descriptor_t *desc,
1264 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001265 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001266{
1267 sp<EffectModule> effect;
1268 sp<EffectHandle> handle;
1269 status_t lStatus;
1270 sp<EffectChain> chain;
1271 bool chainCreated = false;
1272 bool effectCreated = false;
1273 bool effectRegistered = false;
1274
1275 lStatus = initCheck();
1276 if (lStatus != NO_ERROR) {
1277 ALOGW("createEffect_l() Audio driver not initialized.");
1278 goto Exit;
1279 }
1280
Andy Hung98ef9782014-03-04 14:46:50 -08001281 // Reject any effect on Direct output threads for now, since the format of
1282 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1283 if (mType == DIRECT) {
1284 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001285 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001286 lStatus = BAD_VALUE;
1287 goto Exit;
1288 }
1289
Andy Hung389cfdb2014-08-07 17:49:53 -07001290 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001291 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001292 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1293 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1294 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001295 lStatus = BAD_VALUE;
1296 goto Exit;
1297 }
1298
Eric Laurent5baf2af2013-09-12 17:37:00 -07001299 // Allow global effects only on offloaded and mixer threads
1300 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1301 switch (mType) {
1302 case MIXER:
1303 case OFFLOAD:
1304 break;
1305 case DIRECT:
1306 case DUPLICATING:
1307 case RECORD:
1308 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001309 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1310 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001311 lStatus = BAD_VALUE;
1312 goto Exit;
1313 }
Eric Laurent81784c32012-11-19 14:55:58 -08001314 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001315
Eric Laurent81784c32012-11-19 14:55:58 -08001316 // Only Pre processor effects are allowed on input threads and only on input threads
1317 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1318 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1319 desc->name, desc->flags, mType);
1320 lStatus = BAD_VALUE;
1321 goto Exit;
1322 }
1323
1324 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1325
1326 { // scope for mLock
1327 Mutex::Autolock _l(mLock);
1328
1329 // check for existing effect chain with the requested audio session
1330 chain = getEffectChain_l(sessionId);
1331 if (chain == 0) {
1332 // create a new chain for this session
1333 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1334 chain = new EffectChain(this, sessionId);
1335 addEffectChain_l(chain);
1336 chain->setStrategy(getStrategyForSession_l(sessionId));
1337 chainCreated = true;
1338 } else {
1339 effect = chain->getEffectFromDesc_l(desc);
1340 }
1341
1342 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1343
1344 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001345 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001346 // Check CPU and memory usage
1347 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1348 if (lStatus != NO_ERROR) {
1349 goto Exit;
1350 }
1351 effectRegistered = true;
1352 // create a new effect module if none present in the chain
1353 effect = new EffectModule(this, chain, desc, id, sessionId);
1354 lStatus = effect->status();
1355 if (lStatus != NO_ERROR) {
1356 goto Exit;
1357 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001358 effect->setOffloaded(mType == OFFLOAD, mId);
1359
Eric Laurent81784c32012-11-19 14:55:58 -08001360 lStatus = chain->addEffect_l(effect);
1361 if (lStatus != NO_ERROR) {
1362 goto Exit;
1363 }
1364 effectCreated = true;
1365
1366 effect->setDevice(mOutDevice);
1367 effect->setDevice(mInDevice);
1368 effect->setMode(mAudioFlinger->getMode());
1369 effect->setAudioSource(mAudioSource);
1370 }
1371 // create effect handle and connect it to effect module
1372 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001373 lStatus = handle->initCheck();
1374 if (lStatus == OK) {
1375 lStatus = effect->addHandle(handle.get());
1376 }
Eric Laurent81784c32012-11-19 14:55:58 -08001377 if (enabled != NULL) {
1378 *enabled = (int)effect->isEnabled();
1379 }
1380 }
1381
1382Exit:
1383 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1384 Mutex::Autolock _l(mLock);
1385 if (effectCreated) {
1386 chain->removeEffect_l(effect);
1387 }
1388 if (effectRegistered) {
1389 AudioSystem::unregisterEffect(effect->id());
1390 }
1391 if (chainCreated) {
1392 removeEffectChain_l(chain);
1393 }
1394 handle.clear();
1395 }
1396
Glenn Kasten9156ef32013-08-06 15:39:08 -07001397 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001398 return handle;
1399}
1400
1401sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1402{
1403 Mutex::Autolock _l(mLock);
1404 return getEffect_l(sessionId, effectId);
1405}
1406
1407sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1408{
1409 sp<EffectChain> chain = getEffectChain_l(sessionId);
1410 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1411}
1412
1413// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1414// PlaybackThread::mLock held
1415status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1416{
1417 // check for existing effect chain with the requested audio session
1418 int sessionId = effect->sessionId();
1419 sp<EffectChain> chain = getEffectChain_l(sessionId);
1420 bool chainCreated = false;
1421
Eric Laurent5baf2af2013-09-12 17:37:00 -07001422 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1423 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1424 this, effect->desc().name, effect->desc().flags);
1425
Eric Laurent81784c32012-11-19 14:55:58 -08001426 if (chain == 0) {
1427 // create a new chain for this session
1428 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1429 chain = new EffectChain(this, sessionId);
1430 addEffectChain_l(chain);
1431 chain->setStrategy(getStrategyForSession_l(sessionId));
1432 chainCreated = true;
1433 }
1434 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1435
1436 if (chain->getEffectFromId_l(effect->id()) != 0) {
1437 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1438 this, effect->desc().name, chain.get());
1439 return BAD_VALUE;
1440 }
1441
Eric Laurent5baf2af2013-09-12 17:37:00 -07001442 effect->setOffloaded(mType == OFFLOAD, mId);
1443
Eric Laurent81784c32012-11-19 14:55:58 -08001444 status_t status = chain->addEffect_l(effect);
1445 if (status != NO_ERROR) {
1446 if (chainCreated) {
1447 removeEffectChain_l(chain);
1448 }
1449 return status;
1450 }
1451
1452 effect->setDevice(mOutDevice);
1453 effect->setDevice(mInDevice);
1454 effect->setMode(mAudioFlinger->getMode());
1455 effect->setAudioSource(mAudioSource);
1456 return NO_ERROR;
1457}
1458
1459void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1460
1461 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1462 effect_descriptor_t desc = effect->desc();
1463 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1464 detachAuxEffect_l(effect->id());
1465 }
1466
1467 sp<EffectChain> chain = effect->chain().promote();
1468 if (chain != 0) {
1469 // remove effect chain if removing last effect
1470 if (chain->removeEffect_l(effect) == 0) {
1471 removeEffectChain_l(chain);
1472 }
1473 } else {
1474 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1475 }
1476}
1477
1478void AudioFlinger::ThreadBase::lockEffectChains_l(
1479 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1480{
1481 effectChains = mEffectChains;
1482 for (size_t i = 0; i < mEffectChains.size(); i++) {
1483 mEffectChains[i]->lock();
1484 }
1485}
1486
1487void AudioFlinger::ThreadBase::unlockEffectChains(
1488 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1489{
1490 for (size_t i = 0; i < effectChains.size(); i++) {
1491 effectChains[i]->unlock();
1492 }
1493}
1494
1495sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1496{
1497 Mutex::Autolock _l(mLock);
1498 return getEffectChain_l(sessionId);
1499}
1500
1501sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1502{
1503 size_t size = mEffectChains.size();
1504 for (size_t i = 0; i < size; i++) {
1505 if (mEffectChains[i]->sessionId() == sessionId) {
1506 return mEffectChains[i];
1507 }
1508 }
1509 return 0;
1510}
1511
1512void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1513{
1514 Mutex::Autolock _l(mLock);
1515 size_t size = mEffectChains.size();
1516 for (size_t i = 0; i < size; i++) {
1517 mEffectChains[i]->setMode_l(mode);
1518 }
1519}
1520
Eric Laurent83b88082014-06-20 18:31:16 -07001521void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1522{
1523 config->type = AUDIO_PORT_TYPE_MIX;
1524 config->ext.mix.handle = mId;
1525 config->sample_rate = mSampleRate;
1526 config->format = mFormat;
1527 config->channel_mask = mChannelMask;
1528 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1529 AUDIO_PORT_CONFIG_FORMAT;
1530}
1531
Eric Laurent72e3f392015-05-20 14:43:50 -07001532void AudioFlinger::ThreadBase::systemReady()
1533{
1534 Mutex::Autolock _l(mLock);
1535 if (mSystemReady) {
1536 return;
1537 }
1538 mSystemReady = true;
1539
1540 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1541 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1542 }
1543 mPendingConfigEvents.clear();
1544}
1545
Eric Laurent83b88082014-06-20 18:31:16 -07001546
Eric Laurent81784c32012-11-19 14:55:58 -08001547// ----------------------------------------------------------------------------
1548// Playback
1549// ----------------------------------------------------------------------------
1550
1551AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1552 AudioStreamOut* output,
1553 audio_io_handle_t id,
1554 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001555 type_t type,
1556 bool systemReady)
1557 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001558 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001559 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001560 mMixerBuffer(NULL),
1561 mMixerBufferSize(0),
1562 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1563 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001564 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001565 mEffectBuffer(NULL),
1566 mEffectBufferSize(0),
1567 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1568 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001569 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001570 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001571 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001572 // mStreamTypes[] initialized in constructor body
1573 mOutput(output),
1574 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1575 mMixerStatus(MIXER_IDLE),
1576 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001577 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001578 mBytesRemaining(0),
1579 mCurrentWriteLength(0),
1580 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001581 mWriteAckSequence(0),
1582 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001583 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001584 mScreenState(AudioFlinger::mScreenState),
1585 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001586 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001587 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001588{
Glenn Kastend7dca052015-03-05 16:05:54 -08001589 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1590 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001591
1592 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1593 // it would be safer to explicitly pass initial masterVolume/masterMute as
1594 // parameter.
1595 //
1596 // If the HAL we are using has support for master volume or master mute,
1597 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1598 // and the mute set to false).
1599 mMasterVolume = audioFlinger->masterVolume_l();
1600 mMasterMute = audioFlinger->masterMute_l();
1601 if (mOutput && mOutput->audioHwDev) {
1602 if (mOutput->audioHwDev->canSetMasterVolume()) {
1603 mMasterVolume = 1.0;
1604 }
1605
1606 if (mOutput->audioHwDev->canSetMasterMute()) {
1607 mMasterMute = false;
1608 }
1609 }
1610
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001611 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001612
Eric Laurent223fd5c2014-11-11 13:43:36 -08001613 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001614 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001615 stream = (audio_stream_type_t) (stream + 1)) {
1616 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1617 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1618 }
Eric Laurent81784c32012-11-19 14:55:58 -08001619}
1620
1621AudioFlinger::PlaybackThread::~PlaybackThread()
1622{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001623 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001624 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001625 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001626 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001627}
1628
1629void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1630{
1631 dumpInternals(fd, args);
1632 dumpTracks(fd, args);
1633 dumpEffectChains(fd, args);
1634}
1635
Glenn Kasten0f11b512014-01-31 16:18:54 -08001636void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001637{
1638 const size_t SIZE = 256;
1639 char buffer[SIZE];
1640 String8 result;
1641
Marco Nelissenb2208842014-02-07 14:00:50 -08001642 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001643 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1644 const stream_type_t *st = &mStreamTypes[i];
1645 if (i > 0) {
1646 result.appendFormat(", ");
1647 }
1648 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1649 if (st->mute) {
1650 result.append("M");
1651 }
1652 }
1653 result.append("\n");
1654 write(fd, result.string(), result.length());
1655 result.clear();
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1658 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001659 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001660 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001661
1662 size_t numtracks = mTracks.size();
1663 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001664 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001665 size_t numactiveseen = 0;
1666 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001667 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001668 Track::appendDumpHeader(result);
1669 for (size_t i = 0; i < numtracks; ++i) {
1670 sp<Track> track = mTracks[i];
1671 if (track != 0) {
1672 bool active = mActiveTracks.indexOf(track) >= 0;
1673 if (active) {
1674 numactiveseen++;
1675 }
1676 track->dump(buffer, SIZE, active);
1677 result.append(buffer);
1678 }
1679 }
1680 } else {
1681 result.append("\n");
1682 }
1683 if (numactiveseen != numactive) {
1684 // some tracks in the active list were not in the tracks list
1685 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1686 " not in the track list\n");
1687 result.append(buffer);
1688 Track::appendDumpHeader(result);
1689 for (size_t i = 0; i < numactive; ++i) {
1690 sp<Track> track = mActiveTracks[i].promote();
1691 if (track != 0 && mTracks.indexOf(track) < 0) {
1692 track->dump(buffer, SIZE, true);
1693 result.append(buffer);
1694 }
1695 }
1696 }
1697
1698 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001699}
1700
1701void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1702{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001703 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001704
1705 dumpBase(fd, args);
1706
Elliott Hughes87cebad2014-05-22 10:14:43 -07001707 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1708 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1709 dprintf(fd, " Total writes: %d\n", mNumWrites);
1710 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1711 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1712 dprintf(fd, " Suspend count: %d\n", mSuspended);
1713 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1714 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1715 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1716 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001717 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001718 AudioStreamOut *output = mOutput;
1719 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1720 String8 flagsAsString = outputFlagsToString(flags);
1721 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001722}
1723
1724// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001725
1726void AudioFlinger::PlaybackThread::onFirstRef()
1727{
Glenn Kastend7dca052015-03-05 16:05:54 -08001728 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001729}
1730
1731// ThreadBase virtuals
1732void AudioFlinger::PlaybackThread::preExit()
1733{
1734 ALOGV(" preExit()");
1735 // FIXME this is using hard-coded strings but in the future, this functionality will be
1736 // converted to use audio HAL extensions required to support tunneling
1737 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1738}
1739
1740// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1741sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1742 const sp<AudioFlinger::Client>& client,
1743 audio_stream_type_t streamType,
1744 uint32_t sampleRate,
1745 audio_format_t format,
1746 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001747 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001748 const sp<IMemory>& sharedBuffer,
1749 int sessionId,
1750 IAudioFlinger::track_flags_t *flags,
1751 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001752 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001753 status_t *status)
1754{
Glenn Kasten74935e42013-12-19 08:56:45 -08001755 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001756 sp<Track> track;
1757 status_t lStatus;
1758
Eric Laurent81784c32012-11-19 14:55:58 -08001759 // client expresses a preference for FAST, but we get the final say
1760 if (*flags & IAudioFlinger::TRACK_FAST) {
1761 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001762 // either of these use cases:
1763 (
1764 // use case 1: shared buffer with any frame count
1765 (
1766 (sharedBuffer != 0)
1767 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001768 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001769 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001770 // we formerly checked for a callback handler (non-0 tid),
1771 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001772 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001773 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001774 )
1775 ) &&
1776 // PCM data
1777 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001778 // TODO: extract as a data library function that checks that a computationally
1779 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001780 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001781 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1782 (channelMask == AUDIO_CHANNEL_OUT_MONO
1783 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001784 // hardware sample rate
1785 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001786 // normal mixer has an associated fast mixer
1787 hasFastMixer() &&
1788 // there are sufficient fast track slots available
1789 (mFastTrackAvailMask != 0)
1790 // FIXME test that MixerThread for this fast track has a capable output HAL
1791 // FIXME add a permission test also?
1792 ) {
1793 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1794 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001795 // read the fast track multiplier property the first time it is needed
1796 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1797 if (ok != 0) {
1798 ALOGE("%s pthread_once failed: %d", __func__, ok);
1799 }
1800 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001801 }
1802 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1803 frameCount, mFrameCount);
1804 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001805 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001806 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1807 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001808 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001809 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001810 audio_is_linear_pcm(format),
1811 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1812 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001813 }
1814 }
1815 // For normal PCM streaming tracks, update minimum frame count.
1816 // For compatibility with AudioTrack calculation, buffer depth is forced
1817 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1818 // This is probably too conservative, but legacy application code may depend on it.
1819 // If you change this calculation, also review the start threshold which is related.
1820 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001821 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001822 // this must match AudioTrack.cpp calculateMinFrameCount().
1823 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001824 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1825 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1826 if (minBufCount < 2) {
1827 minBufCount = 2;
1828 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001829 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1830 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001831 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001832 minBufCount * sourceFramesNeededWithTimestretch(
1833 sampleRate, mNormalFrameCount,
1834 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001835 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001836 frameCount = minFrameCount;
1837 }
Eric Laurent81784c32012-11-19 14:55:58 -08001838 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001839 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001840
Glenn Kastenc3df8382014-03-13 15:05:25 -07001841 switch (mType) {
1842
1843 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001844 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001845 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001846 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1847 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001848 sampleRate, format, channelMask, mOutput, mFormat);
1849 lStatus = BAD_VALUE;
1850 goto Exit;
1851 }
1852 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001853 break;
1854
1855 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001857 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1858 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859 sampleRate, format, channelMask, mOutput, mFormat);
1860 lStatus = BAD_VALUE;
1861 goto Exit;
1862 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001863 break;
1864
1865 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001866 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001867 ALOGE("createTrack_l() Bad parameter: format %#x \""
1868 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 format, mOutput, mFormat);
1870 lStatus = BAD_VALUE;
1871 goto Exit;
1872 }
Andy Hungcd044842014-08-07 11:04:34 -07001873 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001874 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1875 lStatus = BAD_VALUE;
1876 goto Exit;
1877 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001878 break;
1879
Eric Laurent81784c32012-11-19 14:55:58 -08001880 }
1881
1882 lStatus = initCheck();
1883 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001884 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001885 goto Exit;
1886 }
1887
1888 { // scope for mLock
1889 Mutex::Autolock _l(mLock);
1890
1891 // all tracks in same audio session must share the same routing strategy otherwise
1892 // conflicts will happen when tracks are moved from one output to another by audio policy
1893 // manager
1894 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1895 for (size_t i = 0; i < mTracks.size(); ++i) {
1896 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001897 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001898 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1899 if (sessionId == t->sessionId() && strategy != actual) {
1900 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1901 strategy, actual);
1902 lStatus = BAD_VALUE;
1903 goto Exit;
1904 }
1905 }
1906 }
1907
Glenn Kastend79072e2016-01-06 08:41:20 -08001908 track = new Track(this, client, streamType, sampleRate, format,
1909 channelMask, frameCount, NULL, sharedBuffer,
1910 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001911
Glenn Kasten03003332013-08-06 15:40:54 -07001912 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1913 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001914 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001915 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001916 goto Exit;
1917 }
1918 mTracks.add(track);
1919
1920 sp<EffectChain> chain = getEffectChain_l(sessionId);
1921 if (chain != 0) {
1922 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1923 track->setMainBuffer(chain->inBuffer());
1924 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1925 chain->incTrackCnt();
1926 }
1927
1928 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1929 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1930 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1931 // so ask activity manager to do this on our behalf
1932 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1933 }
1934 }
1935
1936 lStatus = NO_ERROR;
1937
1938Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001939 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001940 return track;
1941}
1942
1943uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1944{
1945 return latency;
1946}
1947
1948uint32_t AudioFlinger::PlaybackThread::latency() const
1949{
1950 Mutex::Autolock _l(mLock);
1951 return latency_l();
1952}
1953uint32_t AudioFlinger::PlaybackThread::latency_l() const
1954{
1955 if (initCheck() == NO_ERROR) {
1956 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1957 } else {
1958 return 0;
1959 }
1960}
1961
1962void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1963{
1964 Mutex::Autolock _l(mLock);
1965 // Don't apply master volume in SW if our HAL can do it for us.
1966 if (mOutput && mOutput->audioHwDev &&
1967 mOutput->audioHwDev->canSetMasterVolume()) {
1968 mMasterVolume = 1.0;
1969 } else {
1970 mMasterVolume = value;
1971 }
1972}
1973
1974void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1975{
1976 Mutex::Autolock _l(mLock);
1977 // Don't apply master mute in SW if our HAL can do it for us.
1978 if (mOutput && mOutput->audioHwDev &&
1979 mOutput->audioHwDev->canSetMasterMute()) {
1980 mMasterMute = false;
1981 } else {
1982 mMasterMute = muted;
1983 }
1984}
1985
1986void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1987{
1988 Mutex::Autolock _l(mLock);
1989 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001990 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001991}
1992
1993void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1994{
1995 Mutex::Autolock _l(mLock);
1996 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001997 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001998}
1999
2000float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2001{
2002 Mutex::Autolock _l(mLock);
2003 return mStreamTypes[stream].volume;
2004}
2005
2006// addTrack_l() must be called with ThreadBase::mLock held
2007status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2008{
2009 status_t status = ALREADY_EXISTS;
2010
2011 // set retry count for buffer fill
2012 track->mRetryCount = kMaxTrackStartupRetries;
2013 if (mActiveTracks.indexOf(track) < 0) {
2014 // the track is newly added, make sure it fills up all its
2015 // buffers before playing. This is to ensure the client will
2016 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002017 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002018 TrackBase::track_state state = track->mState;
2019 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002020 status = AudioSystem::startOutput(mId, track->streamType(),
2021 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022 mLock.lock();
2023 // abort track was stopped/paused while we released the lock
2024 if (state != track->mState) {
2025 if (status == NO_ERROR) {
2026 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002027 AudioSystem::stopOutput(mId, track->streamType(),
2028 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029 mLock.lock();
2030 }
2031 return INVALID_OPERATION;
2032 }
2033 // abort if start is rejected by audio policy manager
2034 if (status != NO_ERROR) {
2035 return PERMISSION_DENIED;
2036 }
2037#ifdef ADD_BATTERY_DATA
2038 // to track the speaker usage
2039 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2040#endif
2041 }
2042
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002043 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002044 track->mResetDone = false;
2045 track->mPresentationCompleteFrames = 0;
2046 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002047 mWakeLockUids.add(track->uid());
2048 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002049 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002050 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2051 if (chain != 0) {
2052 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2053 track->sessionId());
2054 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002055 }
2056
2057 status = NO_ERROR;
2058 }
2059
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002060 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002061 return status;
2062}
2063
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002065{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002067 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2069 track->mState = TrackBase::STOPPED;
2070 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002071 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002072 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002074 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002075
2076 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002077}
2078
2079void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2080{
2081 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2082 mTracks.remove(track);
2083 deleteTrackName_l(track->name());
2084 // redundant as track is about to be destroyed, for dumpsys only
2085 track->mName = -1;
2086 if (track->isFastTrack()) {
2087 int index = track->mFastIndex;
2088 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2089 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2090 mFastTrackAvailMask |= 1 << index;
2091 // redundant as track is about to be destroyed, for dumpsys only
2092 track->mFastIndex = -1;
2093 }
2094 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2095 if (chain != 0) {
2096 chain->decTrackCnt();
2097 }
2098}
2099
Eric Laurentede6c3b2013-09-19 14:37:46 -07002100void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101{
2102 // Thread could be blocked waiting for async
2103 // so signal it to handle state changes immediately
2104 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2105 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2106 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002107 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002108}
2109
Eric Laurent81784c32012-11-19 14:55:58 -08002110String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2111{
Eric Laurent81784c32012-11-19 14:55:58 -08002112 Mutex::Autolock _l(mLock);
2113 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002114 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002115 }
2116
Glenn Kastend8ea6992013-07-16 14:17:15 -07002117 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2118 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002119 free(s);
2120 return out_s8;
2121}
2122
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002123void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002124 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2125 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002126
Eric Laurent73e26b62015-04-27 16:55:58 -07002127 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002128
2129 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002130 case AUDIO_OUTPUT_OPENED:
2131 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002132 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002133 desc->mChannelMask = mChannelMask;
2134 desc->mSamplingRate = mSampleRate;
2135 desc->mFormat = mFormat;
2136 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002137 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002138 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002139 break;
2140
Eric Laurent73e26b62015-04-27 16:55:58 -07002141 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002142 default:
2143 break;
2144 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002145 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002146}
2147
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148void AudioFlinger::PlaybackThread::writeCallback()
2149{
2150 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002151 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152}
2153
2154void AudioFlinger::PlaybackThread::drainCallback()
2155{
2156 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002157 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158}
2159
Eric Laurent3b4529e2013-09-05 18:09:19 -07002160void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002161{
2162 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002163 // reject out of sequence requests
2164 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2165 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 mWaitWorkCV.signal();
2167 }
2168}
2169
Eric Laurent3b4529e2013-09-05 18:09:19 -07002170void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171{
2172 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002173 // reject out of sequence requests
2174 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2175 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176 mWaitWorkCV.signal();
2177 }
2178}
2179
2180// static
2181int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002182 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002183 void *cookie)
2184{
2185 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2186 ALOGV("asyncCallback() event %d", event);
2187 switch (event) {
2188 case STREAM_CBK_EVENT_WRITE_READY:
2189 me->writeCallback();
2190 break;
2191 case STREAM_CBK_EVENT_DRAIN_READY:
2192 me->drainCallback();
2193 break;
2194 default:
2195 ALOGW("asyncCallback() unknown event %d", event);
2196 break;
2197 }
2198 return 0;
2199}
2200
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002201void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002202{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002203 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002204 mSampleRate = mOutput->getSampleRate();
2205 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002206 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002207 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002208 }
Andy Hung9a592762014-07-21 21:56:01 -07002209 if ((mType == MIXER || mType == DUPLICATING)
2210 && !isValidPcmSinkChannelMask(mChannelMask)) {
2211 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2212 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002213 }
Andy Hunge5412692014-05-16 11:25:07 -07002214 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002215
2216 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002217 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002218 // Get format from the shim, which will be different than the HAL format
2219 // if playing compressed audio over HDMI passthrough.
2220 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002221 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002222 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002223 }
Andy Hung6146c082014-03-18 11:56:15 -07002224 if ((mType == MIXER || mType == DUPLICATING)
2225 && !isValidPcmSinkFormat(mFormat)) {
2226 LOG_FATAL("HAL format %#x not supported for mixed output",
2227 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002228 }
Phil Burk062e67a2015-02-11 13:40:50 -08002229 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002230 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2231 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002232 if (mFrameCount & 15) {
2233 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2234 mFrameCount);
2235 }
2236
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2238 (mOutput->stream->set_callback != NULL)) {
2239 if (mOutput->stream->set_callback(mOutput->stream,
2240 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2241 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002242 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243 }
2244 }
2245
Eric Laurentd1f69b02014-12-15 14:33:13 -08002246 mHwSupportsPause = false;
2247 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2248 if (mOutput->stream->pause != NULL) {
2249 if (mOutput->stream->resume != NULL) {
2250 mHwSupportsPause = true;
2251 } else {
2252 ALOGW("direct output implements pause but not resume");
2253 }
2254 } else if (mOutput->stream->resume != NULL) {
2255 ALOGW("direct output implements resume but not pause");
2256 }
2257 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002258 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2259 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2260 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002261
Andy Hungfbfc3952015-01-15 13:33:51 -08002262 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2263 // For best precision, we use float instead of the associated output
2264 // device format (typically PCM 16 bit).
2265
2266 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2267 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2268 mBufferSize = mFrameSize * mFrameCount;
2269
2270 // TODO: We currently use the associated output device channel mask and sample rate.
2271 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2272 // (if a valid mask) to avoid premature downmix.
2273 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2274 // instead of the output device sample rate to avoid loss of high frequency information.
2275 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2276 }
2277
Andy Hung09a50072014-02-27 14:30:47 -08002278 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002279 double multiplier = 1.0;
2280 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2281 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002282 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2283 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002284 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2285 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2286 maxNormalFrameCount = maxNormalFrameCount & ~15;
2287 if (maxNormalFrameCount < minNormalFrameCount) {
2288 maxNormalFrameCount = minNormalFrameCount;
2289 }
2290 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2291 if (multiplier <= 1.0) {
2292 multiplier = 1.0;
2293 } else if (multiplier <= 2.0) {
2294 if (2 * mFrameCount <= maxNormalFrameCount) {
2295 multiplier = 2.0;
2296 } else {
2297 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2298 }
2299 } else {
2300 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002301 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // track, but we sometimes have to do this to satisfy the maximum frame count
2303 // constraint)
2304 // FIXME this rounding up should not be done if no HAL SRC
2305 uint32_t truncMult = (uint32_t) multiplier;
2306 if ((truncMult & 1)) {
2307 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2308 ++truncMult;
2309 }
2310 }
2311 multiplier = (double) truncMult;
2312 }
2313 }
2314 mNormalFrameCount = multiplier * mFrameCount;
2315 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002316 if (mType == MIXER || mType == DUPLICATING) {
2317 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2318 }
Andy Hung09a50072014-02-27 14:30:47 -08002319 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002320 mNormalFrameCount);
2321
Andy Hung08fb1742015-05-31 23:22:10 -07002322 // Check if we want to throttle the processing to no more than 2x normal rate
2323 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002324 mThreadThrottleTimeMs = 0;
2325 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002326 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2327
Andy Hung010a1a12014-03-13 13:57:33 -07002328 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2329 // Originally this was int16_t[] array, need to remove legacy implications.
2330 free(mSinkBuffer);
2331 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002332 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2333 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2334 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002335 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002336
Andy Hung69aed5f2014-02-25 17:24:40 -08002337 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2338 // drives the output.
2339 free(mMixerBuffer);
2340 mMixerBuffer = NULL;
2341 if (mMixerBufferEnabled) {
2342 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2343 mMixerBufferSize = mNormalFrameCount * mChannelCount
2344 * audio_bytes_per_sample(mMixerBufferFormat);
2345 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2346 }
Andy Hung98ef9782014-03-04 14:46:50 -08002347 free(mEffectBuffer);
2348 mEffectBuffer = NULL;
2349 if (mEffectBufferEnabled) {
2350 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2351 mEffectBufferSize = mNormalFrameCount * mChannelCount
2352 * audio_bytes_per_sample(mEffectBufferFormat);
2353 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2354 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002355
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // force reconfiguration of effect chains and engines to take new buffer size and audio
2357 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002358 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002359 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2360 // matter.
2361 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2362 Vector< sp<EffectChain> > effectChains = mEffectChains;
2363 for (size_t i = 0; i < effectChains.size(); i ++) {
2364 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2365 }
2366}
2367
2368
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002369status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002370{
2371 if (halFrames == NULL || dspFrames == NULL) {
2372 return BAD_VALUE;
2373 }
2374 Mutex::Autolock _l(mLock);
2375 if (initCheck() != NO_ERROR) {
2376 return INVALID_OPERATION;
2377 }
Andy Hung818e7a32016-02-16 18:08:07 -08002378 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002379 *halFrames = framesWritten;
2380
2381 if (isSuspended()) {
2382 // return an estimation of rendered frames when the output is suspended
2383 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002384 *dspFrames = (uint32_t)
2385 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002386 return NO_ERROR;
2387 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002388 status_t status;
2389 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002390 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002391 *dspFrames = (size_t)frames;
2392 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002393 }
2394}
2395
2396uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2397{
2398 Mutex::Autolock _l(mLock);
2399 uint32_t result = 0;
2400 if (getEffectChain_l(sessionId) != 0) {
2401 result = EFFECT_SESSION;
2402 }
2403
2404 for (size_t i = 0; i < mTracks.size(); ++i) {
2405 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002406 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002407 result |= TRACK_SESSION;
2408 break;
2409 }
2410 }
2411
2412 return result;
2413}
2414
2415uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2416{
2417 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2418 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2419 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2420 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2421 }
2422 for (size_t i = 0; i < mTracks.size(); i++) {
2423 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002424 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002425 return AudioSystem::getStrategyForStream(track->streamType());
2426 }
2427 }
2428 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2429}
2430
2431
Phil Burk062e67a2015-02-11 13:40:50 -08002432AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002433{
2434 Mutex::Autolock _l(mLock);
2435 return mOutput;
2436}
2437
Phil Burk062e67a2015-02-11 13:40:50 -08002438AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002439{
2440 Mutex::Autolock _l(mLock);
2441 AudioStreamOut *output = mOutput;
2442 mOutput = NULL;
2443 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2444 // must push a NULL and wait for ack
2445 mOutputSink.clear();
2446 mPipeSink.clear();
2447 mNormalSink.clear();
2448 return output;
2449}
2450
2451// this method must always be called either with ThreadBase mLock held or inside the thread loop
2452audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2453{
2454 if (mOutput == NULL) {
2455 return NULL;
2456 }
2457 return &mOutput->stream->common;
2458}
2459
2460uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2461{
2462 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2463}
2464
2465status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2466{
2467 if (!isValidSyncEvent(event)) {
2468 return BAD_VALUE;
2469 }
2470
2471 Mutex::Autolock _l(mLock);
2472
2473 for (size_t i = 0; i < mTracks.size(); ++i) {
2474 sp<Track> track = mTracks[i];
2475 if (event->triggerSession() == track->sessionId()) {
2476 (void) track->setSyncEvent(event);
2477 return NO_ERROR;
2478 }
2479 }
2480
2481 return NAME_NOT_FOUND;
2482}
2483
2484bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2485{
2486 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2487}
2488
2489void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2490 const Vector< sp<Track> >& tracksToRemove)
2491{
2492 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002493 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002494 for (size_t i = 0 ; i < count ; i++) {
2495 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002496 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002497 AudioSystem::stopOutput(mId, track->streamType(),
2498 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002499#ifdef ADD_BATTERY_DATA
2500 // to track the speaker usage
2501 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2502#endif
2503 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002504 AudioSystem::releaseOutput(mId, track->streamType(),
2505 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506 }
Eric Laurent81784c32012-11-19 14:55:58 -08002507 }
2508 }
2509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510}
2511
2512void AudioFlinger::PlaybackThread::checkSilentMode_l()
2513{
2514 if (!mMasterMute) {
2515 char value[PROPERTY_VALUE_MAX];
2516 if (property_get("ro.audio.silent", value, "0") > 0) {
2517 char *endptr;
2518 unsigned long ul = strtoul(value, &endptr, 0);
2519 if (*endptr == '\0' && ul != 0) {
2520 ALOGD("Silence is golden");
2521 // The setprop command will not allow a property to be changed after
2522 // the first time it is set, so we don't have to worry about un-muting.
2523 setMasterMute_l(true);
2524 }
2525 }
2526 }
2527}
2528
2529// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002531{
2532 // FIXME rewrite to reduce number of system calls
2533 mLastWriteTime = systemTime();
2534 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002536 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002537
2538 // If an NBAIO sink is present, use it to write the normal mixer's submix
2539 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002540
Andy Hung010a1a12014-03-13 13:57:33 -07002541 const size_t count = mBytesRemaining / mFrameSize;
2542
Simon Wilson2d590962012-11-29 15:18:50 -08002543 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002544 // update the setpoint when AudioFlinger::mScreenState changes
2545 uint32_t screenState = AudioFlinger::mScreenState;
2546 if (screenState != mScreenState) {
2547 mScreenState = screenState;
2548 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2549 if (pipe != NULL) {
2550 pipe->setAvgFrames((mScreenState & 1) ?
2551 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2552 }
2553 }
Andy Hung010a1a12014-03-13 13:57:33 -07002554 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002555 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002556 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002557 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002558 } else {
2559 bytesWritten = framesWritten;
2560 }
2561 // otherwise use the HAL / AudioStreamOut directly
2562 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002564
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002566 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2567 mWriteAckSequence += 2;
2568 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002569 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002570 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002571 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002572 // FIXME We should have an implementation of timestamps for direct output threads.
2573 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002574 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 if (mUseAsyncWrite &&
2576 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2577 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002578 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002580 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 }
Eric Laurent81784c32012-11-19 14:55:58 -08002582 }
2583
Eric Laurent81784c32012-11-19 14:55:58 -08002584 mNumWrites++;
2585 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002586 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 return bytesWritten;
2588}
2589
2590void AudioFlinger::PlaybackThread::threadLoop_drain()
2591{
2592 if (mOutput->stream->drain) {
2593 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2594 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002595 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2596 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 }
2600 mOutput->stream->drain(mOutput->stream,
2601 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2602 : AUDIO_DRAIN_ALL);
2603 }
2604}
2605
2606void AudioFlinger::PlaybackThread::threadLoop_exit()
2607{
Eric Laurent275e8e92014-11-30 15:14:47 -08002608 {
2609 Mutex::Autolock _l(mLock);
2610 for (size_t i = 0; i < mTracks.size(); i++) {
2611 sp<Track> track = mTracks[i];
2612 track->invalidate();
2613 }
2614 }
Eric Laurent81784c32012-11-19 14:55:58 -08002615}
2616
2617/*
2618The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002619 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002620 - mActiveSleepTimeUs from activeSleepTimeUs()
2621 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002622 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2623 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002624 - maxPeriod from frame count and sample rate (MIXER only)
2625
2626The parameters that affect these derived values are:
2627 - frame count
2628 - frame size
2629 - sample rate
2630 - device type: A2DP or not
2631 - device latency
2632 - format: PCM or not
2633 - active sleep time
2634 - idle sleep time
2635*/
2636
2637void AudioFlinger::PlaybackThread::cacheParameters_l()
2638{
Andy Hung25c2dac2014-02-27 14:56:00 -08002639 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002640 mActiveSleepTimeUs = activeSleepTimeUs();
2641 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002642
2643 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2644 // truncating audio when going to standby.
2645 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2646 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2647 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2648 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2649 }
2650 }
Eric Laurent81784c32012-11-19 14:55:58 -08002651}
2652
2653void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2654{
Glenn Kasten7c027242012-12-26 14:43:16 -08002655 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002656 this, streamType, mTracks.size());
2657 Mutex::Autolock _l(mLock);
2658
2659 size_t size = mTracks.size();
2660 for (size_t i = 0; i < size; i++) {
2661 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002662 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002663 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002664 }
2665 }
2666}
2667
2668status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2669{
2670 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002671 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2672 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002673 bool ownsBuffer = false;
2674
2675 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2676 if (session > 0) {
2677 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002678 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002679 if (mType != DIRECT) {
2680 size_t numSamples = mNormalFrameCount * mChannelCount;
2681 buffer = new int16_t[numSamples];
2682 memset(buffer, 0, numSamples * sizeof(int16_t));
2683 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2684 ownsBuffer = true;
2685 }
2686
2687 // Attach all tracks with same session ID to this chain.
2688 for (size_t i = 0; i < mTracks.size(); ++i) {
2689 sp<Track> track = mTracks[i];
2690 if (session == track->sessionId()) {
2691 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2692 buffer);
2693 track->setMainBuffer(buffer);
2694 chain->incTrackCnt();
2695 }
2696 }
2697
2698 // indicate all active tracks in the chain
2699 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2700 sp<Track> track = mActiveTracks[i].promote();
2701 if (track == 0) {
2702 continue;
2703 }
2704 if (session == track->sessionId()) {
2705 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2706 chain->incActiveTrackCnt();
2707 }
2708 }
2709 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002710 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002711 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002712 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2713 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002714 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2715 // chains list in order to be processed last as it contains output stage effects
2716 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2717 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2718 // after track specific effects and before output stage
2719 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2720 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2721 // Effect chain for other sessions are inserted at beginning of effect
2722 // chains list to be processed before output mix effects. Relative order between other
2723 // sessions is not important
2724 size_t size = mEffectChains.size();
2725 size_t i = 0;
2726 for (i = 0; i < size; i++) {
2727 if (mEffectChains[i]->sessionId() < session) {
2728 break;
2729 }
2730 }
2731 mEffectChains.insertAt(chain, i);
2732 checkSuspendOnAddEffectChain_l(chain);
2733
2734 return NO_ERROR;
2735}
2736
2737size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2738{
2739 int session = chain->sessionId();
2740
2741 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2742
2743 for (size_t i = 0; i < mEffectChains.size(); i++) {
2744 if (chain == mEffectChains[i]) {
2745 mEffectChains.removeAt(i);
2746 // detach all active tracks from the chain
2747 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2748 sp<Track> track = mActiveTracks[i].promote();
2749 if (track == 0) {
2750 continue;
2751 }
2752 if (session == track->sessionId()) {
2753 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2754 chain.get(), session);
2755 chain->decActiveTrackCnt();
2756 }
2757 }
2758
2759 // detach all tracks with same session ID from this chain
2760 for (size_t i = 0; i < mTracks.size(); ++i) {
2761 sp<Track> track = mTracks[i];
2762 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002763 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002764 chain->decTrackCnt();
2765 }
2766 }
2767 break;
2768 }
2769 }
2770 return mEffectChains.size();
2771}
2772
2773status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2774 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2775{
2776 Mutex::Autolock _l(mLock);
2777 return attachAuxEffect_l(track, EffectId);
2778}
2779
2780status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2781 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2782{
2783 status_t status = NO_ERROR;
2784
2785 if (EffectId == 0) {
2786 track->setAuxBuffer(0, NULL);
2787 } else {
2788 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2789 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2790 if (effect != 0) {
2791 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2792 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2793 } else {
2794 status = INVALID_OPERATION;
2795 }
2796 } else {
2797 status = BAD_VALUE;
2798 }
2799 }
2800 return status;
2801}
2802
2803void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2804{
2805 for (size_t i = 0; i < mTracks.size(); ++i) {
2806 sp<Track> track = mTracks[i];
2807 if (track->auxEffectId() == effectId) {
2808 attachAuxEffect_l(track, 0);
2809 }
2810 }
2811}
2812
2813bool AudioFlinger::PlaybackThread::threadLoop()
2814{
2815 Vector< sp<Track> > tracksToRemove;
2816
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002817 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002818
2819 // MIXER
2820 nsecs_t lastWarning = 0;
2821
2822 // DUPLICATING
2823 // FIXME could this be made local to while loop?
2824 writeFrames = 0;
2825
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002826 int lastGeneration = 0;
2827
Eric Laurent81784c32012-11-19 14:55:58 -08002828 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002829 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002830
2831 if (mType == MIXER) {
2832 sleepTimeShift = 0;
2833 }
2834
2835 CpuStats cpuStats;
2836 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2837
2838 acquireWakeLock();
2839
Glenn Kasten9e58b552013-01-18 15:09:48 -08002840 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2841 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2842 // and then that string will be logged at the next convenient opportunity.
2843 const char *logString = NULL;
2844
Eric Laurent664539d2013-09-23 18:24:31 -07002845 checkSilentMode_l();
2846
Eric Laurent81784c32012-11-19 14:55:58 -08002847 while (!exitPending())
2848 {
2849 cpuStats.sample(myName);
2850
2851 Vector< sp<EffectChain> > effectChains;
2852
Eric Laurent81784c32012-11-19 14:55:58 -08002853 { // scope for mLock
2854
2855 Mutex::Autolock _l(mLock);
2856
Eric Laurent021cf962014-05-13 10:18:14 -07002857 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002858
Glenn Kasten9e58b552013-01-18 15:09:48 -08002859 if (logString != NULL) {
2860 mNBLogWriter->logTimestamp();
2861 mNBLogWriter->log(logString);
2862 logString = NULL;
2863 }
2864
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002865 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002866 // and associate with the sink frames written out. We need
2867 // this to convert the sink timestamp to the track timestamp.
2868 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002869 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002870 // We always fetch the timestamp here because often the downstream
2871 // sink will block whie writing.
2872 ExtendedTimestamp timestamp; // use private copy to fetch
2873 (void) mNormalSink->getTimestamp(timestamp);
2874 // copy over kernel info
2875 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2876 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2877 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2878 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002879 }
2880 // mFramesWritten for non-offloaded tracks are contiguous
2881 // even after standby() is called. This is useful for the track frame
2882 // to sink frame mapping.
2883 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2884 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2885 const size_t size = mActiveTracks.size();
2886 for (size_t i = 0; i < size; ++i) {
2887 sp<Track> t = mActiveTracks[i].promote();
2888 if (t != 0 && !t->isFastTrack()) {
2889 t->updateTrackFrameInfo(
2890 t->mAudioTrackServerProxy->framesReleased(),
2891 mFramesWritten,
2892 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002893 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002894 }
2895
Eric Laurent81784c32012-11-19 14:55:58 -08002896 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 if (mSignalPending) {
2898 // A signal was raised while we were unlocked
2899 mSignalPending = false;
2900 } else if (waitingAsyncCallback_l()) {
2901 if (exitPending()) {
2902 break;
2903 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002904 bool released = false;
2905 // The following works around a bug in the offload driver. Ideally we would release
2906 // the wake lock every time, but that causes the last offload buffer(s) to be
2907 // dropped while the device is on battery, so we need to hold a wake lock during
2908 // the drain phase.
2909 if (mBytesRemaining && !(mDrainSequence & 1)) {
2910 releaseWakeLock_l();
2911 released = true;
2912 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002913 mWakeLockUids.clear();
2914 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 ALOGV("wait async completion");
2916 mWaitWorkCV.wait(mLock);
2917 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002918 if (released) {
2919 acquireWakeLock_l();
2920 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002921 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2922 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002923
2924 continue;
2925 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002926 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002927 isSuspended()) {
2928 // put audio hardware into standby after short delay
2929 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002930
2931 threadLoop_standby();
2932
2933 mStandby = true;
2934 }
2935
2936 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2937 // we're about to wait, flush the binder command buffer
2938 IPCThreadState::self()->flushCommands();
2939
2940 clearOutputTracks();
2941
2942 if (exitPending()) {
2943 break;
2944 }
2945
2946 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002947 mWakeLockUids.clear();
2948 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002949 // wait until we have something to do...
2950 ALOGV("%s going to sleep", myName.string());
2951 mWaitWorkCV.wait(mLock);
2952 ALOGV("%s waking up", myName.string());
2953 acquireWakeLock_l();
2954
2955 mMixerStatus = MIXER_IDLE;
2956 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2957 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002959 checkSilentMode_l();
2960
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002961 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2962 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002963 if (mType == MIXER) {
2964 sleepTimeShift = 0;
2965 }
2966
2967 continue;
2968 }
2969 }
Eric Laurent81784c32012-11-19 14:55:58 -08002970 // mMixerStatusIgnoringFastTracks is also updated internally
2971 mMixerStatus = prepareTracks_l(&tracksToRemove);
2972
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002973 // compare with previously applied list
2974 if (lastGeneration != mActiveTracksGeneration) {
2975 // update wakelock
2976 updateWakeLockUids_l(mWakeLockUids);
2977 lastGeneration = mActiveTracksGeneration;
2978 }
2979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 // prevent any changes in effect chain list and in each effect chain
2981 // during mixing and effect process as the audio buffers could be deleted
2982 // or modified if an effect is created or deleted
2983 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002984 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002985
Eric Laurentbfb1b832013-01-07 09:53:42 -08002986 if (mBytesRemaining == 0) {
2987 mCurrentWriteLength = 0;
2988 if (mMixerStatus == MIXER_TRACKS_READY) {
2989 // threadLoop_mix() sets mCurrentWriteLength
2990 threadLoop_mix();
2991 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2992 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002993 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002994 // must be written to HAL
2995 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002996 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002997 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 }
2999 }
Andy Hung98ef9782014-03-04 14:46:50 -08003000 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003001 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003002 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3003 // or mSinkBuffer (if there are no effects).
3004 //
3005 // This is done pre-effects computation; if effects change to
3006 // support higher precision, this needs to move.
3007 //
3008 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003009 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003010 if (mMixerBufferValid) {
3011 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3012 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3013
Andy Hung2ddee192015-12-18 17:34:44 -08003014 // mono blend occurs for mixer threads only (not direct or offloaded)
3015 // and is handled here if we're going directly to the sink.
3016 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003017 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3018 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003019 }
3020
Andy Hung98ef9782014-03-04 14:46:50 -08003021 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3022 mNormalFrameCount * mChannelCount);
3023 }
3024
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025 mBytesRemaining = mCurrentWriteLength;
3026 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003027 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003029 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003030 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003031 mBytesRemaining = 0;
3032 }
Eric Laurent81784c32012-11-19 14:55:58 -08003033
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003035 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003036 for (size_t i = 0; i < effectChains.size(); i ++) {
3037 effectChains[i]->process_l();
3038 }
Eric Laurent81784c32012-11-19 14:55:58 -08003039 }
3040 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003041 // Process effect chains for offloaded thread even if no audio
3042 // was read from audio track: process only updates effect state
3043 // and thus does have to be synchronized with audio writes but may have
3044 // to be called while waiting for async write callback
3045 if (mType == OFFLOAD) {
3046 for (size_t i = 0; i < effectChains.size(); i ++) {
3047 effectChains[i]->process_l();
3048 }
3049 }
Eric Laurent81784c32012-11-19 14:55:58 -08003050
Andy Hung98ef9782014-03-04 14:46:50 -08003051 // Only if the Effects buffer is enabled and there is data in the
3052 // Effects buffer (buffer valid), we need to
3053 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003054 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003055 if (mEffectBufferValid) {
3056 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003057
3058 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003059 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3060 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003061 }
3062
Andy Hung98ef9782014-03-04 14:46:50 -08003063 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3064 mNormalFrameCount * mChannelCount);
3065 }
3066
Eric Laurent81784c32012-11-19 14:55:58 -08003067 // enable changes in effect chain
3068 unlockEffectChains(effectChains);
3069
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003071 // mSleepTimeUs == 0 means we must write to audio hardware
3072 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003073 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003074 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003075 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076 if (ret < 0) {
3077 mBytesRemaining = 0;
3078 } else {
3079 mBytesWritten += ret;
3080 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003081 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003082 }
3083 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3084 (mMixerStatus == MIXER_DRAIN_ALL)) {
3085 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003086 }
Andy Hung08fb1742015-05-31 23:22:10 -07003087 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003088 // write blocked detection
3089 nsecs_t now = systemTime();
3090 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003091 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003092 mNumDelayedWrites++;
3093 if ((now - lastWarning) > kWarningThrottleNs) {
3094 ATRACE_NAME("underrun");
3095 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3096 ns2ms(delta), mNumDelayedWrites, this);
3097 lastWarning = now;
3098 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 }
Andy Hung08fb1742015-05-31 23:22:10 -07003100
3101 if (mThreadThrottle
3102 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3103 && ret > 0) { // we wrote something
3104 // Limit MixerThread data processing to no more than twice the
3105 // expected processing rate.
3106 //
3107 // This helps prevent underruns with NuPlayer and other applications
3108 // which may set up buffers that are close to the minimum size, or use
3109 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3110 //
3111 // The throttle smooths out sudden large data drains from the device,
3112 // e.g. when it comes out of standby, which often causes problems with
3113 // (1) mixer threads without a fast mixer (which has its own warm-up)
3114 // (2) minimum buffer sized tracks (even if the track is full,
3115 // the app won't fill fast enough to handle the sudden draw).
3116
3117 const int32_t deltaMs = delta / 1000000;
3118 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3119 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3120 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003121 // notify of throttle start on verbose log
3122 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3123 "mixer(%p) throttle begin:"
3124 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003125 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003126 mThreadThrottleTimeMs += throttleMs;
3127 } else {
3128 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3129 if (diff > 0) {
3130 // notify of throttle end on debug log
3131 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3132 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3133 }
Andy Hung08fb1742015-05-31 23:22:10 -07003134 }
3135 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 }
Eric Laurent81784c32012-11-19 14:55:58 -08003137
Eric Laurentbfb1b832013-01-07 09:53:42 -08003138 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003139 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003140 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003141 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003142 }
Eric Laurent81784c32012-11-19 14:55:58 -08003143 }
3144
3145 // Finally let go of removed track(s), without the lock held
3146 // since we can't guarantee the destructors won't acquire that
3147 // same lock. This will also mutate and push a new fast mixer state.
3148 threadLoop_removeTracks(tracksToRemove);
3149 tracksToRemove.clear();
3150
3151 // FIXME I don't understand the need for this here;
3152 // it was in the original code but maybe the
3153 // assignment in saveOutputTracks() makes this unnecessary?
3154 clearOutputTracks();
3155
3156 // Effect chains will be actually deleted here if they were removed from
3157 // mEffectChains list during mixing or effects processing
3158 effectChains.clear();
3159
3160 // FIXME Note that the above .clear() is no longer necessary since effectChains
3161 // is now local to this block, but will keep it for now (at least until merge done).
3162 }
3163
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 threadLoop_exit();
3165
Eric Laurentcf817a22014-08-04 20:36:31 -07003166 if (!mStandby) {
3167 threadLoop_standby();
3168 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003169 }
3170
3171 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003172 mWakeLockUids.clear();
3173 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003174
3175 ALOGV("Thread %p type %d exiting", this, mType);
3176 return false;
3177}
3178
Eric Laurentbfb1b832013-01-07 09:53:42 -08003179// removeTracks_l() must be called with ThreadBase::mLock held
3180void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3181{
3182 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003183 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003184 for (size_t i=0 ; i<count ; i++) {
3185 const sp<Track>& track = tracksToRemove.itemAt(i);
3186 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003187 mWakeLockUids.remove(track->uid());
3188 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003189 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3190 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3191 if (chain != 0) {
3192 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3193 track->sessionId());
3194 chain->decActiveTrackCnt();
3195 }
3196 if (track->isTerminated()) {
3197 removeTrack_l(track);
3198 }
3199 }
3200 }
3201
3202}
Eric Laurent81784c32012-11-19 14:55:58 -08003203
Eric Laurentaccc1472013-09-20 09:36:34 -07003204status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3205{
3206 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003207 ExtendedTimestamp ets;
3208 status_t status = mNormalSink->getTimestamp(ets);
3209 if (status == NO_ERROR) {
3210 status = ets.getBestTimestamp(&timestamp);
3211 }
3212 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003213 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003214 if ((mType == OFFLOAD || mType == DIRECT)
3215 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003216 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003217 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003218 if (ret == 0) {
3219 timestamp.mPosition = (uint32_t)position64;
3220 return NO_ERROR;
3221 }
3222 }
3223 return INVALID_OPERATION;
3224}
Eric Laurent1c333e22014-05-20 10:48:17 -07003225
Eric Laurent054d9d32015-04-24 08:48:48 -07003226status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3227 audio_patch_handle_t *handle)
3228{
3229 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3230 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3231 if (mFastMixer != 0) {
3232 FastMixerStateQueue *sq = mFastMixer->sq();
3233 FastMixerState *state = sq->begin();
3234 if (!(state->mCommand & FastMixerState::IDLE)) {
3235 previousCommand = state->mCommand;
3236 state->mCommand = FastMixerState::HOT_IDLE;
3237 sq->end();
3238 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3239 } else {
3240 sq->end(false /*didModify*/);
3241 }
3242 }
3243 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3244
3245 if (!(previousCommand & FastMixerState::IDLE)) {
3246 ALOG_ASSERT(mFastMixer != 0);
3247 FastMixerStateQueue *sq = mFastMixer->sq();
3248 FastMixerState *state = sq->begin();
3249 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3250 state->mCommand = previousCommand;
3251 sq->end();
3252 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3253 }
3254
3255 return status;
3256}
3257
Eric Laurent1c333e22014-05-20 10:48:17 -07003258status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3259 audio_patch_handle_t *handle)
3260{
3261 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003262
3263 // store new device and send to effects
3264 audio_devices_t type = AUDIO_DEVICE_NONE;
3265 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3266 type |= patch->sinks[i].ext.device.type;
3267 }
3268
3269#ifdef ADD_BATTERY_DATA
3270 // when changing the audio output device, call addBatteryData to notify
3271 // the change
3272 if (mOutDevice != type) {
3273 uint32_t params = 0;
3274 // check whether speaker is on
3275 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3276 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003277 }
3278
Eric Laurent054d9d32015-04-24 08:48:48 -07003279 audio_devices_t deviceWithoutSpeaker
3280 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3281 // check if any other device (except speaker) is on
3282 if (type & deviceWithoutSpeaker) {
3283 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3284 }
3285
3286 if (params != 0) {
3287 addBatteryData(params);
3288 }
3289 }
3290#endif
3291
3292 for (size_t i = 0; i < mEffectChains.size(); i++) {
3293 mEffectChains[i]->setDevice_l(type);
3294 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003295
3296 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3297 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3298 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003299 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003300 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003301
3302 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003303 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3304 status = hwDevice->create_audio_patch(hwDevice,
3305 patch->num_sources,
3306 patch->sources,
3307 patch->num_sinks,
3308 patch->sinks,
3309 handle);
3310 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003311 char *address;
3312 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3313 //FIXME: we only support address on first sink with HAL version < 3.0
3314 address = audio_device_address_to_parameter(
3315 patch->sinks[0].ext.device.type,
3316 patch->sinks[0].ext.device.address);
3317 } else {
3318 address = (char *)calloc(1, 1);
3319 }
3320 AudioParameter param = AudioParameter(String8(address));
3321 free(address);
3322 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3323 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3324 param.toString().string());
3325 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003326 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003327 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003328 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003329 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3330 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003331 return status;
3332}
3333
Eric Laurent054d9d32015-04-24 08:48:48 -07003334status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3335{
3336 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3337 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3338 if (mFastMixer != 0) {
3339 FastMixerStateQueue *sq = mFastMixer->sq();
3340 FastMixerState *state = sq->begin();
3341 if (!(state->mCommand & FastMixerState::IDLE)) {
3342 previousCommand = state->mCommand;
3343 state->mCommand = FastMixerState::HOT_IDLE;
3344 sq->end();
3345 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3346 } else {
3347 sq->end(false /*didModify*/);
3348 }
3349 }
3350
3351 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3352
3353 if (!(previousCommand & FastMixerState::IDLE)) {
3354 ALOG_ASSERT(mFastMixer != 0);
3355 FastMixerStateQueue *sq = mFastMixer->sq();
3356 FastMixerState *state = sq->begin();
3357 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3358 state->mCommand = previousCommand;
3359 sq->end();
3360 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3361 }
3362
3363 return status;
3364}
3365
Eric Laurent1c333e22014-05-20 10:48:17 -07003366status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3367{
3368 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003369
3370 mOutDevice = AUDIO_DEVICE_NONE;
3371
Eric Laurent1c333e22014-05-20 10:48:17 -07003372 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3373 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3374 status = hwDevice->release_audio_patch(hwDevice, handle);
3375 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003376 AudioParameter param;
3377 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3378 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3379 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003380 }
3381 return status;
3382}
3383
Eric Laurent83b88082014-06-20 18:31:16 -07003384void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3385{
3386 Mutex::Autolock _l(mLock);
3387 mTracks.add(track);
3388}
3389
3390void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3391{
3392 Mutex::Autolock _l(mLock);
3393 destroyTrack_l(track);
3394}
3395
3396void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3397{
3398 ThreadBase::getAudioPortConfig(config);
3399 config->role = AUDIO_PORT_ROLE_SOURCE;
3400 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3401 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3402}
3403
Eric Laurent81784c32012-11-19 14:55:58 -08003404// ----------------------------------------------------------------------------
3405
3406AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003407 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3408 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003409 // mAudioMixer below
3410 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003411 mFastMixerFutex(0),
3412 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003413 // mOutputSink below
3414 // mPipeSink below
3415 // mNormalSink below
3416{
3417 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003418 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003419 "mFrameCount=%d, mNormalFrameCount=%d",
3420 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3421 mNormalFrameCount);
3422 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3423
Andy Hungfbfc3952015-01-15 13:33:51 -08003424 if (type == DUPLICATING) {
3425 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3426 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3427 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3428 return;
3429 }
Eric Laurent81784c32012-11-19 14:55:58 -08003430 // create an NBAIO sink for the HAL output stream, and negotiate
3431 mOutputSink = new AudioStreamOutSink(output->stream);
3432 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003433 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003434 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3435 ALOG_ASSERT(index == 0);
3436
3437 // initialize fast mixer depending on configuration
3438 bool initFastMixer;
3439 switch (kUseFastMixer) {
3440 case FastMixer_Never:
3441 initFastMixer = false;
3442 break;
3443 case FastMixer_Always:
3444 initFastMixer = true;
3445 break;
3446 case FastMixer_Static:
3447 case FastMixer_Dynamic:
3448 initFastMixer = mFrameCount < mNormalFrameCount;
3449 break;
3450 }
3451 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003452 audio_format_t fastMixerFormat;
3453 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3454 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3455 } else {
3456 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3457 }
3458 if (mFormat != fastMixerFormat) {
3459 // change our Sink format to accept our intermediate precision
3460 mFormat = fastMixerFormat;
3461 free(mSinkBuffer);
3462 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3463 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3464 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466
3467 // create a MonoPipe to connect our submix to FastMixer
3468 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003469 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003470 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003471 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003472 format.mFormat = fastMixerFormat;
3473 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3474
Eric Laurent81784c32012-11-19 14:55:58 -08003475 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3476 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3477 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3478 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3479 const NBAIO_Format offers[1] = {format};
3480 size_t numCounterOffers = 0;
3481 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3482 ALOG_ASSERT(index == 0);
3483 monoPipe->setAvgFrames((mScreenState & 1) ?
3484 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3485 mPipeSink = monoPipe;
3486
Glenn Kasten46909e72013-02-26 09:20:22 -08003487#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003488 if (mTeeSinkOutputEnabled) {
3489 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003490 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3491 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003492 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003493 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003494 ALOG_ASSERT(index == 0);
3495 mTeeSink = teeSink;
3496 PipeReader *teeSource = new PipeReader(*teeSink);
3497 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003498 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003499 ALOG_ASSERT(index == 0);
3500 mTeeSource = teeSource;
3501 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003502#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003503
3504 // create fast mixer and configure it initially with just one fast track for our submix
3505 mFastMixer = new FastMixer();
3506 FastMixerStateQueue *sq = mFastMixer->sq();
3507#ifdef STATE_QUEUE_DUMP
3508 sq->setObserverDump(&mStateQueueObserverDump);
3509 sq->setMutatorDump(&mStateQueueMutatorDump);
3510#endif
3511 FastMixerState *state = sq->begin();
3512 FastTrack *fastTrack = &state->mFastTracks[0];
3513 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3514 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3515 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003516 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3517 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003518 fastTrack->mGeneration++;
3519 state->mFastTracksGen++;
3520 state->mTrackMask = 1;
3521 // fast mixer will use the HAL output sink
3522 state->mOutputSink = mOutputSink.get();
3523 state->mOutputSinkGen++;
3524 state->mFrameCount = mFrameCount;
3525 state->mCommand = FastMixerState::COLD_IDLE;
3526 // already done in constructor initialization list
3527 //mFastMixerFutex = 0;
3528 state->mColdFutexAddr = &mFastMixerFutex;
3529 state->mColdGen++;
3530 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003531#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003532 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003533#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003534 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3535 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003536 sq->end();
3537 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3538
3539 // start the fast mixer
3540 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3541 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003542 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003543
3544#ifdef AUDIO_WATCHDOG
3545 // create and start the watchdog
3546 mAudioWatchdog = new AudioWatchdog();
3547 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3548 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3549 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003550 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003551#endif
3552
Eric Laurent81784c32012-11-19 14:55:58 -08003553 }
3554
3555 switch (kUseFastMixer) {
3556 case FastMixer_Never:
3557 case FastMixer_Dynamic:
3558 mNormalSink = mOutputSink;
3559 break;
3560 case FastMixer_Always:
3561 mNormalSink = mPipeSink;
3562 break;
3563 case FastMixer_Static:
3564 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3565 break;
3566 }
3567}
3568
3569AudioFlinger::MixerThread::~MixerThread()
3570{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003571 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003572 FastMixerStateQueue *sq = mFastMixer->sq();
3573 FastMixerState *state = sq->begin();
3574 if (state->mCommand == FastMixerState::COLD_IDLE) {
3575 int32_t old = android_atomic_inc(&mFastMixerFutex);
3576 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003577 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003578 }
3579 }
3580 state->mCommand = FastMixerState::EXIT;
3581 sq->end();
3582 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3583 mFastMixer->join();
3584 // Though the fast mixer thread has exited, it's state queue is still valid.
3585 // We'll use that extract the final state which contains one remaining fast track
3586 // corresponding to our sub-mix.
3587 state = sq->begin();
3588 ALOG_ASSERT(state->mTrackMask == 1);
3589 FastTrack *fastTrack = &state->mFastTracks[0];
3590 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3591 delete fastTrack->mBufferProvider;
3592 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003593 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003594#ifdef AUDIO_WATCHDOG
3595 if (mAudioWatchdog != 0) {
3596 mAudioWatchdog->requestExit();
3597 mAudioWatchdog->requestExitAndWait();
3598 mAudioWatchdog.clear();
3599 }
3600#endif
3601 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003602 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003603 delete mAudioMixer;
3604}
3605
3606
3607uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3608{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003609 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003610 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3611 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3612 }
3613 return latency;
3614}
3615
3616
3617void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3618{
3619 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3620}
3621
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003623{
3624 // FIXME we should only do one push per cycle; confirm this is true
3625 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003626 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003627 FastMixerStateQueue *sq = mFastMixer->sq();
3628 FastMixerState *state = sq->begin();
3629 if (state->mCommand != FastMixerState::MIX_WRITE &&
3630 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3631 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003632
3633 // FIXME workaround for first HAL write being CPU bound on some devices
3634 ATRACE_BEGIN("write");
3635 mOutput->write((char *)mSinkBuffer, 0);
3636 ATRACE_END();
3637
Eric Laurent81784c32012-11-19 14:55:58 -08003638 int32_t old = android_atomic_inc(&mFastMixerFutex);
3639 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003640 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003641 }
3642#ifdef AUDIO_WATCHDOG
3643 if (mAudioWatchdog != 0) {
3644 mAudioWatchdog->resume();
3645 }
3646#endif
3647 }
3648 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003649#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003650 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003651 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003652#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003653 sq->end();
3654 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3655 if (kUseFastMixer == FastMixer_Dynamic) {
3656 mNormalSink = mPipeSink;
3657 }
3658 } else {
3659 sq->end(false /*didModify*/);
3660 }
3661 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003663}
3664
3665void AudioFlinger::MixerThread::threadLoop_standby()
3666{
3667 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003668 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003669 FastMixerStateQueue *sq = mFastMixer->sq();
3670 FastMixerState *state = sq->begin();
3671 if (!(state->mCommand & FastMixerState::IDLE)) {
3672 state->mCommand = FastMixerState::COLD_IDLE;
3673 state->mColdFutexAddr = &mFastMixerFutex;
3674 state->mColdGen++;
3675 mFastMixerFutex = 0;
3676 sq->end();
3677 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3678 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3679 if (kUseFastMixer == FastMixer_Dynamic) {
3680 mNormalSink = mOutputSink;
3681 }
3682#ifdef AUDIO_WATCHDOG
3683 if (mAudioWatchdog != 0) {
3684 mAudioWatchdog->pause();
3685 }
3686#endif
3687 } else {
3688 sq->end(false /*didModify*/);
3689 }
3690 }
3691 PlaybackThread::threadLoop_standby();
3692}
3693
Eric Laurentbfb1b832013-01-07 09:53:42 -08003694bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3695{
3696 return false;
3697}
3698
3699bool AudioFlinger::PlaybackThread::shouldStandby_l()
3700{
3701 return !mStandby;
3702}
3703
3704bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3705{
3706 Mutex::Autolock _l(mLock);
3707 return waitingAsyncCallback_l();
3708}
3709
Eric Laurent81784c32012-11-19 14:55:58 -08003710// shared by MIXER and DIRECT, overridden by DUPLICATING
3711void AudioFlinger::PlaybackThread::threadLoop_standby()
3712{
3713 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003714 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003715 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003716 // discard any pending drain or write ack by incrementing sequence
3717 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3718 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003719 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003720 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3721 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003722 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003723 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003724}
3725
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003726void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3727{
3728 ALOGV("signal playback thread");
3729 broadcast_l();
3730}
3731
Eric Laurent81784c32012-11-19 14:55:58 -08003732void AudioFlinger::MixerThread::threadLoop_mix()
3733{
Eric Laurent81784c32012-11-19 14:55:58 -08003734 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003735 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003736 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003737 // increase sleep time progressively when application underrun condition clears.
3738 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3739 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3740 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003741 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003742 sleepTimeShift--;
3743 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003744 mSleepTimeUs = 0;
3745 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003746 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003747
Eric Laurent81784c32012-11-19 14:55:58 -08003748}
3749
3750void AudioFlinger::MixerThread::threadLoop_sleepTime()
3751{
3752 // If no tracks are ready, sleep once for the duration of an output
3753 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003754 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003755 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003756 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3757 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3758 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003759 }
3760 // reduce sleep time in case of consecutive application underruns to avoid
3761 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3762 // duration we would end up writing less data than needed by the audio HAL if
3763 // the condition persists.
3764 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3765 sleepTimeShift++;
3766 }
3767 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003768 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003769 }
3770 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003771 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3772 // before effects processing or output.
3773 if (mMixerBufferValid) {
3774 memset(mMixerBuffer, 0, mMixerBufferSize);
3775 } else {
3776 memset(mSinkBuffer, 0, mSinkBufferSize);
3777 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003778 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003779 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3780 "anticipated start");
3781 }
3782 // TODO add standby time extension fct of effect tail
3783}
3784
3785// prepareTracks_l() must be called with ThreadBase::mLock held
3786AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3787 Vector< sp<Track> > *tracksToRemove)
3788{
3789
3790 mixer_state mixerStatus = MIXER_IDLE;
3791 // find out which tracks need to be processed
3792 size_t count = mActiveTracks.size();
3793 size_t mixedTracks = 0;
3794 size_t tracksWithEffect = 0;
3795 // counts only _active_ fast tracks
3796 size_t fastTracks = 0;
3797 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3798
3799 float masterVolume = mMasterVolume;
3800 bool masterMute = mMasterMute;
3801
3802 if (masterMute) {
3803 masterVolume = 0;
3804 }
3805 // Delegate master volume control to effect in output mix effect chain if needed
3806 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3807 if (chain != 0) {
3808 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3809 chain->setVolume_l(&v, &v);
3810 masterVolume = (float)((v + (1 << 23)) >> 24);
3811 chain.clear();
3812 }
3813
3814 // prepare a new state to push
3815 FastMixerStateQueue *sq = NULL;
3816 FastMixerState *state = NULL;
3817 bool didModify = false;
3818 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003819 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820 sq = mFastMixer->sq();
3821 state = sq->begin();
3822 }
3823
Andy Hung69aed5f2014-02-25 17:24:40 -08003824 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003825 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003826
Eric Laurent81784c32012-11-19 14:55:58 -08003827 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003828 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003829 if (t == 0) {
3830 continue;
3831 }
3832
3833 // this const just means the local variable doesn't change
3834 Track* const track = t.get();
3835
3836 // process fast tracks
3837 if (track->isFastTrack()) {
3838
3839 // It's theoretically possible (though unlikely) for a fast track to be created
3840 // and then removed within the same normal mix cycle. This is not a problem, as
3841 // the track never becomes active so it's fast mixer slot is never touched.
3842 // The converse, of removing an (active) track and then creating a new track
3843 // at the identical fast mixer slot within the same normal mix cycle,
3844 // is impossible because the slot isn't marked available until the end of each cycle.
3845 int j = track->mFastIndex;
3846 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3847 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3848 FastTrack *fastTrack = &state->mFastTracks[j];
3849
3850 // Determine whether the track is currently in underrun condition,
3851 // and whether it had a recent underrun.
3852 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3853 FastTrackUnderruns underruns = ftDump->mUnderruns;
3854 uint32_t recentFull = (underruns.mBitFields.mFull -
3855 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3856 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3857 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3858 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3859 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3860 uint32_t recentUnderruns = recentPartial + recentEmpty;
3861 track->mObservedUnderruns = underruns;
3862 // don't count underruns that occur while stopping or pausing
3863 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003864 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3865 recentUnderruns > 0) {
3866 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3867 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003868 } else {
3869 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003870 }
3871
3872 // This is similar to the state machine for normal tracks,
3873 // with a few modifications for fast tracks.
3874 bool isActive = true;
3875 switch (track->mState) {
3876 case TrackBase::STOPPING_1:
3877 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003879 track->mState = TrackBase::STOPPING_2;
3880 }
3881 break;
3882 case TrackBase::PAUSING:
3883 // ramp down is not yet implemented
3884 track->setPaused();
3885 break;
3886 case TrackBase::RESUMING:
3887 // ramp up is not yet implemented
3888 track->mState = TrackBase::ACTIVE;
3889 break;
3890 case TrackBase::ACTIVE:
3891 if (recentFull > 0 || recentPartial > 0) {
3892 // track has provided at least some frames recently: reset retry count
3893 track->mRetryCount = kMaxTrackRetries;
3894 }
3895 if (recentUnderruns == 0) {
3896 // no recent underruns: stay active
3897 break;
3898 }
3899 // there has recently been an underrun of some kind
3900 if (track->sharedBuffer() == 0) {
3901 // were any of the recent underruns "empty" (no frames available)?
3902 if (recentEmpty == 0) {
3903 // no, then ignore the partial underruns as they are allowed indefinitely
3904 break;
3905 }
3906 // there has recently been an "empty" underrun: decrement the retry counter
3907 if (--(track->mRetryCount) > 0) {
3908 break;
3909 }
3910 // indicate to client process that the track was disabled because of underrun;
3911 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003912 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003913 // remove from active list, but state remains ACTIVE [confusing but true]
3914 isActive = false;
3915 break;
3916 }
3917 // fall through
3918 case TrackBase::STOPPING_2:
3919 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003920 case TrackBase::STOPPED:
3921 case TrackBase::FLUSHED: // flush() while active
3922 // Check for presentation complete if track is inactive
3923 // We have consumed all the buffers of this track.
3924 // This would be incomplete if we auto-paused on underrun
3925 {
3926 size_t audioHALFrames =
3927 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003928 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003929 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3930 // track stays in active list until presentation is complete
3931 break;
3932 }
3933 }
3934 if (track->isStopping_2()) {
3935 track->mState = TrackBase::STOPPED;
3936 }
3937 if (track->isStopped()) {
3938 // Can't reset directly, as fast mixer is still polling this track
3939 // track->reset();
3940 // So instead mark this track as needing to be reset after push with ack
3941 resetMask |= 1 << i;
3942 }
3943 isActive = false;
3944 break;
3945 case TrackBase::IDLE:
3946 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003947 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003948 }
3949
3950 if (isActive) {
3951 // was it previously inactive?
3952 if (!(state->mTrackMask & (1 << j))) {
3953 ExtendedAudioBufferProvider *eabp = track;
3954 VolumeProvider *vp = track;
3955 fastTrack->mBufferProvider = eabp;
3956 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003957 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003958 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003959 fastTrack->mGeneration++;
3960 state->mTrackMask |= 1 << j;
3961 didModify = true;
3962 // no acknowledgement required for newly active tracks
3963 }
3964 // cache the combined master volume and stream type volume for fast mixer; this
3965 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003966 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003967 ++fastTracks;
3968 } else {
3969 // was it previously active?
3970 if (state->mTrackMask & (1 << j)) {
3971 fastTrack->mBufferProvider = NULL;
3972 fastTrack->mGeneration++;
3973 state->mTrackMask &= ~(1 << j);
3974 didModify = true;
3975 // If any fast tracks were removed, we must wait for acknowledgement
3976 // because we're about to decrement the last sp<> on those tracks.
3977 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3978 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003979 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3980 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3981 j, track->mState, state->mTrackMask, recentUnderruns,
3982 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003983 }
3984 tracksToRemove->add(track);
3985 // Avoids a misleading display in dumpsys
3986 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3987 }
3988 continue;
3989 }
3990
3991 { // local variable scope to avoid goto warning
3992
3993 audio_track_cblk_t* cblk = track->cblk();
3994
3995 // The first time a track is added we wait
3996 // for all its buffers to be filled before processing it
3997 int name = track->name();
3998 // make sure that we have enough frames to mix one full buffer.
3999 // enforce this condition only once to enable draining the buffer in case the client
4000 // app does not call stop() and relies on underrun to stop:
4001 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4002 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004003 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004004 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004005 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004006
4007 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004008 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004009 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4010 // add frames already consumed but not yet released by the resampler
4011 // because mAudioTrackServerProxy->framesReady() will include these frames
4012 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4013
Eric Laurent81784c32012-11-19 14:55:58 -08004014 uint32_t minFrames = 1;
4015 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4016 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004017 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004018 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004019
4020 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004021 if (ATRACE_ENABLED()) {
4022 // I wish we had formatted trace names
4023 char traceName[16];
4024 strcpy(traceName, "nRdy");
4025 int name = track->name();
4026 if (AudioMixer::TRACK0 <= name &&
4027 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4028 name -= AudioMixer::TRACK0;
4029 traceName[4] = (name / 10) + '0';
4030 traceName[5] = (name % 10) + '0';
4031 } else {
4032 traceName[4] = '?';
4033 traceName[5] = '?';
4034 }
4035 traceName[6] = '\0';
4036 ATRACE_INT(traceName, framesReady);
4037 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004038 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004039 !track->isPaused() && !track->isTerminated())
4040 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004041 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004042
4043 mixedTracks++;
4044
Andy Hung69aed5f2014-02-25 17:24:40 -08004045 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4046 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004047 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004048 if (track->mainBuffer() != mSinkBuffer &&
4049 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004050 if (mEffectBufferEnabled) {
4051 mEffectBufferValid = true; // Later can set directly.
4052 }
Eric Laurent81784c32012-11-19 14:55:58 -08004053 chain = getEffectChain_l(track->sessionId());
4054 // Delegate volume control to effect in track effect chain if needed
4055 if (chain != 0) {
4056 tracksWithEffect++;
4057 } else {
4058 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4059 "session %d",
4060 name, track->sessionId());
4061 }
4062 }
4063
4064
4065 int param = AudioMixer::VOLUME;
4066 if (track->mFillingUpStatus == Track::FS_FILLED) {
4067 // no ramp for the first volume setting
4068 track->mFillingUpStatus = Track::FS_ACTIVE;
4069 if (track->mState == TrackBase::RESUMING) {
4070 track->mState = TrackBase::ACTIVE;
4071 param = AudioMixer::RAMP_VOLUME;
4072 }
4073 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004074 // FIXME should not make a decision based on mServer
4075 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004076 // If the track is stopped before the first frame was mixed,
4077 // do not apply ramp
4078 param = AudioMixer::RAMP_VOLUME;
4079 }
4080
4081 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004082 uint32_t vl, vr; // in U8.24 integer format
4083 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004084 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004085 vl = vr = 0;
4086 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004087 if (track->isPausing()) {
4088 track->setPaused();
4089 }
4090 } else {
4091
4092 // read original volumes with volume control
4093 float typeVolume = mStreamTypes[track->streamType()].volume;
4094 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004095 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004096 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004097 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4098 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004099 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004100 if (vlf > GAIN_FLOAT_UNITY) {
4101 ALOGV("Track left volume out of range: %.3g", vlf);
4102 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004103 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004104 if (vrf > GAIN_FLOAT_UNITY) {
4105 ALOGV("Track right volume out of range: %.3g", vrf);
4106 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004107 }
4108 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004109 vlf *= v;
4110 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004111 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004112 // then derive vl and vr as U8.24 versions for the effect chain
4113 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4114 vl = (uint32_t) (scaleto8_24 * vlf);
4115 vr = (uint32_t) (scaleto8_24 * vrf);
4116 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004117 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004118 // send level comes from shared memory and so may be corrupt
4119 if (sendLevel > MAX_GAIN_INT) {
4120 ALOGV("Track send level out of range: %04X", sendLevel);
4121 sendLevel = MAX_GAIN_INT;
4122 }
Andy Hung6be49402014-05-30 10:42:03 -07004123 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4124 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004125 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // Delegate volume control to effect in track effect chain if needed
4128 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4129 // Do not ramp volume if volume is controlled by effect
4130 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004131 // Update remaining floating point volume levels
4132 vlf = (float)vl / (1 << 24);
4133 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004134 track->mHasVolumeController = true;
4135 } else {
4136 // force no volume ramp when volume controller was just disabled or removed
4137 // from effect chain to avoid volume spike
4138 if (track->mHasVolumeController) {
4139 param = AudioMixer::VOLUME;
4140 }
4141 track->mHasVolumeController = false;
4142 }
4143
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // XXX: these things DON'T need to be done each time
4145 mAudioMixer->setBufferProvider(name, track);
4146 mAudioMixer->enable(name);
4147
Andy Hung6be49402014-05-30 10:42:03 -07004148 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4149 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4150 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 mAudioMixer->setParameter(
4152 name,
4153 AudioMixer::TRACK,
4154 AudioMixer::FORMAT, (void *)track->format());
4155 mAudioMixer->setParameter(
4156 name,
4157 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004158 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004159 mAudioMixer->setParameter(
4160 name,
4161 AudioMixer::TRACK,
4162 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004163 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004164 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004165 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004166 if (reqSampleRate == 0) {
4167 reqSampleRate = mSampleRate;
4168 } else if (reqSampleRate > maxSampleRate) {
4169 reqSampleRate = maxSampleRate;
4170 }
Eric Laurent81784c32012-11-19 14:55:58 -08004171 mAudioMixer->setParameter(
4172 name,
4173 AudioMixer::RESAMPLE,
4174 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004175 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004176
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004177 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004178 mAudioMixer->setParameter(
4179 name,
4180 AudioMixer::TIMESTRETCH,
4181 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004182 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004183
Andy Hung69aed5f2014-02-25 17:24:40 -08004184 /*
4185 * Select the appropriate output buffer for the track.
4186 *
Andy Hung98ef9782014-03-04 14:46:50 -08004187 * Tracks with effects go into their own effects chain buffer
4188 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004189 *
4190 * Other tracks can use mMixerBuffer for higher precision
4191 * channel accumulation. If this buffer is enabled
4192 * (mMixerBufferEnabled true), then selected tracks will accumulate
4193 * into it.
4194 *
4195 */
4196 if (mMixerBufferEnabled
4197 && (track->mainBuffer() == mSinkBuffer
4198 || track->mainBuffer() == mMixerBuffer)) {
4199 mAudioMixer->setParameter(
4200 name,
4201 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004202 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004203 mAudioMixer->setParameter(
4204 name,
4205 AudioMixer::TRACK,
4206 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4207 // TODO: override track->mainBuffer()?
4208 mMixerBufferValid = true;
4209 } else {
4210 mAudioMixer->setParameter(
4211 name,
4212 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004213 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004214 mAudioMixer->setParameter(
4215 name,
4216 AudioMixer::TRACK,
4217 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4218 }
Eric Laurent81784c32012-11-19 14:55:58 -08004219 mAudioMixer->setParameter(
4220 name,
4221 AudioMixer::TRACK,
4222 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4223
4224 // reset retry count
4225 track->mRetryCount = kMaxTrackRetries;
4226
4227 // If one track is ready, set the mixer ready if:
4228 // - the mixer was not ready during previous round OR
4229 // - no other track is not ready
4230 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4231 mixerStatus != MIXER_TRACKS_ENABLED) {
4232 mixerStatus = MIXER_TRACKS_READY;
4233 }
4234 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004235 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004236 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4237 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004238 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004239 } else {
4240 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004241 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004242
Eric Laurent81784c32012-11-19 14:55:58 -08004243 // clear effect chain input buffer if an active track underruns to avoid sending
4244 // previous audio buffer again to effects
4245 chain = getEffectChain_l(track->sessionId());
4246 if (chain != 0) {
4247 chain->clearInputBuffer();
4248 }
4249
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004250 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004251 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4252 track->isStopped() || track->isPaused()) {
4253 // We have consumed all the buffers of this track.
4254 // Remove it from the list of active tracks.
4255 // TODO: use actual buffer filling status instead of latency when available from
4256 // audio HAL
4257 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004258 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004259 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4260 if (track->isStopped()) {
4261 track->reset();
4262 }
4263 tracksToRemove->add(track);
4264 }
4265 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004266 // No buffers for this track. Give it a few chances to
4267 // fill a buffer, then remove it from active list.
4268 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004269 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004270 tracksToRemove->add(track);
4271 // indicate to client process that the track was disabled because of underrun;
4272 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004273 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004274 // If one track is not ready, mark the mixer also not ready if:
4275 // - the mixer was ready during previous round OR
4276 // - no other track is ready
4277 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4278 mixerStatus != MIXER_TRACKS_READY) {
4279 mixerStatus = MIXER_TRACKS_ENABLED;
4280 }
4281 }
4282 mAudioMixer->disable(name);
4283 }
4284
4285 } // local variable scope to avoid goto warning
4286track_is_ready: ;
4287
4288 }
4289
4290 // Push the new FastMixer state if necessary
4291 bool pauseAudioWatchdog = false;
4292 if (didModify) {
4293 state->mFastTracksGen++;
4294 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4295 if (kUseFastMixer == FastMixer_Dynamic &&
4296 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4297 state->mCommand = FastMixerState::COLD_IDLE;
4298 state->mColdFutexAddr = &mFastMixerFutex;
4299 state->mColdGen++;
4300 mFastMixerFutex = 0;
4301 if (kUseFastMixer == FastMixer_Dynamic) {
4302 mNormalSink = mOutputSink;
4303 }
4304 // If we go into cold idle, need to wait for acknowledgement
4305 // so that fast mixer stops doing I/O.
4306 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4307 pauseAudioWatchdog = true;
4308 }
Eric Laurent81784c32012-11-19 14:55:58 -08004309 }
4310 if (sq != NULL) {
4311 sq->end(didModify);
4312 sq->push(block);
4313 }
4314#ifdef AUDIO_WATCHDOG
4315 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4316 mAudioWatchdog->pause();
4317 }
4318#endif
4319
4320 // Now perform the deferred reset on fast tracks that have stopped
4321 while (resetMask != 0) {
4322 size_t i = __builtin_ctz(resetMask);
4323 ALOG_ASSERT(i < count);
4324 resetMask &= ~(1 << i);
4325 sp<Track> t = mActiveTracks[i].promote();
4326 if (t == 0) {
4327 continue;
4328 }
4329 Track* track = t.get();
4330 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4331 track->reset();
4332 }
4333
4334 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004335 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004336
Eric Laurent97d547d2014-09-02 14:45:53 -07004337 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4338 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004339 }
4340
4341 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004342 // as long as there are effects we should clear the effects buffer, to avoid
4343 // passing a non-clean buffer to the effect chain
4344 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004345 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004346 // sink or mix buffer must be cleared if all tracks are connected to an
4347 // effect chain as in this case the mixer will not write to the sink or mix buffer
4348 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004349 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4350 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004351 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004352 if (mMixerBufferValid) {
4353 memset(mMixerBuffer, 0, mMixerBufferSize);
4354 // TODO: In testing, mSinkBuffer below need not be cleared because
4355 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4356 // after mixing.
4357 //
4358 // To enforce this guarantee:
4359 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4360 // (mixedTracks == 0 && fastTracks > 0))
4361 // must imply MIXER_TRACKS_READY.
4362 // Later, we may clear buffers regardless, and skip much of this logic.
4363 }
Andy Hung98ef9782014-03-04 14:46:50 -08004364 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004365 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004366 }
4367
4368 // if any fast tracks, then status is ready
4369 mMixerStatusIgnoringFastTracks = mixerStatus;
4370 if (fastTracks > 0) {
4371 mixerStatus = MIXER_TRACKS_READY;
4372 }
4373 return mixerStatus;
4374}
4375
4376// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004377int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4378 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004379{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004380 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004381}
4382
4383// deleteTrackName_l() must be called with ThreadBase::mLock held
4384void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4385{
4386 ALOGV("remove track (%d) and delete from mixer", name);
4387 mAudioMixer->deleteTrackName(name);
4388}
4389
Eric Laurent10351942014-05-08 18:49:52 -07004390// checkForNewParameter_l() must be called with ThreadBase::mLock held
4391bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4392 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004393{
Eric Laurent81784c32012-11-19 14:55:58 -08004394 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004395 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004396
Eric Laurent10351942014-05-08 18:49:52 -07004397 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004398
Eric Laurent10351942014-05-08 18:49:52 -07004399 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4400 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004401 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004402 FastMixerStateQueue *sq = mFastMixer->sq();
4403 FastMixerState *state = sq->begin();
4404 if (!(state->mCommand & FastMixerState::IDLE)) {
4405 previousCommand = state->mCommand;
4406 state->mCommand = FastMixerState::HOT_IDLE;
4407 sq->end();
4408 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4409 } else {
4410 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004411 }
Eric Laurent10351942014-05-08 18:49:52 -07004412 }
Eric Laurent81784c32012-11-19 14:55:58 -08004413
Eric Laurent10351942014-05-08 18:49:52 -07004414 AudioParameter param = AudioParameter(keyValuePair);
4415 int value;
4416 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4417 reconfig = true;
4418 }
4419 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004420 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004421 status = BAD_VALUE;
4422 } else {
4423 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004424 reconfig = true;
4425 }
Eric Laurent10351942014-05-08 18:49:52 -07004426 }
4427 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004428 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004429 status = BAD_VALUE;
4430 } else {
4431 // no need to save value, since it's constant
4432 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004433 }
Eric Laurent10351942014-05-08 18:49:52 -07004434 }
4435 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4436 // do not accept frame count changes if tracks are open as the track buffer
4437 // size depends on frame count and correct behavior would not be guaranteed
4438 // if frame count is changed after track creation
4439 if (!mTracks.isEmpty()) {
4440 status = INVALID_OPERATION;
4441 } else {
4442 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004443 }
Eric Laurent10351942014-05-08 18:49:52 -07004444 }
4445 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004446#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004447 // when changing the audio output device, call addBatteryData to notify
4448 // the change
4449 if (mOutDevice != value) {
4450 uint32_t params = 0;
4451 // check whether speaker is on
4452 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4453 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004454 }
Eric Laurent10351942014-05-08 18:49:52 -07004455
4456 audio_devices_t deviceWithoutSpeaker
4457 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4458 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004459 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004460 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4461 }
4462
4463 if (params != 0) {
4464 addBatteryData(params);
4465 }
4466 }
Eric Laurent81784c32012-11-19 14:55:58 -08004467#endif
4468
Eric Laurent10351942014-05-08 18:49:52 -07004469 // forward device change to effects that have requested to be
4470 // aware of attached audio device.
4471 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004472 a2dpDeviceChanged =
4473 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004474 mOutDevice = value;
4475 for (size_t i = 0; i < mEffectChains.size(); i++) {
4476 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004477 }
4478 }
Eric Laurent10351942014-05-08 18:49:52 -07004479 }
Eric Laurent81784c32012-11-19 14:55:58 -08004480
Eric Laurent10351942014-05-08 18:49:52 -07004481 if (status == NO_ERROR) {
4482 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4483 keyValuePair.string());
4484 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004485 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004486 mStandby = true;
4487 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004488 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004489 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004490 }
Eric Laurent10351942014-05-08 18:49:52 -07004491 if (status == NO_ERROR && reconfig) {
4492 readOutputParameters_l();
4493 delete mAudioMixer;
4494 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4495 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004496 int name = getTrackName_l(mTracks[i]->mChannelMask,
4497 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004498 if (name < 0) {
4499 break;
4500 }
4501 mTracks[i]->mName = name;
4502 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004503 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004504 }
Eric Laurent81784c32012-11-19 14:55:58 -08004505 }
4506
4507 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004508 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004509 FastMixerStateQueue *sq = mFastMixer->sq();
4510 FastMixerState *state = sq->begin();
4511 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4512 state->mCommand = previousCommand;
4513 sq->end();
4514 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4515 }
4516
Eric Laurent42537be2016-01-08 17:16:42 -08004517 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004518}
4519
4520
4521void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4522{
4523 const size_t SIZE = 256;
4524 char buffer[SIZE];
4525 String8 result;
4526
4527 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004528 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004529 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004530 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004531
4532 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004533 // while we are dumping it. It may be inconsistent, but it won't mutate!
4534 // This is a large object so we place it on the heap.
4535 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4536 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4537 copy->dump(fd);
4538 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004539
4540#ifdef STATE_QUEUE_DUMP
4541 // Similar for state queue
4542 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4543 observerCopy.dump(fd);
4544 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4545 mutatorCopy.dump(fd);
4546#endif
4547
Glenn Kasten46909e72013-02-26 09:20:22 -08004548#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004549 // Write the tee output to a .wav file
4550 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004551#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004552
4553#ifdef AUDIO_WATCHDOG
4554 if (mAudioWatchdog != 0) {
4555 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4556 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4557 wdCopy.dump(fd);
4558 }
4559#endif
4560}
4561
4562uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4563{
4564 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4565}
4566
4567uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4568{
4569 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4570}
4571
4572void AudioFlinger::MixerThread::cacheParameters_l()
4573{
4574 PlaybackThread::cacheParameters_l();
4575
4576 // FIXME: Relaxed timing because of a certain device that can't meet latency
4577 // Should be reduced to 2x after the vendor fixes the driver issue
4578 // increase threshold again due to low power audio mode. The way this warning
4579 // threshold is calculated and its usefulness should be reconsidered anyway.
4580 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4581}
4582
4583// ----------------------------------------------------------------------------
4584
4585AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004586 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4587 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004588 // mLeftVolFloat, mRightVolFloat
4589{
4590}
4591
Eric Laurentbfb1b832013-01-07 09:53:42 -08004592AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4593 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004594 ThreadBase::type_t type, bool systemReady)
4595 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 // mLeftVolFloat, mRightVolFloat
4597{
4598}
4599
Eric Laurent81784c32012-11-19 14:55:58 -08004600AudioFlinger::DirectOutputThread::~DirectOutputThread()
4601{
4602}
4603
Eric Laurentbfb1b832013-01-07 09:53:42 -08004604void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4605{
4606 audio_track_cblk_t* cblk = track->cblk();
4607 float left, right;
4608
4609 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4610 left = right = 0;
4611 } else {
4612 float typeVolume = mStreamTypes[track->streamType()].volume;
4613 float v = mMasterVolume * typeVolume;
4614 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004615 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4616 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4617 if (left > GAIN_FLOAT_UNITY) {
4618 left = GAIN_FLOAT_UNITY;
4619 }
4620 left *= v;
4621 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4622 if (right > GAIN_FLOAT_UNITY) {
4623 right = GAIN_FLOAT_UNITY;
4624 }
4625 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004626 }
4627
4628 if (lastTrack) {
4629 if (left != mLeftVolFloat || right != mRightVolFloat) {
4630 mLeftVolFloat = left;
4631 mRightVolFloat = right;
4632
4633 // Convert volumes from float to 8.24
4634 uint32_t vl = (uint32_t)(left * (1 << 24));
4635 uint32_t vr = (uint32_t)(right * (1 << 24));
4636
4637 // Delegate volume control to effect in track effect chain if needed
4638 // only one effect chain can be present on DirectOutputThread, so if
4639 // there is one, the track is connected to it
4640 if (!mEffectChains.isEmpty()) {
4641 mEffectChains[0]->setVolume_l(&vl, &vr);
4642 left = (float)vl / (1 << 24);
4643 right = (float)vr / (1 << 24);
4644 }
4645 if (mOutput->stream->set_volume) {
4646 mOutput->stream->set_volume(mOutput->stream, left, right);
4647 }
4648 }
4649 }
4650}
4651
Phil Burk43b4dcc2015-06-09 16:53:44 -07004652void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4653{
4654 sp<Track> previousTrack = mPreviousTrack.promote();
4655 sp<Track> latestTrack = mLatestActiveTrack.promote();
4656
Eric Laurent0f0631e2015-07-06 18:01:25 -07004657 if (previousTrack != 0 && latestTrack != 0) {
4658 if (mType == DIRECT) {
4659 if (previousTrack.get() != latestTrack.get()) {
4660 mFlushPending = true;
4661 }
4662 } else /* mType == OFFLOAD */ {
4663 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4664 mFlushPending = true;
4665 }
4666 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004667 }
4668 PlaybackThread::onAddNewTrack_l();
4669}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004670
Eric Laurent81784c32012-11-19 14:55:58 -08004671AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4672 Vector< sp<Track> > *tracksToRemove
4673)
4674{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004675 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004676 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004677 bool doHwPause = false;
4678 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004679
4680 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004681 for (size_t i = 0; i < count; i++) {
4682 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004683 // The track died recently
4684 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004685 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
4687
Phil Burk43b4dcc2015-06-09 16:53:44 -07004688 if (t->isInvalid()) {
4689 ALOGW("An invalidated track shouldn't be in active list");
4690 tracksToRemove->add(t);
4691 continue;
4692 }
4693
Eric Laurent81784c32012-11-19 14:55:58 -08004694 Track* const track = t.get();
4695 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004696 // Only consider last track started for volume and mixer state control.
4697 // In theory an older track could underrun and restart after the new one starts
4698 // but as we only care about the transition phase between two tracks on a
4699 // direct output, it is not a problem to ignore the underrun case.
4700 sp<Track> l = mLatestActiveTrack.promote();
4701 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004702
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004703 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004704 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004705 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 doHwPause = true;
4707 mHwPaused = true;
4708 }
4709 tracksToRemove->add(track);
4710 } else if (track->isFlushPending()) {
4711 track->flushAck();
4712 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004713 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004715 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004716 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004717 if (last && mHwPaused) {
4718 doHwResume = true;
4719 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004720 }
4721 }
4722
Eric Laurent81784c32012-11-19 14:55:58 -08004723 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004724 // for all its buffers to be filled before processing it.
4725 // Allow draining the buffer in case the client
4726 // app does not call stop() and relies on underrun to stop:
4727 // hence the test on (track->mRetryCount > 1).
4728 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004729 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004730 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004731 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004732 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004733 minFrames = mNormalFrameCount;
4734 } else {
4735 minFrames = 1;
4736 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737
Eric Laurentab5cdba2014-06-09 17:22:27 -07004738 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4739 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004740 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004741 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004742
4743 if (track->mFillingUpStatus == Track::FS_FILLED) {
4744 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004745 // make sure processVolume_l() will apply new volume even if 0
4746 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004747 if (!mHwSupportsPause) {
4748 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004749 }
4750 }
4751
4752 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004753 processVolume_l(track, last);
4754 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004755 sp<Track> previousTrack = mPreviousTrack.promote();
4756 if (previousTrack != 0) {
4757 if (track != previousTrack.get()) {
4758 // Flush any data still being written from last track
4759 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004760 // Invalidate previous track to force a seek when resuming.
4761 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004762 }
4763 }
4764 mPreviousTrack = track;
4765
Eric Laurentd595b7c2013-04-03 17:27:56 -07004766 // reset retry count
4767 track->mRetryCount = kMaxTrackRetriesDirect;
4768 mActiveTrack = t;
4769 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004770 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004771 doHwResume = true;
4772 mHwPaused = false;
4773 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004776 // clear effect chain input buffer if the last active track started underruns
4777 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004778 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004779 mEffectChains[0]->clearInputBuffer();
4780 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004781 if (track->isStopping_1()) {
4782 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004783 if (last && mHwPaused) {
4784 doHwResume = true;
4785 mHwPaused = false;
4786 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004787 }
4788 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4789 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004790 // We have consumed all the buffers of this track.
4791 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004792 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004793 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004794 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4795 } else {
4796 audioHALFrames = 0;
4797 }
4798
Andy Hung818e7a32016-02-16 18:08:07 -08004799 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004800 if (mStandby || !last ||
4801 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004802 if (track->isStopping_2()) {
4803 track->mState = TrackBase::STOPPED;
4804 }
Eric Laurent81784c32012-11-19 14:55:58 -08004805 if (track->isStopped()) {
4806 track->reset();
4807 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004808 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004809 }
4810 } else {
4811 // No buffers for this track. Give it a few chances to
4812 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004813 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004814 if (--(track->mRetryCount) <= 0) {
4815 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004816 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004817 // indicate to client process that the track was disabled because of underrun;
4818 // it will then automatically call start() when data is available
4819 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004821 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4822 "minFrames = %u, mFormat = %#x",
4823 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004825 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004826 doHwPause = true;
4827 mHwPaused = true;
4828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829 }
4830 }
4831 }
4832 }
4833
Eric Laurentd1f69b02014-12-15 14:33:13 -08004834 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004835 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004836 for (size_t i = 0; i < mTracks.size(); i++) {
4837 if (mTracks[i]->isFlushPending()) {
4838 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004839 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004840 }
4841 }
4842 }
4843
4844 // make sure the pause/flush/resume sequence is executed in the right order.
4845 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4846 // before flush and then resume HW. This can happen in case of pause/flush/resume
4847 // if resume is received before pause is executed.
4848 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004849 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004850 mOutput->stream->pause(mOutput->stream);
4851 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004852 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004853 flushHw_l();
4854 }
4855 if (mHwSupportsPause && !mStandby && doHwResume) {
4856 mOutput->stream->resume(mOutput->stream);
4857 }
Eric Laurent81784c32012-11-19 14:55:58 -08004858 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004859 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004860
4861 return mixerStatus;
4862}
4863
4864void AudioFlinger::DirectOutputThread::threadLoop_mix()
4865{
Eric Laurent81784c32012-11-19 14:55:58 -08004866 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004867 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004868 // output audio to hardware
4869 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004870 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004871 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004872 status_t status = mActiveTrack->getNextBuffer(&buffer);
4873 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004874 memset(curBuf, 0, frameCount * mFrameSize);
4875 break;
4876 }
4877 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4878 frameCount -= buffer.frameCount;
4879 curBuf += buffer.frameCount * mFrameSize;
4880 mActiveTrack->releaseBuffer(&buffer);
4881 }
Andy Hung2098f272014-02-27 14:00:06 -08004882 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004883 mSleepTimeUs = 0;
4884 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004885 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004886}
4887
4888void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4889{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004890 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004891 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004892 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 return;
4894 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004896 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004897 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004898 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004899 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004900 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004901 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004902 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004903 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004904 }
4905}
4906
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907void AudioFlinger::DirectOutputThread::threadLoop_exit()
4908{
4909 {
4910 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004911 for (size_t i = 0; i < mTracks.size(); i++) {
4912 if (mTracks[i]->isFlushPending()) {
4913 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004914 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004915 }
4916 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004918 flushHw_l();
4919 }
4920 }
4921 PlaybackThread::threadLoop_exit();
4922}
4923
4924// must be called with thread mutex locked
4925bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4926{
4927 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004928 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004929
4930 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4931 // after a timeout and we will enter standby then.
4932 if (mTracks.size() > 0) {
4933 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004934 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4935 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004936 }
4937
Eric Laurent5cff4032015-05-26 13:49:58 -07004938 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004939}
4940
Eric Laurent81784c32012-11-19 14:55:58 -08004941// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004942int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004943 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004944{
4945 return 0;
4946}
4947
4948// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004949void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004950{
4951}
4952
Eric Laurent10351942014-05-08 18:49:52 -07004953// checkForNewParameter_l() must be called with ThreadBase::mLock held
4954bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4955 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004956{
4957 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004958 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004959
Eric Laurent10351942014-05-08 18:49:52 -07004960 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004961
Eric Laurent10351942014-05-08 18:49:52 -07004962 AudioParameter param = AudioParameter(keyValuePair);
4963 int value;
4964 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4965 // forward device change to effects that have requested to be
4966 // aware of attached audio device.
4967 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004968 a2dpDeviceChanged =
4969 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004970 mOutDevice = value;
4971 for (size_t i = 0; i < mEffectChains.size(); i++) {
4972 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004973 }
4974 }
Eric Laurent81784c32012-11-19 14:55:58 -08004975 }
Eric Laurent10351942014-05-08 18:49:52 -07004976 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4977 // do not accept frame count changes if tracks are open as the track buffer
4978 // size depends on frame count and correct behavior would not be garantied
4979 // if frame count is changed after track creation
4980 if (!mTracks.isEmpty()) {
4981 status = INVALID_OPERATION;
4982 } else {
4983 reconfig = true;
4984 }
4985 }
4986 if (status == NO_ERROR) {
4987 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4988 keyValuePair.string());
4989 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004990 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004991 mStandby = true;
4992 mBytesWritten = 0;
4993 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4994 keyValuePair.string());
4995 }
4996 if (status == NO_ERROR && reconfig) {
4997 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004998 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004999 }
5000 }
5001
Eric Laurent42537be2016-01-08 17:16:42 -08005002 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005003}
5004
5005uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5006{
5007 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005008 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005009 time = PlaybackThread::activeSleepTimeUs();
5010 } else {
5011 time = 10000;
5012 }
5013 return time;
5014}
5015
5016uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5017{
5018 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005019 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005020 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5021 } else {
5022 time = 10000;
5023 }
5024 return time;
5025}
5026
5027uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5028{
5029 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005030 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005031 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5032 } else {
5033 time = 10000;
5034 }
5035 return time;
5036}
5037
5038void AudioFlinger::DirectOutputThread::cacheParameters_l()
5039{
5040 PlaybackThread::cacheParameters_l();
5041
5042 // use shorter standby delay as on normal output to release
5043 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005044 // no delay on outputs with HW A/V sync
5045 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005046 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005047 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005048 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005049 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005050 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005051 }
Eric Laurent81784c32012-11-19 14:55:58 -08005052}
5053
Eric Laurente659ef42014-09-29 13:06:46 -07005054void AudioFlinger::DirectOutputThread::flushHw_l()
5055{
Phil Burk062e67a2015-02-11 13:40:50 -08005056 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005058 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005059}
5060
Eric Laurent81784c32012-11-19 14:55:58 -08005061// ----------------------------------------------------------------------------
5062
Eric Laurentbfb1b832013-01-07 09:53:42 -08005063AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005064 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005065 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005066 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005067 mWriteAckSequence(0),
5068 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069{
5070}
5071
5072AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5073{
5074}
5075
5076void AudioFlinger::AsyncCallbackThread::onFirstRef()
5077{
5078 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5079}
5080
5081bool AudioFlinger::AsyncCallbackThread::threadLoop()
5082{
5083 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005084 uint32_t writeAckSequence;
5085 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005086
5087 {
5088 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005089 while (!((mWriteAckSequence & 1) ||
5090 (mDrainSequence & 1) ||
5091 exitPending())) {
5092 mWaitWorkCV.wait(mLock);
5093 }
5094
Eric Laurentbfb1b832013-01-07 09:53:42 -08005095 if (exitPending()) {
5096 break;
5097 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005098 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5099 mWriteAckSequence, mDrainSequence);
5100 writeAckSequence = mWriteAckSequence;
5101 mWriteAckSequence &= ~1;
5102 drainSequence = mDrainSequence;
5103 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005104 }
5105 {
Eric Laurent4de95592013-09-26 15:28:21 -07005106 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5107 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005108 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005109 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005110 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005111 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005112 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005113 }
5114 }
5115 }
5116 }
5117 return false;
5118}
5119
5120void AudioFlinger::AsyncCallbackThread::exit()
5121{
5122 ALOGV("AsyncCallbackThread::exit");
5123 Mutex::Autolock _l(mLock);
5124 requestExit();
5125 mWaitWorkCV.broadcast();
5126}
5127
Eric Laurent3b4529e2013-09-05 18:09:19 -07005128void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005129{
5130 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005131 // bit 0 is cleared
5132 mWriteAckSequence = sequence << 1;
5133}
5134
5135void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5136{
5137 Mutex::Autolock _l(mLock);
5138 // ignore unexpected callbacks
5139 if (mWriteAckSequence & 2) {
5140 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005141 mWaitWorkCV.signal();
5142 }
5143}
5144
Eric Laurent3b4529e2013-09-05 18:09:19 -07005145void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005146{
5147 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005148 // bit 0 is cleared
5149 mDrainSequence = sequence << 1;
5150}
5151
5152void AudioFlinger::AsyncCallbackThread::resetDraining()
5153{
5154 Mutex::Autolock _l(mLock);
5155 // ignore unexpected callbacks
5156 if (mDrainSequence & 2) {
5157 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 mWaitWorkCV.signal();
5159 }
5160}
5161
5162
5163// ----------------------------------------------------------------------------
5164AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005165 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5166 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005167 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005168{
Eric Laurentfd477972013-10-25 18:10:40 -07005169 //FIXME: mStandby should be set to true by ThreadBase constructor
5170 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171}
5172
Eric Laurentbfb1b832013-01-07 09:53:42 -08005173void AudioFlinger::OffloadThread::threadLoop_exit()
5174{
5175 if (mFlushPending || mHwPaused) {
5176 // If a flush is pending or track was paused, just discard buffered data
5177 flushHw_l();
5178 } else {
5179 mMixerStatus = MIXER_DRAIN_ALL;
5180 threadLoop_drain();
5181 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005182 if (mUseAsyncWrite) {
5183 ALOG_ASSERT(mCallbackThread != 0);
5184 mCallbackThread->exit();
5185 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186 PlaybackThread::threadLoop_exit();
5187}
5188
5189AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5190 Vector< sp<Track> > *tracksToRemove
5191)
5192{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 size_t count = mActiveTracks.size();
5194
5195 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005196 bool doHwPause = false;
5197 bool doHwResume = false;
5198
Eric Laurentede6c3b2013-09-19 14:37:46 -07005199 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5200
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201 // find out which tracks need to be processed
5202 for (size_t i = 0; i < count; i++) {
5203 sp<Track> t = mActiveTracks[i].promote();
5204 // The track died recently
5205 if (t == 0) {
5206 continue;
5207 }
5208 Track* const track = t.get();
5209 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005210 // Only consider last track started for volume and mixer state control.
5211 // In theory an older track could underrun and restart after the new one starts
5212 // but as we only care about the transition phase between two tracks on a
5213 // direct output, it is not a problem to ignore the underrun case.
5214 sp<Track> l = mLatestActiveTrack.promote();
5215 bool last = l.get() == track;
5216
Haynes Mathew George7844f672014-01-15 12:32:55 -08005217 if (track->isInvalid()) {
5218 ALOGW("An invalidated track shouldn't be in active list");
5219 tracksToRemove->add(track);
5220 continue;
5221 }
5222
5223 if (track->mState == TrackBase::IDLE) {
5224 ALOGW("An idle track shouldn't be in active list");
5225 continue;
5226 }
5227
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 if (track->isPausing()) {
5229 track->setPaused();
5230 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005231 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005232 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233 mHwPaused = true;
5234 }
5235 // If we were part way through writing the mixbuffer to
5236 // the HAL we must save this until we resume
5237 // BUG - this will be wrong if a different track is made active,
5238 // in that case we want to discard the pending data in the
5239 // mixbuffer and tell the client to present it again when the
5240 // track is resumed
5241 mPausedWriteLength = mCurrentWriteLength;
5242 mPausedBytesRemaining = mBytesRemaining;
5243 mBytesRemaining = 0; // stop writing
5244 }
5245 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005246 } else if (track->isFlushPending()) {
5247 track->flushAck();
5248 if (last) {
5249 mFlushPending = true;
5250 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005251 } else if (track->isResumePending()){
5252 track->resumeAck();
5253 if (last) {
5254 if (mPausedBytesRemaining) {
5255 // Need to continue write that was interrupted
5256 mCurrentWriteLength = mPausedWriteLength;
5257 mBytesRemaining = mPausedBytesRemaining;
5258 mPausedBytesRemaining = 0;
5259 }
5260 if (mHwPaused) {
5261 doHwResume = true;
5262 mHwPaused = false;
5263 // threadLoop_mix() will handle the case that we need to
5264 // resume an interrupted write
5265 }
5266 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005267 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005268
5269 // Do not handle new data in this iteration even if track->framesReady()
5270 mixerStatus = MIXER_TRACKS_ENABLED;
5271 }
5272 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005273 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005274 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275 if (track->mFillingUpStatus == Track::FS_FILLED) {
5276 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005277 // make sure processVolume_l() will apply new volume even if 0
5278 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 }
5280
5281 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005282 sp<Track> previousTrack = mPreviousTrack.promote();
5283 if (previousTrack != 0) {
5284 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005285 // Flush any data still being written from last track
5286 mBytesRemaining = 0;
5287 if (mPausedBytesRemaining) {
5288 // Last track was paused so we also need to flush saved
5289 // mixbuffer state and invalidate track so that it will
5290 // re-submit that unwritten data when it is next resumed
5291 mPausedBytesRemaining = 0;
5292 // Invalidate is a bit drastic - would be more efficient
5293 // to have a flag to tell client that some of the
5294 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005295 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005296 }
5297 // flush data already sent to the DSP if changing audio session as audio
5298 // comes from a different source. Also invalidate previous track to force a
5299 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005300 if (previousTrack->sessionId() != track->sessionId()) {
5301 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005302 }
5303 }
5304 }
5305 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 // reset retry count
5307 track->mRetryCount = kMaxTrackRetriesOffload;
5308 mActiveTrack = t;
5309 mixerStatus = MIXER_TRACKS_READY;
5310 }
5311 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005312 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 if (track->isStopping_1()) {
5314 // Hardware buffer can hold a large amount of audio so we must
5315 // wait for all current track's data to drain before we say
5316 // that the track is stopped.
5317 if (mBytesRemaining == 0) {
5318 // Only start draining when all data in mixbuffer
5319 // has been written
5320 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5321 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005322 // do not drain if no data was ever sent to HAL (mStandby == true)
5323 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005324 // do not modify drain sequence if we are already draining. This happens
5325 // when resuming from pause after drain.
5326 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005327 mSleepTimeUs = 0;
5328 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005329 mixerStatus = MIXER_DRAIN_TRACK;
5330 mDrainSequence += 2;
5331 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332 if (mHwPaused) {
5333 // It is possible to move from PAUSED to STOPPING_1 without
5334 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005335 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005336 mHwPaused = false;
5337 }
5338 }
5339 }
5340 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005341 // Drain has completed or we are in standby, signal presentation complete
5342 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 track->mState = TrackBase::STOPPED;
5344 size_t audioHALFrames =
5345 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005346 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005347 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348 track->presentationComplete(framesWritten, audioHALFrames);
5349 track->reset();
5350 tracksToRemove->add(track);
5351 }
5352 } else {
5353 // No buffers for this track. Give it a few chances to
5354 // fill a buffer, then remove it from active list.
5355 if (--(track->mRetryCount) <= 0) {
5356 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5357 track->name());
5358 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005359 // indicate to client process that the track was disabled because of underrun;
5360 // it will then automatically call start() when data is available
5361 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 } else if (last){
5363 mixerStatus = MIXER_TRACKS_ENABLED;
5364 }
5365 }
5366 }
5367 // compute volume for this track
5368 processVolume_l(track, last);
5369 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005370
Eric Laurentea0fade2013-10-04 16:23:48 -07005371 // make sure the pause/flush/resume sequence is executed in the right order.
5372 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5373 // before flush and then resume HW. This can happen in case of pause/flush/resume
5374 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005375 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005376 mOutput->stream->pause(mOutput->stream);
5377 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005378 if (mFlushPending) {
5379 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005380 }
Eric Laurentfd477972013-10-25 18:10:40 -07005381 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005382 mOutput->stream->resume(mOutput->stream);
5383 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005384
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385 // remove all the tracks that need to be...
5386 removeTracks_l(*tracksToRemove);
5387
5388 return mixerStatus;
5389}
5390
Eric Laurentbfb1b832013-01-07 09:53:42 -08005391// must be called with thread mutex locked
5392bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5393{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005394 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5395 mWriteAckSequence, mDrainSequence);
5396 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 return true;
5398 }
5399 return false;
5400}
5401
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5403{
5404 Mutex::Autolock _l(mLock);
5405 return waitingAsyncCallback_l();
5406}
5407
5408void AudioFlinger::OffloadThread::flushHw_l()
5409{
Eric Laurente659ef42014-09-29 13:06:46 -07005410 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005411 // Flush anything still waiting in the mixbuffer
5412 mCurrentWriteLength = 0;
5413 mBytesRemaining = 0;
5414 mPausedWriteLength = 0;
5415 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005416
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005418 // discard any pending drain or write ack by incrementing sequence
5419 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5420 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005422 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5423 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424 }
5425}
5426
5427// ----------------------------------------------------------------------------
5428
Eric Laurent81784c32012-11-19 14:55:58 -08005429AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005430 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005431 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005432 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005433 mWaitTimeMs(UINT_MAX)
5434{
5435 addOutputTrack(mainThread);
5436}
5437
5438AudioFlinger::DuplicatingThread::~DuplicatingThread()
5439{
5440 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5441 mOutputTracks[i]->destroy();
5442 }
5443}
5444
5445void AudioFlinger::DuplicatingThread::threadLoop_mix()
5446{
5447 // mix buffers...
5448 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005449 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005450 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005451 if (mMixerBufferValid) {
5452 memset(mMixerBuffer, 0, mMixerBufferSize);
5453 } else {
5454 memset(mSinkBuffer, 0, mSinkBufferSize);
5455 }
Eric Laurent81784c32012-11-19 14:55:58 -08005456 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005457 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005458 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005459 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005460 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005461}
5462
5463void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5464{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005465 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005466 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005467 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005468 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005469 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005470 }
5471 } else if (mBytesWritten != 0) {
5472 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5473 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005474 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005475 } else {
5476 // flush remaining overflow buffers in output tracks
5477 writeFrames = 0;
5478 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005479 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005480 }
5481}
5482
Eric Laurentbfb1b832013-01-07 09:53:42 -08005483ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005484{
5485 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005486 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005487 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005488 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005489 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005490}
5491
5492void AudioFlinger::DuplicatingThread::threadLoop_standby()
5493{
5494 // DuplicatingThread implements standby by stopping all tracks
5495 for (size_t i = 0; i < outputTracks.size(); i++) {
5496 outputTracks[i]->stop();
5497 }
5498}
5499
5500void AudioFlinger::DuplicatingThread::saveOutputTracks()
5501{
5502 outputTracks = mOutputTracks;
5503}
5504
5505void AudioFlinger::DuplicatingThread::clearOutputTracks()
5506{
5507 outputTracks.clear();
5508}
5509
5510void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5511{
5512 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005513 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5514 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5515 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5516 const size_t frameCount =
5517 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5518 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5519 // from different OutputTracks and their associated MixerThreads (e.g. one may
5520 // nearly empty and the other may be dropping data).
5521
5522 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005523 this,
5524 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005525 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005526 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005527 frameCount,
5528 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005529 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005530 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005531 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005532 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005533 updateWaitTime_l();
5534 }
5535}
5536
5537void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5538{
5539 Mutex::Autolock _l(mLock);
5540 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5541 if (mOutputTracks[i]->thread() == thread) {
5542 mOutputTracks[i]->destroy();
5543 mOutputTracks.removeAt(i);
5544 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005545 if (thread->getOutput() == mOutput) {
5546 mOutput = NULL;
5547 }
Eric Laurent81784c32012-11-19 14:55:58 -08005548 return;
5549 }
5550 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005551 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005552}
5553
5554// caller must hold mLock
5555void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5556{
5557 mWaitTimeMs = UINT_MAX;
5558 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5559 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5560 if (strong != 0) {
5561 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5562 if (waitTimeMs < mWaitTimeMs) {
5563 mWaitTimeMs = waitTimeMs;
5564 }
5565 }
5566 }
5567}
5568
5569
5570bool AudioFlinger::DuplicatingThread::outputsReady(
5571 const SortedVector< sp<OutputTrack> > &outputTracks)
5572{
5573 for (size_t i = 0; i < outputTracks.size(); i++) {
5574 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5575 if (thread == 0) {
5576 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5577 outputTracks[i].get());
5578 return false;
5579 }
5580 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5581 // see note at standby() declaration
5582 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5583 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5584 thread.get());
5585 return false;
5586 }
5587 }
5588 return true;
5589}
5590
5591uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5592{
5593 return (mWaitTimeMs * 1000) / 2;
5594}
5595
5596void AudioFlinger::DuplicatingThread::cacheParameters_l()
5597{
5598 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5599 updateWaitTime_l();
5600
5601 MixerThread::cacheParameters_l();
5602}
5603
5604// ----------------------------------------------------------------------------
5605// Record
5606// ----------------------------------------------------------------------------
5607
5608AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5609 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005610 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005611 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005612 audio_devices_t inDevice,
5613 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005614#ifdef TEE_SINK
5615 , const sp<NBAIO_Sink>& teeSink
5616#endif
5617 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005618 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005620 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005621 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005622#ifdef TEE_SINK
5623 , mTeeSink(teeSink)
5624#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005625 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5626 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005627 // mFastCapture below
5628 , mFastCaptureFutex(0)
5629 // mInputSource
5630 // mPipeSink
5631 // mPipeSource
5632 , mPipeFramesP2(0)
5633 // mPipeMemory
5634 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005635 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005636{
Glenn Kastend7dca052015-03-05 16:05:54 -08005637 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5638 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005639
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005640 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005641
5642 // create an NBAIO source for the HAL input stream, and negotiate
5643 mInputSource = new AudioStreamInSource(input->stream);
5644 size_t numCounterOffers = 0;
5645 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5646 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5647 ALOG_ASSERT(index == 0);
5648
5649 // initialize fast capture depending on configuration
5650 bool initFastCapture;
5651 switch (kUseFastCapture) {
5652 case FastCapture_Never:
5653 initFastCapture = false;
5654 break;
5655 case FastCapture_Always:
5656 initFastCapture = true;
5657 break;
5658 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005659 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005660 break;
5661 // case FastCapture_Dynamic:
5662 }
5663
5664 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005665 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005666 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005667 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005668 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5669 void *pipeBuffer;
5670 const sp<MemoryDealer> roHeap(readOnlyHeap());
5671 sp<IMemory> pipeMemory;
5672 if ((roHeap == 0) ||
5673 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5674 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5675 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5676 goto failed;
5677 }
5678 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5679 memset(pipeBuffer, 0, pipeSize);
5680 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5681 const NBAIO_Format offers[1] = {format};
5682 size_t numCounterOffers = 0;
5683 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5684 ALOG_ASSERT(index == 0);
5685 mPipeSink = pipe;
5686 PipeReader *pipeReader = new PipeReader(*pipe);
5687 numCounterOffers = 0;
5688 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5689 ALOG_ASSERT(index == 0);
5690 mPipeSource = pipeReader;
5691 mPipeFramesP2 = pipeFramesP2;
5692 mPipeMemory = pipeMemory;
5693
5694 // create fast capture
5695 mFastCapture = new FastCapture();
5696 FastCaptureStateQueue *sq = mFastCapture->sq();
5697#ifdef STATE_QUEUE_DUMP
5698 // FIXME
5699#endif
5700 FastCaptureState *state = sq->begin();
5701 state->mCblk = NULL;
5702 state->mInputSource = mInputSource.get();
5703 state->mInputSourceGen++;
5704 state->mPipeSink = pipe;
5705 state->mPipeSinkGen++;
5706 state->mFrameCount = mFrameCount;
5707 state->mCommand = FastCaptureState::COLD_IDLE;
5708 // already done in constructor initialization list
5709 //mFastCaptureFutex = 0;
5710 state->mColdFutexAddr = &mFastCaptureFutex;
5711 state->mColdGen++;
5712 state->mDumpState = &mFastCaptureDumpState;
5713#ifdef TEE_SINK
5714 // FIXME
5715#endif
5716 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5717 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5718 sq->end();
5719 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5720
5721 // start the fast capture
5722 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5723 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005724 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005725#ifdef AUDIO_WATCHDOG
5726 // FIXME
5727#endif
5728
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005729 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005730 }
5731failed: ;
5732
5733 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005734}
5735
Eric Laurent81784c32012-11-19 14:55:58 -08005736AudioFlinger::RecordThread::~RecordThread()
5737{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005738 if (mFastCapture != 0) {
5739 FastCaptureStateQueue *sq = mFastCapture->sq();
5740 FastCaptureState *state = sq->begin();
5741 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5742 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5743 if (old == -1) {
5744 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5745 }
5746 }
5747 state->mCommand = FastCaptureState::EXIT;
5748 sq->end();
5749 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5750 mFastCapture->join();
5751 mFastCapture.clear();
5752 }
5753 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005754 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005755 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005756}
5757
5758void AudioFlinger::RecordThread::onFirstRef()
5759{
Glenn Kastend7dca052015-03-05 16:05:54 -08005760 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005761}
5762
Eric Laurent81784c32012-11-19 14:55:58 -08005763bool AudioFlinger::RecordThread::threadLoop()
5764{
Eric Laurent81784c32012-11-19 14:55:58 -08005765 nsecs_t lastWarning = 0;
5766
5767 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005768
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005769reacquire_wakelock:
5770 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005771 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005772 {
5773 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005774 size_t size = mActiveTracks.size();
5775 activeTracksGen = mActiveTracksGen;
5776 if (size > 0) {
5777 // FIXME an arbitrary choice
5778 activeTrack = mActiveTracks[0];
5779 acquireWakeLock_l(activeTrack->uid());
5780 if (size > 1) {
5781 SortedVector<int> tmp;
5782 for (size_t i = 0; i < size; i++) {
5783 tmp.add(mActiveTracks[i]->uid());
5784 }
5785 updateWakeLockUids_l(tmp);
5786 }
5787 } else {
5788 acquireWakeLock_l(-1);
5789 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005790 }
5791
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005792 // used to request a deferred sleep, to be executed later while mutex is unlocked
5793 uint32_t sleepUs = 0;
5794
5795 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005796 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005797 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005798
Glenn Kasten5edadd42013-08-14 16:30:49 -07005799 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005801 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005803 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005804 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005805 }
5806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 // activeTracks accumulates a copy of a subset of mActiveTracks
5808 Vector< sp<RecordTrack> > activeTracks;
5809
Glenn Kasten735f45f2014-08-18 15:51:59 -07005810 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005811 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005812
Glenn Kasten735f45f2014-08-18 15:51:59 -07005813 // reference to a fast track which is about to be removed
5814 sp<RecordTrack> fastTrackToRemove;
5815
Eric Laurent81784c32012-11-19 14:55:58 -08005816 { // scope for mLock
5817 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005818
Eric Laurent021cf962014-05-13 10:18:14 -07005819 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005820
Eric Laurent000a4192014-01-29 15:17:32 -08005821 // check exitPending here because checkForNewParameters_l() and
5822 // checkForNewParameters_l() can temporarily release mLock
5823 if (exitPending()) {
5824 break;
5825 }
5826
Glenn Kasten2b806402013-11-20 16:37:38 -08005827 // if no active track(s), then standby and release wakelock
5828 size_t size = mActiveTracks.size();
5829 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005830 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005831 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005832 releaseWakeLock_l();
5833 ALOGV("RecordThread: loop stopping");
5834 // go to sleep
5835 mWaitWorkCV.wait(mLock);
5836 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005837 goto reacquire_wakelock;
5838 }
5839
Glenn Kasten2b806402013-11-20 16:37:38 -08005840 if (mActiveTracksGen != activeTracksGen) {
5841 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005842 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005843 for (size_t i = 0; i < size; i++) {
5844 tmp.add(mActiveTracks[i]->uid());
5845 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005846 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005847 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005848
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005849 bool doBroadcast = false;
5850 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005851
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005852 activeTrack = mActiveTracks[i];
5853 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005854 if (activeTrack->isFastTrack()) {
5855 ALOG_ASSERT(fastTrackToRemove == 0);
5856 fastTrackToRemove = activeTrack;
5857 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005859 mActiveTracks.remove(activeTrack);
5860 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005861 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005862 continue;
5863 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005864
5865 TrackBase::track_state activeTrackState = activeTrack->mState;
5866 switch (activeTrackState) {
5867
5868 case TrackBase::PAUSING:
5869 mActiveTracks.remove(activeTrack);
5870 mActiveTracksGen++;
5871 doBroadcast = true;
5872 size--;
5873 continue;
5874
5875 case TrackBase::STARTING_1:
5876 sleepUs = 10000;
5877 i++;
5878 continue;
5879
5880 case TrackBase::STARTING_2:
5881 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005883 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884 break;
5885
5886 case TrackBase::ACTIVE:
5887 break;
5888
5889 case TrackBase::IDLE:
5890 i++;
5891 continue;
5892
5893 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005894 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005895 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005896
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005897 activeTracks.add(activeTrack);
5898 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005899
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005900 if (activeTrack->isFastTrack()) {
5901 ALOG_ASSERT(!mFastTrackAvail);
5902 ALOG_ASSERT(fastTrack == 0);
5903 fastTrack = activeTrack;
5904 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005905 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005906 if (doBroadcast) {
5907 mStartStopCond.broadcast();
5908 }
5909
5910 // sleep if there are no active tracks to process
5911 if (activeTracks.size() == 0) {
5912 if (sleepUs == 0) {
5913 sleepUs = kRecordThreadSleepUs;
5914 }
5915 continue;
5916 }
5917 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005918
Eric Laurent81784c32012-11-19 14:55:58 -08005919 lockEffectChains_l(effectChains);
5920 }
5921
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005922 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005923
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005924 size_t size = effectChains.size();
5925 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005926 // thread mutex is not locked, but effect chain is locked
5927 effectChains[i]->process_l();
5928 }
5929
Glenn Kasten735f45f2014-08-18 15:51:59 -07005930 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 if (mFastCapture != 0) {
5932 FastCaptureStateQueue *sq = mFastCapture->sq();
5933 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005934 bool didModify = false;
5935 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005936 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5937 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5938 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5939 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5940 if (old == -1) {
5941 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5942 }
5943 }
5944 state->mCommand = FastCaptureState::READ_WRITE;
5945#if 0 // FIXME
5946 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005947 FastThreadDumpState::kSamplingNforLowRamDevice :
5948 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005949#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005950 didModify = true;
5951 }
5952 audio_track_cblk_t *cblkOld = state->mCblk;
5953 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5954 if (cblkNew != cblkOld) {
5955 state->mCblk = cblkNew;
5956 // block until acked if removing a fast track
5957 if (cblkOld != NULL) {
5958 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5959 }
5960 didModify = true;
5961 }
5962 sq->end(didModify);
5963 if (didModify) {
5964 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005965#if 0
5966 if (kUseFastCapture == FastCapture_Dynamic) {
5967 mNormalSource = mPipeSource;
5968 }
5969#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005970 }
5971 }
5972
Glenn Kasten735f45f2014-08-18 15:51:59 -07005973 // now run the fast track destructor with thread mutex unlocked
5974 fastTrackToRemove.clear();
5975
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005976 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5977 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5978 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5979 // If destination is non-contiguous, first read past the nominal end of buffer, then
5980 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005983 ssize_t framesRead;
5984
5985 // If an NBAIO source is present, use it to read the normal capture's data
5986 if (mPipeSource != 0) {
5987 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005988 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08005989 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005990 if (framesRead == 0) {
5991 // since pipe is non-blocking, simulate blocking input
5992 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5993 }
5994 // otherwise use the HAL / AudioStreamIn directly
5995 } else {
5996 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005997 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005998 if (bytesRead < 0) {
5999 framesRead = bytesRead;
6000 } else {
6001 framesRead = bytesRead / mFrameSize;
6002 }
6003 }
6004
Andy Hung3f0c9022016-01-15 17:49:46 -08006005 // Update server timestamp with server stats
6006 // systemTime() is optional if the hardware supports timestamps.
6007 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6009
6010 // Update server timestamp with kernel stats
6011 if (mInput->stream->get_capture_position != nullptr) {
6012 int64_t position, time;
6013 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6014 if (ret == NO_ERROR) {
6015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6017 // Note: In general record buffers should tend to be empty in
6018 // a properly running pipeline.
6019 //
6020 // Also, it is not advantageous to call get_presentation_position during the read
6021 // as the read obtains a lock, preventing the timestamp call from executing.
6022 }
6023 }
6024 // Use this to track timestamp information
6025 // ALOGD("%s", mTimestamp.toString().c_str());
6026
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006027 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6028 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 // Force input into standby so that it tries to recover at next read attempt
6030 inputStandBy();
6031 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006032 }
6033 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006034 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006035 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006037
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006039 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006040 }
6041 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006042 {
6043 size_t part1 = mRsmpInFramesP2 - rear;
6044 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006045 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006046 (framesRead - part1) * mFrameSize);
6047 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006048 }
6049 rear = mRsmpInRear += framesRead;
6050
6051 size = activeTracks.size();
6052 // loop over each active track
6053 for (size_t i = 0; i < size; i++) {
6054 activeTrack = activeTracks[i];
6055
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056 // skip fast tracks, as those are handled directly by FastCapture
6057 if (activeTrack->isFastTrack()) {
6058 continue;
6059 }
6060
Andy Hung73c02e42015-03-29 01:13:58 -07006061 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006062 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6063
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006064 enum {
6065 OVERRUN_UNKNOWN,
6066 OVERRUN_TRUE,
6067 OVERRUN_FALSE
6068 } overrun = OVERRUN_UNKNOWN;
6069
6070 // loop over getNextBuffer to handle circular sink
6071 for (;;) {
6072
6073 activeTrack->mSink.frameCount = ~0;
6074 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6075 size_t framesOut = activeTrack->mSink.frameCount;
6076 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6077
Andy Hung73c02e42015-03-29 01:13:58 -07006078 // check available frames and handle overrun conditions
6079 // if the record track isn't draining fast enough.
6080 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006082 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6083 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006084 overrun = OVERRUN_TRUE;
6085 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006086 if (framesOut == 0 || framesIn == 0) {
6087 break;
6088 }
6089
Andy Hung6770c6f2015-04-07 13:43:36 -07006090 // Don't allow framesOut to be larger than what is possible with resampling
6091 // from framesIn.
6092 // This isn't strictly necessary but helps limit buffer resizing in
6093 // RecordBufferConverter. TODO: remove when no longer needed.
6094 framesOut = min(framesOut,
6095 destinationFramesPossible(
6096 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006097 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6098 framesOut = activeTrack->mRecordBufferConverter->convert(
6099 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006100
6101 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6102 overrun = OVERRUN_FALSE;
6103 }
6104
6105 if (activeTrack->mFramesToDrop == 0) {
6106 if (framesOut > 0) {
6107 activeTrack->mSink.frameCount = framesOut;
6108 activeTrack->releaseBuffer(&activeTrack->mSink);
6109 }
6110 } else {
6111 // FIXME could do a partial drop of framesOut
6112 if (activeTrack->mFramesToDrop > 0) {
6113 activeTrack->mFramesToDrop -= framesOut;
6114 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006115 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006116 }
6117 } else {
6118 activeTrack->mFramesToDrop += framesOut;
6119 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6120 activeTrack->mSyncStartEvent->isCancelled()) {
6121 ALOGW("Synced record %s, session %d, trigger session %d",
6122 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6123 activeTrack->sessionId(),
6124 (activeTrack->mSyncStartEvent != 0) ?
6125 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006126 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 }
6128 }
6129 }
6130
6131 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006133 }
6134 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006135
6136 switch (overrun) {
6137 case OVERRUN_TRUE:
6138 // client isn't retrieving buffers fast enough
6139 if (!activeTrack->setOverflow()) {
6140 nsecs_t now = systemTime();
6141 // FIXME should lastWarning per track?
6142 if ((now - lastWarning) > kWarningThrottleNs) {
6143 ALOGW("RecordThread: buffer overflow");
6144 lastWarning = now;
6145 }
6146 }
6147 break;
6148 case OVERRUN_FALSE:
6149 activeTrack->clearOverflow();
6150 break;
6151 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 break;
6153 }
6154
Andy Hung3f0c9022016-01-15 17:49:46 -08006155 // update frame information and push timestamp out
6156 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006157 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006158 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6159 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006160 }
6161
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006162unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006163 // enable changes in effect chain
6164 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006165 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006166 }
6167
Glenn Kasten93e471f2013-08-19 08:40:07 -07006168 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006169
6170 {
6171 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006172 for (size_t i = 0; i < mTracks.size(); i++) {
6173 sp<RecordTrack> track = mTracks[i];
6174 track->invalidate();
6175 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006176 mActiveTracks.clear();
6177 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006178 mStartStopCond.broadcast();
6179 }
6180
6181 releaseWakeLock();
6182
6183 ALOGV("RecordThread %p exiting", this);
6184 return false;
6185}
6186
Glenn Kasten93e471f2013-08-19 08:40:07 -07006187void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006188{
6189 if (!mStandby) {
6190 inputStandBy();
6191 mStandby = true;
6192 }
6193}
6194
6195void AudioFlinger::RecordThread::inputStandBy()
6196{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006197 // Idle the fast capture if it's currently running
6198 if (mFastCapture != 0) {
6199 FastCaptureStateQueue *sq = mFastCapture->sq();
6200 FastCaptureState *state = sq->begin();
6201 if (!(state->mCommand & FastCaptureState::IDLE)) {
6202 state->mCommand = FastCaptureState::COLD_IDLE;
6203 state->mColdFutexAddr = &mFastCaptureFutex;
6204 state->mColdGen++;
6205 mFastCaptureFutex = 0;
6206 sq->end();
6207 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6208 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6209#if 0
6210 if (kUseFastCapture == FastCapture_Dynamic) {
6211 // FIXME
6212 }
6213#endif
6214#ifdef AUDIO_WATCHDOG
6215 // FIXME
6216#endif
6217 } else {
6218 sq->end(false /*didModify*/);
6219 }
6220 }
Eric Laurent81784c32012-11-19 14:55:58 -08006221 mInput->stream->common.standby(&mInput->stream->common);
6222}
6223
Glenn Kasten05997e22014-03-13 15:08:33 -07006224// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006225sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006226 const sp<AudioFlinger::Client>& client,
6227 uint32_t sampleRate,
6228 audio_format_t format,
6229 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006230 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006231 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006232 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006233 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006234 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006235 pid_t tid,
6236 status_t *status)
6237{
Glenn Kasten74935e42013-12-19 08:56:45 -08006238 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006239 sp<RecordTrack> track;
6240 status_t lStatus;
6241
Glenn Kasten90e58b12013-07-31 16:16:02 -07006242 // client expresses a preference for FAST, but we get the final say
6243 if (*flags & IAudioFlinger::TRACK_FAST) {
6244 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006245 // we formerly checked for a callback handler (non-0 tid),
6246 // but that is no longer required for TRANSFER_OBTAIN mode
6247 //
Glenn Kasten74105912014-07-03 12:28:53 -07006248 // frame count is not specified, or is exactly the pipe depth
6249 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006250 // PCM data
6251 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006252 // native format
6253 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006254 // native channel mask
6255 (channelMask == mChannelMask) &&
6256 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006257 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006258 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006259 hasFastCapture() &&
6260 // there are sufficient fast track slots available
6261 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006262 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006263 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006264 frameCount, mFrameCount);
6265 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006266 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6267 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006268 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006269 frameCount, mFrameCount, mPipeFramesP2,
6270 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6271 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006272 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006273 }
6274 }
6275
6276 // compute track buffer size in frames, and suggest the notification frame count
6277 if (*flags & IAudioFlinger::TRACK_FAST) {
6278 // fast track: frame count is exactly the pipe depth
6279 frameCount = mPipeFramesP2;
6280 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6281 *notificationFrames = mFrameCount;
6282 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006283 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6284 // or 20 ms if there is a fast capture
6285 // TODO This could be a roundupRatio inline, and const
6286 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6287 * sampleRate + mSampleRate - 1) / mSampleRate;
6288 // minimum number of notification periods is at least kMinNotifications,
6289 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6290 static const size_t kMinNotifications = 3;
6291 static const uint32_t kMinMs = 30;
6292 // TODO This could be a roundupRatio inline
6293 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6294 // TODO This could be a roundupRatio inline
6295 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6296 maxNotificationFrames;
6297 const size_t minFrameCount = maxNotificationFrames *
6298 max(kMinNotifications, minNotificationsByMs);
6299 frameCount = max(frameCount, minFrameCount);
6300 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6301 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006302 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006303 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006304 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006305
Glenn Kasten15e57982013-09-24 11:52:37 -07006306 lStatus = initCheck();
6307 if (lStatus != NO_ERROR) {
6308 ALOGE("createRecordTrack_l() audio driver not initialized");
6309 goto Exit;
6310 }
Eric Laurent81784c32012-11-19 14:55:58 -08006311
6312 { // scope for mLock
6313 Mutex::Autolock _l(mLock);
6314
6315 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006316 format, channelMask, frameCount, NULL, sessionId, uid,
6317 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006318
Glenn Kasten03003332013-08-06 15:40:54 -07006319 lStatus = track->initCheck();
6320 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006321 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006322 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006323 goto Exit;
6324 }
6325 mTracks.add(track);
6326
6327 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6328 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6329 mAudioFlinger->btNrecIsOff();
6330 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6331 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006332
6333 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6334 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6335 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6336 // so ask activity manager to do this on our behalf
6337 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6338 }
Eric Laurent81784c32012-11-19 14:55:58 -08006339 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006340
Eric Laurent81784c32012-11-19 14:55:58 -08006341 lStatus = NO_ERROR;
6342
6343Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006344 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006345 return track;
6346}
6347
6348status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6349 AudioSystem::sync_event_t event,
6350 int triggerSession)
6351{
6352 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6353 sp<ThreadBase> strongMe = this;
6354 status_t status = NO_ERROR;
6355
6356 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006357 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006358 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006360 triggerSession,
6361 recordTrack->sessionId(),
6362 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006363 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006364 // Sync event can be cancelled by the trigger session if the track is not in a
6365 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006366 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006367 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006368 } else {
6369 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006370 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006371 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006372 }
6373 }
6374
6375 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006376 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006377 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006378 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6379 if (recordTrack->mState == TrackBase::PAUSING) {
6380 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006381 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 } else {
6383 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006384 }
6385 return status;
6386 }
6387
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006388 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6389 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6390 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006392 mActiveTracks.add(recordTrack);
6393 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006394 status_t status = NO_ERROR;
6395 if (recordTrack->isExternalTrack()) {
6396 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006397 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006398 mLock.lock();
6399 // FIXME should verify that recordTrack is still in mActiveTracks
6400 if (status != NO_ERROR) {
6401 mActiveTracks.remove(recordTrack);
6402 mActiveTracksGen++;
6403 recordTrack->clearSyncStartEvent();
6404 ALOGV("RecordThread::start error %d", status);
6405 return status;
6406 }
Eric Laurent81784c32012-11-19 14:55:58 -08006407 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006408 // Catch up with current buffer indices if thread is already running.
6409 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6410 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6411 // see previously buffered data before it called start(), but with greater risk of overrun.
6412
Andy Hung73c02e42015-03-29 01:13:58 -07006413 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006414 // clear any converter state as new data will be discontinuous
6415 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006416 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006417 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006418 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006419 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006420 ALOGV("Record failed to start");
6421 status = BAD_VALUE;
6422 goto startError;
6423 }
Eric Laurent81784c32012-11-19 14:55:58 -08006424 return status;
6425 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006426
Eric Laurent81784c32012-11-19 14:55:58 -08006427startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006428 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006429 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006430 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006431 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006433 return status;
6434}
6435
Eric Laurent81784c32012-11-19 14:55:58 -08006436void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6437{
6438 sp<SyncEvent> strongEvent = event.promote();
6439
6440 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006441 sp<RefBase> ptr = strongEvent->cookie().promote();
6442 if (ptr != 0) {
6443 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6444 recordTrack->handleSyncStartEvent(strongEvent);
6445 }
Eric Laurent81784c32012-11-19 14:55:58 -08006446 }
6447}
6448
Glenn Kastena8356f62013-07-25 14:37:52 -07006449bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006450 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006451 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006452 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006453 return false;
6454 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006455 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006456 recordTrack->mState = TrackBase::PAUSING;
6457 // do not wait for mStartStopCond if exiting
6458 if (exitPending()) {
6459 return true;
6460 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006461 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006462 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006463 // if we have been restarted, recordTrack is in mActiveTracks here
6464 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006465 ALOGV("Record stopped OK");
6466 return true;
6467 }
6468 return false;
6469}
6470
Glenn Kasten0f11b512014-01-31 16:18:54 -08006471bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006472{
6473 return false;
6474}
6475
Glenn Kasten0f11b512014-01-31 16:18:54 -08006476status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006477{
6478#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6479 if (!isValidSyncEvent(event)) {
6480 return BAD_VALUE;
6481 }
6482
6483 int eventSession = event->triggerSession();
6484 status_t ret = NAME_NOT_FOUND;
6485
6486 Mutex::Autolock _l(mLock);
6487
6488 for (size_t i = 0; i < mTracks.size(); i++) {
6489 sp<RecordTrack> track = mTracks[i];
6490 if (eventSession == track->sessionId()) {
6491 (void) track->setSyncEvent(event);
6492 ret = NO_ERROR;
6493 }
6494 }
6495 return ret;
6496#else
6497 return BAD_VALUE;
6498#endif
6499}
6500
6501// destroyTrack_l() must be called with ThreadBase::mLock held
6502void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6503{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006504 track->terminate();
6505 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006506 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006507 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006508 removeTrack_l(track);
6509 }
6510}
6511
6512void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6513{
6514 mTracks.remove(track);
6515 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006516 if (track->isFastTrack()) {
6517 ALOG_ASSERT(!mFastTrackAvail);
6518 mFastTrackAvail = true;
6519 }
Eric Laurent81784c32012-11-19 14:55:58 -08006520}
6521
6522void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6523{
6524 dumpInternals(fd, args);
6525 dumpTracks(fd, args);
6526 dumpEffectChains(fd, args);
6527}
6528
6529void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6530{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006531 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006532
Glenn Kasten44182c22015-03-05 17:12:23 -08006533 dumpBase(fd, args);
6534
6535 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006536 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006537 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006538 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006539 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006540
Glenn Kasten2f90c512015-12-02 11:40:09 -08006541 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6542 // while we are dumping it. It may be inconsistent, but it won't mutate!
6543 // This is a large object so we place it on the heap.
6544 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6545 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6546 copy->dump(fd);
6547 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006548}
6549
Glenn Kasten0f11b512014-01-31 16:18:54 -08006550void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006551{
6552 const size_t SIZE = 256;
6553 char buffer[SIZE];
6554 String8 result;
6555
Marco Nelissenb2208842014-02-07 14:00:50 -08006556 size_t numtracks = mTracks.size();
6557 size_t numactive = mActiveTracks.size();
6558 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006559 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006560 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006561 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006562 RecordTrack::appendDumpHeader(result);
6563 for (size_t i = 0; i < numtracks ; ++i) {
6564 sp<RecordTrack> track = mTracks[i];
6565 if (track != 0) {
6566 bool active = mActiveTracks.indexOf(track) >= 0;
6567 if (active) {
6568 numactiveseen++;
6569 }
6570 track->dump(buffer, SIZE, active);
6571 result.append(buffer);
6572 }
Eric Laurent81784c32012-11-19 14:55:58 -08006573 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006574 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006575 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006576 }
6577
Marco Nelissenb2208842014-02-07 14:00:50 -08006578 if (numactiveseen != numactive) {
6579 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6580 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006581 result.append(buffer);
6582 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006583 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006584 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006585 if (mTracks.indexOf(track) < 0) {
6586 track->dump(buffer, SIZE, true);
6587 result.append(buffer);
6588 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006589 }
Eric Laurent81784c32012-11-19 14:55:58 -08006590
6591 }
6592 write(fd, result.string(), result.size());
6593}
6594
Andy Hung73c02e42015-03-29 01:13:58 -07006595
6596void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6597{
6598 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6599 RecordThread *recordThread = (RecordThread *) threadBase.get();
6600 mRsmpInFront = recordThread->mRsmpInRear;
6601 mRsmpInUnrel = 0;
6602}
6603
6604void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6605 size_t *framesAvailable, bool *hasOverrun)
6606{
6607 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6608 RecordThread *recordThread = (RecordThread *) threadBase.get();
6609 const int32_t rear = recordThread->mRsmpInRear;
6610 const int32_t front = mRsmpInFront;
6611 const ssize_t filled = rear - front;
6612
6613 size_t framesIn;
6614 bool overrun = false;
6615 if (filled < 0) {
6616 // should not happen, but treat like a massive overrun and re-sync
6617 framesIn = 0;
6618 mRsmpInFront = rear;
6619 overrun = true;
6620 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6621 framesIn = (size_t) filled;
6622 } else {
6623 // client is not keeping up with server, but give it latest data
6624 framesIn = recordThread->mRsmpInFrames;
6625 mRsmpInFront = /* front = */ rear - framesIn;
6626 overrun = true;
6627 }
6628 if (framesAvailable != NULL) {
6629 *framesAvailable = framesIn;
6630 }
6631 if (hasOverrun != NULL) {
6632 *hasOverrun = overrun;
6633 }
6634}
6635
Eric Laurent81784c32012-11-19 14:55:58 -08006636// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006637status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006638 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006639{
Andy Hung73c02e42015-03-29 01:13:58 -07006640 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006641 if (threadBase == 0) {
6642 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006643 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006644 return NOT_ENOUGH_DATA;
6645 }
6646 RecordThread *recordThread = (RecordThread *) threadBase.get();
6647 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006648 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006649 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006650 // FIXME should not be P2 (don't want to increase latency)
6651 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006652 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006653 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 front &= recordThread->mRsmpInFramesP2 - 1;
6655 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006656 if (part1 > (size_t) filled) {
6657 part1 = filled;
6658 }
6659 size_t ask = buffer->frameCount;
6660 ALOG_ASSERT(ask > 0);
6661 if (part1 > ask) {
6662 part1 = ask;
6663 }
6664 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006665 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006666 buffer->raw = NULL;
6667 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006668 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006669 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006670 }
6671
Andy Hung57446612015-04-19 23:56:46 -07006672 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006673 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006674 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006675 return NO_ERROR;
6676}
6677
6678// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006679void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6680 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006681{
Glenn Kasten85948432013-08-19 12:09:05 -07006682 size_t stepCount = buffer->frameCount;
6683 if (stepCount == 0) {
6684 return;
6685 }
Andy Hung73c02e42015-03-29 01:13:58 -07006686 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6687 mRsmpInUnrel -= stepCount;
6688 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006689 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006690 buffer->frameCount = 0;
6691}
6692
Andy Hung97a893e2015-03-29 01:03:07 -07006693AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6694 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6695 uint32_t srcSampleRate,
6696 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6697 uint32_t dstSampleRate) :
6698 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6699 // mSrcFormat
6700 // mSrcSampleRate
6701 // mDstChannelMask
6702 // mDstFormat
6703 // mDstSampleRate
6704 // mSrcChannelCount
6705 // mDstChannelCount
6706 // mDstFrameSize
6707 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006708 mResampler(NULL),
6709 mIsLegacyDownmix(false),
6710 mIsLegacyUpmix(false),
6711 mRequiresFloat(false),
6712 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006713{
6714 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6715 dstChannelMask, dstFormat, dstSampleRate);
6716}
6717
6718AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6719 free(mBuf);
6720 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006721 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006722}
6723
6724size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6725 AudioBufferProvider *provider, size_t frames)
6726{
Andy Hungd330ee42015-04-20 13:23:41 -07006727 if (mInputConverterProvider != NULL) {
6728 mInputConverterProvider->setBufferProvider(provider);
6729 provider = mInputConverterProvider;
6730 }
6731
6732 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006733 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6734 mSrcSampleRate, mSrcFormat, mDstFormat);
6735
6736 AudioBufferProvider::Buffer buffer;
6737 for (size_t i = frames; i > 0; ) {
6738 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006739 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006740 if (status != OK || buffer.frameCount == 0) {
6741 frames -= i; // cannot fill request.
6742 break;
6743 }
Andy Hungd330ee42015-04-20 13:23:41 -07006744 // format convert to destination buffer
6745 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006746
6747 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6748 i -= buffer.frameCount;
6749 provider->releaseBuffer(&buffer);
6750 }
6751 } else {
6752 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6753 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6754
Andy Hungd330ee42015-04-20 13:23:41 -07006755 // reallocate buffer if needed
6756 if (mBufFrameSize != 0 && mBufFrames < frames) {
6757 free(mBuf);
6758 mBufFrames = frames;
6759 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6760 }
Andy Hung97a893e2015-03-29 01:03:07 -07006761 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006762 memset(mBuf, 0, frames * mBufFrameSize);
6763 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6764 // format convert to destination buffer
6765 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006766 }
6767 return frames;
6768}
6769
6770status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6771 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6772 uint32_t srcSampleRate,
6773 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6774 uint32_t dstSampleRate)
6775{
6776 // quick evaluation if there is any change.
6777 if (mSrcFormat == srcFormat
6778 && mSrcChannelMask == srcChannelMask
6779 && mSrcSampleRate == srcSampleRate
6780 && mDstFormat == dstFormat
6781 && mDstChannelMask == dstChannelMask
6782 && mDstSampleRate == dstSampleRate) {
6783 return NO_ERROR;
6784 }
6785
Andy Hungdb4c0312015-05-06 08:46:52 -07006786 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6787 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6788 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006789 const bool valid =
6790 audio_is_input_channel(srcChannelMask)
6791 && audio_is_input_channel(dstChannelMask)
6792 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6793 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6794 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6795 ; // no upsampling checks for now
6796 if (!valid) {
6797 return BAD_VALUE;
6798 }
6799
6800 mSrcFormat = srcFormat;
6801 mSrcChannelMask = srcChannelMask;
6802 mSrcSampleRate = srcSampleRate;
6803 mDstFormat = dstFormat;
6804 mDstChannelMask = dstChannelMask;
6805 mDstSampleRate = dstSampleRate;
6806
6807 // compute derived parameters
6808 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6809 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6810 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6811
Andy Hungd330ee42015-04-20 13:23:41 -07006812 // do we need to resample?
6813 delete mResampler;
6814 mResampler = NULL;
6815 if (mSrcSampleRate != mDstSampleRate) {
6816 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6817 mSrcChannelCount, mDstSampleRate);
6818 mResampler->setSampleRate(mSrcSampleRate);
6819 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6820 }
6821
6822 // are we running legacy channel conversion modes?
6823 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6824 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6825 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6826 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6827 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6828 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6829
6830 // do we need to process in float?
6831 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6832
6833 // do we need a staging buffer to convert for destination (we can still optimize this)?
6834 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6835 if (mResampler != NULL) {
6836 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6837 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006838 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006839 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6840 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006841 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6842 } else {
6843 mBufFrameSize = 0;
6844 }
6845 mBufFrames = 0; // force the buffer to be resized.
6846
Andy Hungd330ee42015-04-20 13:23:41 -07006847 // do we need an input converter buffer provider to give us float?
6848 delete mInputConverterProvider;
6849 mInputConverterProvider = NULL;
6850 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6851 mInputConverterProvider = new ReformatBufferProvider(
6852 audio_channel_count_from_in_mask(mSrcChannelMask),
6853 mSrcFormat,
6854 AUDIO_FORMAT_PCM_FLOAT,
6855 256 /* provider buffer frame count */);
6856 }
6857
6858 // do we need a remixer to do channel mask conversion
6859 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6860 (void) memcpy_by_index_array_initialization_from_channel_mask(
6861 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006862 }
6863 return NO_ERROR;
6864}
6865
Andy Hungd330ee42015-04-20 13:23:41 -07006866void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6867 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006868{
Andy Hungd330ee42015-04-20 13:23:41 -07006869 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006870 if (mBufFrameSize != 0 && mBufFrames < frames) {
6871 free(mBuf);
6872 mBufFrames = frames;
6873 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6874 }
Andy Hungd330ee42015-04-20 13:23:41 -07006875 // do we need to do legacy upmix and downmix?
6876 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006877 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006878 if (mIsLegacyUpmix) {
6879 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6880 (const float *)src, frames);
6881 } else /*mIsLegacyDownmix */ {
6882 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6883 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006884 }
Andy Hungd330ee42015-04-20 13:23:41 -07006885 if (mBuf != NULL) {
6886 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6887 frames * mDstChannelCount);
6888 }
6889 return;
6890 }
6891 // do we need to do channel mask conversion?
6892 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006893 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006894 memcpy_by_index_array(dstBuf, mDstChannelCount,
6895 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6896 if (dstBuf == dst) {
6897 return; // format is the same
6898 }
6899 }
6900 // convert to destination buffer
6901 const void *convertBuf = mBuf != NULL ? mBuf : src;
6902 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6903 frames * mDstChannelCount);
6904}
6905
6906void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6907 void *dst, /*not-a-const*/ void *src, size_t frames)
6908{
6909 // src buffer format is ALWAYS float when entering this routine
6910 if (mIsLegacyUpmix) {
6911 ; // mono to stereo already handled by resampler
6912 } else if (mIsLegacyDownmix
6913 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6914 // the resampler outputs stereo for mono input channel (a feature?)
6915 // must convert to mono
6916 downmix_to_mono_float_from_stereo_float((float *)src,
6917 (const float *)src, frames);
6918 } else if (mSrcChannelMask != mDstChannelMask) {
6919 // convert to mono channel again for channel mask conversion (could be skipped
6920 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006921 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006922 downmix_to_mono_float_from_stereo_float((float *)src,
6923 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006924 }
Andy Hungd330ee42015-04-20 13:23:41 -07006925 // convert to destination format (in place, OK as float is larger than other types)
6926 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6927 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6928 frames * mSrcChannelCount);
6929 }
6930 // channel convert and save to dst
6931 memcpy_by_index_array(dst, mDstChannelCount,
6932 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6933 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006934 }
Andy Hungd330ee42015-04-20 13:23:41 -07006935 // convert to destination format and save to dst
6936 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6937 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006938}
6939
Eric Laurent10351942014-05-08 18:49:52 -07006940bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6941 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006942{
6943 bool reconfig = false;
6944
Eric Laurent10351942014-05-08 18:49:52 -07006945 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006946
Eric Laurent10351942014-05-08 18:49:52 -07006947 audio_format_t reqFormat = mFormat;
6948 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006949 // 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 -07006950 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6951
6952 AudioParameter param = AudioParameter(keyValuePair);
6953 int value;
6954 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6955 // channel count change can be requested. Do we mandate the first client defines the
6956 // HAL sampling rate and channel count or do we allow changes on the fly?
6957 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6958 samplingRate = value;
6959 reconfig = true;
6960 }
6961 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006962 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006963 status = BAD_VALUE;
6964 } else {
6965 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006966 reconfig = true;
6967 }
Eric Laurent10351942014-05-08 18:49:52 -07006968 }
6969 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6970 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006971 if (!audio_is_input_channel(mask) ||
6972 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006973 status = BAD_VALUE;
6974 } else {
6975 channelMask = mask;
6976 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006977 }
Eric Laurent10351942014-05-08 18:49:52 -07006978 }
6979 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6980 // do not accept frame count changes if tracks are open as the track buffer
6981 // size depends on frame count and correct behavior would not be guaranteed
6982 // if frame count is changed after track creation
6983 if (mActiveTracks.size() > 0) {
6984 status = INVALID_OPERATION;
6985 } else {
6986 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006987 }
Eric Laurent10351942014-05-08 18:49:52 -07006988 }
6989 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6990 // forward device change to effects that have requested to be
6991 // aware of attached audio device.
6992 for (size_t i = 0; i < mEffectChains.size(); i++) {
6993 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006994 }
Eric Laurent81784c32012-11-19 14:55:58 -08006995
Eric Laurent10351942014-05-08 18:49:52 -07006996 // store input device and output device but do not forward output device to audio HAL.
6997 // Note that status is ignored by the caller for output device
6998 // (see AudioFlinger::setParameters()
6999 if (audio_is_output_devices(value)) {
7000 mOutDevice = value;
7001 status = BAD_VALUE;
7002 } else {
7003 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007004 if (value != AUDIO_DEVICE_NONE) {
7005 mPrevInDevice = value;
7006 }
Eric Laurent10351942014-05-08 18:49:52 -07007007 // disable AEC and NS if the device is a BT SCO headset supporting those
7008 // pre processings
7009 if (mTracks.size() > 0) {
7010 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7011 mAudioFlinger->btNrecIsOff();
7012 for (size_t i = 0; i < mTracks.size(); i++) {
7013 sp<RecordTrack> track = mTracks[i];
7014 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7015 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007016 }
7017 }
7018 }
Eric Laurent10351942014-05-08 18:49:52 -07007019 }
7020 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7021 mAudioSource != (audio_source_t)value) {
7022 // forward device change to effects that have requested to be
7023 // aware of attached audio device.
7024 for (size_t i = 0; i < mEffectChains.size(); i++) {
7025 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007026 }
Eric Laurent10351942014-05-08 18:49:52 -07007027 mAudioSource = (audio_source_t)value;
7028 }
Glenn Kastene198c362013-08-13 09:13:36 -07007029
Eric Laurent10351942014-05-08 18:49:52 -07007030 if (status == NO_ERROR) {
7031 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7032 keyValuePair.string());
7033 if (status == INVALID_OPERATION) {
7034 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007035 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7036 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007037 }
7038 if (reconfig) {
7039 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007040 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7041 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007042 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007043 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007044 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007045 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007046 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007047 }
Eric Laurent10351942014-05-08 18:49:52 -07007048 if (status == NO_ERROR) {
7049 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007050 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007051 }
7052 }
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
Eric Laurent10351942014-05-08 18:49:52 -07007054
Eric Laurent81784c32012-11-19 14:55:58 -08007055 return reconfig;
7056}
7057
7058String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7059{
Eric Laurent81784c32012-11-19 14:55:58 -08007060 Mutex::Autolock _l(mLock);
7061 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007062 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
7064
Glenn Kastend8ea6992013-07-16 14:17:15 -07007065 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7066 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007067 free(s);
7068 return out_s8;
7069}
7070
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007071void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007072 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7073
7074 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007075
7076 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007077 case AUDIO_INPUT_OPENED:
7078 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007079 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007080 desc->mChannelMask = mChannelMask;
7081 desc->mSamplingRate = mSampleRate;
7082 desc->mFormat = mFormat;
7083 desc->mFrameCount = mFrameCount;
7084 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007085 break;
7086
Eric Laurent73e26b62015-04-27 16:55:58 -07007087 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007088 default:
7089 break;
7090 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007091 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007092}
7093
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007094void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007095{
Eric Laurent81784c32012-11-19 14:55:58 -08007096 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7097 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007098 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007099 if (mChannelCount > FCC_8) {
7100 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7101 }
Andy Hung463be252014-07-10 16:56:07 -07007102 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7103 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007104 if (!audio_is_linear_pcm(mFormat)) {
7105 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007106 }
Eric Laurent665470b2014-07-03 16:37:08 -07007107 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007108 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7109 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007110 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007111 // 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 -07007112 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007113 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007114 // A larger value should allow more old data to be read after a track calls start(),
7115 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007116 //
7117 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007118 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007119 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007120 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007121 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007122
7123 // TODO optimize audio capture buffer sizes ...
7124 // Here we calculate the size of the sliding buffer used as a source
7125 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7126 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7127 // be better to have it derived from the pipe depth in the long term.
7128 // The current value is higher than necessary. However it should not add to latency.
7129
Glenn Kasten85948432013-08-19 12:09:05 -07007130 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007131 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7132 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7133 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007134
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007135 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7136 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007137}
7138
Glenn Kasten5f972c02014-01-13 09:59:31 -08007139uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007140{
7141 Mutex::Autolock _l(mLock);
7142 if (initCheck() != NO_ERROR) {
7143 return 0;
7144 }
7145
7146 return mInput->stream->get_input_frames_lost(mInput->stream);
7147}
7148
7149uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7150{
7151 Mutex::Autolock _l(mLock);
7152 uint32_t result = 0;
7153 if (getEffectChain_l(sessionId) != 0) {
7154 result = EFFECT_SESSION;
7155 }
7156
7157 for (size_t i = 0; i < mTracks.size(); ++i) {
7158 if (sessionId == mTracks[i]->sessionId()) {
7159 result |= TRACK_SESSION;
7160 break;
7161 }
7162 }
7163
7164 return result;
7165}
7166
7167KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7168{
7169 KeyedVector<int, bool> ids;
7170 Mutex::Autolock _l(mLock);
7171 for (size_t j = 0; j < mTracks.size(); ++j) {
7172 sp<RecordThread::RecordTrack> track = mTracks[j];
7173 int sessionId = track->sessionId();
7174 if (ids.indexOfKey(sessionId) < 0) {
7175 ids.add(sessionId, true);
7176 }
7177 }
7178 return ids;
7179}
7180
7181AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7182{
7183 Mutex::Autolock _l(mLock);
7184 AudioStreamIn *input = mInput;
7185 mInput = NULL;
7186 return input;
7187}
7188
7189// this method must always be called either with ThreadBase mLock held or inside the thread loop
7190audio_stream_t* AudioFlinger::RecordThread::stream() const
7191{
7192 if (mInput == NULL) {
7193 return NULL;
7194 }
7195 return &mInput->stream->common;
7196}
7197
7198status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7199{
7200 // only one chain per input thread
7201 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007202 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007203 return INVALID_OPERATION;
7204 }
7205 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007206 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007207 chain->setInBuffer(NULL);
7208 chain->setOutBuffer(NULL);
7209
7210 checkSuspendOnAddEffectChain_l(chain);
7211
Eric Laurent1b928682014-10-02 19:41:47 -07007212 // make sure enabled pre processing effects state is communicated to the HAL as we
7213 // just moved them to a new input stream.
7214 chain->syncHalEffectsState();
7215
Eric Laurent81784c32012-11-19 14:55:58 -08007216 mEffectChains.add(chain);
7217
7218 return NO_ERROR;
7219}
7220
7221size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7222{
7223 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7224 ALOGW_IF(mEffectChains.size() != 1,
7225 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7226 chain.get(), mEffectChains.size(), this);
7227 if (mEffectChains.size() == 1) {
7228 mEffectChains.removeAt(0);
7229 }
7230 return 0;
7231}
7232
Eric Laurent1c333e22014-05-20 10:48:17 -07007233status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7234 audio_patch_handle_t *handle)
7235{
7236 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007237
7238 // store new device and send to effects
7239 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007240 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007241 for (size_t i = 0; i < mEffectChains.size(); i++) {
7242 mEffectChains[i]->setDevice_l(mInDevice);
7243 }
7244
7245 // disable AEC and NS if the device is a BT SCO headset supporting those
7246 // pre processings
7247 if (mTracks.size() > 0) {
7248 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7249 mAudioFlinger->btNrecIsOff();
7250 for (size_t i = 0; i < mTracks.size(); i++) {
7251 sp<RecordTrack> track = mTracks[i];
7252 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7253 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7254 }
7255 }
7256
7257 // store new source and send to effects
7258 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7259 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007260 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007261 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007262 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007263 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007264
Eric Laurent054d9d32015-04-24 08:48:48 -07007265 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007266 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7267 status = hwDevice->create_audio_patch(hwDevice,
7268 patch->num_sources,
7269 patch->sources,
7270 patch->num_sinks,
7271 patch->sinks,
7272 handle);
7273 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007274 char *address;
7275 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7276 address = audio_device_address_to_parameter(
7277 patch->sources[0].ext.device.type,
7278 patch->sources[0].ext.device.address);
7279 } else {
7280 address = (char *)calloc(1, 1);
7281 }
7282 AudioParameter param = AudioParameter(String8(address));
7283 free(address);
7284 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7285 (int)patch->sources[0].ext.device.type);
7286 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7287 (int)patch->sinks[0].ext.mix.usecase.source);
7288 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7289 param.toString().string());
7290 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007291 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007292
Eric Laurente8726fe2015-06-26 09:39:24 -07007293 if (mInDevice != mPrevInDevice) {
7294 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7295 mPrevInDevice = mInDevice;
7296 }
Eric Laurent296fb132015-05-01 11:38:42 -07007297
Eric Laurent1c333e22014-05-20 10:48:17 -07007298 return status;
7299}
7300
7301status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7302{
7303 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007304
7305 mInDevice = AUDIO_DEVICE_NONE;
7306
Eric Laurent1c333e22014-05-20 10:48:17 -07007307 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7308 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7309 status = hwDevice->release_audio_patch(hwDevice, handle);
7310 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007311 AudioParameter param;
7312 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7313 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7314 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007315 }
7316 return status;
7317}
7318
Eric Laurent83b88082014-06-20 18:31:16 -07007319void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7320{
7321 Mutex::Autolock _l(mLock);
7322 mTracks.add(record);
7323}
7324
7325void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7326{
7327 Mutex::Autolock _l(mLock);
7328 destroyTrack_l(record);
7329}
7330
7331void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7332{
7333 ThreadBase::getAudioPortConfig(config);
7334 config->role = AUDIO_PORT_ROLE_SINK;
7335 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7336 config->ext.mix.usecase.source = mAudioSource;
7337}
Eric Laurent1c333e22014-05-20 10:48:17 -07007338
Glenn Kasten63238ef2015-03-02 15:50:29 -08007339} // namespace android