blob: e0d8f7586664fcd5ea98363aa63fc703a04449c4 [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"},
471 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800472 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800473 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
474 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
475 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
476 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
477 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
478 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
479 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
480 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
481 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
482 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
483 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
484 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
485 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
486 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
487 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
488 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
489 {AUDIO_DEVICE_IN_LINE, "LINE"},
490 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
491 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
492 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
493 {AUDIO_DEVICE_IN_IP, "IP"},
494 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800495 };
496 String8 result;
497 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
498 const mapping *entry;
499 if (devices & AUDIO_DEVICE_BIT_IN) {
500 devices &= ~AUDIO_DEVICE_BIT_IN;
501 entry = mappingsIn;
502 } else {
503 entry = mappingsOut;
504 }
505 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
506 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
507 if (devices & entry->mDevices) {
508 if (!result.isEmpty()) {
509 result.append("|");
510 }
511 result.append(entry->mString);
512 }
513 }
514 if (devices & ~allDevices) {
515 if (!result.isEmpty()) {
516 result.append("|");
517 }
518 result.appendFormat("0x%X", devices & ~allDevices);
519 }
520 if (result.isEmpty()) {
521 result.append(entry->mString);
522 }
523 return result;
524}
525
526String8 inputFlagsToString(audio_input_flags_t flags)
527{
528 static const struct mapping {
529 audio_input_flags_t mFlag;
530 const char * mString;
531 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800532 {AUDIO_INPUT_FLAG_FAST, "FAST"},
533 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
534 {AUDIO_INPUT_FLAG_RAW, "RAW"},
535 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
536 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800537 };
538 String8 result;
539 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
540 const mapping *entry;
541 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
542 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
543 if (flags & entry->mFlag) {
544 if (!result.isEmpty()) {
545 result.append("|");
546 }
547 result.append(entry->mString);
548 }
549 }
550 if (flags & ~allFlags) {
551 if (!result.isEmpty()) {
552 result.append("|");
553 }
554 result.appendFormat("0x%X", flags & ~allFlags);
555 }
556 if (result.isEmpty()) {
557 result.append(entry->mString);
558 }
559 return result;
560}
561
562String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700563{
564 static const struct mapping {
565 audio_output_flags_t mFlag;
566 const char * mString;
567 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800568 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
569 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
570 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
571 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
572 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
573 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
574 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
575 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
576 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
577 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
578 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700579 };
580 String8 result;
581 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
582 const mapping *entry;
583 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
584 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
585 if (flags & entry->mFlag) {
586 if (!result.isEmpty()) {
587 result.append("|");
588 }
589 result.append(entry->mString);
590 }
591 }
592 if (flags & ~allFlags) {
593 if (!result.isEmpty()) {
594 result.append("|");
595 }
596 result.appendFormat("0x%X", flags & ~allFlags);
597 }
598 if (result.isEmpty()) {
599 result.append(entry->mString);
600 }
601 return result;
602}
603
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800604const char *sourceToString(audio_source_t source)
605{
606 switch (source) {
607 case AUDIO_SOURCE_DEFAULT: return "default";
608 case AUDIO_SOURCE_MIC: return "mic";
609 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
610 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
611 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
612 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
613 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
614 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
615 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800616 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800617 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
618 case AUDIO_SOURCE_HOTWORD: return "hotword";
619 default: return "unknown";
620 }
621}
622
Eric Laurent81784c32012-11-19 14:55:58 -0800623AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700624 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800625 : Thread(false /*canCallJava*/),
626 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700627 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700628 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800629 // are set by PlaybackThread::readOutputParameters_l() or
630 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700631 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800632 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700633 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
634 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800635 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700636 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800637 mSystemReady(systemReady),
638 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800639{
Eric Laurent296fb132015-05-01 11:38:42 -0700640 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800641}
642
643AudioFlinger::ThreadBase::~ThreadBase()
644{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700645 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700646 mConfigEvents.clear();
647
Eric Laurent81784c32012-11-19 14:55:58 -0800648 // do not lock the mutex in destructor
649 releaseWakeLock_l();
650 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800651 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800652 binder->unlinkToDeath(mDeathRecipient);
653 }
654}
655
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700656status_t AudioFlinger::ThreadBase::readyToRun()
657{
658 status_t status = initCheck();
659 if (status == NO_ERROR) {
660 ALOGI("AudioFlinger's thread %p ready to run", this);
661 } else {
662 ALOGE("No working audio driver found.");
663 }
664 return status;
665}
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667void AudioFlinger::ThreadBase::exit()
668{
669 ALOGV("ThreadBase::exit");
670 // do any cleanup required for exit to succeed
671 preExit();
672 {
673 // This lock prevents the following race in thread (uniprocessor for illustration):
674 // if (!exitPending()) {
675 // // context switch from here to exit()
676 // // exit() calls requestExit(), what exitPending() observes
677 // // exit() calls signal(), which is dropped since no waiters
678 // // context switch back from exit() to here
679 // mWaitWorkCV.wait(...);
680 // // now thread is hung
681 // }
682 AutoMutex lock(mLock);
683 requestExit();
684 mWaitWorkCV.broadcast();
685 }
686 // When Thread::requestExitAndWait is made virtual and this method is renamed to
687 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
688 requestExitAndWait();
689}
690
691status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
692{
693 status_t status;
694
695 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
696 Mutex::Autolock _l(mLock);
697
Eric Laurent10351942014-05-08 18:49:52 -0700698 return sendSetParameterConfigEvent_l(keyValuePairs);
699}
700
701// sendConfigEvent_l() must be called with ThreadBase::mLock held
702// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
703status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
704{
705 status_t status = NO_ERROR;
706
Eric Laurent72e3f392015-05-20 14:43:50 -0700707 if (event->mRequiresSystemReady && !mSystemReady) {
708 event->mWaitStatus = false;
709 mPendingConfigEvents.add(event);
710 return status;
711 }
Eric Laurent10351942014-05-08 18:49:52 -0700712 mConfigEvents.add(event);
713 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800714 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700715 mLock.unlock();
716 {
717 Mutex::Autolock _l(event->mLock);
718 while (event->mWaitStatus) {
719 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
720 event->mStatus = TIMED_OUT;
721 event->mWaitStatus = false;
722 }
723 }
724 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800725 }
Eric Laurent10351942014-05-08 18:49:52 -0700726 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800727 return status;
728}
729
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700730void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800731{
732 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700733 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800734}
735
736// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700737void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800738{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700739 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700740 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Eric Laurent72e3f392015-05-20 14:43:50 -0700743void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
744{
745 Mutex::Autolock _l(mLock);
746 sendPrioConfigEvent_l(pid, tid, prio);
747}
748
Eric Laurent81784c32012-11-19 14:55:58 -0800749// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
750void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
751{
Eric Laurent10351942014-05-08 18:49:52 -0700752 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
753 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800754}
755
Eric Laurent10351942014-05-08 18:49:52 -0700756// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
757status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800758{
Andy Hung2ddee192015-12-18 17:34:44 -0800759 sp<ConfigEvent> configEvent;
760 AudioParameter param(keyValuePair);
761 int value;
762 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
763 setMasterMono_l(value != 0);
764 if (param.size() == 1) {
765 return NO_ERROR; // should be a solo parameter - we don't pass down
766 }
767 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
768 configEvent = new SetParameterConfigEvent(param.toString());
769 } else {
770 configEvent = new SetParameterConfigEvent(keyValuePair);
771 }
Eric Laurent10351942014-05-08 18:49:52 -0700772 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700773}
774
Eric Laurent1c333e22014-05-20 10:48:17 -0700775status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
776 const struct audio_patch *patch,
777 audio_patch_handle_t *handle)
778{
779 Mutex::Autolock _l(mLock);
780 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
781 status_t status = sendConfigEvent_l(configEvent);
782 if (status == NO_ERROR) {
783 CreateAudioPatchConfigEventData *data =
784 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
785 *handle = data->mHandle;
786 }
787 return status;
788}
789
790status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
791 const audio_patch_handle_t handle)
792{
793 Mutex::Autolock _l(mLock);
794 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
795 return sendConfigEvent_l(configEvent);
796}
797
798
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700799// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700800void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700801{
Eric Laurent10351942014-05-08 18:49:52 -0700802 bool configChanged = false;
803
Eric Laurent81784c32012-11-19 14:55:58 -0800804 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700805 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
806 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800807 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700808 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700809 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700810 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
811 // FIXME Need to understand why this has to be done asynchronously
812 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700813 true /*asynchronous*/);
814 if (err != 0) {
815 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700816 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700817 }
818 } break;
819 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700820 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700821 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700822 } break;
823 case CFG_EVENT_SET_PARAMETER: {
824 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
825 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
826 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700827 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700828 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700829 case CFG_EVENT_CREATE_AUDIO_PATCH: {
830 CreateAudioPatchConfigEventData *data =
831 (CreateAudioPatchConfigEventData *)event->mData.get();
832 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
833 } break;
834 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
835 ReleaseAudioPatchConfigEventData *data =
836 (ReleaseAudioPatchConfigEventData *)event->mData.get();
837 event->mStatus = releaseAudioPatch_l(data->mHandle);
838 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700839 default:
Eric Laurent10351942014-05-08 18:49:52 -0700840 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700841 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800842 }
Eric Laurent10351942014-05-08 18:49:52 -0700843 {
844 Mutex::Autolock _l(event->mLock);
845 if (event->mWaitStatus) {
846 event->mWaitStatus = false;
847 event->mCond.signal();
848 }
849 }
850 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
851 }
852
853 if (configChanged) {
854 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
Eric Laurent81784c32012-11-19 14:55:58 -0800856}
857
Marco Nelissenb2208842014-02-07 14:00:50 -0800858String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
859 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700860 const audio_channel_representation_t representation =
861 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700862
863 switch (representation) {
864 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
865 if (output) {
866 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
867 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
868 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
869 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
870 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
871 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
873 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
874 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
875 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
876 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
877 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
878 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
879 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
880 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
883 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
884 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
885 } else {
886 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
887 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
888 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
889 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
890 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
891 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
892 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
893 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
894 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
895 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
896 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
897 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
898 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
899 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
900 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
901 }
902 const int len = s.length();
903 if (len > 2) {
904 char *str = s.lockBuffer(len); // needed?
905 s.unlockBuffer(len - 2); // remove trailing ", "
906 }
907 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800908 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700909 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
910 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
911 return s;
912 default:
913 s.appendFormat("unknown mask, representation:%d bits:%#x",
914 representation, audio_channel_mask_get_bits(mask));
915 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800916 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800917}
918
Glenn Kasten0f11b512014-01-31 16:18:54 -0800919void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800920{
921 const size_t SIZE = 256;
922 char buffer[SIZE];
923 String8 result;
924
925 bool locked = AudioFlinger::dumpTryLock(mLock);
926 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700927 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 }
929
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800930 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700931 dprintf(fd, " I/O handle: %d\n", mId);
932 dprintf(fd, " TID: %d\n", getTid());
933 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700934 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700935 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700936 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700937 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700938 dprintf(fd, " Channel count: %u\n", mChannelCount);
939 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800940 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700941 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
942 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700943 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800944 size_t numConfig = mConfigEvents.size();
945 if (numConfig) {
946 for (size_t i = 0; i < numConfig; i++) {
947 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800949 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800954 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
955 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
956 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800957
958 if (locked) {
959 mLock.unlock();
960 }
961}
962
963void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
964{
965 const size_t SIZE = 256;
966 char buffer[SIZE];
967 String8 result;
968
Marco Nelissenb2208842014-02-07 14:00:50 -0800969 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000970 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800971 write(fd, buffer, strlen(buffer));
972
Marco Nelissenb2208842014-02-07 14:00:50 -0800973 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800974 sp<EffectChain> chain = mEffectChains[i];
975 if (chain != 0) {
976 chain->dump(fd, args);
977 }
978 }
979}
980
Marco Nelissene14a5d62013-10-03 08:51:24 -0700981void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800982{
983 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700984 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800985}
986
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100987String16 AudioFlinger::ThreadBase::getWakeLockTag()
988{
989 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800990 case MIXER:
991 return String16("AudioMix");
992 case DIRECT:
993 return String16("AudioDirectOut");
994 case DUPLICATING:
995 return String16("AudioDup");
996 case RECORD:
997 return String16("AudioIn");
998 case OFFLOAD:
999 return String16("AudioOffload");
1000 default:
1001 ALOG_ASSERT(false);
1002 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001003 }
1004}
1005
Marco Nelissene14a5d62013-10-03 08:51:24 -07001006void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001007{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001008 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001009 if (mPowerManager != 0) {
1010 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001011 status_t status;
1012 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001013 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001014 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001015 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001016 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001017 uid,
1018 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001019 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001020 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001021 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001022 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001023 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001024 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001025 }
Eric Laurent81784c32012-11-19 14:55:58 -08001026 if (status == NO_ERROR) {
1027 mWakeLockToken = binder;
1028 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001029 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001030 }
Wei Jia3f273d12015-11-24 09:06:49 -08001031
1032 if (!mNotifiedBatteryStart) {
1033 BatteryNotifier::getInstance().noteStartAudio();
1034 mNotifiedBatteryStart = true;
1035 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001036 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001037 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1038 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001039}
1040
1041void AudioFlinger::ThreadBase::releaseWakeLock()
1042{
1043 Mutex::Autolock _l(mLock);
1044 releaseWakeLock_l();
1045}
1046
1047void AudioFlinger::ThreadBase::releaseWakeLock_l()
1048{
Andy Hung3f0c9022016-01-15 17:49:46 -08001049 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001050 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001051 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001052 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001053 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1054 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001055 }
1056 mWakeLockToken.clear();
1057 }
Wei Jia3f273d12015-11-24 09:06:49 -08001058
1059 if (mNotifiedBatteryStart) {
1060 BatteryNotifier::getInstance().noteStopAudio();
1061 mNotifiedBatteryStart = false;
1062 }
Eric Laurent81784c32012-11-19 14:55:58 -08001063}
1064
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1066 Mutex::Autolock _l(mLock);
1067 updateWakeLockUids_l(uids);
1068}
1069
1070void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001071 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001072 // use checkService() to avoid blocking if power service is not up yet
1073 sp<IBinder> binder =
1074 defaultServiceManager()->checkService(String16("power"));
1075 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001076 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001077 } else {
1078 mPowerManager = interface_cast<IPowerManager>(binder);
1079 binder->linkToDeath(mDeathRecipient);
1080 }
1081 }
1082}
1083
1084void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001086 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1087 if (mSystemReady) {
1088 ALOGE("no wake lock to update, but system ready!");
1089 } else {
1090 ALOGW("no wake lock to update, system not ready yet");
1091 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001092 return;
1093 }
1094 if (mPowerManager != 0) {
1095 sp<IBinder> binder = new BBinder();
1096 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001097 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1098 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -08001099 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 }
1101}
1102
Eric Laurent81784c32012-11-19 14:55:58 -08001103void AudioFlinger::ThreadBase::clearPowerManager()
1104{
1105 Mutex::Autolock _l(mLock);
1106 releaseWakeLock_l();
1107 mPowerManager.clear();
1108}
1109
Glenn Kasten0f11b512014-01-31 16:18:54 -08001110void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001111{
1112 sp<ThreadBase> thread = mThread.promote();
1113 if (thread != 0) {
1114 thread->clearPowerManager();
1115 }
1116 ALOGW("power manager service died !!!");
1117}
1118
1119void AudioFlinger::ThreadBase::setEffectSuspended(
1120 const effect_uuid_t *type, bool suspend, int sessionId)
1121{
1122 Mutex::Autolock _l(mLock);
1123 setEffectSuspended_l(type, suspend, sessionId);
1124}
1125
1126void AudioFlinger::ThreadBase::setEffectSuspended_l(
1127 const effect_uuid_t *type, bool suspend, int sessionId)
1128{
1129 sp<EffectChain> chain = getEffectChain_l(sessionId);
1130 if (chain != 0) {
1131 if (type != NULL) {
1132 chain->setEffectSuspended_l(type, suspend);
1133 } else {
1134 chain->setEffectSuspendedAll_l(suspend);
1135 }
1136 }
1137
1138 updateSuspendedSessions_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142{
1143 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144 if (index < 0) {
1145 return;
1146 }
1147
1148 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149 mSuspendedSessions.valueAt(index);
1150
1151 for (size_t i = 0; i < sessionEffects.size(); i++) {
1152 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1153 for (int j = 0; j < desc->mRefCount; j++) {
1154 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155 chain->setEffectSuspendedAll_l(true);
1156 } else {
1157 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158 desc->mType.timeLow);
1159 chain->setEffectSuspended_l(&desc->mType, true);
1160 }
1161 }
1162 }
1163}
1164
1165void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166 bool suspend,
1167 int sessionId)
1168{
1169 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170
1171 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172
1173 if (suspend) {
1174 if (index >= 0) {
1175 sessionEffects = mSuspendedSessions.valueAt(index);
1176 } else {
1177 mSuspendedSessions.add(sessionId, sessionEffects);
1178 }
1179 } else {
1180 if (index < 0) {
1181 return;
1182 }
1183 sessionEffects = mSuspendedSessions.valueAt(index);
1184 }
1185
1186
1187 int key = EffectChain::kKeyForSuspendAll;
1188 if (type != NULL) {
1189 key = type->timeLow;
1190 }
1191 index = sessionEffects.indexOfKey(key);
1192
1193 sp<SuspendedSessionDesc> desc;
1194 if (suspend) {
1195 if (index >= 0) {
1196 desc = sessionEffects.valueAt(index);
1197 } else {
1198 desc = new SuspendedSessionDesc();
1199 if (type != NULL) {
1200 desc->mType = *type;
1201 }
1202 sessionEffects.add(key, desc);
1203 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204 }
1205 desc->mRefCount++;
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 desc = sessionEffects.valueAt(index);
1211 if (--desc->mRefCount == 0) {
1212 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213 sessionEffects.removeItemsAt(index);
1214 if (sessionEffects.isEmpty()) {
1215 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216 sessionId);
1217 mSuspendedSessions.removeItem(sessionId);
1218 }
1219 }
1220 }
1221 if (!sessionEffects.isEmpty()) {
1222 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223 }
1224}
1225
1226void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1227 bool enabled,
1228 int sessionId)
1229{
1230 Mutex::Autolock _l(mLock);
1231 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1232}
1233
1234void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1235 bool enabled,
1236 int sessionId)
1237{
1238 if (mType != RECORD) {
1239 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1240 // another session. This gives the priority to well behaved effect control panels
1241 // and applications not using global effects.
1242 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1243 // global effects
1244 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1245 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1246 }
1247 }
1248
1249 sp<EffectChain> chain = getEffectChain_l(sessionId);
1250 if (chain != 0) {
1251 chain->checkSuspendOnEffectEnabled(effect, enabled);
1252 }
1253}
1254
1255// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1256sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1257 const sp<AudioFlinger::Client>& client,
1258 const sp<IEffectClient>& effectClient,
1259 int32_t priority,
1260 int sessionId,
1261 effect_descriptor_t *desc,
1262 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001263 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001264{
1265 sp<EffectModule> effect;
1266 sp<EffectHandle> handle;
1267 status_t lStatus;
1268 sp<EffectChain> chain;
1269 bool chainCreated = false;
1270 bool effectCreated = false;
1271 bool effectRegistered = false;
1272
1273 lStatus = initCheck();
1274 if (lStatus != NO_ERROR) {
1275 ALOGW("createEffect_l() Audio driver not initialized.");
1276 goto Exit;
1277 }
1278
Andy Hung98ef9782014-03-04 14:46:50 -08001279 // Reject any effect on Direct output threads for now, since the format of
1280 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1281 if (mType == DIRECT) {
1282 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001283 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001284 lStatus = BAD_VALUE;
1285 goto Exit;
1286 }
1287
Andy Hung389cfdb2014-08-07 17:49:53 -07001288 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001289 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001290 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1291 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1292 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001293 lStatus = BAD_VALUE;
1294 goto Exit;
1295 }
1296
Eric Laurent5baf2af2013-09-12 17:37:00 -07001297 // Allow global effects only on offloaded and mixer threads
1298 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1299 switch (mType) {
1300 case MIXER:
1301 case OFFLOAD:
1302 break;
1303 case DIRECT:
1304 case DUPLICATING:
1305 case RECORD:
1306 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001307 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1308 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001309 lStatus = BAD_VALUE;
1310 goto Exit;
1311 }
Eric Laurent81784c32012-11-19 14:55:58 -08001312 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001313
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // Only Pre processor effects are allowed on input threads and only on input threads
1315 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1316 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1317 desc->name, desc->flags, mType);
1318 lStatus = BAD_VALUE;
1319 goto Exit;
1320 }
1321
1322 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1323
1324 { // scope for mLock
1325 Mutex::Autolock _l(mLock);
1326
1327 // check for existing effect chain with the requested audio session
1328 chain = getEffectChain_l(sessionId);
1329 if (chain == 0) {
1330 // create a new chain for this session
1331 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1332 chain = new EffectChain(this, sessionId);
1333 addEffectChain_l(chain);
1334 chain->setStrategy(getStrategyForSession_l(sessionId));
1335 chainCreated = true;
1336 } else {
1337 effect = chain->getEffectFromDesc_l(desc);
1338 }
1339
1340 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1341
1342 if (effect == 0) {
1343 int id = mAudioFlinger->nextUniqueId();
1344 // Check CPU and memory usage
1345 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1346 if (lStatus != NO_ERROR) {
1347 goto Exit;
1348 }
1349 effectRegistered = true;
1350 // create a new effect module if none present in the chain
1351 effect = new EffectModule(this, chain, desc, id, sessionId);
1352 lStatus = effect->status();
1353 if (lStatus != NO_ERROR) {
1354 goto Exit;
1355 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001356 effect->setOffloaded(mType == OFFLOAD, mId);
1357
Eric Laurent81784c32012-11-19 14:55:58 -08001358 lStatus = chain->addEffect_l(effect);
1359 if (lStatus != NO_ERROR) {
1360 goto Exit;
1361 }
1362 effectCreated = true;
1363
1364 effect->setDevice(mOutDevice);
1365 effect->setDevice(mInDevice);
1366 effect->setMode(mAudioFlinger->getMode());
1367 effect->setAudioSource(mAudioSource);
1368 }
1369 // create effect handle and connect it to effect module
1370 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001371 lStatus = handle->initCheck();
1372 if (lStatus == OK) {
1373 lStatus = effect->addHandle(handle.get());
1374 }
Eric Laurent81784c32012-11-19 14:55:58 -08001375 if (enabled != NULL) {
1376 *enabled = (int)effect->isEnabled();
1377 }
1378 }
1379
1380Exit:
1381 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1382 Mutex::Autolock _l(mLock);
1383 if (effectCreated) {
1384 chain->removeEffect_l(effect);
1385 }
1386 if (effectRegistered) {
1387 AudioSystem::unregisterEffect(effect->id());
1388 }
1389 if (chainCreated) {
1390 removeEffectChain_l(chain);
1391 }
1392 handle.clear();
1393 }
1394
Glenn Kasten9156ef32013-08-06 15:39:08 -07001395 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001396 return handle;
1397}
1398
1399sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1400{
1401 Mutex::Autolock _l(mLock);
1402 return getEffect_l(sessionId, effectId);
1403}
1404
1405sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1406{
1407 sp<EffectChain> chain = getEffectChain_l(sessionId);
1408 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1409}
1410
1411// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1412// PlaybackThread::mLock held
1413status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1414{
1415 // check for existing effect chain with the requested audio session
1416 int sessionId = effect->sessionId();
1417 sp<EffectChain> chain = getEffectChain_l(sessionId);
1418 bool chainCreated = false;
1419
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1421 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1422 this, effect->desc().name, effect->desc().flags);
1423
Eric Laurent81784c32012-11-19 14:55:58 -08001424 if (chain == 0) {
1425 // create a new chain for this session
1426 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1427 chain = new EffectChain(this, sessionId);
1428 addEffectChain_l(chain);
1429 chain->setStrategy(getStrategyForSession_l(sessionId));
1430 chainCreated = true;
1431 }
1432 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1433
1434 if (chain->getEffectFromId_l(effect->id()) != 0) {
1435 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1436 this, effect->desc().name, chain.get());
1437 return BAD_VALUE;
1438 }
1439
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 effect->setOffloaded(mType == OFFLOAD, mId);
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 status_t status = chain->addEffect_l(effect);
1443 if (status != NO_ERROR) {
1444 if (chainCreated) {
1445 removeEffectChain_l(chain);
1446 }
1447 return status;
1448 }
1449
1450 effect->setDevice(mOutDevice);
1451 effect->setDevice(mInDevice);
1452 effect->setMode(mAudioFlinger->getMode());
1453 effect->setAudioSource(mAudioSource);
1454 return NO_ERROR;
1455}
1456
1457void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1458
1459 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1460 effect_descriptor_t desc = effect->desc();
1461 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1462 detachAuxEffect_l(effect->id());
1463 }
1464
1465 sp<EffectChain> chain = effect->chain().promote();
1466 if (chain != 0) {
1467 // remove effect chain if removing last effect
1468 if (chain->removeEffect_l(effect) == 0) {
1469 removeEffectChain_l(chain);
1470 }
1471 } else {
1472 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1473 }
1474}
1475
1476void AudioFlinger::ThreadBase::lockEffectChains_l(
1477 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1478{
1479 effectChains = mEffectChains;
1480 for (size_t i = 0; i < mEffectChains.size(); i++) {
1481 mEffectChains[i]->lock();
1482 }
1483}
1484
1485void AudioFlinger::ThreadBase::unlockEffectChains(
1486 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1487{
1488 for (size_t i = 0; i < effectChains.size(); i++) {
1489 effectChains[i]->unlock();
1490 }
1491}
1492
1493sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1494{
1495 Mutex::Autolock _l(mLock);
1496 return getEffectChain_l(sessionId);
1497}
1498
1499sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1500{
1501 size_t size = mEffectChains.size();
1502 for (size_t i = 0; i < size; i++) {
1503 if (mEffectChains[i]->sessionId() == sessionId) {
1504 return mEffectChains[i];
1505 }
1506 }
1507 return 0;
1508}
1509
1510void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1511{
1512 Mutex::Autolock _l(mLock);
1513 size_t size = mEffectChains.size();
1514 for (size_t i = 0; i < size; i++) {
1515 mEffectChains[i]->setMode_l(mode);
1516 }
1517}
1518
Eric Laurent83b88082014-06-20 18:31:16 -07001519void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1520{
1521 config->type = AUDIO_PORT_TYPE_MIX;
1522 config->ext.mix.handle = mId;
1523 config->sample_rate = mSampleRate;
1524 config->format = mFormat;
1525 config->channel_mask = mChannelMask;
1526 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1527 AUDIO_PORT_CONFIG_FORMAT;
1528}
1529
Eric Laurent72e3f392015-05-20 14:43:50 -07001530void AudioFlinger::ThreadBase::systemReady()
1531{
1532 Mutex::Autolock _l(mLock);
1533 if (mSystemReady) {
1534 return;
1535 }
1536 mSystemReady = true;
1537
1538 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1539 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1540 }
1541 mPendingConfigEvents.clear();
1542}
1543
Eric Laurent83b88082014-06-20 18:31:16 -07001544
Eric Laurent81784c32012-11-19 14:55:58 -08001545// ----------------------------------------------------------------------------
1546// Playback
1547// ----------------------------------------------------------------------------
1548
1549AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1550 AudioStreamOut* output,
1551 audio_io_handle_t id,
1552 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001553 type_t type,
1554 bool systemReady)
1555 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001556 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001557 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001558 mMixerBuffer(NULL),
1559 mMixerBufferSize(0),
1560 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1561 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001562 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001563 mEffectBuffer(NULL),
1564 mEffectBufferSize(0),
1565 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1566 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001567 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001568 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001569 // mStreamTypes[] initialized in constructor body
1570 mOutput(output),
1571 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1572 mMixerStatus(MIXER_IDLE),
1573 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001574 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001575 mBytesRemaining(0),
1576 mCurrentWriteLength(0),
1577 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001578 mWriteAckSequence(0),
1579 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001580 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001581 mScreenState(AudioFlinger::mScreenState),
1582 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001583 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001584 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001585{
Glenn Kastend7dca052015-03-05 16:05:54 -08001586 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1587 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001588
1589 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1590 // it would be safer to explicitly pass initial masterVolume/masterMute as
1591 // parameter.
1592 //
1593 // If the HAL we are using has support for master volume or master mute,
1594 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1595 // and the mute set to false).
1596 mMasterVolume = audioFlinger->masterVolume_l();
1597 mMasterMute = audioFlinger->masterMute_l();
1598 if (mOutput && mOutput->audioHwDev) {
1599 if (mOutput->audioHwDev->canSetMasterVolume()) {
1600 mMasterVolume = 1.0;
1601 }
1602
1603 if (mOutput->audioHwDev->canSetMasterMute()) {
1604 mMasterMute = false;
1605 }
1606 }
1607
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001608 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001609
Eric Laurent223fd5c2014-11-11 13:43:36 -08001610 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001611 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001612 stream = (audio_stream_type_t) (stream + 1)) {
1613 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1614 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1615 }
Eric Laurent81784c32012-11-19 14:55:58 -08001616}
1617
1618AudioFlinger::PlaybackThread::~PlaybackThread()
1619{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001620 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001621 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001622 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001623 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001624}
1625
1626void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1627{
1628 dumpInternals(fd, args);
1629 dumpTracks(fd, args);
1630 dumpEffectChains(fd, args);
1631}
1632
Glenn Kasten0f11b512014-01-31 16:18:54 -08001633void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001634{
1635 const size_t SIZE = 256;
1636 char buffer[SIZE];
1637 String8 result;
1638
Marco Nelissenb2208842014-02-07 14:00:50 -08001639 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001640 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1641 const stream_type_t *st = &mStreamTypes[i];
1642 if (i > 0) {
1643 result.appendFormat(", ");
1644 }
1645 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1646 if (st->mute) {
1647 result.append("M");
1648 }
1649 }
1650 result.append("\n");
1651 write(fd, result.string(), result.length());
1652 result.clear();
1653
Eric Laurent81784c32012-11-19 14:55:58 -08001654 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1655 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001656 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001657 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001658
1659 size_t numtracks = mTracks.size();
1660 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001661 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001662 size_t numactiveseen = 0;
1663 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001664 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001665 Track::appendDumpHeader(result);
1666 for (size_t i = 0; i < numtracks; ++i) {
1667 sp<Track> track = mTracks[i];
1668 if (track != 0) {
1669 bool active = mActiveTracks.indexOf(track) >= 0;
1670 if (active) {
1671 numactiveseen++;
1672 }
1673 track->dump(buffer, SIZE, active);
1674 result.append(buffer);
1675 }
1676 }
1677 } else {
1678 result.append("\n");
1679 }
1680 if (numactiveseen != numactive) {
1681 // some tracks in the active list were not in the tracks list
1682 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1683 " not in the track list\n");
1684 result.append(buffer);
1685 Track::appendDumpHeader(result);
1686 for (size_t i = 0; i < numactive; ++i) {
1687 sp<Track> track = mActiveTracks[i].promote();
1688 if (track != 0 && mTracks.indexOf(track) < 0) {
1689 track->dump(buffer, SIZE, true);
1690 result.append(buffer);
1691 }
1692 }
1693 }
1694
1695 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001696}
1697
1698void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1699{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001700 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001701
1702 dumpBase(fd, args);
1703
Elliott Hughes87cebad2014-05-22 10:14:43 -07001704 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1705 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1706 dprintf(fd, " Total writes: %d\n", mNumWrites);
1707 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1708 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1709 dprintf(fd, " Suspend count: %d\n", mSuspended);
1710 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1711 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1712 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1713 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001714 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001715 AudioStreamOut *output = mOutput;
1716 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1717 String8 flagsAsString = outputFlagsToString(flags);
1718 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001719}
1720
1721// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001722
1723void AudioFlinger::PlaybackThread::onFirstRef()
1724{
Glenn Kastend7dca052015-03-05 16:05:54 -08001725 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001726}
1727
1728// ThreadBase virtuals
1729void AudioFlinger::PlaybackThread::preExit()
1730{
1731 ALOGV(" preExit()");
1732 // FIXME this is using hard-coded strings but in the future, this functionality will be
1733 // converted to use audio HAL extensions required to support tunneling
1734 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1735}
1736
1737// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1738sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1739 const sp<AudioFlinger::Client>& client,
1740 audio_stream_type_t streamType,
1741 uint32_t sampleRate,
1742 audio_format_t format,
1743 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001744 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001745 const sp<IMemory>& sharedBuffer,
1746 int sessionId,
1747 IAudioFlinger::track_flags_t *flags,
1748 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001749 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001750 status_t *status)
1751{
Glenn Kasten74935e42013-12-19 08:56:45 -08001752 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001753 sp<Track> track;
1754 status_t lStatus;
1755
Eric Laurent81784c32012-11-19 14:55:58 -08001756 // client expresses a preference for FAST, but we get the final say
1757 if (*flags & IAudioFlinger::TRACK_FAST) {
1758 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001759 // either of these use cases:
1760 (
1761 // use case 1: shared buffer with any frame count
1762 (
1763 (sharedBuffer != 0)
1764 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001765 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001766 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001767 // we formerly checked for a callback handler (non-0 tid),
1768 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001769 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001770 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001771 )
1772 ) &&
1773 // PCM data
1774 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001775 // TODO: extract as a data library function that checks that a computationally
1776 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001777 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001778 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1779 (channelMask == AUDIO_CHANNEL_OUT_MONO
1780 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001781 // hardware sample rate
1782 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001783 // normal mixer has an associated fast mixer
1784 hasFastMixer() &&
1785 // there are sufficient fast track slots available
1786 (mFastTrackAvailMask != 0)
1787 // FIXME test that MixerThread for this fast track has a capable output HAL
1788 // FIXME add a permission test also?
1789 ) {
1790 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1791 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001792 // read the fast track multiplier property the first time it is needed
1793 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1794 if (ok != 0) {
1795 ALOGE("%s pthread_once failed: %d", __func__, ok);
1796 }
1797 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001798 }
1799 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1800 frameCount, mFrameCount);
1801 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001802 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001803 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1804 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001805 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001806 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001807 audio_is_linear_pcm(format),
1808 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1809 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001810 }
1811 }
1812 // For normal PCM streaming tracks, update minimum frame count.
1813 // For compatibility with AudioTrack calculation, buffer depth is forced
1814 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1815 // This is probably too conservative, but legacy application code may depend on it.
1816 // If you change this calculation, also review the start threshold which is related.
1817 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001818 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001819 // this must match AudioTrack.cpp calculateMinFrameCount().
1820 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001821 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1822 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1823 if (minBufCount < 2) {
1824 minBufCount = 2;
1825 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001826 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1827 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001828 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001829 minBufCount * sourceFramesNeededWithTimestretch(
1830 sampleRate, mNormalFrameCount,
1831 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001832 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001833 frameCount = minFrameCount;
1834 }
Eric Laurent81784c32012-11-19 14:55:58 -08001835 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001836 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001837
Glenn Kastenc3df8382014-03-13 15:05:25 -07001838 switch (mType) {
1839
1840 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001841 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001842 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001843 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1844 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001845 sampleRate, format, channelMask, mOutput, mFormat);
1846 lStatus = BAD_VALUE;
1847 goto Exit;
1848 }
1849 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001850 break;
1851
1852 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001853 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001854 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1855 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 sampleRate, format, channelMask, mOutput, mFormat);
1857 lStatus = BAD_VALUE;
1858 goto Exit;
1859 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001860 break;
1861
1862 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001863 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001864 ALOGE("createTrack_l() Bad parameter: format %#x \""
1865 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001866 format, mOutput, mFormat);
1867 lStatus = BAD_VALUE;
1868 goto Exit;
1869 }
Andy Hungcd044842014-08-07 11:04:34 -07001870 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001871 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1872 lStatus = BAD_VALUE;
1873 goto Exit;
1874 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001875 break;
1876
Eric Laurent81784c32012-11-19 14:55:58 -08001877 }
1878
1879 lStatus = initCheck();
1880 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001881 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001882 goto Exit;
1883 }
1884
1885 { // scope for mLock
1886 Mutex::Autolock _l(mLock);
1887
1888 // all tracks in same audio session must share the same routing strategy otherwise
1889 // conflicts will happen when tracks are moved from one output to another by audio policy
1890 // manager
1891 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1892 for (size_t i = 0; i < mTracks.size(); ++i) {
1893 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001894 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001895 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1896 if (sessionId == t->sessionId() && strategy != actual) {
1897 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1898 strategy, actual);
1899 lStatus = BAD_VALUE;
1900 goto Exit;
1901 }
1902 }
1903 }
1904
Glenn Kastend79072e2016-01-06 08:41:20 -08001905 track = new Track(this, client, streamType, sampleRate, format,
1906 channelMask, frameCount, NULL, sharedBuffer,
1907 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001908
Glenn Kasten03003332013-08-06 15:40:54 -07001909 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1910 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001911 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001912 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001913 goto Exit;
1914 }
1915 mTracks.add(track);
1916
1917 sp<EffectChain> chain = getEffectChain_l(sessionId);
1918 if (chain != 0) {
1919 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1920 track->setMainBuffer(chain->inBuffer());
1921 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1922 chain->incTrackCnt();
1923 }
1924
1925 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1926 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1927 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1928 // so ask activity manager to do this on our behalf
1929 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1930 }
1931 }
1932
1933 lStatus = NO_ERROR;
1934
1935Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001936 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001937 return track;
1938}
1939
1940uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1941{
1942 return latency;
1943}
1944
1945uint32_t AudioFlinger::PlaybackThread::latency() const
1946{
1947 Mutex::Autolock _l(mLock);
1948 return latency_l();
1949}
1950uint32_t AudioFlinger::PlaybackThread::latency_l() const
1951{
1952 if (initCheck() == NO_ERROR) {
1953 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1954 } else {
1955 return 0;
1956 }
1957}
1958
1959void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1960{
1961 Mutex::Autolock _l(mLock);
1962 // Don't apply master volume in SW if our HAL can do it for us.
1963 if (mOutput && mOutput->audioHwDev &&
1964 mOutput->audioHwDev->canSetMasterVolume()) {
1965 mMasterVolume = 1.0;
1966 } else {
1967 mMasterVolume = value;
1968 }
1969}
1970
1971void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1972{
1973 Mutex::Autolock _l(mLock);
1974 // Don't apply master mute in SW if our HAL can do it for us.
1975 if (mOutput && mOutput->audioHwDev &&
1976 mOutput->audioHwDev->canSetMasterMute()) {
1977 mMasterMute = false;
1978 } else {
1979 mMasterMute = muted;
1980 }
1981}
1982
1983void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1984{
1985 Mutex::Autolock _l(mLock);
1986 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001987 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001988}
1989
1990void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1991{
1992 Mutex::Autolock _l(mLock);
1993 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001994 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001995}
1996
1997float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1998{
1999 Mutex::Autolock _l(mLock);
2000 return mStreamTypes[stream].volume;
2001}
2002
2003// addTrack_l() must be called with ThreadBase::mLock held
2004status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2005{
2006 status_t status = ALREADY_EXISTS;
2007
2008 // set retry count for buffer fill
2009 track->mRetryCount = kMaxTrackStartupRetries;
2010 if (mActiveTracks.indexOf(track) < 0) {
2011 // the track is newly added, make sure it fills up all its
2012 // buffers before playing. This is to ensure the client will
2013 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002014 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015 TrackBase::track_state state = track->mState;
2016 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002017 status = AudioSystem::startOutput(mId, track->streamType(),
2018 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002019 mLock.lock();
2020 // abort track was stopped/paused while we released the lock
2021 if (state != track->mState) {
2022 if (status == NO_ERROR) {
2023 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002024 AudioSystem::stopOutput(mId, track->streamType(),
2025 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002026 mLock.lock();
2027 }
2028 return INVALID_OPERATION;
2029 }
2030 // abort if start is rejected by audio policy manager
2031 if (status != NO_ERROR) {
2032 return PERMISSION_DENIED;
2033 }
2034#ifdef ADD_BATTERY_DATA
2035 // to track the speaker usage
2036 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2037#endif
2038 }
2039
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002040 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002041 track->mResetDone = false;
2042 track->mPresentationCompleteFrames = 0;
2043 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002044 mWakeLockUids.add(track->uid());
2045 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002046 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002047 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2048 if (chain != 0) {
2049 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2050 track->sessionId());
2051 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002052 }
2053
2054 status = NO_ERROR;
2055 }
2056
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002057 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002058 return status;
2059}
2060
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002062{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002063 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002064 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2066 track->mState = TrackBase::STOPPED;
2067 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002068 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002069 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002070 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002071 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002072
2073 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002074}
2075
2076void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2077{
2078 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2079 mTracks.remove(track);
2080 deleteTrackName_l(track->name());
2081 // redundant as track is about to be destroyed, for dumpsys only
2082 track->mName = -1;
2083 if (track->isFastTrack()) {
2084 int index = track->mFastIndex;
2085 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2086 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2087 mFastTrackAvailMask |= 1 << index;
2088 // redundant as track is about to be destroyed, for dumpsys only
2089 track->mFastIndex = -1;
2090 }
2091 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2092 if (chain != 0) {
2093 chain->decTrackCnt();
2094 }
2095}
2096
Eric Laurentede6c3b2013-09-19 14:37:46 -07002097void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098{
2099 // Thread could be blocked waiting for async
2100 // so signal it to handle state changes immediately
2101 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2102 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2103 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002104 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105}
2106
Eric Laurent81784c32012-11-19 14:55:58 -08002107String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2108{
Eric Laurent81784c32012-11-19 14:55:58 -08002109 Mutex::Autolock _l(mLock);
2110 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002111 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002112 }
2113
Glenn Kastend8ea6992013-07-16 14:17:15 -07002114 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2115 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002116 free(s);
2117 return out_s8;
2118}
2119
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002120void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002121 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2122 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002123
Eric Laurent73e26b62015-04-27 16:55:58 -07002124 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002125
2126 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002127 case AUDIO_OUTPUT_OPENED:
2128 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002129 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002130 desc->mChannelMask = mChannelMask;
2131 desc->mSamplingRate = mSampleRate;
2132 desc->mFormat = mFormat;
2133 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002134 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002135 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002136 break;
2137
Eric Laurent73e26b62015-04-27 16:55:58 -07002138 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002139 default:
2140 break;
2141 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002142 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002143}
2144
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145void AudioFlinger::PlaybackThread::writeCallback()
2146{
2147 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002148 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002149}
2150
2151void AudioFlinger::PlaybackThread::drainCallback()
2152{
2153 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002154 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002155}
2156
Eric Laurent3b4529e2013-09-05 18:09:19 -07002157void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158{
2159 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002160 // reject out of sequence requests
2161 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2162 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002163 mWaitWorkCV.signal();
2164 }
2165}
2166
Eric Laurent3b4529e2013-09-05 18:09:19 -07002167void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168{
2169 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002170 // reject out of sequence requests
2171 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2172 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 mWaitWorkCV.signal();
2174 }
2175}
2176
2177// static
2178int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002179 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180 void *cookie)
2181{
2182 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2183 ALOGV("asyncCallback() event %d", event);
2184 switch (event) {
2185 case STREAM_CBK_EVENT_WRITE_READY:
2186 me->writeCallback();
2187 break;
2188 case STREAM_CBK_EVENT_DRAIN_READY:
2189 me->drainCallback();
2190 break;
2191 default:
2192 ALOGW("asyncCallback() unknown event %d", event);
2193 break;
2194 }
2195 return 0;
2196}
2197
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002198void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002199{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002200 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002201 mSampleRate = mOutput->getSampleRate();
2202 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002203 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002204 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002205 }
Andy Hung9a592762014-07-21 21:56:01 -07002206 if ((mType == MIXER || mType == DUPLICATING)
2207 && !isValidPcmSinkChannelMask(mChannelMask)) {
2208 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2209 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002210 }
Andy Hunge5412692014-05-16 11:25:07 -07002211 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002212
2213 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002214 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002215 // Get format from the shim, which will be different than the HAL format
2216 // if playing compressed audio over HDMI passthrough.
2217 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002218 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002219 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002220 }
Andy Hung6146c082014-03-18 11:56:15 -07002221 if ((mType == MIXER || mType == DUPLICATING)
2222 && !isValidPcmSinkFormat(mFormat)) {
2223 LOG_FATAL("HAL format %#x not supported for mixed output",
2224 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002225 }
Phil Burk062e67a2015-02-11 13:40:50 -08002226 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002227 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2228 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002229 if (mFrameCount & 15) {
2230 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2231 mFrameCount);
2232 }
2233
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2235 (mOutput->stream->set_callback != NULL)) {
2236 if (mOutput->stream->set_callback(mOutput->stream,
2237 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2238 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002239 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 }
2241 }
2242
Eric Laurentd1f69b02014-12-15 14:33:13 -08002243 mHwSupportsPause = false;
2244 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2245 if (mOutput->stream->pause != NULL) {
2246 if (mOutput->stream->resume != NULL) {
2247 mHwSupportsPause = true;
2248 } else {
2249 ALOGW("direct output implements pause but not resume");
2250 }
2251 } else if (mOutput->stream->resume != NULL) {
2252 ALOGW("direct output implements resume but not pause");
2253 }
2254 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002255 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2256 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2257 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002258
Andy Hungfbfc3952015-01-15 13:33:51 -08002259 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2260 // For best precision, we use float instead of the associated output
2261 // device format (typically PCM 16 bit).
2262
2263 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2264 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2265 mBufferSize = mFrameSize * mFrameCount;
2266
2267 // TODO: We currently use the associated output device channel mask and sample rate.
2268 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2269 // (if a valid mask) to avoid premature downmix.
2270 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2271 // instead of the output device sample rate to avoid loss of high frequency information.
2272 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2273 }
2274
Andy Hung09a50072014-02-27 14:30:47 -08002275 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002276 double multiplier = 1.0;
2277 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2278 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002279 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2280 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002281 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2282 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2283 maxNormalFrameCount = maxNormalFrameCount & ~15;
2284 if (maxNormalFrameCount < minNormalFrameCount) {
2285 maxNormalFrameCount = minNormalFrameCount;
2286 }
2287 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2288 if (multiplier <= 1.0) {
2289 multiplier = 1.0;
2290 } else if (multiplier <= 2.0) {
2291 if (2 * mFrameCount <= maxNormalFrameCount) {
2292 multiplier = 2.0;
2293 } else {
2294 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2295 }
2296 } else {
2297 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002298 // 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 -08002299 // track, but we sometimes have to do this to satisfy the maximum frame count
2300 // constraint)
2301 // FIXME this rounding up should not be done if no HAL SRC
2302 uint32_t truncMult = (uint32_t) multiplier;
2303 if ((truncMult & 1)) {
2304 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2305 ++truncMult;
2306 }
2307 }
2308 multiplier = (double) truncMult;
2309 }
2310 }
2311 mNormalFrameCount = multiplier * mFrameCount;
2312 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002313 if (mType == MIXER || mType == DUPLICATING) {
2314 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2315 }
Andy Hung09a50072014-02-27 14:30:47 -08002316 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002317 mNormalFrameCount);
2318
Andy Hung08fb1742015-05-31 23:22:10 -07002319 // Check if we want to throttle the processing to no more than 2x normal rate
2320 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002321 mThreadThrottleTimeMs = 0;
2322 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002323 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2324
Andy Hung010a1a12014-03-13 13:57:33 -07002325 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2326 // Originally this was int16_t[] array, need to remove legacy implications.
2327 free(mSinkBuffer);
2328 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002329 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2330 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2331 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002332 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002333
Andy Hung69aed5f2014-02-25 17:24:40 -08002334 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2335 // drives the output.
2336 free(mMixerBuffer);
2337 mMixerBuffer = NULL;
2338 if (mMixerBufferEnabled) {
2339 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2340 mMixerBufferSize = mNormalFrameCount * mChannelCount
2341 * audio_bytes_per_sample(mMixerBufferFormat);
2342 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2343 }
Andy Hung98ef9782014-03-04 14:46:50 -08002344 free(mEffectBuffer);
2345 mEffectBuffer = NULL;
2346 if (mEffectBufferEnabled) {
2347 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2348 mEffectBufferSize = mNormalFrameCount * mChannelCount
2349 * audio_bytes_per_sample(mEffectBufferFormat);
2350 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2351 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002352
Eric Laurent81784c32012-11-19 14:55:58 -08002353 // force reconfiguration of effect chains and engines to take new buffer size and audio
2354 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002355 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2357 // matter.
2358 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2359 Vector< sp<EffectChain> > effectChains = mEffectChains;
2360 for (size_t i = 0; i < effectChains.size(); i ++) {
2361 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2362 }
2363}
2364
2365
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002366status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002367{
2368 if (halFrames == NULL || dspFrames == NULL) {
2369 return BAD_VALUE;
2370 }
2371 Mutex::Autolock _l(mLock);
2372 if (initCheck() != NO_ERROR) {
2373 return INVALID_OPERATION;
2374 }
Andy Hung818e7a32016-02-16 18:08:07 -08002375 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002376 *halFrames = framesWritten;
2377
2378 if (isSuspended()) {
2379 // return an estimation of rendered frames when the output is suspended
2380 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002381 *dspFrames = (uint32_t)
2382 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002383 return NO_ERROR;
2384 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002385 status_t status;
2386 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002387 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002388 *dspFrames = (size_t)frames;
2389 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002390 }
2391}
2392
2393uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2394{
2395 Mutex::Autolock _l(mLock);
2396 uint32_t result = 0;
2397 if (getEffectChain_l(sessionId) != 0) {
2398 result = EFFECT_SESSION;
2399 }
2400
2401 for (size_t i = 0; i < mTracks.size(); ++i) {
2402 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002403 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002404 result |= TRACK_SESSION;
2405 break;
2406 }
2407 }
2408
2409 return result;
2410}
2411
2412uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2413{
2414 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2415 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2416 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2417 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2418 }
2419 for (size_t i = 0; i < mTracks.size(); i++) {
2420 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002421 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002422 return AudioSystem::getStrategyForStream(track->streamType());
2423 }
2424 }
2425 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2426}
2427
2428
Phil Burk062e67a2015-02-11 13:40:50 -08002429AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002430{
2431 Mutex::Autolock _l(mLock);
2432 return mOutput;
2433}
2434
Phil Burk062e67a2015-02-11 13:40:50 -08002435AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002436{
2437 Mutex::Autolock _l(mLock);
2438 AudioStreamOut *output = mOutput;
2439 mOutput = NULL;
2440 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2441 // must push a NULL and wait for ack
2442 mOutputSink.clear();
2443 mPipeSink.clear();
2444 mNormalSink.clear();
2445 return output;
2446}
2447
2448// this method must always be called either with ThreadBase mLock held or inside the thread loop
2449audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2450{
2451 if (mOutput == NULL) {
2452 return NULL;
2453 }
2454 return &mOutput->stream->common;
2455}
2456
2457uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2458{
2459 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2460}
2461
2462status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2463{
2464 if (!isValidSyncEvent(event)) {
2465 return BAD_VALUE;
2466 }
2467
2468 Mutex::Autolock _l(mLock);
2469
2470 for (size_t i = 0; i < mTracks.size(); ++i) {
2471 sp<Track> track = mTracks[i];
2472 if (event->triggerSession() == track->sessionId()) {
2473 (void) track->setSyncEvent(event);
2474 return NO_ERROR;
2475 }
2476 }
2477
2478 return NAME_NOT_FOUND;
2479}
2480
2481bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2482{
2483 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2484}
2485
2486void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2487 const Vector< sp<Track> >& tracksToRemove)
2488{
2489 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002490 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002491 for (size_t i = 0 ; i < count ; i++) {
2492 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002493 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002494 AudioSystem::stopOutput(mId, track->streamType(),
2495 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002496#ifdef ADD_BATTERY_DATA
2497 // to track the speaker usage
2498 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2499#endif
2500 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002501 AudioSystem::releaseOutput(mId, track->streamType(),
2502 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 }
Eric Laurent81784c32012-11-19 14:55:58 -08002504 }
2505 }
2506 }
Eric Laurent81784c32012-11-19 14:55:58 -08002507}
2508
2509void AudioFlinger::PlaybackThread::checkSilentMode_l()
2510{
2511 if (!mMasterMute) {
2512 char value[PROPERTY_VALUE_MAX];
2513 if (property_get("ro.audio.silent", value, "0") > 0) {
2514 char *endptr;
2515 unsigned long ul = strtoul(value, &endptr, 0);
2516 if (*endptr == '\0' && ul != 0) {
2517 ALOGD("Silence is golden");
2518 // The setprop command will not allow a property to be changed after
2519 // the first time it is set, so we don't have to worry about un-muting.
2520 setMasterMute_l(true);
2521 }
2522 }
2523 }
2524}
2525
2526// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002528{
2529 // FIXME rewrite to reduce number of system calls
2530 mLastWriteTime = systemTime();
2531 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002533 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002534
2535 // If an NBAIO sink is present, use it to write the normal mixer's submix
2536 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002537
Andy Hung010a1a12014-03-13 13:57:33 -07002538 const size_t count = mBytesRemaining / mFrameSize;
2539
Simon Wilson2d590962012-11-29 15:18:50 -08002540 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002541 // update the setpoint when AudioFlinger::mScreenState changes
2542 uint32_t screenState = AudioFlinger::mScreenState;
2543 if (screenState != mScreenState) {
2544 mScreenState = screenState;
2545 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2546 if (pipe != NULL) {
2547 pipe->setAvgFrames((mScreenState & 1) ?
2548 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2549 }
2550 }
Andy Hung010a1a12014-03-13 13:57:33 -07002551 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002552 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002553 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002554 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002555 } else {
2556 bytesWritten = framesWritten;
2557 }
2558 // otherwise use the HAL / AudioStreamOut directly
2559 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002561
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002563 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2564 mWriteAckSequence += 2;
2565 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002567 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002569 // FIXME We should have an implementation of timestamps for direct output threads.
2570 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002571 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 if (mUseAsyncWrite &&
2573 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2574 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002575 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002577 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578 }
Eric Laurent81784c32012-11-19 14:55:58 -08002579 }
2580
Eric Laurent81784c32012-11-19 14:55:58 -08002581 mNumWrites++;
2582 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002583 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 return bytesWritten;
2585}
2586
2587void AudioFlinger::PlaybackThread::threadLoop_drain()
2588{
2589 if (mOutput->stream->drain) {
2590 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2591 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002592 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2593 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002595 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 }
2597 mOutput->stream->drain(mOutput->stream,
2598 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2599 : AUDIO_DRAIN_ALL);
2600 }
2601}
2602
2603void AudioFlinger::PlaybackThread::threadLoop_exit()
2604{
Eric Laurent275e8e92014-11-30 15:14:47 -08002605 {
2606 Mutex::Autolock _l(mLock);
2607 for (size_t i = 0; i < mTracks.size(); i++) {
2608 sp<Track> track = mTracks[i];
2609 track->invalidate();
2610 }
2611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612}
2613
2614/*
2615The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002616 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002617 - mActiveSleepTimeUs from activeSleepTimeUs()
2618 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002619 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2620 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002621 - maxPeriod from frame count and sample rate (MIXER only)
2622
2623The parameters that affect these derived values are:
2624 - frame count
2625 - frame size
2626 - sample rate
2627 - device type: A2DP or not
2628 - device latency
2629 - format: PCM or not
2630 - active sleep time
2631 - idle sleep time
2632*/
2633
2634void AudioFlinger::PlaybackThread::cacheParameters_l()
2635{
Andy Hung25c2dac2014-02-27 14:56:00 -08002636 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002637 mActiveSleepTimeUs = activeSleepTimeUs();
2638 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002639
2640 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2641 // truncating audio when going to standby.
2642 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2643 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2644 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2645 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2646 }
2647 }
Eric Laurent81784c32012-11-19 14:55:58 -08002648}
2649
2650void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2651{
Glenn Kasten7c027242012-12-26 14:43:16 -08002652 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002653 this, streamType, mTracks.size());
2654 Mutex::Autolock _l(mLock);
2655
2656 size_t size = mTracks.size();
2657 for (size_t i = 0; i < size; i++) {
2658 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002659 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002660 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002661 }
2662 }
2663}
2664
2665status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2666{
2667 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002668 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2669 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002670 bool ownsBuffer = false;
2671
2672 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2673 if (session > 0) {
2674 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002675 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002676 if (mType != DIRECT) {
2677 size_t numSamples = mNormalFrameCount * mChannelCount;
2678 buffer = new int16_t[numSamples];
2679 memset(buffer, 0, numSamples * sizeof(int16_t));
2680 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2681 ownsBuffer = true;
2682 }
2683
2684 // Attach all tracks with same session ID to this chain.
2685 for (size_t i = 0; i < mTracks.size(); ++i) {
2686 sp<Track> track = mTracks[i];
2687 if (session == track->sessionId()) {
2688 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2689 buffer);
2690 track->setMainBuffer(buffer);
2691 chain->incTrackCnt();
2692 }
2693 }
2694
2695 // indicate all active tracks in the chain
2696 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2697 sp<Track> track = mActiveTracks[i].promote();
2698 if (track == 0) {
2699 continue;
2700 }
2701 if (session == track->sessionId()) {
2702 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2703 chain->incActiveTrackCnt();
2704 }
2705 }
2706 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002707 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002708 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002709 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2710 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002711 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2712 // chains list in order to be processed last as it contains output stage effects
2713 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2714 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2715 // after track specific effects and before output stage
2716 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2717 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2718 // Effect chain for other sessions are inserted at beginning of effect
2719 // chains list to be processed before output mix effects. Relative order between other
2720 // sessions is not important
2721 size_t size = mEffectChains.size();
2722 size_t i = 0;
2723 for (i = 0; i < size; i++) {
2724 if (mEffectChains[i]->sessionId() < session) {
2725 break;
2726 }
2727 }
2728 mEffectChains.insertAt(chain, i);
2729 checkSuspendOnAddEffectChain_l(chain);
2730
2731 return NO_ERROR;
2732}
2733
2734size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2735{
2736 int session = chain->sessionId();
2737
2738 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2739
2740 for (size_t i = 0; i < mEffectChains.size(); i++) {
2741 if (chain == mEffectChains[i]) {
2742 mEffectChains.removeAt(i);
2743 // detach all active tracks from the chain
2744 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2745 sp<Track> track = mActiveTracks[i].promote();
2746 if (track == 0) {
2747 continue;
2748 }
2749 if (session == track->sessionId()) {
2750 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2751 chain.get(), session);
2752 chain->decActiveTrackCnt();
2753 }
2754 }
2755
2756 // detach all tracks with same session ID from this chain
2757 for (size_t i = 0; i < mTracks.size(); ++i) {
2758 sp<Track> track = mTracks[i];
2759 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002760 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002761 chain->decTrackCnt();
2762 }
2763 }
2764 break;
2765 }
2766 }
2767 return mEffectChains.size();
2768}
2769
2770status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2771 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2772{
2773 Mutex::Autolock _l(mLock);
2774 return attachAuxEffect_l(track, EffectId);
2775}
2776
2777status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2778 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2779{
2780 status_t status = NO_ERROR;
2781
2782 if (EffectId == 0) {
2783 track->setAuxBuffer(0, NULL);
2784 } else {
2785 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2786 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2787 if (effect != 0) {
2788 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2789 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2790 } else {
2791 status = INVALID_OPERATION;
2792 }
2793 } else {
2794 status = BAD_VALUE;
2795 }
2796 }
2797 return status;
2798}
2799
2800void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2801{
2802 for (size_t i = 0; i < mTracks.size(); ++i) {
2803 sp<Track> track = mTracks[i];
2804 if (track->auxEffectId() == effectId) {
2805 attachAuxEffect_l(track, 0);
2806 }
2807 }
2808}
2809
2810bool AudioFlinger::PlaybackThread::threadLoop()
2811{
2812 Vector< sp<Track> > tracksToRemove;
2813
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002814 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002815
2816 // MIXER
2817 nsecs_t lastWarning = 0;
2818
2819 // DUPLICATING
2820 // FIXME could this be made local to while loop?
2821 writeFrames = 0;
2822
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002823 int lastGeneration = 0;
2824
Eric Laurent81784c32012-11-19 14:55:58 -08002825 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002826 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002827
2828 if (mType == MIXER) {
2829 sleepTimeShift = 0;
2830 }
2831
2832 CpuStats cpuStats;
2833 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2834
2835 acquireWakeLock();
2836
Glenn Kasten9e58b552013-01-18 15:09:48 -08002837 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2838 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2839 // and then that string will be logged at the next convenient opportunity.
2840 const char *logString = NULL;
2841
Eric Laurent664539d2013-09-23 18:24:31 -07002842 checkSilentMode_l();
2843
Eric Laurent81784c32012-11-19 14:55:58 -08002844 while (!exitPending())
2845 {
2846 cpuStats.sample(myName);
2847
2848 Vector< sp<EffectChain> > effectChains;
2849
Eric Laurent81784c32012-11-19 14:55:58 -08002850 { // scope for mLock
2851
2852 Mutex::Autolock _l(mLock);
2853
Eric Laurent021cf962014-05-13 10:18:14 -07002854 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002855
Glenn Kasten9e58b552013-01-18 15:09:48 -08002856 if (logString != NULL) {
2857 mNBLogWriter->logTimestamp();
2858 mNBLogWriter->log(logString);
2859 logString = NULL;
2860 }
2861
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002862 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002863 // and associate with the sink frames written out. We need
2864 // this to convert the sink timestamp to the track timestamp.
2865 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08002866 // We always fetch the timestamp here because often the downstream
2867 // sink will block whie writing.
2868 ExtendedTimestamp timestamp; // use private copy to fetch
2869 (void) mNormalSink->getTimestamp(timestamp);
2870 // copy over kernel info
2871 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2872 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2873 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2874 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2875
2876 // sinkFramesWritten for non-offloaded tracks are contiguous
2877 // even after standby() is called. This is useful for the track frame
2878 // to sink frame mapping.
2879 const int64_t sinkFramesWritten = mNormalSink->framesWritten();
2880 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = sinkFramesWritten;
2881 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2882
2883 const size_t size = mActiveTracks.size();
2884 for (size_t i = 0; i < size; ++i) {
2885 sp<Track> t = mActiveTracks[i].promote();
2886 if (t != 0 && !t->isFastTrack()) {
2887 t->updateTrackFrameInfo(
2888 t->mAudioTrackServerProxy->framesReleased(),
2889 sinkFramesWritten,
2890 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002891 }
2892 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002893 }
2894
Eric Laurent81784c32012-11-19 14:55:58 -08002895 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 if (mSignalPending) {
2897 // A signal was raised while we were unlocked
2898 mSignalPending = false;
2899 } else if (waitingAsyncCallback_l()) {
2900 if (exitPending()) {
2901 break;
2902 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002903 bool released = false;
2904 // The following works around a bug in the offload driver. Ideally we would release
2905 // the wake lock every time, but that causes the last offload buffer(s) to be
2906 // dropped while the device is on battery, so we need to hold a wake lock during
2907 // the drain phase.
2908 if (mBytesRemaining && !(mDrainSequence & 1)) {
2909 releaseWakeLock_l();
2910 released = true;
2911 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002912 mWakeLockUids.clear();
2913 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 ALOGV("wait async completion");
2915 mWaitWorkCV.wait(mLock);
2916 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002917 if (released) {
2918 acquireWakeLock_l();
2919 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002920 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2921 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002922
2923 continue;
2924 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002925 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 isSuspended()) {
2927 // put audio hardware into standby after short delay
2928 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002929
2930 threadLoop_standby();
2931
2932 mStandby = true;
2933 }
2934
2935 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2936 // we're about to wait, flush the binder command buffer
2937 IPCThreadState::self()->flushCommands();
2938
2939 clearOutputTracks();
2940
2941 if (exitPending()) {
2942 break;
2943 }
2944
2945 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002946 mWakeLockUids.clear();
2947 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002948 // wait until we have something to do...
2949 ALOGV("%s going to sleep", myName.string());
2950 mWaitWorkCV.wait(mLock);
2951 ALOGV("%s waking up", myName.string());
2952 acquireWakeLock_l();
2953
2954 mMixerStatus = MIXER_IDLE;
2955 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2956 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002957 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002958 checkSilentMode_l();
2959
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002960 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2961 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002962 if (mType == MIXER) {
2963 sleepTimeShift = 0;
2964 }
2965
2966 continue;
2967 }
2968 }
Eric Laurent81784c32012-11-19 14:55:58 -08002969 // mMixerStatusIgnoringFastTracks is also updated internally
2970 mMixerStatus = prepareTracks_l(&tracksToRemove);
2971
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002972 // compare with previously applied list
2973 if (lastGeneration != mActiveTracksGeneration) {
2974 // update wakelock
2975 updateWakeLockUids_l(mWakeLockUids);
2976 lastGeneration = mActiveTracksGeneration;
2977 }
2978
Eric Laurent81784c32012-11-19 14:55:58 -08002979 // prevent any changes in effect chain list and in each effect chain
2980 // during mixing and effect process as the audio buffers could be deleted
2981 // or modified if an effect is created or deleted
2982 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002983 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002984
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 if (mBytesRemaining == 0) {
2986 mCurrentWriteLength = 0;
2987 if (mMixerStatus == MIXER_TRACKS_READY) {
2988 // threadLoop_mix() sets mCurrentWriteLength
2989 threadLoop_mix();
2990 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2991 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002992 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002993 // must be written to HAL
2994 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002995 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002996 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997 }
2998 }
Andy Hung98ef9782014-03-04 14:46:50 -08002999 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003000 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003001 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3002 // or mSinkBuffer (if there are no effects).
3003 //
3004 // This is done pre-effects computation; if effects change to
3005 // support higher precision, this needs to move.
3006 //
3007 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003008 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003009 if (mMixerBufferValid) {
3010 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3011 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3012
Andy Hung2ddee192015-12-18 17:34:44 -08003013 // mono blend occurs for mixer threads only (not direct or offloaded)
3014 // and is handled here if we're going directly to the sink.
3015 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003016 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3017 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003018 }
3019
Andy Hung98ef9782014-03-04 14:46:50 -08003020 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3021 mNormalFrameCount * mChannelCount);
3022 }
3023
Eric Laurentbfb1b832013-01-07 09:53:42 -08003024 mBytesRemaining = mCurrentWriteLength;
3025 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003026 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003027 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003028 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003029 mBytesRemaining = 0;
3030 }
Eric Laurent81784c32012-11-19 14:55:58 -08003031
Eric Laurentbfb1b832013-01-07 09:53:42 -08003032 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003033 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034 for (size_t i = 0; i < effectChains.size(); i ++) {
3035 effectChains[i]->process_l();
3036 }
Eric Laurent81784c32012-11-19 14:55:58 -08003037 }
3038 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003039 // Process effect chains for offloaded thread even if no audio
3040 // was read from audio track: process only updates effect state
3041 // and thus does have to be synchronized with audio writes but may have
3042 // to be called while waiting for async write callback
3043 if (mType == OFFLOAD) {
3044 for (size_t i = 0; i < effectChains.size(); i ++) {
3045 effectChains[i]->process_l();
3046 }
3047 }
Eric Laurent81784c32012-11-19 14:55:58 -08003048
Andy Hung98ef9782014-03-04 14:46:50 -08003049 // Only if the Effects buffer is enabled and there is data in the
3050 // Effects buffer (buffer valid), we need to
3051 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003052 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003053 if (mEffectBufferValid) {
3054 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003055
3056 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003057 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3058 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003059 }
3060
Andy Hung98ef9782014-03-04 14:46:50 -08003061 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3062 mNormalFrameCount * mChannelCount);
3063 }
3064
Eric Laurent81784c32012-11-19 14:55:58 -08003065 // enable changes in effect chain
3066 unlockEffectChains(effectChains);
3067
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003069 // mSleepTimeUs == 0 means we must write to audio hardware
3070 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003071 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003073 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003074 if (ret < 0) {
3075 mBytesRemaining = 0;
3076 } else {
3077 mBytesWritten += ret;
3078 mBytesRemaining -= ret;
3079 }
3080 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3081 (mMixerStatus == MIXER_DRAIN_ALL)) {
3082 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003083 }
Andy Hung08fb1742015-05-31 23:22:10 -07003084 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003085 // write blocked detection
3086 nsecs_t now = systemTime();
3087 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003088 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003089 mNumDelayedWrites++;
3090 if ((now - lastWarning) > kWarningThrottleNs) {
3091 ATRACE_NAME("underrun");
3092 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3093 ns2ms(delta), mNumDelayedWrites, this);
3094 lastWarning = now;
3095 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003096 }
Andy Hung08fb1742015-05-31 23:22:10 -07003097
3098 if (mThreadThrottle
3099 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3100 && ret > 0) { // we wrote something
3101 // Limit MixerThread data processing to no more than twice the
3102 // expected processing rate.
3103 //
3104 // This helps prevent underruns with NuPlayer and other applications
3105 // which may set up buffers that are close to the minimum size, or use
3106 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3107 //
3108 // The throttle smooths out sudden large data drains from the device,
3109 // e.g. when it comes out of standby, which often causes problems with
3110 // (1) mixer threads without a fast mixer (which has its own warm-up)
3111 // (2) minimum buffer sized tracks (even if the track is full,
3112 // the app won't fill fast enough to handle the sudden draw).
3113
3114 const int32_t deltaMs = delta / 1000000;
3115 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3116 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3117 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003118 // notify of throttle start on verbose log
3119 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3120 "mixer(%p) throttle begin:"
3121 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003122 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003123 mThreadThrottleTimeMs += throttleMs;
3124 } else {
3125 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3126 if (diff > 0) {
3127 // notify of throttle end on debug log
3128 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3129 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3130 }
Andy Hung08fb1742015-05-31 23:22:10 -07003131 }
3132 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133 }
Eric Laurent81784c32012-11-19 14:55:58 -08003134
Eric Laurentbfb1b832013-01-07 09:53:42 -08003135 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003136 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003137 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003138 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139 }
Eric Laurent81784c32012-11-19 14:55:58 -08003140 }
3141
3142 // Finally let go of removed track(s), without the lock held
3143 // since we can't guarantee the destructors won't acquire that
3144 // same lock. This will also mutate and push a new fast mixer state.
3145 threadLoop_removeTracks(tracksToRemove);
3146 tracksToRemove.clear();
3147
3148 // FIXME I don't understand the need for this here;
3149 // it was in the original code but maybe the
3150 // assignment in saveOutputTracks() makes this unnecessary?
3151 clearOutputTracks();
3152
3153 // Effect chains will be actually deleted here if they were removed from
3154 // mEffectChains list during mixing or effects processing
3155 effectChains.clear();
3156
3157 // FIXME Note that the above .clear() is no longer necessary since effectChains
3158 // is now local to this block, but will keep it for now (at least until merge done).
3159 }
3160
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 threadLoop_exit();
3162
Eric Laurentcf817a22014-08-04 20:36:31 -07003163 if (!mStandby) {
3164 threadLoop_standby();
3165 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003166 }
3167
3168 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003169 mWakeLockUids.clear();
3170 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003171
3172 ALOGV("Thread %p type %d exiting", this, mType);
3173 return false;
3174}
3175
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176// removeTracks_l() must be called with ThreadBase::mLock held
3177void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3178{
3179 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003180 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 for (size_t i=0 ; i<count ; i++) {
3182 const sp<Track>& track = tracksToRemove.itemAt(i);
3183 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003184 mWakeLockUids.remove(track->uid());
3185 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3187 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3188 if (chain != 0) {
3189 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3190 track->sessionId());
3191 chain->decActiveTrackCnt();
3192 }
3193 if (track->isTerminated()) {
3194 removeTrack_l(track);
3195 }
3196 }
3197 }
3198
3199}
Eric Laurent81784c32012-11-19 14:55:58 -08003200
Eric Laurentaccc1472013-09-20 09:36:34 -07003201status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3202{
3203 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003204 ExtendedTimestamp ets;
3205 status_t status = mNormalSink->getTimestamp(ets);
3206 if (status == NO_ERROR) {
3207 status = ets.getBestTimestamp(&timestamp);
3208 }
3209 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003210 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003211 if ((mType == OFFLOAD || mType == DIRECT)
3212 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003213 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003214 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003215 if (ret == 0) {
3216 timestamp.mPosition = (uint32_t)position64;
3217 return NO_ERROR;
3218 }
3219 }
3220 return INVALID_OPERATION;
3221}
Eric Laurent1c333e22014-05-20 10:48:17 -07003222
Eric Laurent054d9d32015-04-24 08:48:48 -07003223status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3224 audio_patch_handle_t *handle)
3225{
3226 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3227 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3228 if (mFastMixer != 0) {
3229 FastMixerStateQueue *sq = mFastMixer->sq();
3230 FastMixerState *state = sq->begin();
3231 if (!(state->mCommand & FastMixerState::IDLE)) {
3232 previousCommand = state->mCommand;
3233 state->mCommand = FastMixerState::HOT_IDLE;
3234 sq->end();
3235 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3236 } else {
3237 sq->end(false /*didModify*/);
3238 }
3239 }
3240 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3241
3242 if (!(previousCommand & FastMixerState::IDLE)) {
3243 ALOG_ASSERT(mFastMixer != 0);
3244 FastMixerStateQueue *sq = mFastMixer->sq();
3245 FastMixerState *state = sq->begin();
3246 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3247 state->mCommand = previousCommand;
3248 sq->end();
3249 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3250 }
3251
3252 return status;
3253}
3254
Eric Laurent1c333e22014-05-20 10:48:17 -07003255status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3256 audio_patch_handle_t *handle)
3257{
3258 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003259
3260 // store new device and send to effects
3261 audio_devices_t type = AUDIO_DEVICE_NONE;
3262 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3263 type |= patch->sinks[i].ext.device.type;
3264 }
3265
3266#ifdef ADD_BATTERY_DATA
3267 // when changing the audio output device, call addBatteryData to notify
3268 // the change
3269 if (mOutDevice != type) {
3270 uint32_t params = 0;
3271 // check whether speaker is on
3272 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3273 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003274 }
3275
Eric Laurent054d9d32015-04-24 08:48:48 -07003276 audio_devices_t deviceWithoutSpeaker
3277 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3278 // check if any other device (except speaker) is on
3279 if (type & deviceWithoutSpeaker) {
3280 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3281 }
3282
3283 if (params != 0) {
3284 addBatteryData(params);
3285 }
3286 }
3287#endif
3288
3289 for (size_t i = 0; i < mEffectChains.size(); i++) {
3290 mEffectChains[i]->setDevice_l(type);
3291 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003292
3293 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3294 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3295 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003296 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003297 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003298
3299 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003300 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3301 status = hwDevice->create_audio_patch(hwDevice,
3302 patch->num_sources,
3303 patch->sources,
3304 patch->num_sinks,
3305 patch->sinks,
3306 handle);
3307 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003308 char *address;
3309 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3310 //FIXME: we only support address on first sink with HAL version < 3.0
3311 address = audio_device_address_to_parameter(
3312 patch->sinks[0].ext.device.type,
3313 patch->sinks[0].ext.device.address);
3314 } else {
3315 address = (char *)calloc(1, 1);
3316 }
3317 AudioParameter param = AudioParameter(String8(address));
3318 free(address);
3319 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3320 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3321 param.toString().string());
3322 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003323 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003324 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003325 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003326 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3327 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003328 return status;
3329}
3330
Eric Laurent054d9d32015-04-24 08:48:48 -07003331status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3332{
3333 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3334 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3335 if (mFastMixer != 0) {
3336 FastMixerStateQueue *sq = mFastMixer->sq();
3337 FastMixerState *state = sq->begin();
3338 if (!(state->mCommand & FastMixerState::IDLE)) {
3339 previousCommand = state->mCommand;
3340 state->mCommand = FastMixerState::HOT_IDLE;
3341 sq->end();
3342 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3343 } else {
3344 sq->end(false /*didModify*/);
3345 }
3346 }
3347
3348 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3349
3350 if (!(previousCommand & FastMixerState::IDLE)) {
3351 ALOG_ASSERT(mFastMixer != 0);
3352 FastMixerStateQueue *sq = mFastMixer->sq();
3353 FastMixerState *state = sq->begin();
3354 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3355 state->mCommand = previousCommand;
3356 sq->end();
3357 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3358 }
3359
3360 return status;
3361}
3362
Eric Laurent1c333e22014-05-20 10:48:17 -07003363status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3364{
3365 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003366
3367 mOutDevice = AUDIO_DEVICE_NONE;
3368
Eric Laurent1c333e22014-05-20 10:48:17 -07003369 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3370 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3371 status = hwDevice->release_audio_patch(hwDevice, handle);
3372 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003373 AudioParameter param;
3374 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3375 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3376 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003377 }
3378 return status;
3379}
3380
Eric Laurent83b88082014-06-20 18:31:16 -07003381void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3382{
3383 Mutex::Autolock _l(mLock);
3384 mTracks.add(track);
3385}
3386
3387void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3388{
3389 Mutex::Autolock _l(mLock);
3390 destroyTrack_l(track);
3391}
3392
3393void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3394{
3395 ThreadBase::getAudioPortConfig(config);
3396 config->role = AUDIO_PORT_ROLE_SOURCE;
3397 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3398 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3399}
3400
Eric Laurent81784c32012-11-19 14:55:58 -08003401// ----------------------------------------------------------------------------
3402
3403AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003404 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3405 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003406 // mAudioMixer below
3407 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003408 mFastMixerFutex(0),
3409 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003410 // mOutputSink below
3411 // mPipeSink below
3412 // mNormalSink below
3413{
3414 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003415 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003416 "mFrameCount=%d, mNormalFrameCount=%d",
3417 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3418 mNormalFrameCount);
3419 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3420
Andy Hungfbfc3952015-01-15 13:33:51 -08003421 if (type == DUPLICATING) {
3422 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3423 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3424 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3425 return;
3426 }
Eric Laurent81784c32012-11-19 14:55:58 -08003427 // create an NBAIO sink for the HAL output stream, and negotiate
3428 mOutputSink = new AudioStreamOutSink(output->stream);
3429 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003430 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003431 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3432 ALOG_ASSERT(index == 0);
3433
3434 // initialize fast mixer depending on configuration
3435 bool initFastMixer;
3436 switch (kUseFastMixer) {
3437 case FastMixer_Never:
3438 initFastMixer = false;
3439 break;
3440 case FastMixer_Always:
3441 initFastMixer = true;
3442 break;
3443 case FastMixer_Static:
3444 case FastMixer_Dynamic:
3445 initFastMixer = mFrameCount < mNormalFrameCount;
3446 break;
3447 }
3448 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003449 audio_format_t fastMixerFormat;
3450 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3451 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3452 } else {
3453 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3454 }
3455 if (mFormat != fastMixerFormat) {
3456 // change our Sink format to accept our intermediate precision
3457 mFormat = fastMixerFormat;
3458 free(mSinkBuffer);
3459 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3460 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3461 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3462 }
Eric Laurent81784c32012-11-19 14:55:58 -08003463
3464 // create a MonoPipe to connect our submix to FastMixer
3465 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003466 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003467 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003468 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003469 format.mFormat = fastMixerFormat;
3470 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3471
Eric Laurent81784c32012-11-19 14:55:58 -08003472 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3473 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3474 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3475 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3476 const NBAIO_Format offers[1] = {format};
3477 size_t numCounterOffers = 0;
3478 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3479 ALOG_ASSERT(index == 0);
3480 monoPipe->setAvgFrames((mScreenState & 1) ?
3481 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3482 mPipeSink = monoPipe;
3483
Glenn Kasten46909e72013-02-26 09:20:22 -08003484#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003485 if (mTeeSinkOutputEnabled) {
3486 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003487 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3488 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003489 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003490 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003491 ALOG_ASSERT(index == 0);
3492 mTeeSink = teeSink;
3493 PipeReader *teeSource = new PipeReader(*teeSink);
3494 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003495 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003496 ALOG_ASSERT(index == 0);
3497 mTeeSource = teeSource;
3498 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003499#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003500
3501 // create fast mixer and configure it initially with just one fast track for our submix
3502 mFastMixer = new FastMixer();
3503 FastMixerStateQueue *sq = mFastMixer->sq();
3504#ifdef STATE_QUEUE_DUMP
3505 sq->setObserverDump(&mStateQueueObserverDump);
3506 sq->setMutatorDump(&mStateQueueMutatorDump);
3507#endif
3508 FastMixerState *state = sq->begin();
3509 FastTrack *fastTrack = &state->mFastTracks[0];
3510 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3511 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3512 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003513 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3514 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003515 fastTrack->mGeneration++;
3516 state->mFastTracksGen++;
3517 state->mTrackMask = 1;
3518 // fast mixer will use the HAL output sink
3519 state->mOutputSink = mOutputSink.get();
3520 state->mOutputSinkGen++;
3521 state->mFrameCount = mFrameCount;
3522 state->mCommand = FastMixerState::COLD_IDLE;
3523 // already done in constructor initialization list
3524 //mFastMixerFutex = 0;
3525 state->mColdFutexAddr = &mFastMixerFutex;
3526 state->mColdGen++;
3527 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003528#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003529 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003530#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003531 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3532 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003533 sq->end();
3534 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3535
3536 // start the fast mixer
3537 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3538 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003539 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003540
3541#ifdef AUDIO_WATCHDOG
3542 // create and start the watchdog
3543 mAudioWatchdog = new AudioWatchdog();
3544 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3545 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3546 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003547 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003548#endif
3549
Eric Laurent81784c32012-11-19 14:55:58 -08003550 }
3551
3552 switch (kUseFastMixer) {
3553 case FastMixer_Never:
3554 case FastMixer_Dynamic:
3555 mNormalSink = mOutputSink;
3556 break;
3557 case FastMixer_Always:
3558 mNormalSink = mPipeSink;
3559 break;
3560 case FastMixer_Static:
3561 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3562 break;
3563 }
3564}
3565
3566AudioFlinger::MixerThread::~MixerThread()
3567{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003568 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003569 FastMixerStateQueue *sq = mFastMixer->sq();
3570 FastMixerState *state = sq->begin();
3571 if (state->mCommand == FastMixerState::COLD_IDLE) {
3572 int32_t old = android_atomic_inc(&mFastMixerFutex);
3573 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003574 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003575 }
3576 }
3577 state->mCommand = FastMixerState::EXIT;
3578 sq->end();
3579 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3580 mFastMixer->join();
3581 // Though the fast mixer thread has exited, it's state queue is still valid.
3582 // We'll use that extract the final state which contains one remaining fast track
3583 // corresponding to our sub-mix.
3584 state = sq->begin();
3585 ALOG_ASSERT(state->mTrackMask == 1);
3586 FastTrack *fastTrack = &state->mFastTracks[0];
3587 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3588 delete fastTrack->mBufferProvider;
3589 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003590 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003591#ifdef AUDIO_WATCHDOG
3592 if (mAudioWatchdog != 0) {
3593 mAudioWatchdog->requestExit();
3594 mAudioWatchdog->requestExitAndWait();
3595 mAudioWatchdog.clear();
3596 }
3597#endif
3598 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003599 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003600 delete mAudioMixer;
3601}
3602
3603
3604uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3605{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003606 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003607 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3608 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3609 }
3610 return latency;
3611}
3612
3613
3614void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3615{
3616 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3617}
3618
Eric Laurentbfb1b832013-01-07 09:53:42 -08003619ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003620{
3621 // FIXME we should only do one push per cycle; confirm this is true
3622 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003623 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003624 FastMixerStateQueue *sq = mFastMixer->sq();
3625 FastMixerState *state = sq->begin();
3626 if (state->mCommand != FastMixerState::MIX_WRITE &&
3627 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3628 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003629
3630 // FIXME workaround for first HAL write being CPU bound on some devices
3631 ATRACE_BEGIN("write");
3632 mOutput->write((char *)mSinkBuffer, 0);
3633 ATRACE_END();
3634
Eric Laurent81784c32012-11-19 14:55:58 -08003635 int32_t old = android_atomic_inc(&mFastMixerFutex);
3636 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003637 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003638 }
3639#ifdef AUDIO_WATCHDOG
3640 if (mAudioWatchdog != 0) {
3641 mAudioWatchdog->resume();
3642 }
3643#endif
3644 }
3645 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003646#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003647 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003648 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003649#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003650 sq->end();
3651 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3652 if (kUseFastMixer == FastMixer_Dynamic) {
3653 mNormalSink = mPipeSink;
3654 }
3655 } else {
3656 sq->end(false /*didModify*/);
3657 }
3658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003659 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003660}
3661
3662void AudioFlinger::MixerThread::threadLoop_standby()
3663{
3664 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003665 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003666 FastMixerStateQueue *sq = mFastMixer->sq();
3667 FastMixerState *state = sq->begin();
3668 if (!(state->mCommand & FastMixerState::IDLE)) {
3669 state->mCommand = FastMixerState::COLD_IDLE;
3670 state->mColdFutexAddr = &mFastMixerFutex;
3671 state->mColdGen++;
3672 mFastMixerFutex = 0;
3673 sq->end();
3674 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3675 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3676 if (kUseFastMixer == FastMixer_Dynamic) {
3677 mNormalSink = mOutputSink;
3678 }
3679#ifdef AUDIO_WATCHDOG
3680 if (mAudioWatchdog != 0) {
3681 mAudioWatchdog->pause();
3682 }
3683#endif
3684 } else {
3685 sq->end(false /*didModify*/);
3686 }
3687 }
3688 PlaybackThread::threadLoop_standby();
3689}
3690
Eric Laurentbfb1b832013-01-07 09:53:42 -08003691bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3692{
3693 return false;
3694}
3695
3696bool AudioFlinger::PlaybackThread::shouldStandby_l()
3697{
3698 return !mStandby;
3699}
3700
3701bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3702{
3703 Mutex::Autolock _l(mLock);
3704 return waitingAsyncCallback_l();
3705}
3706
Eric Laurent81784c32012-11-19 14:55:58 -08003707// shared by MIXER and DIRECT, overridden by DUPLICATING
3708void AudioFlinger::PlaybackThread::threadLoop_standby()
3709{
3710 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003711 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003712 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003713 // discard any pending drain or write ack by incrementing sequence
3714 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3715 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003717 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3718 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003719 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003720 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003721}
3722
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003723void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3724{
3725 ALOGV("signal playback thread");
3726 broadcast_l();
3727}
3728
Eric Laurent81784c32012-11-19 14:55:58 -08003729void AudioFlinger::MixerThread::threadLoop_mix()
3730{
Eric Laurent81784c32012-11-19 14:55:58 -08003731 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003732 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003733 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003734 // increase sleep time progressively when application underrun condition clears.
3735 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3736 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3737 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003738 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003739 sleepTimeShift--;
3740 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003741 mSleepTimeUs = 0;
3742 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003743 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003744
Eric Laurent81784c32012-11-19 14:55:58 -08003745}
3746
3747void AudioFlinger::MixerThread::threadLoop_sleepTime()
3748{
3749 // If no tracks are ready, sleep once for the duration of an output
3750 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003751 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003752 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003753 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3754 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3755 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003756 }
3757 // reduce sleep time in case of consecutive application underruns to avoid
3758 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3759 // duration we would end up writing less data than needed by the audio HAL if
3760 // the condition persists.
3761 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3762 sleepTimeShift++;
3763 }
3764 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003765 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003766 }
3767 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003768 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3769 // before effects processing or output.
3770 if (mMixerBufferValid) {
3771 memset(mMixerBuffer, 0, mMixerBufferSize);
3772 } else {
3773 memset(mSinkBuffer, 0, mSinkBufferSize);
3774 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003775 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003776 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3777 "anticipated start");
3778 }
3779 // TODO add standby time extension fct of effect tail
3780}
3781
3782// prepareTracks_l() must be called with ThreadBase::mLock held
3783AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3784 Vector< sp<Track> > *tracksToRemove)
3785{
3786
3787 mixer_state mixerStatus = MIXER_IDLE;
3788 // find out which tracks need to be processed
3789 size_t count = mActiveTracks.size();
3790 size_t mixedTracks = 0;
3791 size_t tracksWithEffect = 0;
3792 // counts only _active_ fast tracks
3793 size_t fastTracks = 0;
3794 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3795
3796 float masterVolume = mMasterVolume;
3797 bool masterMute = mMasterMute;
3798
3799 if (masterMute) {
3800 masterVolume = 0;
3801 }
3802 // Delegate master volume control to effect in output mix effect chain if needed
3803 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3804 if (chain != 0) {
3805 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3806 chain->setVolume_l(&v, &v);
3807 masterVolume = (float)((v + (1 << 23)) >> 24);
3808 chain.clear();
3809 }
3810
3811 // prepare a new state to push
3812 FastMixerStateQueue *sq = NULL;
3813 FastMixerState *state = NULL;
3814 bool didModify = false;
3815 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003816 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003817 sq = mFastMixer->sq();
3818 state = sq->begin();
3819 }
3820
Andy Hung69aed5f2014-02-25 17:24:40 -08003821 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003822 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003823
Eric Laurent81784c32012-11-19 14:55:58 -08003824 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003825 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003826 if (t == 0) {
3827 continue;
3828 }
3829
3830 // this const just means the local variable doesn't change
3831 Track* const track = t.get();
3832
3833 // process fast tracks
3834 if (track->isFastTrack()) {
3835
3836 // It's theoretically possible (though unlikely) for a fast track to be created
3837 // and then removed within the same normal mix cycle. This is not a problem, as
3838 // the track never becomes active so it's fast mixer slot is never touched.
3839 // The converse, of removing an (active) track and then creating a new track
3840 // at the identical fast mixer slot within the same normal mix cycle,
3841 // is impossible because the slot isn't marked available until the end of each cycle.
3842 int j = track->mFastIndex;
3843 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3844 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3845 FastTrack *fastTrack = &state->mFastTracks[j];
3846
3847 // Determine whether the track is currently in underrun condition,
3848 // and whether it had a recent underrun.
3849 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3850 FastTrackUnderruns underruns = ftDump->mUnderruns;
3851 uint32_t recentFull = (underruns.mBitFields.mFull -
3852 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3853 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3854 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3855 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3856 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3857 uint32_t recentUnderruns = recentPartial + recentEmpty;
3858 track->mObservedUnderruns = underruns;
3859 // don't count underruns that occur while stopping or pausing
3860 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003861 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3862 recentUnderruns > 0) {
3863 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3864 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003865 } else {
3866 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003867 }
3868
3869 // This is similar to the state machine for normal tracks,
3870 // with a few modifications for fast tracks.
3871 bool isActive = true;
3872 switch (track->mState) {
3873 case TrackBase::STOPPING_1:
3874 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003875 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003876 track->mState = TrackBase::STOPPING_2;
3877 }
3878 break;
3879 case TrackBase::PAUSING:
3880 // ramp down is not yet implemented
3881 track->setPaused();
3882 break;
3883 case TrackBase::RESUMING:
3884 // ramp up is not yet implemented
3885 track->mState = TrackBase::ACTIVE;
3886 break;
3887 case TrackBase::ACTIVE:
3888 if (recentFull > 0 || recentPartial > 0) {
3889 // track has provided at least some frames recently: reset retry count
3890 track->mRetryCount = kMaxTrackRetries;
3891 }
3892 if (recentUnderruns == 0) {
3893 // no recent underruns: stay active
3894 break;
3895 }
3896 // there has recently been an underrun of some kind
3897 if (track->sharedBuffer() == 0) {
3898 // were any of the recent underruns "empty" (no frames available)?
3899 if (recentEmpty == 0) {
3900 // no, then ignore the partial underruns as they are allowed indefinitely
3901 break;
3902 }
3903 // there has recently been an "empty" underrun: decrement the retry counter
3904 if (--(track->mRetryCount) > 0) {
3905 break;
3906 }
3907 // indicate to client process that the track was disabled because of underrun;
3908 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003909 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003910 // remove from active list, but state remains ACTIVE [confusing but true]
3911 isActive = false;
3912 break;
3913 }
3914 // fall through
3915 case TrackBase::STOPPING_2:
3916 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003917 case TrackBase::STOPPED:
3918 case TrackBase::FLUSHED: // flush() while active
3919 // Check for presentation complete if track is inactive
3920 // We have consumed all the buffers of this track.
3921 // This would be incomplete if we auto-paused on underrun
3922 {
3923 size_t audioHALFrames =
3924 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003925 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003926 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3927 // track stays in active list until presentation is complete
3928 break;
3929 }
3930 }
3931 if (track->isStopping_2()) {
3932 track->mState = TrackBase::STOPPED;
3933 }
3934 if (track->isStopped()) {
3935 // Can't reset directly, as fast mixer is still polling this track
3936 // track->reset();
3937 // So instead mark this track as needing to be reset after push with ack
3938 resetMask |= 1 << i;
3939 }
3940 isActive = false;
3941 break;
3942 case TrackBase::IDLE:
3943 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003944 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003945 }
3946
3947 if (isActive) {
3948 // was it previously inactive?
3949 if (!(state->mTrackMask & (1 << j))) {
3950 ExtendedAudioBufferProvider *eabp = track;
3951 VolumeProvider *vp = track;
3952 fastTrack->mBufferProvider = eabp;
3953 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003954 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003955 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003956 fastTrack->mGeneration++;
3957 state->mTrackMask |= 1 << j;
3958 didModify = true;
3959 // no acknowledgement required for newly active tracks
3960 }
3961 // cache the combined master volume and stream type volume for fast mixer; this
3962 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003963 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003964 ++fastTracks;
3965 } else {
3966 // was it previously active?
3967 if (state->mTrackMask & (1 << j)) {
3968 fastTrack->mBufferProvider = NULL;
3969 fastTrack->mGeneration++;
3970 state->mTrackMask &= ~(1 << j);
3971 didModify = true;
3972 // If any fast tracks were removed, we must wait for acknowledgement
3973 // because we're about to decrement the last sp<> on those tracks.
3974 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3975 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003976 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3977 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3978 j, track->mState, state->mTrackMask, recentUnderruns,
3979 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003980 }
3981 tracksToRemove->add(track);
3982 // Avoids a misleading display in dumpsys
3983 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3984 }
3985 continue;
3986 }
3987
3988 { // local variable scope to avoid goto warning
3989
3990 audio_track_cblk_t* cblk = track->cblk();
3991
3992 // The first time a track is added we wait
3993 // for all its buffers to be filled before processing it
3994 int name = track->name();
3995 // make sure that we have enough frames to mix one full buffer.
3996 // enforce this condition only once to enable draining the buffer in case the client
3997 // app does not call stop() and relies on underrun to stop:
3998 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3999 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004000 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004001 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004002 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004003
4004 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004005 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004006 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4007 // add frames already consumed but not yet released by the resampler
4008 // because mAudioTrackServerProxy->framesReady() will include these frames
4009 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4010
Eric Laurent81784c32012-11-19 14:55:58 -08004011 uint32_t minFrames = 1;
4012 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4013 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004014 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004015 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004016
4017 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004018 if (ATRACE_ENABLED()) {
4019 // I wish we had formatted trace names
4020 char traceName[16];
4021 strcpy(traceName, "nRdy");
4022 int name = track->name();
4023 if (AudioMixer::TRACK0 <= name &&
4024 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4025 name -= AudioMixer::TRACK0;
4026 traceName[4] = (name / 10) + '0';
4027 traceName[5] = (name % 10) + '0';
4028 } else {
4029 traceName[4] = '?';
4030 traceName[5] = '?';
4031 }
4032 traceName[6] = '\0';
4033 ATRACE_INT(traceName, framesReady);
4034 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004035 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004036 !track->isPaused() && !track->isTerminated())
4037 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004038 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004039
4040 mixedTracks++;
4041
Andy Hung69aed5f2014-02-25 17:24:40 -08004042 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4043 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004044 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004045 if (track->mainBuffer() != mSinkBuffer &&
4046 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004047 if (mEffectBufferEnabled) {
4048 mEffectBufferValid = true; // Later can set directly.
4049 }
Eric Laurent81784c32012-11-19 14:55:58 -08004050 chain = getEffectChain_l(track->sessionId());
4051 // Delegate volume control to effect in track effect chain if needed
4052 if (chain != 0) {
4053 tracksWithEffect++;
4054 } else {
4055 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4056 "session %d",
4057 name, track->sessionId());
4058 }
4059 }
4060
4061
4062 int param = AudioMixer::VOLUME;
4063 if (track->mFillingUpStatus == Track::FS_FILLED) {
4064 // no ramp for the first volume setting
4065 track->mFillingUpStatus = Track::FS_ACTIVE;
4066 if (track->mState == TrackBase::RESUMING) {
4067 track->mState = TrackBase::ACTIVE;
4068 param = AudioMixer::RAMP_VOLUME;
4069 }
4070 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004071 // FIXME should not make a decision based on mServer
4072 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004073 // If the track is stopped before the first frame was mixed,
4074 // do not apply ramp
4075 param = AudioMixer::RAMP_VOLUME;
4076 }
4077
4078 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004079 uint32_t vl, vr; // in U8.24 integer format
4080 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004081 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004082 vl = vr = 0;
4083 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004084 if (track->isPausing()) {
4085 track->setPaused();
4086 }
4087 } else {
4088
4089 // read original volumes with volume control
4090 float typeVolume = mStreamTypes[track->streamType()].volume;
4091 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004092 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004093 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004094 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4095 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004096 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004097 if (vlf > GAIN_FLOAT_UNITY) {
4098 ALOGV("Track left volume out of range: %.3g", vlf);
4099 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004100 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004101 if (vrf > GAIN_FLOAT_UNITY) {
4102 ALOGV("Track right volume out of range: %.3g", vrf);
4103 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004104 }
4105 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004106 vlf *= v;
4107 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004108 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004109 // then derive vl and vr as U8.24 versions for the effect chain
4110 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4111 vl = (uint32_t) (scaleto8_24 * vlf);
4112 vr = (uint32_t) (scaleto8_24 * vrf);
4113 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004114 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004115 // send level comes from shared memory and so may be corrupt
4116 if (sendLevel > MAX_GAIN_INT) {
4117 ALOGV("Track send level out of range: %04X", sendLevel);
4118 sendLevel = MAX_GAIN_INT;
4119 }
Andy Hung6be49402014-05-30 10:42:03 -07004120 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4121 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004122 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123
Eric Laurent81784c32012-11-19 14:55:58 -08004124 // Delegate volume control to effect in track effect chain if needed
4125 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4126 // Do not ramp volume if volume is controlled by effect
4127 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004128 // Update remaining floating point volume levels
4129 vlf = (float)vl / (1 << 24);
4130 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004131 track->mHasVolumeController = true;
4132 } else {
4133 // force no volume ramp when volume controller was just disabled or removed
4134 // from effect chain to avoid volume spike
4135 if (track->mHasVolumeController) {
4136 param = AudioMixer::VOLUME;
4137 }
4138 track->mHasVolumeController = false;
4139 }
4140
Eric Laurent81784c32012-11-19 14:55:58 -08004141 // XXX: these things DON'T need to be done each time
4142 mAudioMixer->setBufferProvider(name, track);
4143 mAudioMixer->enable(name);
4144
Andy Hung6be49402014-05-30 10:42:03 -07004145 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4146 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4147 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004148 mAudioMixer->setParameter(
4149 name,
4150 AudioMixer::TRACK,
4151 AudioMixer::FORMAT, (void *)track->format());
4152 mAudioMixer->setParameter(
4153 name,
4154 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004155 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004156 mAudioMixer->setParameter(
4157 name,
4158 AudioMixer::TRACK,
4159 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004160 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004161 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004162 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004163 if (reqSampleRate == 0) {
4164 reqSampleRate = mSampleRate;
4165 } else if (reqSampleRate > maxSampleRate) {
4166 reqSampleRate = maxSampleRate;
4167 }
Eric Laurent81784c32012-11-19 14:55:58 -08004168 mAudioMixer->setParameter(
4169 name,
4170 AudioMixer::RESAMPLE,
4171 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004172 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004173
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004174 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004175 mAudioMixer->setParameter(
4176 name,
4177 AudioMixer::TIMESTRETCH,
4178 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004179 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004180
Andy Hung69aed5f2014-02-25 17:24:40 -08004181 /*
4182 * Select the appropriate output buffer for the track.
4183 *
Andy Hung98ef9782014-03-04 14:46:50 -08004184 * Tracks with effects go into their own effects chain buffer
4185 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004186 *
4187 * Other tracks can use mMixerBuffer for higher precision
4188 * channel accumulation. If this buffer is enabled
4189 * (mMixerBufferEnabled true), then selected tracks will accumulate
4190 * into it.
4191 *
4192 */
4193 if (mMixerBufferEnabled
4194 && (track->mainBuffer() == mSinkBuffer
4195 || track->mainBuffer() == mMixerBuffer)) {
4196 mAudioMixer->setParameter(
4197 name,
4198 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004199 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004200 mAudioMixer->setParameter(
4201 name,
4202 AudioMixer::TRACK,
4203 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4204 // TODO: override track->mainBuffer()?
4205 mMixerBufferValid = true;
4206 } else {
4207 mAudioMixer->setParameter(
4208 name,
4209 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004210 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004211 mAudioMixer->setParameter(
4212 name,
4213 AudioMixer::TRACK,
4214 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4215 }
Eric Laurent81784c32012-11-19 14:55:58 -08004216 mAudioMixer->setParameter(
4217 name,
4218 AudioMixer::TRACK,
4219 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4220
4221 // reset retry count
4222 track->mRetryCount = kMaxTrackRetries;
4223
4224 // If one track is ready, set the mixer ready if:
4225 // - the mixer was not ready during previous round OR
4226 // - no other track is not ready
4227 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4228 mixerStatus != MIXER_TRACKS_ENABLED) {
4229 mixerStatus = MIXER_TRACKS_READY;
4230 }
4231 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004232 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004233 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4234 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004235 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004236 } else {
4237 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004238 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004239
Eric Laurent81784c32012-11-19 14:55:58 -08004240 // clear effect chain input buffer if an active track underruns to avoid sending
4241 // previous audio buffer again to effects
4242 chain = getEffectChain_l(track->sessionId());
4243 if (chain != 0) {
4244 chain->clearInputBuffer();
4245 }
4246
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004247 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004248 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4249 track->isStopped() || track->isPaused()) {
4250 // We have consumed all the buffers of this track.
4251 // Remove it from the list of active tracks.
4252 // TODO: use actual buffer filling status instead of latency when available from
4253 // audio HAL
4254 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004255 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004256 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4257 if (track->isStopped()) {
4258 track->reset();
4259 }
4260 tracksToRemove->add(track);
4261 }
4262 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004263 // No buffers for this track. Give it a few chances to
4264 // fill a buffer, then remove it from active list.
4265 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004266 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004267 tracksToRemove->add(track);
4268 // indicate to client process that the track was disabled because of underrun;
4269 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004270 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004271 // If one track is not ready, mark the mixer also not ready if:
4272 // - the mixer was ready during previous round OR
4273 // - no other track is ready
4274 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4275 mixerStatus != MIXER_TRACKS_READY) {
4276 mixerStatus = MIXER_TRACKS_ENABLED;
4277 }
4278 }
4279 mAudioMixer->disable(name);
4280 }
4281
4282 } // local variable scope to avoid goto warning
4283track_is_ready: ;
4284
4285 }
4286
4287 // Push the new FastMixer state if necessary
4288 bool pauseAudioWatchdog = false;
4289 if (didModify) {
4290 state->mFastTracksGen++;
4291 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4292 if (kUseFastMixer == FastMixer_Dynamic &&
4293 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4294 state->mCommand = FastMixerState::COLD_IDLE;
4295 state->mColdFutexAddr = &mFastMixerFutex;
4296 state->mColdGen++;
4297 mFastMixerFutex = 0;
4298 if (kUseFastMixer == FastMixer_Dynamic) {
4299 mNormalSink = mOutputSink;
4300 }
4301 // If we go into cold idle, need to wait for acknowledgement
4302 // so that fast mixer stops doing I/O.
4303 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4304 pauseAudioWatchdog = true;
4305 }
Eric Laurent81784c32012-11-19 14:55:58 -08004306 }
4307 if (sq != NULL) {
4308 sq->end(didModify);
4309 sq->push(block);
4310 }
4311#ifdef AUDIO_WATCHDOG
4312 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4313 mAudioWatchdog->pause();
4314 }
4315#endif
4316
4317 // Now perform the deferred reset on fast tracks that have stopped
4318 while (resetMask != 0) {
4319 size_t i = __builtin_ctz(resetMask);
4320 ALOG_ASSERT(i < count);
4321 resetMask &= ~(1 << i);
4322 sp<Track> t = mActiveTracks[i].promote();
4323 if (t == 0) {
4324 continue;
4325 }
4326 Track* track = t.get();
4327 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4328 track->reset();
4329 }
4330
4331 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004333
Eric Laurent97d547d2014-09-02 14:45:53 -07004334 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4335 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004336 }
4337
4338 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004339 // as long as there are effects we should clear the effects buffer, to avoid
4340 // passing a non-clean buffer to the effect chain
4341 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004342 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004343 // sink or mix buffer must be cleared if all tracks are connected to an
4344 // effect chain as in this case the mixer will not write to the sink or mix buffer
4345 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004346 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4347 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004348 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004349 if (mMixerBufferValid) {
4350 memset(mMixerBuffer, 0, mMixerBufferSize);
4351 // TODO: In testing, mSinkBuffer below need not be cleared because
4352 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4353 // after mixing.
4354 //
4355 // To enforce this guarantee:
4356 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4357 // (mixedTracks == 0 && fastTracks > 0))
4358 // must imply MIXER_TRACKS_READY.
4359 // Later, we may clear buffers regardless, and skip much of this logic.
4360 }
Andy Hung98ef9782014-03-04 14:46:50 -08004361 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004362 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004363 }
4364
4365 // if any fast tracks, then status is ready
4366 mMixerStatusIgnoringFastTracks = mixerStatus;
4367 if (fastTracks > 0) {
4368 mixerStatus = MIXER_TRACKS_READY;
4369 }
4370 return mixerStatus;
4371}
4372
4373// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004374int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4375 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004376{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004377 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004378}
4379
4380// deleteTrackName_l() must be called with ThreadBase::mLock held
4381void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4382{
4383 ALOGV("remove track (%d) and delete from mixer", name);
4384 mAudioMixer->deleteTrackName(name);
4385}
4386
Eric Laurent10351942014-05-08 18:49:52 -07004387// checkForNewParameter_l() must be called with ThreadBase::mLock held
4388bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4389 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004390{
Eric Laurent81784c32012-11-19 14:55:58 -08004391 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004392 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004393
Eric Laurent10351942014-05-08 18:49:52 -07004394 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004395
Eric Laurent10351942014-05-08 18:49:52 -07004396 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4397 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004398 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004399 FastMixerStateQueue *sq = mFastMixer->sq();
4400 FastMixerState *state = sq->begin();
4401 if (!(state->mCommand & FastMixerState::IDLE)) {
4402 previousCommand = state->mCommand;
4403 state->mCommand = FastMixerState::HOT_IDLE;
4404 sq->end();
4405 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4406 } else {
4407 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004408 }
Eric Laurent10351942014-05-08 18:49:52 -07004409 }
Eric Laurent81784c32012-11-19 14:55:58 -08004410
Eric Laurent10351942014-05-08 18:49:52 -07004411 AudioParameter param = AudioParameter(keyValuePair);
4412 int value;
4413 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4414 reconfig = true;
4415 }
4416 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004417 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004418 status = BAD_VALUE;
4419 } else {
4420 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004421 reconfig = true;
4422 }
Eric Laurent10351942014-05-08 18:49:52 -07004423 }
4424 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004425 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004426 status = BAD_VALUE;
4427 } else {
4428 // no need to save value, since it's constant
4429 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004430 }
Eric Laurent10351942014-05-08 18:49:52 -07004431 }
4432 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4433 // do not accept frame count changes if tracks are open as the track buffer
4434 // size depends on frame count and correct behavior would not be guaranteed
4435 // if frame count is changed after track creation
4436 if (!mTracks.isEmpty()) {
4437 status = INVALID_OPERATION;
4438 } else {
4439 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004440 }
Eric Laurent10351942014-05-08 18:49:52 -07004441 }
4442 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004443#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004444 // when changing the audio output device, call addBatteryData to notify
4445 // the change
4446 if (mOutDevice != value) {
4447 uint32_t params = 0;
4448 // check whether speaker is on
4449 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4450 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004451 }
Eric Laurent10351942014-05-08 18:49:52 -07004452
4453 audio_devices_t deviceWithoutSpeaker
4454 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4455 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004456 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004457 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4458 }
4459
4460 if (params != 0) {
4461 addBatteryData(params);
4462 }
4463 }
Eric Laurent81784c32012-11-19 14:55:58 -08004464#endif
4465
Eric Laurent10351942014-05-08 18:49:52 -07004466 // forward device change to effects that have requested to be
4467 // aware of attached audio device.
4468 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004469 a2dpDeviceChanged =
4470 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004471 mOutDevice = value;
4472 for (size_t i = 0; i < mEffectChains.size(); i++) {
4473 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004474 }
4475 }
Eric Laurent10351942014-05-08 18:49:52 -07004476 }
Eric Laurent81784c32012-11-19 14:55:58 -08004477
Eric Laurent10351942014-05-08 18:49:52 -07004478 if (status == NO_ERROR) {
4479 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4480 keyValuePair.string());
4481 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004482 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004483 mStandby = true;
4484 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004486 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004487 }
Eric Laurent10351942014-05-08 18:49:52 -07004488 if (status == NO_ERROR && reconfig) {
4489 readOutputParameters_l();
4490 delete mAudioMixer;
4491 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4492 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004493 int name = getTrackName_l(mTracks[i]->mChannelMask,
4494 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004495 if (name < 0) {
4496 break;
4497 }
4498 mTracks[i]->mName = name;
4499 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004500 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004501 }
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503
4504 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004505 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004506 FastMixerStateQueue *sq = mFastMixer->sq();
4507 FastMixerState *state = sq->begin();
4508 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4509 state->mCommand = previousCommand;
4510 sq->end();
4511 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4512 }
4513
Eric Laurent42537be2016-01-08 17:16:42 -08004514 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004515}
4516
4517
4518void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4519{
4520 const size_t SIZE = 256;
4521 char buffer[SIZE];
4522 String8 result;
4523
4524 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004525 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004526 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004527 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004528
4529 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004530 // while we are dumping it. It may be inconsistent, but it won't mutate!
4531 // This is a large object so we place it on the heap.
4532 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4533 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4534 copy->dump(fd);
4535 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004536
4537#ifdef STATE_QUEUE_DUMP
4538 // Similar for state queue
4539 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4540 observerCopy.dump(fd);
4541 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4542 mutatorCopy.dump(fd);
4543#endif
4544
Glenn Kasten46909e72013-02-26 09:20:22 -08004545#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004546 // Write the tee output to a .wav file
4547 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004548#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004549
4550#ifdef AUDIO_WATCHDOG
4551 if (mAudioWatchdog != 0) {
4552 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4553 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4554 wdCopy.dump(fd);
4555 }
4556#endif
4557}
4558
4559uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4560{
4561 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4562}
4563
4564uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4565{
4566 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4567}
4568
4569void AudioFlinger::MixerThread::cacheParameters_l()
4570{
4571 PlaybackThread::cacheParameters_l();
4572
4573 // FIXME: Relaxed timing because of a certain device that can't meet latency
4574 // Should be reduced to 2x after the vendor fixes the driver issue
4575 // increase threshold again due to low power audio mode. The way this warning
4576 // threshold is calculated and its usefulness should be reconsidered anyway.
4577 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4578}
4579
4580// ----------------------------------------------------------------------------
4581
4582AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004583 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4584 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004585 // mLeftVolFloat, mRightVolFloat
4586{
4587}
4588
Eric Laurentbfb1b832013-01-07 09:53:42 -08004589AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4590 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004591 ThreadBase::type_t type, bool systemReady)
4592 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593 // mLeftVolFloat, mRightVolFloat
4594{
4595}
4596
Eric Laurent81784c32012-11-19 14:55:58 -08004597AudioFlinger::DirectOutputThread::~DirectOutputThread()
4598{
4599}
4600
Eric Laurentbfb1b832013-01-07 09:53:42 -08004601void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4602{
4603 audio_track_cblk_t* cblk = track->cblk();
4604 float left, right;
4605
4606 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4607 left = right = 0;
4608 } else {
4609 float typeVolume = mStreamTypes[track->streamType()].volume;
4610 float v = mMasterVolume * typeVolume;
4611 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004612 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4613 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4614 if (left > GAIN_FLOAT_UNITY) {
4615 left = GAIN_FLOAT_UNITY;
4616 }
4617 left *= v;
4618 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4619 if (right > GAIN_FLOAT_UNITY) {
4620 right = GAIN_FLOAT_UNITY;
4621 }
4622 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004623 }
4624
4625 if (lastTrack) {
4626 if (left != mLeftVolFloat || right != mRightVolFloat) {
4627 mLeftVolFloat = left;
4628 mRightVolFloat = right;
4629
4630 // Convert volumes from float to 8.24
4631 uint32_t vl = (uint32_t)(left * (1 << 24));
4632 uint32_t vr = (uint32_t)(right * (1 << 24));
4633
4634 // Delegate volume control to effect in track effect chain if needed
4635 // only one effect chain can be present on DirectOutputThread, so if
4636 // there is one, the track is connected to it
4637 if (!mEffectChains.isEmpty()) {
4638 mEffectChains[0]->setVolume_l(&vl, &vr);
4639 left = (float)vl / (1 << 24);
4640 right = (float)vr / (1 << 24);
4641 }
4642 if (mOutput->stream->set_volume) {
4643 mOutput->stream->set_volume(mOutput->stream, left, right);
4644 }
4645 }
4646 }
4647}
4648
Phil Burk43b4dcc2015-06-09 16:53:44 -07004649void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4650{
4651 sp<Track> previousTrack = mPreviousTrack.promote();
4652 sp<Track> latestTrack = mLatestActiveTrack.promote();
4653
Eric Laurent0f0631e2015-07-06 18:01:25 -07004654 if (previousTrack != 0 && latestTrack != 0) {
4655 if (mType == DIRECT) {
4656 if (previousTrack.get() != latestTrack.get()) {
4657 mFlushPending = true;
4658 }
4659 } else /* mType == OFFLOAD */ {
4660 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4661 mFlushPending = true;
4662 }
4663 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004664 }
4665 PlaybackThread::onAddNewTrack_l();
4666}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004667
Eric Laurent81784c32012-11-19 14:55:58 -08004668AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4669 Vector< sp<Track> > *tracksToRemove
4670)
4671{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004672 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004673 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004674 bool doHwPause = false;
4675 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004676
4677 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004678 for (size_t i = 0; i < count; i++) {
4679 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004680 // The track died recently
4681 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004682 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004683 }
4684
Phil Burk43b4dcc2015-06-09 16:53:44 -07004685 if (t->isInvalid()) {
4686 ALOGW("An invalidated track shouldn't be in active list");
4687 tracksToRemove->add(t);
4688 continue;
4689 }
4690
Eric Laurent81784c32012-11-19 14:55:58 -08004691 Track* const track = t.get();
4692 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004693 // Only consider last track started for volume and mixer state control.
4694 // In theory an older track could underrun and restart after the new one starts
4695 // but as we only care about the transition phase between two tracks on a
4696 // direct output, it is not a problem to ignore the underrun case.
4697 sp<Track> l = mLatestActiveTrack.promote();
4698 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004699
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004700 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004701 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004702 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004703 doHwPause = true;
4704 mHwPaused = true;
4705 }
4706 tracksToRemove->add(track);
4707 } else if (track->isFlushPending()) {
4708 track->flushAck();
4709 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004710 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004711 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004712 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004713 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004714 if (last && mHwPaused) {
4715 doHwResume = true;
4716 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004717 }
4718 }
4719
Eric Laurent81784c32012-11-19 14:55:58 -08004720 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004721 // for all its buffers to be filled before processing it.
4722 // Allow draining the buffer in case the client
4723 // app does not call stop() and relies on underrun to stop:
4724 // hence the test on (track->mRetryCount > 1).
4725 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004726 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004727 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004728 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004729 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004730 minFrames = mNormalFrameCount;
4731 } else {
4732 minFrames = 1;
4733 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734
Eric Laurentab5cdba2014-06-09 17:22:27 -07004735 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4736 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004737 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004738 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004739
4740 if (track->mFillingUpStatus == Track::FS_FILLED) {
4741 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004742 // make sure processVolume_l() will apply new volume even if 0
4743 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004744 if (!mHwSupportsPause) {
4745 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004746 }
4747 }
4748
4749 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750 processVolume_l(track, last);
4751 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004752 sp<Track> previousTrack = mPreviousTrack.promote();
4753 if (previousTrack != 0) {
4754 if (track != previousTrack.get()) {
4755 // Flush any data still being written from last track
4756 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004757 // Invalidate previous track to force a seek when resuming.
4758 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004759 }
4760 }
4761 mPreviousTrack = track;
4762
Eric Laurentd595b7c2013-04-03 17:27:56 -07004763 // reset retry count
4764 track->mRetryCount = kMaxTrackRetriesDirect;
4765 mActiveTrack = t;
4766 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004767 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004768 doHwResume = true;
4769 mHwPaused = false;
4770 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004771 }
Eric Laurent81784c32012-11-19 14:55:58 -08004772 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004773 // clear effect chain input buffer if the last active track started underruns
4774 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004775 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004776 mEffectChains[0]->clearInputBuffer();
4777 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004778 if (track->isStopping_1()) {
4779 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004780 if (last && mHwPaused) {
4781 doHwResume = true;
4782 mHwPaused = false;
4783 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004784 }
4785 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4786 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004787 // We have consumed all the buffers of this track.
4788 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004789 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004790 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004791 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4792 } else {
4793 audioHALFrames = 0;
4794 }
4795
Andy Hung818e7a32016-02-16 18:08:07 -08004796 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004797 if (mStandby || !last ||
4798 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004799 if (track->isStopping_2()) {
4800 track->mState = TrackBase::STOPPED;
4801 }
Eric Laurent81784c32012-11-19 14:55:58 -08004802 if (track->isStopped()) {
4803 track->reset();
4804 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004805 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004806 }
4807 } else {
4808 // No buffers for this track. Give it a few chances to
4809 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004810 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004811 if (--(track->mRetryCount) <= 0) {
4812 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004813 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004814 // indicate to client process that the track was disabled because of underrun;
4815 // it will then automatically call start() when data is available
4816 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004818 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4819 "minFrames = %u, mFormat = %#x",
4820 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004821 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004822 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004823 doHwPause = true;
4824 mHwPaused = true;
4825 }
Eric Laurent81784c32012-11-19 14:55:58 -08004826 }
4827 }
4828 }
4829 }
4830
Eric Laurentd1f69b02014-12-15 14:33:13 -08004831 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004832 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004833 for (size_t i = 0; i < mTracks.size(); i++) {
4834 if (mTracks[i]->isFlushPending()) {
4835 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004836 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004837 }
4838 }
4839 }
4840
4841 // make sure the pause/flush/resume sequence is executed in the right order.
4842 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4843 // before flush and then resume HW. This can happen in case of pause/flush/resume
4844 // if resume is received before pause is executed.
4845 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004846 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004847 mOutput->stream->pause(mOutput->stream);
4848 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004849 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004850 flushHw_l();
4851 }
4852 if (mHwSupportsPause && !mStandby && doHwResume) {
4853 mOutput->stream->resume(mOutput->stream);
4854 }
Eric Laurent81784c32012-11-19 14:55:58 -08004855 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004857
4858 return mixerStatus;
4859}
4860
4861void AudioFlinger::DirectOutputThread::threadLoop_mix()
4862{
Eric Laurent81784c32012-11-19 14:55:58 -08004863 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004864 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004865 // output audio to hardware
4866 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004867 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004868 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004869 status_t status = mActiveTrack->getNextBuffer(&buffer);
4870 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004871 memset(curBuf, 0, frameCount * mFrameSize);
4872 break;
4873 }
4874 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4875 frameCount -= buffer.frameCount;
4876 curBuf += buffer.frameCount * mFrameSize;
4877 mActiveTrack->releaseBuffer(&buffer);
4878 }
Andy Hung2098f272014-02-27 14:00:06 -08004879 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004880 mSleepTimeUs = 0;
4881 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004882 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004883}
4884
4885void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4886{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004887 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004888 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004889 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004890 return;
4891 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004892 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004893 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004894 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004895 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004896 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004897 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004898 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004899 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004900 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004901 }
4902}
4903
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904void AudioFlinger::DirectOutputThread::threadLoop_exit()
4905{
4906 {
4907 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004908 for (size_t i = 0; i < mTracks.size(); i++) {
4909 if (mTracks[i]->isFlushPending()) {
4910 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004911 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004912 }
4913 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004914 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004915 flushHw_l();
4916 }
4917 }
4918 PlaybackThread::threadLoop_exit();
4919}
4920
4921// must be called with thread mutex locked
4922bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4923{
4924 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004925 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004926
4927 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4928 // after a timeout and we will enter standby then.
4929 if (mTracks.size() > 0) {
4930 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004931 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4932 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004933 }
4934
Eric Laurent5cff4032015-05-26 13:49:58 -07004935 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004936}
4937
Eric Laurent81784c32012-11-19 14:55:58 -08004938// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004939int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004940 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004941{
4942 return 0;
4943}
4944
4945// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004946void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004947{
4948}
4949
Eric Laurent10351942014-05-08 18:49:52 -07004950// checkForNewParameter_l() must be called with ThreadBase::mLock held
4951bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4952 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004953{
4954 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004955 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004956
Eric Laurent10351942014-05-08 18:49:52 -07004957 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004958
Eric Laurent10351942014-05-08 18:49:52 -07004959 AudioParameter param = AudioParameter(keyValuePair);
4960 int value;
4961 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4962 // forward device change to effects that have requested to be
4963 // aware of attached audio device.
4964 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004965 a2dpDeviceChanged =
4966 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004967 mOutDevice = value;
4968 for (size_t i = 0; i < mEffectChains.size(); i++) {
4969 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004970 }
4971 }
Eric Laurent81784c32012-11-19 14:55:58 -08004972 }
Eric Laurent10351942014-05-08 18:49:52 -07004973 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4974 // do not accept frame count changes if tracks are open as the track buffer
4975 // size depends on frame count and correct behavior would not be garantied
4976 // if frame count is changed after track creation
4977 if (!mTracks.isEmpty()) {
4978 status = INVALID_OPERATION;
4979 } else {
4980 reconfig = true;
4981 }
4982 }
4983 if (status == NO_ERROR) {
4984 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4985 keyValuePair.string());
4986 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004987 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004988 mStandby = true;
4989 mBytesWritten = 0;
4990 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4991 keyValuePair.string());
4992 }
4993 if (status == NO_ERROR && reconfig) {
4994 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004995 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004996 }
4997 }
4998
Eric Laurent42537be2016-01-08 17:16:42 -08004999 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005000}
5001
5002uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5003{
5004 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005005 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005006 time = PlaybackThread::activeSleepTimeUs();
5007 } else {
5008 time = 10000;
5009 }
5010 return time;
5011}
5012
5013uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5014{
5015 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005016 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005017 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5018 } else {
5019 time = 10000;
5020 }
5021 return time;
5022}
5023
5024uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5025{
5026 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005027 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005028 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5029 } else {
5030 time = 10000;
5031 }
5032 return time;
5033}
5034
5035void AudioFlinger::DirectOutputThread::cacheParameters_l()
5036{
5037 PlaybackThread::cacheParameters_l();
5038
5039 // use shorter standby delay as on normal output to release
5040 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005041 // no delay on outputs with HW A/V sync
5042 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005043 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005044 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005045 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005046 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005047 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005048 }
Eric Laurent81784c32012-11-19 14:55:58 -08005049}
5050
Eric Laurente659ef42014-09-29 13:06:46 -07005051void AudioFlinger::DirectOutputThread::flushHw_l()
5052{
Phil Burk062e67a2015-02-11 13:40:50 -08005053 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005054 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005055 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005056}
5057
Eric Laurent81784c32012-11-19 14:55:58 -08005058// ----------------------------------------------------------------------------
5059
Eric Laurentbfb1b832013-01-07 09:53:42 -08005060AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005061 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005062 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005063 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005064 mWriteAckSequence(0),
5065 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005066{
5067}
5068
5069AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5070{
5071}
5072
5073void AudioFlinger::AsyncCallbackThread::onFirstRef()
5074{
5075 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5076}
5077
5078bool AudioFlinger::AsyncCallbackThread::threadLoop()
5079{
5080 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005081 uint32_t writeAckSequence;
5082 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005083
5084 {
5085 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005086 while (!((mWriteAckSequence & 1) ||
5087 (mDrainSequence & 1) ||
5088 exitPending())) {
5089 mWaitWorkCV.wait(mLock);
5090 }
5091
Eric Laurentbfb1b832013-01-07 09:53:42 -08005092 if (exitPending()) {
5093 break;
5094 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005095 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5096 mWriteAckSequence, mDrainSequence);
5097 writeAckSequence = mWriteAckSequence;
5098 mWriteAckSequence &= ~1;
5099 drainSequence = mDrainSequence;
5100 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005101 }
5102 {
Eric Laurent4de95592013-09-26 15:28:21 -07005103 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5104 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005105 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005106 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005107 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005108 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005109 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005110 }
5111 }
5112 }
5113 }
5114 return false;
5115}
5116
5117void AudioFlinger::AsyncCallbackThread::exit()
5118{
5119 ALOGV("AsyncCallbackThread::exit");
5120 Mutex::Autolock _l(mLock);
5121 requestExit();
5122 mWaitWorkCV.broadcast();
5123}
5124
Eric Laurent3b4529e2013-09-05 18:09:19 -07005125void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005126{
5127 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005128 // bit 0 is cleared
5129 mWriteAckSequence = sequence << 1;
5130}
5131
5132void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5133{
5134 Mutex::Autolock _l(mLock);
5135 // ignore unexpected callbacks
5136 if (mWriteAckSequence & 2) {
5137 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005138 mWaitWorkCV.signal();
5139 }
5140}
5141
Eric Laurent3b4529e2013-09-05 18:09:19 -07005142void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005143{
5144 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005145 // bit 0 is cleared
5146 mDrainSequence = sequence << 1;
5147}
5148
5149void AudioFlinger::AsyncCallbackThread::resetDraining()
5150{
5151 Mutex::Autolock _l(mLock);
5152 // ignore unexpected callbacks
5153 if (mDrainSequence & 2) {
5154 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005155 mWaitWorkCV.signal();
5156 }
5157}
5158
5159
5160// ----------------------------------------------------------------------------
5161AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005162 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5163 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005164 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005165{
Eric Laurentfd477972013-10-25 18:10:40 -07005166 //FIXME: mStandby should be set to true by ThreadBase constructor
5167 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005168}
5169
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170void AudioFlinger::OffloadThread::threadLoop_exit()
5171{
5172 if (mFlushPending || mHwPaused) {
5173 // If a flush is pending or track was paused, just discard buffered data
5174 flushHw_l();
5175 } else {
5176 mMixerStatus = MIXER_DRAIN_ALL;
5177 threadLoop_drain();
5178 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005179 if (mUseAsyncWrite) {
5180 ALOG_ASSERT(mCallbackThread != 0);
5181 mCallbackThread->exit();
5182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183 PlaybackThread::threadLoop_exit();
5184}
5185
5186AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5187 Vector< sp<Track> > *tracksToRemove
5188)
5189{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005190 size_t count = mActiveTracks.size();
5191
5192 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005193 bool doHwPause = false;
5194 bool doHwResume = false;
5195
Eric Laurentede6c3b2013-09-19 14:37:46 -07005196 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5197
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198 // find out which tracks need to be processed
5199 for (size_t i = 0; i < count; i++) {
5200 sp<Track> t = mActiveTracks[i].promote();
5201 // The track died recently
5202 if (t == 0) {
5203 continue;
5204 }
5205 Track* const track = t.get();
5206 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005207 // Only consider last track started for volume and mixer state control.
5208 // In theory an older track could underrun and restart after the new one starts
5209 // but as we only care about the transition phase between two tracks on a
5210 // direct output, it is not a problem to ignore the underrun case.
5211 sp<Track> l = mLatestActiveTrack.promote();
5212 bool last = l.get() == track;
5213
Haynes Mathew George7844f672014-01-15 12:32:55 -08005214 if (track->isInvalid()) {
5215 ALOGW("An invalidated track shouldn't be in active list");
5216 tracksToRemove->add(track);
5217 continue;
5218 }
5219
5220 if (track->mState == TrackBase::IDLE) {
5221 ALOGW("An idle track shouldn't be in active list");
5222 continue;
5223 }
5224
Eric Laurentbfb1b832013-01-07 09:53:42 -08005225 if (track->isPausing()) {
5226 track->setPaused();
5227 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005228 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005229 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 mHwPaused = true;
5231 }
5232 // If we were part way through writing the mixbuffer to
5233 // the HAL we must save this until we resume
5234 // BUG - this will be wrong if a different track is made active,
5235 // in that case we want to discard the pending data in the
5236 // mixbuffer and tell the client to present it again when the
5237 // track is resumed
5238 mPausedWriteLength = mCurrentWriteLength;
5239 mPausedBytesRemaining = mBytesRemaining;
5240 mBytesRemaining = 0; // stop writing
5241 }
5242 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005243 } else if (track->isFlushPending()) {
5244 track->flushAck();
5245 if (last) {
5246 mFlushPending = true;
5247 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005248 } else if (track->isResumePending()){
5249 track->resumeAck();
5250 if (last) {
5251 if (mPausedBytesRemaining) {
5252 // Need to continue write that was interrupted
5253 mCurrentWriteLength = mPausedWriteLength;
5254 mBytesRemaining = mPausedBytesRemaining;
5255 mPausedBytesRemaining = 0;
5256 }
5257 if (mHwPaused) {
5258 doHwResume = true;
5259 mHwPaused = false;
5260 // threadLoop_mix() will handle the case that we need to
5261 // resume an interrupted write
5262 }
5263 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005264 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005265
5266 // Do not handle new data in this iteration even if track->framesReady()
5267 mixerStatus = MIXER_TRACKS_ENABLED;
5268 }
5269 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005270 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005271 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005272 if (track->mFillingUpStatus == Track::FS_FILLED) {
5273 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005274 // make sure processVolume_l() will apply new volume even if 0
5275 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276 }
5277
5278 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005279 sp<Track> previousTrack = mPreviousTrack.promote();
5280 if (previousTrack != 0) {
5281 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005282 // Flush any data still being written from last track
5283 mBytesRemaining = 0;
5284 if (mPausedBytesRemaining) {
5285 // Last track was paused so we also need to flush saved
5286 // mixbuffer state and invalidate track so that it will
5287 // re-submit that unwritten data when it is next resumed
5288 mPausedBytesRemaining = 0;
5289 // Invalidate is a bit drastic - would be more efficient
5290 // to have a flag to tell client that some of the
5291 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005292 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005293 }
5294 // flush data already sent to the DSP if changing audio session as audio
5295 // comes from a different source. Also invalidate previous track to force a
5296 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005297 if (previousTrack->sessionId() != track->sessionId()) {
5298 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005299 }
5300 }
5301 }
5302 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 // reset retry count
5304 track->mRetryCount = kMaxTrackRetriesOffload;
5305 mActiveTrack = t;
5306 mixerStatus = MIXER_TRACKS_READY;
5307 }
5308 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005309 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310 if (track->isStopping_1()) {
5311 // Hardware buffer can hold a large amount of audio so we must
5312 // wait for all current track's data to drain before we say
5313 // that the track is stopped.
5314 if (mBytesRemaining == 0) {
5315 // Only start draining when all data in mixbuffer
5316 // has been written
5317 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5318 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005319 // do not drain if no data was ever sent to HAL (mStandby == true)
5320 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005321 // do not modify drain sequence if we are already draining. This happens
5322 // when resuming from pause after drain.
5323 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005324 mSleepTimeUs = 0;
5325 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005326 mixerStatus = MIXER_DRAIN_TRACK;
5327 mDrainSequence += 2;
5328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 if (mHwPaused) {
5330 // It is possible to move from PAUSED to STOPPING_1 without
5331 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005332 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005333 mHwPaused = false;
5334 }
5335 }
5336 }
5337 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005338 // Drain has completed or we are in standby, signal presentation complete
5339 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 track->mState = TrackBase::STOPPED;
5341 size_t audioHALFrames =
5342 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005343 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005344 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 track->presentationComplete(framesWritten, audioHALFrames);
5346 track->reset();
5347 tracksToRemove->add(track);
5348 }
5349 } else {
5350 // No buffers for this track. Give it a few chances to
5351 // fill a buffer, then remove it from active list.
5352 if (--(track->mRetryCount) <= 0) {
5353 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5354 track->name());
5355 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005356 // indicate to client process that the track was disabled because of underrun;
5357 // it will then automatically call start() when data is available
5358 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 } else if (last){
5360 mixerStatus = MIXER_TRACKS_ENABLED;
5361 }
5362 }
5363 }
5364 // compute volume for this track
5365 processVolume_l(track, last);
5366 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005367
Eric Laurentea0fade2013-10-04 16:23:48 -07005368 // make sure the pause/flush/resume sequence is executed in the right order.
5369 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5370 // before flush and then resume HW. This can happen in case of pause/flush/resume
5371 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005372 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005373 mOutput->stream->pause(mOutput->stream);
5374 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005375 if (mFlushPending) {
5376 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005377 }
Eric Laurentfd477972013-10-25 18:10:40 -07005378 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005379 mOutput->stream->resume(mOutput->stream);
5380 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005381
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382 // remove all the tracks that need to be...
5383 removeTracks_l(*tracksToRemove);
5384
5385 return mixerStatus;
5386}
5387
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388// must be called with thread mutex locked
5389bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5390{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005391 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5392 mWriteAckSequence, mDrainSequence);
5393 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 return true;
5395 }
5396 return false;
5397}
5398
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5400{
5401 Mutex::Autolock _l(mLock);
5402 return waitingAsyncCallback_l();
5403}
5404
5405void AudioFlinger::OffloadThread::flushHw_l()
5406{
Eric Laurente659ef42014-09-29 13:06:46 -07005407 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005408 // Flush anything still waiting in the mixbuffer
5409 mCurrentWriteLength = 0;
5410 mBytesRemaining = 0;
5411 mPausedWriteLength = 0;
5412 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005413
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005415 // discard any pending drain or write ack by incrementing sequence
5416 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5417 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005419 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5420 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421 }
5422}
5423
5424// ----------------------------------------------------------------------------
5425
Eric Laurent81784c32012-11-19 14:55:58 -08005426AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005427 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005428 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005429 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005430 mWaitTimeMs(UINT_MAX)
5431{
5432 addOutputTrack(mainThread);
5433}
5434
5435AudioFlinger::DuplicatingThread::~DuplicatingThread()
5436{
5437 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5438 mOutputTracks[i]->destroy();
5439 }
5440}
5441
5442void AudioFlinger::DuplicatingThread::threadLoop_mix()
5443{
5444 // mix buffers...
5445 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005446 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005447 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005448 if (mMixerBufferValid) {
5449 memset(mMixerBuffer, 0, mMixerBufferSize);
5450 } else {
5451 memset(mSinkBuffer, 0, mSinkBufferSize);
5452 }
Eric Laurent81784c32012-11-19 14:55:58 -08005453 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005454 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005455 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005456 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005457 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005458}
5459
5460void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5461{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005462 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005463 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005464 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005465 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005466 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005467 }
5468 } else if (mBytesWritten != 0) {
5469 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5470 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005471 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005472 } else {
5473 // flush remaining overflow buffers in output tracks
5474 writeFrames = 0;
5475 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005476 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 }
5478}
5479
Eric Laurentbfb1b832013-01-07 09:53:42 -08005480ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005481{
5482 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005483 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005484 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005485 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005486 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005487}
5488
5489void AudioFlinger::DuplicatingThread::threadLoop_standby()
5490{
5491 // DuplicatingThread implements standby by stopping all tracks
5492 for (size_t i = 0; i < outputTracks.size(); i++) {
5493 outputTracks[i]->stop();
5494 }
5495}
5496
5497void AudioFlinger::DuplicatingThread::saveOutputTracks()
5498{
5499 outputTracks = mOutputTracks;
5500}
5501
5502void AudioFlinger::DuplicatingThread::clearOutputTracks()
5503{
5504 outputTracks.clear();
5505}
5506
5507void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5508{
5509 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005510 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5511 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5512 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5513 const size_t frameCount =
5514 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5515 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5516 // from different OutputTracks and their associated MixerThreads (e.g. one may
5517 // nearly empty and the other may be dropping data).
5518
5519 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005520 this,
5521 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005522 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005523 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005524 frameCount,
5525 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005526 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005527 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005528 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005529 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005530 updateWaitTime_l();
5531 }
5532}
5533
5534void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5535{
5536 Mutex::Autolock _l(mLock);
5537 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5538 if (mOutputTracks[i]->thread() == thread) {
5539 mOutputTracks[i]->destroy();
5540 mOutputTracks.removeAt(i);
5541 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005542 if (thread->getOutput() == mOutput) {
5543 mOutput = NULL;
5544 }
Eric Laurent81784c32012-11-19 14:55:58 -08005545 return;
5546 }
5547 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005548 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005549}
5550
5551// caller must hold mLock
5552void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5553{
5554 mWaitTimeMs = UINT_MAX;
5555 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5556 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5557 if (strong != 0) {
5558 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5559 if (waitTimeMs < mWaitTimeMs) {
5560 mWaitTimeMs = waitTimeMs;
5561 }
5562 }
5563 }
5564}
5565
5566
5567bool AudioFlinger::DuplicatingThread::outputsReady(
5568 const SortedVector< sp<OutputTrack> > &outputTracks)
5569{
5570 for (size_t i = 0; i < outputTracks.size(); i++) {
5571 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5572 if (thread == 0) {
5573 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5574 outputTracks[i].get());
5575 return false;
5576 }
5577 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5578 // see note at standby() declaration
5579 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5580 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5581 thread.get());
5582 return false;
5583 }
5584 }
5585 return true;
5586}
5587
5588uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5589{
5590 return (mWaitTimeMs * 1000) / 2;
5591}
5592
5593void AudioFlinger::DuplicatingThread::cacheParameters_l()
5594{
5595 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5596 updateWaitTime_l();
5597
5598 MixerThread::cacheParameters_l();
5599}
5600
5601// ----------------------------------------------------------------------------
5602// Record
5603// ----------------------------------------------------------------------------
5604
5605AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5606 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005607 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005608 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005609 audio_devices_t inDevice,
5610 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005611#ifdef TEE_SINK
5612 , const sp<NBAIO_Sink>& teeSink
5613#endif
5614 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005615 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005616 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005617 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005618 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005619#ifdef TEE_SINK
5620 , mTeeSink(teeSink)
5621#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005622 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5623 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005624 // mFastCapture below
5625 , mFastCaptureFutex(0)
5626 // mInputSource
5627 // mPipeSink
5628 // mPipeSource
5629 , mPipeFramesP2(0)
5630 // mPipeMemory
5631 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005632 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005633{
Glenn Kastend7dca052015-03-05 16:05:54 -08005634 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5635 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005636
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005637 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005638
5639 // create an NBAIO source for the HAL input stream, and negotiate
5640 mInputSource = new AudioStreamInSource(input->stream);
5641 size_t numCounterOffers = 0;
5642 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5643 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5644 ALOG_ASSERT(index == 0);
5645
5646 // initialize fast capture depending on configuration
5647 bool initFastCapture;
5648 switch (kUseFastCapture) {
5649 case FastCapture_Never:
5650 initFastCapture = false;
5651 break;
5652 case FastCapture_Always:
5653 initFastCapture = true;
5654 break;
5655 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005656 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005657 break;
5658 // case FastCapture_Dynamic:
5659 }
5660
5661 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005662 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005663 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005664 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005665 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5666 void *pipeBuffer;
5667 const sp<MemoryDealer> roHeap(readOnlyHeap());
5668 sp<IMemory> pipeMemory;
5669 if ((roHeap == 0) ||
5670 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5671 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5672 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5673 goto failed;
5674 }
5675 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5676 memset(pipeBuffer, 0, pipeSize);
5677 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5678 const NBAIO_Format offers[1] = {format};
5679 size_t numCounterOffers = 0;
5680 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5681 ALOG_ASSERT(index == 0);
5682 mPipeSink = pipe;
5683 PipeReader *pipeReader = new PipeReader(*pipe);
5684 numCounterOffers = 0;
5685 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5686 ALOG_ASSERT(index == 0);
5687 mPipeSource = pipeReader;
5688 mPipeFramesP2 = pipeFramesP2;
5689 mPipeMemory = pipeMemory;
5690
5691 // create fast capture
5692 mFastCapture = new FastCapture();
5693 FastCaptureStateQueue *sq = mFastCapture->sq();
5694#ifdef STATE_QUEUE_DUMP
5695 // FIXME
5696#endif
5697 FastCaptureState *state = sq->begin();
5698 state->mCblk = NULL;
5699 state->mInputSource = mInputSource.get();
5700 state->mInputSourceGen++;
5701 state->mPipeSink = pipe;
5702 state->mPipeSinkGen++;
5703 state->mFrameCount = mFrameCount;
5704 state->mCommand = FastCaptureState::COLD_IDLE;
5705 // already done in constructor initialization list
5706 //mFastCaptureFutex = 0;
5707 state->mColdFutexAddr = &mFastCaptureFutex;
5708 state->mColdGen++;
5709 state->mDumpState = &mFastCaptureDumpState;
5710#ifdef TEE_SINK
5711 // FIXME
5712#endif
5713 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5714 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5715 sq->end();
5716 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5717
5718 // start the fast capture
5719 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5720 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005721 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005722#ifdef AUDIO_WATCHDOG
5723 // FIXME
5724#endif
5725
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005726 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005727 }
5728failed: ;
5729
5730 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005731}
5732
Eric Laurent81784c32012-11-19 14:55:58 -08005733AudioFlinger::RecordThread::~RecordThread()
5734{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005735 if (mFastCapture != 0) {
5736 FastCaptureStateQueue *sq = mFastCapture->sq();
5737 FastCaptureState *state = sq->begin();
5738 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5739 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5740 if (old == -1) {
5741 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5742 }
5743 }
5744 state->mCommand = FastCaptureState::EXIT;
5745 sq->end();
5746 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5747 mFastCapture->join();
5748 mFastCapture.clear();
5749 }
5750 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005751 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005752 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005753}
5754
5755void AudioFlinger::RecordThread::onFirstRef()
5756{
Glenn Kastend7dca052015-03-05 16:05:54 -08005757 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005758}
5759
Eric Laurent81784c32012-11-19 14:55:58 -08005760bool AudioFlinger::RecordThread::threadLoop()
5761{
Eric Laurent81784c32012-11-19 14:55:58 -08005762 nsecs_t lastWarning = 0;
5763
5764 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005765
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005766reacquire_wakelock:
5767 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005768 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005769 {
5770 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005771 size_t size = mActiveTracks.size();
5772 activeTracksGen = mActiveTracksGen;
5773 if (size > 0) {
5774 // FIXME an arbitrary choice
5775 activeTrack = mActiveTracks[0];
5776 acquireWakeLock_l(activeTrack->uid());
5777 if (size > 1) {
5778 SortedVector<int> tmp;
5779 for (size_t i = 0; i < size; i++) {
5780 tmp.add(mActiveTracks[i]->uid());
5781 }
5782 updateWakeLockUids_l(tmp);
5783 }
5784 } else {
5785 acquireWakeLock_l(-1);
5786 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005787 }
5788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005789 // used to request a deferred sleep, to be executed later while mutex is unlocked
5790 uint32_t sleepUs = 0;
5791
5792 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005793 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005794 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005795
Glenn Kasten5edadd42013-08-14 16:30:49 -07005796 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005797 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005798 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005799 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005800 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005801 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005802 }
5803
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005804 // activeTracks accumulates a copy of a subset of mActiveTracks
5805 Vector< sp<RecordTrack> > activeTracks;
5806
Glenn Kasten735f45f2014-08-18 15:51:59 -07005807 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005808 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005809
Glenn Kasten735f45f2014-08-18 15:51:59 -07005810 // reference to a fast track which is about to be removed
5811 sp<RecordTrack> fastTrackToRemove;
5812
Eric Laurent81784c32012-11-19 14:55:58 -08005813 { // scope for mLock
5814 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005815
Eric Laurent021cf962014-05-13 10:18:14 -07005816 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005817
Eric Laurent000a4192014-01-29 15:17:32 -08005818 // check exitPending here because checkForNewParameters_l() and
5819 // checkForNewParameters_l() can temporarily release mLock
5820 if (exitPending()) {
5821 break;
5822 }
5823
Glenn Kasten2b806402013-11-20 16:37:38 -08005824 // if no active track(s), then standby and release wakelock
5825 size_t size = mActiveTracks.size();
5826 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005827 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005828 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005829 releaseWakeLock_l();
5830 ALOGV("RecordThread: loop stopping");
5831 // go to sleep
5832 mWaitWorkCV.wait(mLock);
5833 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005834 goto reacquire_wakelock;
5835 }
5836
Glenn Kasten2b806402013-11-20 16:37:38 -08005837 if (mActiveTracksGen != activeTracksGen) {
5838 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005839 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005840 for (size_t i = 0; i < size; i++) {
5841 tmp.add(mActiveTracks[i]->uid());
5842 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005843 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005844 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005845
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005846 bool doBroadcast = false;
5847 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005848
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005849 activeTrack = mActiveTracks[i];
5850 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005851 if (activeTrack->isFastTrack()) {
5852 ALOG_ASSERT(fastTrackToRemove == 0);
5853 fastTrackToRemove = activeTrack;
5854 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005855 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005856 mActiveTracks.remove(activeTrack);
5857 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005859 continue;
5860 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005861
5862 TrackBase::track_state activeTrackState = activeTrack->mState;
5863 switch (activeTrackState) {
5864
5865 case TrackBase::PAUSING:
5866 mActiveTracks.remove(activeTrack);
5867 mActiveTracksGen++;
5868 doBroadcast = true;
5869 size--;
5870 continue;
5871
5872 case TrackBase::STARTING_1:
5873 sleepUs = 10000;
5874 i++;
5875 continue;
5876
5877 case TrackBase::STARTING_2:
5878 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005880 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 break;
5882
5883 case TrackBase::ACTIVE:
5884 break;
5885
5886 case TrackBase::IDLE:
5887 i++;
5888 continue;
5889
5890 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005891 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005892 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005893
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005894 activeTracks.add(activeTrack);
5895 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005896
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005897 if (activeTrack->isFastTrack()) {
5898 ALOG_ASSERT(!mFastTrackAvail);
5899 ALOG_ASSERT(fastTrack == 0);
5900 fastTrack = activeTrack;
5901 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005902 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 if (doBroadcast) {
5904 mStartStopCond.broadcast();
5905 }
5906
5907 // sleep if there are no active tracks to process
5908 if (activeTracks.size() == 0) {
5909 if (sleepUs == 0) {
5910 sleepUs = kRecordThreadSleepUs;
5911 }
5912 continue;
5913 }
5914 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005915
Eric Laurent81784c32012-11-19 14:55:58 -08005916 lockEffectChains_l(effectChains);
5917 }
5918
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005919 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005920
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005921 size_t size = effectChains.size();
5922 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005923 // thread mutex is not locked, but effect chain is locked
5924 effectChains[i]->process_l();
5925 }
5926
Glenn Kasten735f45f2014-08-18 15:51:59 -07005927 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005928 if (mFastCapture != 0) {
5929 FastCaptureStateQueue *sq = mFastCapture->sq();
5930 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005931 bool didModify = false;
5932 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005933 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5934 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5935 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5936 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5937 if (old == -1) {
5938 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5939 }
5940 }
5941 state->mCommand = FastCaptureState::READ_WRITE;
5942#if 0 // FIXME
5943 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005944 FastThreadDumpState::kSamplingNforLowRamDevice :
5945 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005946#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005947 didModify = true;
5948 }
5949 audio_track_cblk_t *cblkOld = state->mCblk;
5950 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5951 if (cblkNew != cblkOld) {
5952 state->mCblk = cblkNew;
5953 // block until acked if removing a fast track
5954 if (cblkOld != NULL) {
5955 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5956 }
5957 didModify = true;
5958 }
5959 sq->end(didModify);
5960 if (didModify) {
5961 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005962#if 0
5963 if (kUseFastCapture == FastCapture_Dynamic) {
5964 mNormalSource = mPipeSource;
5965 }
5966#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005967 }
5968 }
5969
Glenn Kasten735f45f2014-08-18 15:51:59 -07005970 // now run the fast track destructor with thread mutex unlocked
5971 fastTrackToRemove.clear();
5972
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005973 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5974 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5975 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5976 // If destination is non-contiguous, first read past the nominal end of buffer, then
5977 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005978
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005979 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005980 ssize_t framesRead;
5981
5982 // If an NBAIO source is present, use it to read the normal capture's data
5983 if (mPipeSource != 0) {
5984 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005985 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08005986 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005987 if (framesRead == 0) {
5988 // since pipe is non-blocking, simulate blocking input
5989 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5990 }
5991 // otherwise use the HAL / AudioStreamIn directly
5992 } else {
5993 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005994 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005995 if (bytesRead < 0) {
5996 framesRead = bytesRead;
5997 } else {
5998 framesRead = bytesRead / mFrameSize;
5999 }
6000 }
6001
Andy Hung3f0c9022016-01-15 17:49:46 -08006002 // Update server timestamp with server stats
6003 // systemTime() is optional if the hardware supports timestamps.
6004 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6005 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6006
6007 // Update server timestamp with kernel stats
6008 if (mInput->stream->get_capture_position != nullptr) {
6009 int64_t position, time;
6010 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6011 if (ret == NO_ERROR) {
6012 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6013 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6014 // Note: In general record buffers should tend to be empty in
6015 // a properly running pipeline.
6016 //
6017 // Also, it is not advantageous to call get_presentation_position during the read
6018 // as the read obtains a lock, preventing the timestamp call from executing.
6019 }
6020 }
6021 // Use this to track timestamp information
6022 // ALOGD("%s", mTimestamp.toString().c_str());
6023
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006024 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6025 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 // Force input into standby so that it tries to recover at next read attempt
6027 inputStandBy();
6028 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006029 }
6030 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006031 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006032 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006033 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006034
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006035 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006036 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037 }
6038 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006039 {
6040 size_t part1 = mRsmpInFramesP2 - rear;
6041 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006042 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006043 (framesRead - part1) * mFrameSize);
6044 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 }
6046 rear = mRsmpInRear += framesRead;
6047
6048 size = activeTracks.size();
6049 // loop over each active track
6050 for (size_t i = 0; i < size; i++) {
6051 activeTrack = activeTracks[i];
6052
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006053 // skip fast tracks, as those are handled directly by FastCapture
6054 if (activeTrack->isFastTrack()) {
6055 continue;
6056 }
6057
Andy Hung73c02e42015-03-29 01:13:58 -07006058 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006059 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6060
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 enum {
6062 OVERRUN_UNKNOWN,
6063 OVERRUN_TRUE,
6064 OVERRUN_FALSE
6065 } overrun = OVERRUN_UNKNOWN;
6066
6067 // loop over getNextBuffer to handle circular sink
6068 for (;;) {
6069
6070 activeTrack->mSink.frameCount = ~0;
6071 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6072 size_t framesOut = activeTrack->mSink.frameCount;
6073 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6074
Andy Hung73c02e42015-03-29 01:13:58 -07006075 // check available frames and handle overrun conditions
6076 // if the record track isn't draining fast enough.
6077 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006079 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6080 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 overrun = OVERRUN_TRUE;
6082 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006083 if (framesOut == 0 || framesIn == 0) {
6084 break;
6085 }
6086
Andy Hung6770c6f2015-04-07 13:43:36 -07006087 // Don't allow framesOut to be larger than what is possible with resampling
6088 // from framesIn.
6089 // This isn't strictly necessary but helps limit buffer resizing in
6090 // RecordBufferConverter. TODO: remove when no longer needed.
6091 framesOut = min(framesOut,
6092 destinationFramesPossible(
6093 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006094 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6095 framesOut = activeTrack->mRecordBufferConverter->convert(
6096 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006097
6098 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6099 overrun = OVERRUN_FALSE;
6100 }
6101
6102 if (activeTrack->mFramesToDrop == 0) {
6103 if (framesOut > 0) {
6104 activeTrack->mSink.frameCount = framesOut;
6105 activeTrack->releaseBuffer(&activeTrack->mSink);
6106 }
6107 } else {
6108 // FIXME could do a partial drop of framesOut
6109 if (activeTrack->mFramesToDrop > 0) {
6110 activeTrack->mFramesToDrop -= framesOut;
6111 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006112 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 }
6114 } else {
6115 activeTrack->mFramesToDrop += framesOut;
6116 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6117 activeTrack->mSyncStartEvent->isCancelled()) {
6118 ALOGW("Synced record %s, session %d, trigger session %d",
6119 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6120 activeTrack->sessionId(),
6121 (activeTrack->mSyncStartEvent != 0) ?
6122 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006123 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 }
6125 }
6126 }
6127
6128 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006130 }
6131 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132
6133 switch (overrun) {
6134 case OVERRUN_TRUE:
6135 // client isn't retrieving buffers fast enough
6136 if (!activeTrack->setOverflow()) {
6137 nsecs_t now = systemTime();
6138 // FIXME should lastWarning per track?
6139 if ((now - lastWarning) > kWarningThrottleNs) {
6140 ALOGW("RecordThread: buffer overflow");
6141 lastWarning = now;
6142 }
6143 }
6144 break;
6145 case OVERRUN_FALSE:
6146 activeTrack->clearOverflow();
6147 break;
6148 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149 break;
6150 }
6151
Andy Hung3f0c9022016-01-15 17:49:46 -08006152 // update frame information and push timestamp out
6153 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006154 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006155 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6156 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006157 }
6158
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006159unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006160 // enable changes in effect chain
6161 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006162 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006163 }
6164
Glenn Kasten93e471f2013-08-19 08:40:07 -07006165 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006166
6167 {
6168 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006169 for (size_t i = 0; i < mTracks.size(); i++) {
6170 sp<RecordTrack> track = mTracks[i];
6171 track->invalidate();
6172 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006173 mActiveTracks.clear();
6174 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006175 mStartStopCond.broadcast();
6176 }
6177
6178 releaseWakeLock();
6179
6180 ALOGV("RecordThread %p exiting", this);
6181 return false;
6182}
6183
Glenn Kasten93e471f2013-08-19 08:40:07 -07006184void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006185{
6186 if (!mStandby) {
6187 inputStandBy();
6188 mStandby = true;
6189 }
6190}
6191
6192void AudioFlinger::RecordThread::inputStandBy()
6193{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006194 // Idle the fast capture if it's currently running
6195 if (mFastCapture != 0) {
6196 FastCaptureStateQueue *sq = mFastCapture->sq();
6197 FastCaptureState *state = sq->begin();
6198 if (!(state->mCommand & FastCaptureState::IDLE)) {
6199 state->mCommand = FastCaptureState::COLD_IDLE;
6200 state->mColdFutexAddr = &mFastCaptureFutex;
6201 state->mColdGen++;
6202 mFastCaptureFutex = 0;
6203 sq->end();
6204 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6205 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6206#if 0
6207 if (kUseFastCapture == FastCapture_Dynamic) {
6208 // FIXME
6209 }
6210#endif
6211#ifdef AUDIO_WATCHDOG
6212 // FIXME
6213#endif
6214 } else {
6215 sq->end(false /*didModify*/);
6216 }
6217 }
Eric Laurent81784c32012-11-19 14:55:58 -08006218 mInput->stream->common.standby(&mInput->stream->common);
6219}
6220
Glenn Kasten05997e22014-03-13 15:08:33 -07006221// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006222sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006223 const sp<AudioFlinger::Client>& client,
6224 uint32_t sampleRate,
6225 audio_format_t format,
6226 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006227 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006228 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006229 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006230 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006231 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006232 pid_t tid,
6233 status_t *status)
6234{
Glenn Kasten74935e42013-12-19 08:56:45 -08006235 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 sp<RecordTrack> track;
6237 status_t lStatus;
6238
Glenn Kasten90e58b12013-07-31 16:16:02 -07006239 // client expresses a preference for FAST, but we get the final say
6240 if (*flags & IAudioFlinger::TRACK_FAST) {
6241 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006242 // we formerly checked for a callback handler (non-0 tid),
6243 // but that is no longer required for TRANSFER_OBTAIN mode
6244 //
Glenn Kasten74105912014-07-03 12:28:53 -07006245 // frame count is not specified, or is exactly the pipe depth
6246 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006247 // PCM data
6248 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006249 // native format
6250 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251 // native channel mask
6252 (channelMask == mChannelMask) &&
6253 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006254 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006255 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 hasFastCapture() &&
6257 // there are sufficient fast track slots available
6258 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006259 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006260 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006261 frameCount, mFrameCount);
6262 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006263 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6264 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006266 frameCount, mFrameCount, mPipeFramesP2,
6267 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6268 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006269 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006270 }
6271 }
6272
6273 // compute track buffer size in frames, and suggest the notification frame count
6274 if (*flags & IAudioFlinger::TRACK_FAST) {
6275 // fast track: frame count is exactly the pipe depth
6276 frameCount = mPipeFramesP2;
6277 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6278 *notificationFrames = mFrameCount;
6279 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006280 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6281 // or 20 ms if there is a fast capture
6282 // TODO This could be a roundupRatio inline, and const
6283 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6284 * sampleRate + mSampleRate - 1) / mSampleRate;
6285 // minimum number of notification periods is at least kMinNotifications,
6286 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6287 static const size_t kMinNotifications = 3;
6288 static const uint32_t kMinMs = 30;
6289 // TODO This could be a roundupRatio inline
6290 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6291 // TODO This could be a roundupRatio inline
6292 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6293 maxNotificationFrames;
6294 const size_t minFrameCount = maxNotificationFrames *
6295 max(kMinNotifications, minNotificationsByMs);
6296 frameCount = max(frameCount, minFrameCount);
6297 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6298 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006299 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006300 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006301 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006302
Glenn Kasten15e57982013-09-24 11:52:37 -07006303 lStatus = initCheck();
6304 if (lStatus != NO_ERROR) {
6305 ALOGE("createRecordTrack_l() audio driver not initialized");
6306 goto Exit;
6307 }
Eric Laurent81784c32012-11-19 14:55:58 -08006308
6309 { // scope for mLock
6310 Mutex::Autolock _l(mLock);
6311
6312 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006313 format, channelMask, frameCount, NULL, sessionId, uid,
6314 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006315
Glenn Kasten03003332013-08-06 15:40:54 -07006316 lStatus = track->initCheck();
6317 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006318 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006319 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006320 goto Exit;
6321 }
6322 mTracks.add(track);
6323
6324 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6325 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6326 mAudioFlinger->btNrecIsOff();
6327 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6328 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006329
6330 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6331 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6332 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6333 // so ask activity manager to do this on our behalf
6334 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6335 }
Eric Laurent81784c32012-11-19 14:55:58 -08006336 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006337
Eric Laurent81784c32012-11-19 14:55:58 -08006338 lStatus = NO_ERROR;
6339
6340Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006341 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006342 return track;
6343}
6344
6345status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6346 AudioSystem::sync_event_t event,
6347 int triggerSession)
6348{
6349 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6350 sp<ThreadBase> strongMe = this;
6351 status_t status = NO_ERROR;
6352
6353 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006354 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006355 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006357 triggerSession,
6358 recordTrack->sessionId(),
6359 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006360 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006361 // Sync event can be cancelled by the trigger session if the track is not in a
6362 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006363 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006364 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006365 } else {
6366 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006367 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006368 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006369 }
6370 }
6371
6372 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006373 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006374 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006375 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6376 if (recordTrack->mState == TrackBase::PAUSING) {
6377 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006378 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006379 } else {
6380 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006381 }
6382 return status;
6383 }
6384
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006385 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6386 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6387 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006388 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006389 mActiveTracks.add(recordTrack);
6390 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006391 status_t status = NO_ERROR;
6392 if (recordTrack->isExternalTrack()) {
6393 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006394 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006395 mLock.lock();
6396 // FIXME should verify that recordTrack is still in mActiveTracks
6397 if (status != NO_ERROR) {
6398 mActiveTracks.remove(recordTrack);
6399 mActiveTracksGen++;
6400 recordTrack->clearSyncStartEvent();
6401 ALOGV("RecordThread::start error %d", status);
6402 return status;
6403 }
Eric Laurent81784c32012-11-19 14:55:58 -08006404 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405 // Catch up with current buffer indices if thread is already running.
6406 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6407 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6408 // see previously buffered data before it called start(), but with greater risk of overrun.
6409
Andy Hung73c02e42015-03-29 01:13:58 -07006410 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006411 // clear any converter state as new data will be discontinuous
6412 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006413 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006414 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006415 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006416 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006417 ALOGV("Record failed to start");
6418 status = BAD_VALUE;
6419 goto startError;
6420 }
Eric Laurent81784c32012-11-19 14:55:58 -08006421 return status;
6422 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006423
Eric Laurent81784c32012-11-19 14:55:58 -08006424startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006425 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006426 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006427 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006428 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006429 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006430 return status;
6431}
6432
Eric Laurent81784c32012-11-19 14:55:58 -08006433void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6434{
6435 sp<SyncEvent> strongEvent = event.promote();
6436
6437 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006438 sp<RefBase> ptr = strongEvent->cookie().promote();
6439 if (ptr != 0) {
6440 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6441 recordTrack->handleSyncStartEvent(strongEvent);
6442 }
Eric Laurent81784c32012-11-19 14:55:58 -08006443 }
6444}
6445
Glenn Kastena8356f62013-07-25 14:37:52 -07006446bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006447 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006448 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006449 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006450 return false;
6451 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006452 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006453 recordTrack->mState = TrackBase::PAUSING;
6454 // do not wait for mStartStopCond if exiting
6455 if (exitPending()) {
6456 return true;
6457 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006458 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006459 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006460 // if we have been restarted, recordTrack is in mActiveTracks here
6461 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006462 ALOGV("Record stopped OK");
6463 return true;
6464 }
6465 return false;
6466}
6467
Glenn Kasten0f11b512014-01-31 16:18:54 -08006468bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006469{
6470 return false;
6471}
6472
Glenn Kasten0f11b512014-01-31 16:18:54 -08006473status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006474{
6475#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6476 if (!isValidSyncEvent(event)) {
6477 return BAD_VALUE;
6478 }
6479
6480 int eventSession = event->triggerSession();
6481 status_t ret = NAME_NOT_FOUND;
6482
6483 Mutex::Autolock _l(mLock);
6484
6485 for (size_t i = 0; i < mTracks.size(); i++) {
6486 sp<RecordTrack> track = mTracks[i];
6487 if (eventSession == track->sessionId()) {
6488 (void) track->setSyncEvent(event);
6489 ret = NO_ERROR;
6490 }
6491 }
6492 return ret;
6493#else
6494 return BAD_VALUE;
6495#endif
6496}
6497
6498// destroyTrack_l() must be called with ThreadBase::mLock held
6499void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6500{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006501 track->terminate();
6502 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006503 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006504 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006505 removeTrack_l(track);
6506 }
6507}
6508
6509void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6510{
6511 mTracks.remove(track);
6512 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006513 if (track->isFastTrack()) {
6514 ALOG_ASSERT(!mFastTrackAvail);
6515 mFastTrackAvail = true;
6516 }
Eric Laurent81784c32012-11-19 14:55:58 -08006517}
6518
6519void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6520{
6521 dumpInternals(fd, args);
6522 dumpTracks(fd, args);
6523 dumpEffectChains(fd, args);
6524}
6525
6526void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6527{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006528 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006529
Glenn Kasten44182c22015-03-05 17:12:23 -08006530 dumpBase(fd, args);
6531
6532 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006533 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006534 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006535 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006536 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006537
Glenn Kasten2f90c512015-12-02 11:40:09 -08006538 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6539 // while we are dumping it. It may be inconsistent, but it won't mutate!
6540 // This is a large object so we place it on the heap.
6541 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6542 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6543 copy->dump(fd);
6544 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006545}
6546
Glenn Kasten0f11b512014-01-31 16:18:54 -08006547void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006548{
6549 const size_t SIZE = 256;
6550 char buffer[SIZE];
6551 String8 result;
6552
Marco Nelissenb2208842014-02-07 14:00:50 -08006553 size_t numtracks = mTracks.size();
6554 size_t numactive = mActiveTracks.size();
6555 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006556 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006557 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006558 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006559 RecordTrack::appendDumpHeader(result);
6560 for (size_t i = 0; i < numtracks ; ++i) {
6561 sp<RecordTrack> track = mTracks[i];
6562 if (track != 0) {
6563 bool active = mActiveTracks.indexOf(track) >= 0;
6564 if (active) {
6565 numactiveseen++;
6566 }
6567 track->dump(buffer, SIZE, active);
6568 result.append(buffer);
6569 }
Eric Laurent81784c32012-11-19 14:55:58 -08006570 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006571 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006572 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006573 }
6574
Marco Nelissenb2208842014-02-07 14:00:50 -08006575 if (numactiveseen != numactive) {
6576 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6577 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006578 result.append(buffer);
6579 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006580 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006581 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006582 if (mTracks.indexOf(track) < 0) {
6583 track->dump(buffer, SIZE, true);
6584 result.append(buffer);
6585 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006586 }
Eric Laurent81784c32012-11-19 14:55:58 -08006587
6588 }
6589 write(fd, result.string(), result.size());
6590}
6591
Andy Hung73c02e42015-03-29 01:13:58 -07006592
6593void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6594{
6595 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6596 RecordThread *recordThread = (RecordThread *) threadBase.get();
6597 mRsmpInFront = recordThread->mRsmpInRear;
6598 mRsmpInUnrel = 0;
6599}
6600
6601void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6602 size_t *framesAvailable, bool *hasOverrun)
6603{
6604 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6605 RecordThread *recordThread = (RecordThread *) threadBase.get();
6606 const int32_t rear = recordThread->mRsmpInRear;
6607 const int32_t front = mRsmpInFront;
6608 const ssize_t filled = rear - front;
6609
6610 size_t framesIn;
6611 bool overrun = false;
6612 if (filled < 0) {
6613 // should not happen, but treat like a massive overrun and re-sync
6614 framesIn = 0;
6615 mRsmpInFront = rear;
6616 overrun = true;
6617 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6618 framesIn = (size_t) filled;
6619 } else {
6620 // client is not keeping up with server, but give it latest data
6621 framesIn = recordThread->mRsmpInFrames;
6622 mRsmpInFront = /* front = */ rear - framesIn;
6623 overrun = true;
6624 }
6625 if (framesAvailable != NULL) {
6626 *framesAvailable = framesIn;
6627 }
6628 if (hasOverrun != NULL) {
6629 *hasOverrun = overrun;
6630 }
6631}
6632
Eric Laurent81784c32012-11-19 14:55:58 -08006633// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006634status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006635 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006636{
Andy Hung73c02e42015-03-29 01:13:58 -07006637 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006638 if (threadBase == 0) {
6639 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006640 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006641 return NOT_ENOUGH_DATA;
6642 }
6643 RecordThread *recordThread = (RecordThread *) threadBase.get();
6644 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006645 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006646 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006647 // FIXME should not be P2 (don't want to increase latency)
6648 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006649 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006650 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 front &= recordThread->mRsmpInFramesP2 - 1;
6652 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006653 if (part1 > (size_t) filled) {
6654 part1 = filled;
6655 }
6656 size_t ask = buffer->frameCount;
6657 ALOG_ASSERT(ask > 0);
6658 if (part1 > ask) {
6659 part1 = ask;
6660 }
6661 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006662 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006663 buffer->raw = NULL;
6664 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006665 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006666 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006667 }
6668
Andy Hung57446612015-04-19 23:56:46 -07006669 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006670 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006671 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006672 return NO_ERROR;
6673}
6674
6675// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006676void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6677 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006678{
Glenn Kasten85948432013-08-19 12:09:05 -07006679 size_t stepCount = buffer->frameCount;
6680 if (stepCount == 0) {
6681 return;
6682 }
Andy Hung73c02e42015-03-29 01:13:58 -07006683 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6684 mRsmpInUnrel -= stepCount;
6685 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006686 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006687 buffer->frameCount = 0;
6688}
6689
Andy Hung97a893e2015-03-29 01:03:07 -07006690AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6691 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6692 uint32_t srcSampleRate,
6693 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6694 uint32_t dstSampleRate) :
6695 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6696 // mSrcFormat
6697 // mSrcSampleRate
6698 // mDstChannelMask
6699 // mDstFormat
6700 // mDstSampleRate
6701 // mSrcChannelCount
6702 // mDstChannelCount
6703 // mDstFrameSize
6704 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006705 mResampler(NULL),
6706 mIsLegacyDownmix(false),
6707 mIsLegacyUpmix(false),
6708 mRequiresFloat(false),
6709 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006710{
6711 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6712 dstChannelMask, dstFormat, dstSampleRate);
6713}
6714
6715AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6716 free(mBuf);
6717 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006718 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006719}
6720
6721size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6722 AudioBufferProvider *provider, size_t frames)
6723{
Andy Hungd330ee42015-04-20 13:23:41 -07006724 if (mInputConverterProvider != NULL) {
6725 mInputConverterProvider->setBufferProvider(provider);
6726 provider = mInputConverterProvider;
6727 }
6728
6729 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006730 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6731 mSrcSampleRate, mSrcFormat, mDstFormat);
6732
6733 AudioBufferProvider::Buffer buffer;
6734 for (size_t i = frames; i > 0; ) {
6735 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006736 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006737 if (status != OK || buffer.frameCount == 0) {
6738 frames -= i; // cannot fill request.
6739 break;
6740 }
Andy Hungd330ee42015-04-20 13:23:41 -07006741 // format convert to destination buffer
6742 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006743
6744 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6745 i -= buffer.frameCount;
6746 provider->releaseBuffer(&buffer);
6747 }
6748 } else {
6749 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6750 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6751
Andy Hungd330ee42015-04-20 13:23:41 -07006752 // reallocate buffer if needed
6753 if (mBufFrameSize != 0 && mBufFrames < frames) {
6754 free(mBuf);
6755 mBufFrames = frames;
6756 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6757 }
Andy Hung97a893e2015-03-29 01:03:07 -07006758 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006759 memset(mBuf, 0, frames * mBufFrameSize);
6760 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6761 // format convert to destination buffer
6762 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006763 }
6764 return frames;
6765}
6766
6767status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6768 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6769 uint32_t srcSampleRate,
6770 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6771 uint32_t dstSampleRate)
6772{
6773 // quick evaluation if there is any change.
6774 if (mSrcFormat == srcFormat
6775 && mSrcChannelMask == srcChannelMask
6776 && mSrcSampleRate == srcSampleRate
6777 && mDstFormat == dstFormat
6778 && mDstChannelMask == dstChannelMask
6779 && mDstSampleRate == dstSampleRate) {
6780 return NO_ERROR;
6781 }
6782
Andy Hungdb4c0312015-05-06 08:46:52 -07006783 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6784 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6785 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006786 const bool valid =
6787 audio_is_input_channel(srcChannelMask)
6788 && audio_is_input_channel(dstChannelMask)
6789 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6790 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6791 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6792 ; // no upsampling checks for now
6793 if (!valid) {
6794 return BAD_VALUE;
6795 }
6796
6797 mSrcFormat = srcFormat;
6798 mSrcChannelMask = srcChannelMask;
6799 mSrcSampleRate = srcSampleRate;
6800 mDstFormat = dstFormat;
6801 mDstChannelMask = dstChannelMask;
6802 mDstSampleRate = dstSampleRate;
6803
6804 // compute derived parameters
6805 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6806 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6807 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6808
Andy Hungd330ee42015-04-20 13:23:41 -07006809 // do we need to resample?
6810 delete mResampler;
6811 mResampler = NULL;
6812 if (mSrcSampleRate != mDstSampleRate) {
6813 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6814 mSrcChannelCount, mDstSampleRate);
6815 mResampler->setSampleRate(mSrcSampleRate);
6816 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6817 }
6818
6819 // are we running legacy channel conversion modes?
6820 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6821 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6822 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6823 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6824 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6825 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6826
6827 // do we need to process in float?
6828 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6829
6830 // do we need a staging buffer to convert for destination (we can still optimize this)?
6831 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6832 if (mResampler != NULL) {
6833 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6834 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006835 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006836 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6837 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006838 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6839 } else {
6840 mBufFrameSize = 0;
6841 }
6842 mBufFrames = 0; // force the buffer to be resized.
6843
Andy Hungd330ee42015-04-20 13:23:41 -07006844 // do we need an input converter buffer provider to give us float?
6845 delete mInputConverterProvider;
6846 mInputConverterProvider = NULL;
6847 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6848 mInputConverterProvider = new ReformatBufferProvider(
6849 audio_channel_count_from_in_mask(mSrcChannelMask),
6850 mSrcFormat,
6851 AUDIO_FORMAT_PCM_FLOAT,
6852 256 /* provider buffer frame count */);
6853 }
6854
6855 // do we need a remixer to do channel mask conversion
6856 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6857 (void) memcpy_by_index_array_initialization_from_channel_mask(
6858 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006859 }
6860 return NO_ERROR;
6861}
6862
Andy Hungd330ee42015-04-20 13:23:41 -07006863void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6864 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006865{
Andy Hungd330ee42015-04-20 13:23:41 -07006866 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006867 if (mBufFrameSize != 0 && mBufFrames < frames) {
6868 free(mBuf);
6869 mBufFrames = frames;
6870 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6871 }
Andy Hungd330ee42015-04-20 13:23:41 -07006872 // do we need to do legacy upmix and downmix?
6873 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006874 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006875 if (mIsLegacyUpmix) {
6876 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6877 (const float *)src, frames);
6878 } else /*mIsLegacyDownmix */ {
6879 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6880 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006881 }
Andy Hungd330ee42015-04-20 13:23:41 -07006882 if (mBuf != NULL) {
6883 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6884 frames * mDstChannelCount);
6885 }
6886 return;
6887 }
6888 // do we need to do channel mask conversion?
6889 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006890 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006891 memcpy_by_index_array(dstBuf, mDstChannelCount,
6892 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6893 if (dstBuf == dst) {
6894 return; // format is the same
6895 }
6896 }
6897 // convert to destination buffer
6898 const void *convertBuf = mBuf != NULL ? mBuf : src;
6899 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6900 frames * mDstChannelCount);
6901}
6902
6903void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6904 void *dst, /*not-a-const*/ void *src, size_t frames)
6905{
6906 // src buffer format is ALWAYS float when entering this routine
6907 if (mIsLegacyUpmix) {
6908 ; // mono to stereo already handled by resampler
6909 } else if (mIsLegacyDownmix
6910 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6911 // the resampler outputs stereo for mono input channel (a feature?)
6912 // must convert to mono
6913 downmix_to_mono_float_from_stereo_float((float *)src,
6914 (const float *)src, frames);
6915 } else if (mSrcChannelMask != mDstChannelMask) {
6916 // convert to mono channel again for channel mask conversion (could be skipped
6917 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006918 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006919 downmix_to_mono_float_from_stereo_float((float *)src,
6920 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006921 }
Andy Hungd330ee42015-04-20 13:23:41 -07006922 // convert to destination format (in place, OK as float is larger than other types)
6923 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6924 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6925 frames * mSrcChannelCount);
6926 }
6927 // channel convert and save to dst
6928 memcpy_by_index_array(dst, mDstChannelCount,
6929 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6930 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006931 }
Andy Hungd330ee42015-04-20 13:23:41 -07006932 // convert to destination format and save to dst
6933 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6934 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006935}
6936
Eric Laurent10351942014-05-08 18:49:52 -07006937bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6938 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006939{
6940 bool reconfig = false;
6941
Eric Laurent10351942014-05-08 18:49:52 -07006942 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006943
Eric Laurent10351942014-05-08 18:49:52 -07006944 audio_format_t reqFormat = mFormat;
6945 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006946 // 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 -07006947 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6948
6949 AudioParameter param = AudioParameter(keyValuePair);
6950 int value;
6951 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6952 // channel count change can be requested. Do we mandate the first client defines the
6953 // HAL sampling rate and channel count or do we allow changes on the fly?
6954 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6955 samplingRate = value;
6956 reconfig = true;
6957 }
6958 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006959 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006960 status = BAD_VALUE;
6961 } else {
6962 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006963 reconfig = true;
6964 }
Eric Laurent10351942014-05-08 18:49:52 -07006965 }
6966 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6967 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006968 if (!audio_is_input_channel(mask) ||
6969 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006970 status = BAD_VALUE;
6971 } else {
6972 channelMask = mask;
6973 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006974 }
Eric Laurent10351942014-05-08 18:49:52 -07006975 }
6976 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6977 // do not accept frame count changes if tracks are open as the track buffer
6978 // size depends on frame count and correct behavior would not be guaranteed
6979 // if frame count is changed after track creation
6980 if (mActiveTracks.size() > 0) {
6981 status = INVALID_OPERATION;
6982 } else {
6983 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006984 }
Eric Laurent10351942014-05-08 18:49:52 -07006985 }
6986 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6987 // forward device change to effects that have requested to be
6988 // aware of attached audio device.
6989 for (size_t i = 0; i < mEffectChains.size(); i++) {
6990 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006991 }
Eric Laurent81784c32012-11-19 14:55:58 -08006992
Eric Laurent10351942014-05-08 18:49:52 -07006993 // store input device and output device but do not forward output device to audio HAL.
6994 // Note that status is ignored by the caller for output device
6995 // (see AudioFlinger::setParameters()
6996 if (audio_is_output_devices(value)) {
6997 mOutDevice = value;
6998 status = BAD_VALUE;
6999 } else {
7000 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007001 if (value != AUDIO_DEVICE_NONE) {
7002 mPrevInDevice = value;
7003 }
Eric Laurent10351942014-05-08 18:49:52 -07007004 // disable AEC and NS if the device is a BT SCO headset supporting those
7005 // pre processings
7006 if (mTracks.size() > 0) {
7007 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7008 mAudioFlinger->btNrecIsOff();
7009 for (size_t i = 0; i < mTracks.size(); i++) {
7010 sp<RecordTrack> track = mTracks[i];
7011 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7012 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007013 }
7014 }
7015 }
Eric Laurent10351942014-05-08 18:49:52 -07007016 }
7017 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7018 mAudioSource != (audio_source_t)value) {
7019 // forward device change to effects that have requested to be
7020 // aware of attached audio device.
7021 for (size_t i = 0; i < mEffectChains.size(); i++) {
7022 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007023 }
Eric Laurent10351942014-05-08 18:49:52 -07007024 mAudioSource = (audio_source_t)value;
7025 }
Glenn Kastene198c362013-08-13 09:13:36 -07007026
Eric Laurent10351942014-05-08 18:49:52 -07007027 if (status == NO_ERROR) {
7028 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7029 keyValuePair.string());
7030 if (status == INVALID_OPERATION) {
7031 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007032 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7033 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007034 }
7035 if (reconfig) {
7036 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007037 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7038 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007039 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007040 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007041 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007042 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007043 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007044 }
Eric Laurent10351942014-05-08 18:49:52 -07007045 if (status == NO_ERROR) {
7046 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007047 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007048 }
7049 }
Eric Laurent81784c32012-11-19 14:55:58 -08007050 }
Eric Laurent10351942014-05-08 18:49:52 -07007051
Eric Laurent81784c32012-11-19 14:55:58 -08007052 return reconfig;
7053}
7054
7055String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7056{
Eric Laurent81784c32012-11-19 14:55:58 -08007057 Mutex::Autolock _l(mLock);
7058 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007059 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007060 }
7061
Glenn Kastend8ea6992013-07-16 14:17:15 -07007062 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7063 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007064 free(s);
7065 return out_s8;
7066}
7067
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007068void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007069 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7070
7071 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007072
7073 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007074 case AUDIO_INPUT_OPENED:
7075 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007076 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007077 desc->mChannelMask = mChannelMask;
7078 desc->mSamplingRate = mSampleRate;
7079 desc->mFormat = mFormat;
7080 desc->mFrameCount = mFrameCount;
7081 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007082 break;
7083
Eric Laurent73e26b62015-04-27 16:55:58 -07007084 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007085 default:
7086 break;
7087 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007088 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007089}
7090
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007091void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007092{
Eric Laurent81784c32012-11-19 14:55:58 -08007093 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7094 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007095 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007096 if (mChannelCount > FCC_8) {
7097 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7098 }
Andy Hung463be252014-07-10 16:56:07 -07007099 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7100 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007101 if (!audio_is_linear_pcm(mFormat)) {
7102 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007103 }
Eric Laurent665470b2014-07-03 16:37:08 -07007104 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007105 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7106 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007107 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007108 // 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 -07007109 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007110 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007111 // A larger value should allow more old data to be read after a track calls start(),
7112 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007113 //
7114 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007115 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007116 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007117 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007118 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007119
7120 // TODO optimize audio capture buffer sizes ...
7121 // Here we calculate the size of the sliding buffer used as a source
7122 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7123 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7124 // be better to have it derived from the pipe depth in the long term.
7125 // The current value is higher than necessary. However it should not add to latency.
7126
Glenn Kasten85948432013-08-19 12:09:05 -07007127 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007128 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7129 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7130 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007131
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007132 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7133 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007134}
7135
Glenn Kasten5f972c02014-01-13 09:59:31 -08007136uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007137{
7138 Mutex::Autolock _l(mLock);
7139 if (initCheck() != NO_ERROR) {
7140 return 0;
7141 }
7142
7143 return mInput->stream->get_input_frames_lost(mInput->stream);
7144}
7145
7146uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7147{
7148 Mutex::Autolock _l(mLock);
7149 uint32_t result = 0;
7150 if (getEffectChain_l(sessionId) != 0) {
7151 result = EFFECT_SESSION;
7152 }
7153
7154 for (size_t i = 0; i < mTracks.size(); ++i) {
7155 if (sessionId == mTracks[i]->sessionId()) {
7156 result |= TRACK_SESSION;
7157 break;
7158 }
7159 }
7160
7161 return result;
7162}
7163
7164KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7165{
7166 KeyedVector<int, bool> ids;
7167 Mutex::Autolock _l(mLock);
7168 for (size_t j = 0; j < mTracks.size(); ++j) {
7169 sp<RecordThread::RecordTrack> track = mTracks[j];
7170 int sessionId = track->sessionId();
7171 if (ids.indexOfKey(sessionId) < 0) {
7172 ids.add(sessionId, true);
7173 }
7174 }
7175 return ids;
7176}
7177
7178AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7179{
7180 Mutex::Autolock _l(mLock);
7181 AudioStreamIn *input = mInput;
7182 mInput = NULL;
7183 return input;
7184}
7185
7186// this method must always be called either with ThreadBase mLock held or inside the thread loop
7187audio_stream_t* AudioFlinger::RecordThread::stream() const
7188{
7189 if (mInput == NULL) {
7190 return NULL;
7191 }
7192 return &mInput->stream->common;
7193}
7194
7195status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7196{
7197 // only one chain per input thread
7198 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007199 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007200 return INVALID_OPERATION;
7201 }
7202 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007203 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007204 chain->setInBuffer(NULL);
7205 chain->setOutBuffer(NULL);
7206
7207 checkSuspendOnAddEffectChain_l(chain);
7208
Eric Laurent1b928682014-10-02 19:41:47 -07007209 // make sure enabled pre processing effects state is communicated to the HAL as we
7210 // just moved them to a new input stream.
7211 chain->syncHalEffectsState();
7212
Eric Laurent81784c32012-11-19 14:55:58 -08007213 mEffectChains.add(chain);
7214
7215 return NO_ERROR;
7216}
7217
7218size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7219{
7220 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7221 ALOGW_IF(mEffectChains.size() != 1,
7222 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7223 chain.get(), mEffectChains.size(), this);
7224 if (mEffectChains.size() == 1) {
7225 mEffectChains.removeAt(0);
7226 }
7227 return 0;
7228}
7229
Eric Laurent1c333e22014-05-20 10:48:17 -07007230status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7231 audio_patch_handle_t *handle)
7232{
7233 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007234
7235 // store new device and send to effects
7236 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007237 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007238 for (size_t i = 0; i < mEffectChains.size(); i++) {
7239 mEffectChains[i]->setDevice_l(mInDevice);
7240 }
7241
7242 // disable AEC and NS if the device is a BT SCO headset supporting those
7243 // pre processings
7244 if (mTracks.size() > 0) {
7245 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7246 mAudioFlinger->btNrecIsOff();
7247 for (size_t i = 0; i < mTracks.size(); i++) {
7248 sp<RecordTrack> track = mTracks[i];
7249 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7250 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7251 }
7252 }
7253
7254 // store new source and send to effects
7255 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7256 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007257 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007258 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007259 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007260 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007261
Eric Laurent054d9d32015-04-24 08:48:48 -07007262 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007263 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7264 status = hwDevice->create_audio_patch(hwDevice,
7265 patch->num_sources,
7266 patch->sources,
7267 patch->num_sinks,
7268 patch->sinks,
7269 handle);
7270 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007271 char *address;
7272 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7273 address = audio_device_address_to_parameter(
7274 patch->sources[0].ext.device.type,
7275 patch->sources[0].ext.device.address);
7276 } else {
7277 address = (char *)calloc(1, 1);
7278 }
7279 AudioParameter param = AudioParameter(String8(address));
7280 free(address);
7281 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7282 (int)patch->sources[0].ext.device.type);
7283 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7284 (int)patch->sinks[0].ext.mix.usecase.source);
7285 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7286 param.toString().string());
7287 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007288 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007289
Eric Laurente8726fe2015-06-26 09:39:24 -07007290 if (mInDevice != mPrevInDevice) {
7291 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7292 mPrevInDevice = mInDevice;
7293 }
Eric Laurent296fb132015-05-01 11:38:42 -07007294
Eric Laurent1c333e22014-05-20 10:48:17 -07007295 return status;
7296}
7297
7298status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7299{
7300 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007301
7302 mInDevice = AUDIO_DEVICE_NONE;
7303
Eric Laurent1c333e22014-05-20 10:48:17 -07007304 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7305 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7306 status = hwDevice->release_audio_patch(hwDevice, handle);
7307 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007308 AudioParameter param;
7309 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7310 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7311 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007312 }
7313 return status;
7314}
7315
Eric Laurent83b88082014-06-20 18:31:16 -07007316void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7317{
7318 Mutex::Autolock _l(mLock);
7319 mTracks.add(record);
7320}
7321
7322void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7323{
7324 Mutex::Autolock _l(mLock);
7325 destroyTrack_l(record);
7326}
7327
7328void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7329{
7330 ThreadBase::getAudioPortConfig(config);
7331 config->role = AUDIO_PORT_ROLE_SINK;
7332 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7333 config->ext.mix.usecase.source = mAudioSource;
7334}
Eric Laurent1c333e22014-05-20 10:48:17 -07007335
Glenn Kasten63238ef2015-03-02 15:50:29 -08007336} // namespace android