blob: e056ef2a630ad16104c9d6424ab84757d826f5aa [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),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001568 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001569 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001570 // mStreamTypes[] initialized in constructor body
1571 mOutput(output),
1572 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1573 mMixerStatus(MIXER_IDLE),
1574 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001575 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001576 mBytesRemaining(0),
1577 mCurrentWriteLength(0),
1578 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001579 mWriteAckSequence(0),
1580 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001581 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001582 mScreenState(AudioFlinger::mScreenState),
1583 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001584 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001585 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001586{
Glenn Kastend7dca052015-03-05 16:05:54 -08001587 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1588 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001589
1590 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1591 // it would be safer to explicitly pass initial masterVolume/masterMute as
1592 // parameter.
1593 //
1594 // If the HAL we are using has support for master volume or master mute,
1595 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1596 // and the mute set to false).
1597 mMasterVolume = audioFlinger->masterVolume_l();
1598 mMasterMute = audioFlinger->masterMute_l();
1599 if (mOutput && mOutput->audioHwDev) {
1600 if (mOutput->audioHwDev->canSetMasterVolume()) {
1601 mMasterVolume = 1.0;
1602 }
1603
1604 if (mOutput->audioHwDev->canSetMasterMute()) {
1605 mMasterMute = false;
1606 }
1607 }
1608
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001609 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001610
Eric Laurent223fd5c2014-11-11 13:43:36 -08001611 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001612 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001613 stream = (audio_stream_type_t) (stream + 1)) {
1614 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1615 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1616 }
Eric Laurent81784c32012-11-19 14:55:58 -08001617}
1618
1619AudioFlinger::PlaybackThread::~PlaybackThread()
1620{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001621 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001622 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001623 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001624 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001625}
1626
1627void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1628{
1629 dumpInternals(fd, args);
1630 dumpTracks(fd, args);
1631 dumpEffectChains(fd, args);
1632}
1633
Glenn Kasten0f11b512014-01-31 16:18:54 -08001634void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001635{
1636 const size_t SIZE = 256;
1637 char buffer[SIZE];
1638 String8 result;
1639
Marco Nelissenb2208842014-02-07 14:00:50 -08001640 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001641 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1642 const stream_type_t *st = &mStreamTypes[i];
1643 if (i > 0) {
1644 result.appendFormat(", ");
1645 }
1646 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1647 if (st->mute) {
1648 result.append("M");
1649 }
1650 }
1651 result.append("\n");
1652 write(fd, result.string(), result.length());
1653 result.clear();
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1656 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001657 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001658 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001659
1660 size_t numtracks = mTracks.size();
1661 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001662 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001663 size_t numactiveseen = 0;
1664 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001665 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001666 Track::appendDumpHeader(result);
1667 for (size_t i = 0; i < numtracks; ++i) {
1668 sp<Track> track = mTracks[i];
1669 if (track != 0) {
1670 bool active = mActiveTracks.indexOf(track) >= 0;
1671 if (active) {
1672 numactiveseen++;
1673 }
1674 track->dump(buffer, SIZE, active);
1675 result.append(buffer);
1676 }
1677 }
1678 } else {
1679 result.append("\n");
1680 }
1681 if (numactiveseen != numactive) {
1682 // some tracks in the active list were not in the tracks list
1683 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1684 " not in the track list\n");
1685 result.append(buffer);
1686 Track::appendDumpHeader(result);
1687 for (size_t i = 0; i < numactive; ++i) {
1688 sp<Track> track = mActiveTracks[i].promote();
1689 if (track != 0 && mTracks.indexOf(track) < 0) {
1690 track->dump(buffer, SIZE, true);
1691 result.append(buffer);
1692 }
1693 }
1694 }
1695
1696 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001697}
1698
1699void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1700{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001701 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001702
1703 dumpBase(fd, args);
1704
Elliott Hughes87cebad2014-05-22 10:14:43 -07001705 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1706 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1707 dprintf(fd, " Total writes: %d\n", mNumWrites);
1708 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1709 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1710 dprintf(fd, " Suspend count: %d\n", mSuspended);
1711 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1712 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1713 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1714 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001715 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001716 AudioStreamOut *output = mOutput;
1717 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1718 String8 flagsAsString = outputFlagsToString(flags);
1719 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001720}
1721
1722// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001723
1724void AudioFlinger::PlaybackThread::onFirstRef()
1725{
Glenn Kastend7dca052015-03-05 16:05:54 -08001726 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001727}
1728
1729// ThreadBase virtuals
1730void AudioFlinger::PlaybackThread::preExit()
1731{
1732 ALOGV(" preExit()");
1733 // FIXME this is using hard-coded strings but in the future, this functionality will be
1734 // converted to use audio HAL extensions required to support tunneling
1735 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1736}
1737
1738// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1739sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1740 const sp<AudioFlinger::Client>& client,
1741 audio_stream_type_t streamType,
1742 uint32_t sampleRate,
1743 audio_format_t format,
1744 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001745 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001746 const sp<IMemory>& sharedBuffer,
1747 int sessionId,
1748 IAudioFlinger::track_flags_t *flags,
1749 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001750 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001751 status_t *status)
1752{
Glenn Kasten74935e42013-12-19 08:56:45 -08001753 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001754 sp<Track> track;
1755 status_t lStatus;
1756
Eric Laurent81784c32012-11-19 14:55:58 -08001757 // client expresses a preference for FAST, but we get the final say
1758 if (*flags & IAudioFlinger::TRACK_FAST) {
1759 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001760 // either of these use cases:
1761 (
1762 // use case 1: shared buffer with any frame count
1763 (
1764 (sharedBuffer != 0)
1765 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001766 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001767 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001768 // we formerly checked for a callback handler (non-0 tid),
1769 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001770 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001771 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001772 )
1773 ) &&
1774 // PCM data
1775 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001776 // TODO: extract as a data library function that checks that a computationally
1777 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001778 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001779 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1780 (channelMask == AUDIO_CHANNEL_OUT_MONO
1781 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // hardware sample rate
1783 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001784 // normal mixer has an associated fast mixer
1785 hasFastMixer() &&
1786 // there are sufficient fast track slots available
1787 (mFastTrackAvailMask != 0)
1788 // FIXME test that MixerThread for this fast track has a capable output HAL
1789 // FIXME add a permission test also?
1790 ) {
1791 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1792 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001793 // read the fast track multiplier property the first time it is needed
1794 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1795 if (ok != 0) {
1796 ALOGE("%s pthread_once failed: %d", __func__, ok);
1797 }
1798 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001799 }
1800 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1801 frameCount, mFrameCount);
1802 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001803 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001804 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1805 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001806 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001807 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001808 audio_is_linear_pcm(format),
1809 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1810 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001811 }
1812 }
1813 // For normal PCM streaming tracks, update minimum frame count.
1814 // For compatibility with AudioTrack calculation, buffer depth is forced
1815 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1816 // This is probably too conservative, but legacy application code may depend on it.
1817 // If you change this calculation, also review the start threshold which is related.
1818 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001819 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001820 // this must match AudioTrack.cpp calculateMinFrameCount().
1821 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001822 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1823 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1824 if (minBufCount < 2) {
1825 minBufCount = 2;
1826 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001827 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1828 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001829 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001830 minBufCount * sourceFramesNeededWithTimestretch(
1831 sampleRate, mNormalFrameCount,
1832 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001833 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001834 frameCount = minFrameCount;
1835 }
Eric Laurent81784c32012-11-19 14:55:58 -08001836 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001837 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001838
Glenn Kastenc3df8382014-03-13 15:05:25 -07001839 switch (mType) {
1840
1841 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001842 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001843 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001844 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1845 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001846 sampleRate, format, channelMask, mOutput, mFormat);
1847 lStatus = BAD_VALUE;
1848 goto Exit;
1849 }
1850 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001851 break;
1852
1853 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001854 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001855 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1856 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857 sampleRate, format, channelMask, mOutput, mFormat);
1858 lStatus = BAD_VALUE;
1859 goto Exit;
1860 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001861 break;
1862
1863 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001864 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001865 ALOGE("createTrack_l() Bad parameter: format %#x \""
1866 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867 format, mOutput, mFormat);
1868 lStatus = BAD_VALUE;
1869 goto Exit;
1870 }
Andy Hungcd044842014-08-07 11:04:34 -07001871 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001872 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1873 lStatus = BAD_VALUE;
1874 goto Exit;
1875 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001876 break;
1877
Eric Laurent81784c32012-11-19 14:55:58 -08001878 }
1879
1880 lStatus = initCheck();
1881 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001882 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001883 goto Exit;
1884 }
1885
1886 { // scope for mLock
1887 Mutex::Autolock _l(mLock);
1888
1889 // all tracks in same audio session must share the same routing strategy otherwise
1890 // conflicts will happen when tracks are moved from one output to another by audio policy
1891 // manager
1892 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1893 for (size_t i = 0; i < mTracks.size(); ++i) {
1894 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001895 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001896 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1897 if (sessionId == t->sessionId() && strategy != actual) {
1898 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1899 strategy, actual);
1900 lStatus = BAD_VALUE;
1901 goto Exit;
1902 }
1903 }
1904 }
1905
Glenn Kastend79072e2016-01-06 08:41:20 -08001906 track = new Track(this, client, streamType, sampleRate, format,
1907 channelMask, frameCount, NULL, sharedBuffer,
1908 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001909
Glenn Kasten03003332013-08-06 15:40:54 -07001910 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1911 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001912 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001913 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001914 goto Exit;
1915 }
1916 mTracks.add(track);
1917
1918 sp<EffectChain> chain = getEffectChain_l(sessionId);
1919 if (chain != 0) {
1920 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1921 track->setMainBuffer(chain->inBuffer());
1922 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1923 chain->incTrackCnt();
1924 }
1925
1926 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1927 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1928 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1929 // so ask activity manager to do this on our behalf
1930 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1931 }
1932 }
1933
1934 lStatus = NO_ERROR;
1935
1936Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001937 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001938 return track;
1939}
1940
1941uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1942{
1943 return latency;
1944}
1945
1946uint32_t AudioFlinger::PlaybackThread::latency() const
1947{
1948 Mutex::Autolock _l(mLock);
1949 return latency_l();
1950}
1951uint32_t AudioFlinger::PlaybackThread::latency_l() const
1952{
1953 if (initCheck() == NO_ERROR) {
1954 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1955 } else {
1956 return 0;
1957 }
1958}
1959
1960void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1961{
1962 Mutex::Autolock _l(mLock);
1963 // Don't apply master volume in SW if our HAL can do it for us.
1964 if (mOutput && mOutput->audioHwDev &&
1965 mOutput->audioHwDev->canSetMasterVolume()) {
1966 mMasterVolume = 1.0;
1967 } else {
1968 mMasterVolume = value;
1969 }
1970}
1971
1972void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1973{
1974 Mutex::Autolock _l(mLock);
1975 // Don't apply master mute in SW if our HAL can do it for us.
1976 if (mOutput && mOutput->audioHwDev &&
1977 mOutput->audioHwDev->canSetMasterMute()) {
1978 mMasterMute = false;
1979 } else {
1980 mMasterMute = muted;
1981 }
1982}
1983
1984void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1985{
1986 Mutex::Autolock _l(mLock);
1987 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001988 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1992{
1993 Mutex::Autolock _l(mLock);
1994 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001995 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
1998float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1999{
2000 Mutex::Autolock _l(mLock);
2001 return mStreamTypes[stream].volume;
2002}
2003
2004// addTrack_l() must be called with ThreadBase::mLock held
2005status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2006{
2007 status_t status = ALREADY_EXISTS;
2008
2009 // set retry count for buffer fill
2010 track->mRetryCount = kMaxTrackStartupRetries;
2011 if (mActiveTracks.indexOf(track) < 0) {
2012 // the track is newly added, make sure it fills up all its
2013 // buffers before playing. This is to ensure the client will
2014 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002015 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002016 TrackBase::track_state state = track->mState;
2017 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002018 status = AudioSystem::startOutput(mId, track->streamType(),
2019 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002020 mLock.lock();
2021 // abort track was stopped/paused while we released the lock
2022 if (state != track->mState) {
2023 if (status == NO_ERROR) {
2024 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002025 AudioSystem::stopOutput(mId, track->streamType(),
2026 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027 mLock.lock();
2028 }
2029 return INVALID_OPERATION;
2030 }
2031 // abort if start is rejected by audio policy manager
2032 if (status != NO_ERROR) {
2033 return PERMISSION_DENIED;
2034 }
2035#ifdef ADD_BATTERY_DATA
2036 // to track the speaker usage
2037 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2038#endif
2039 }
2040
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002041 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002042 track->mResetDone = false;
2043 track->mPresentationCompleteFrames = 0;
2044 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002045 mWakeLockUids.add(track->uid());
2046 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002047 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002048 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2049 if (chain != 0) {
2050 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2051 track->sessionId());
2052 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002053 }
2054
2055 status = NO_ERROR;
2056 }
2057
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002058 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002059 return status;
2060}
2061
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002063{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002065 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2067 track->mState = TrackBase::STOPPED;
2068 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002069 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002070 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002071 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002072 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073
2074 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002075}
2076
2077void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2078{
2079 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2080 mTracks.remove(track);
2081 deleteTrackName_l(track->name());
2082 // redundant as track is about to be destroyed, for dumpsys only
2083 track->mName = -1;
2084 if (track->isFastTrack()) {
2085 int index = track->mFastIndex;
2086 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2087 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2088 mFastTrackAvailMask |= 1 << index;
2089 // redundant as track is about to be destroyed, for dumpsys only
2090 track->mFastIndex = -1;
2091 }
2092 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2093 if (chain != 0) {
2094 chain->decTrackCnt();
2095 }
2096}
2097
Eric Laurentede6c3b2013-09-19 14:37:46 -07002098void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099{
2100 // Thread could be blocked waiting for async
2101 // so signal it to handle state changes immediately
2102 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2103 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2104 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002105 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002106}
2107
Eric Laurent81784c32012-11-19 14:55:58 -08002108String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2109{
Eric Laurent81784c32012-11-19 14:55:58 -08002110 Mutex::Autolock _l(mLock);
2111 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002112 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002113 }
2114
Glenn Kastend8ea6992013-07-16 14:17:15 -07002115 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2116 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002117 free(s);
2118 return out_s8;
2119}
2120
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002121void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002122 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2123 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002124
Eric Laurent73e26b62015-04-27 16:55:58 -07002125 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002126
2127 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002128 case AUDIO_OUTPUT_OPENED:
2129 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002130 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002131 desc->mChannelMask = mChannelMask;
2132 desc->mSamplingRate = mSampleRate;
2133 desc->mFormat = mFormat;
2134 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002135 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002136 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002137 break;
2138
Eric Laurent73e26b62015-04-27 16:55:58 -07002139 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002140 default:
2141 break;
2142 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002143 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002144}
2145
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146void AudioFlinger::PlaybackThread::writeCallback()
2147{
2148 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002149 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150}
2151
2152void AudioFlinger::PlaybackThread::drainCallback()
2153{
2154 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002155 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156}
2157
Eric Laurent3b4529e2013-09-05 18:09:19 -07002158void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159{
2160 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002161 // reject out of sequence requests
2162 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2163 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 mWaitWorkCV.signal();
2165 }
2166}
2167
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169{
2170 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002171 // reject out of sequence requests
2172 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2173 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 mWaitWorkCV.signal();
2175 }
2176}
2177
2178// static
2179int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002180 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002181 void *cookie)
2182{
2183 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2184 ALOGV("asyncCallback() event %d", event);
2185 switch (event) {
2186 case STREAM_CBK_EVENT_WRITE_READY:
2187 me->writeCallback();
2188 break;
2189 case STREAM_CBK_EVENT_DRAIN_READY:
2190 me->drainCallback();
2191 break;
2192 default:
2193 ALOGW("asyncCallback() unknown event %d", event);
2194 break;
2195 }
2196 return 0;
2197}
2198
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002199void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002200{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002201 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002202 mSampleRate = mOutput->getSampleRate();
2203 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002204 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002205 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002206 }
Andy Hung9a592762014-07-21 21:56:01 -07002207 if ((mType == MIXER || mType == DUPLICATING)
2208 && !isValidPcmSinkChannelMask(mChannelMask)) {
2209 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2210 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002211 }
Andy Hunge5412692014-05-16 11:25:07 -07002212 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002213
2214 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002215 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002216 // Get format from the shim, which will be different than the HAL format
2217 // if playing compressed audio over HDMI passthrough.
2218 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002219 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002220 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002221 }
Andy Hung6146c082014-03-18 11:56:15 -07002222 if ((mType == MIXER || mType == DUPLICATING)
2223 && !isValidPcmSinkFormat(mFormat)) {
2224 LOG_FATAL("HAL format %#x not supported for mixed output",
2225 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002226 }
Phil Burk062e67a2015-02-11 13:40:50 -08002227 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002228 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2229 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002230 if (mFrameCount & 15) {
2231 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2232 mFrameCount);
2233 }
2234
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2236 (mOutput->stream->set_callback != NULL)) {
2237 if (mOutput->stream->set_callback(mOutput->stream,
2238 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2239 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002240 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 }
2242 }
2243
Eric Laurentd1f69b02014-12-15 14:33:13 -08002244 mHwSupportsPause = false;
2245 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2246 if (mOutput->stream->pause != NULL) {
2247 if (mOutput->stream->resume != NULL) {
2248 mHwSupportsPause = true;
2249 } else {
2250 ALOGW("direct output implements pause but not resume");
2251 }
2252 } else if (mOutput->stream->resume != NULL) {
2253 ALOGW("direct output implements resume but not pause");
2254 }
2255 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002256 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2257 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2258 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002259
Andy Hungfbfc3952015-01-15 13:33:51 -08002260 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2261 // For best precision, we use float instead of the associated output
2262 // device format (typically PCM 16 bit).
2263
2264 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2265 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2266 mBufferSize = mFrameSize * mFrameCount;
2267
2268 // TODO: We currently use the associated output device channel mask and sample rate.
2269 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2270 // (if a valid mask) to avoid premature downmix.
2271 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2272 // instead of the output device sample rate to avoid loss of high frequency information.
2273 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2274 }
2275
Andy Hung09a50072014-02-27 14:30:47 -08002276 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002277 double multiplier = 1.0;
2278 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2279 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002280 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2281 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002282 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2283 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2284 maxNormalFrameCount = maxNormalFrameCount & ~15;
2285 if (maxNormalFrameCount < minNormalFrameCount) {
2286 maxNormalFrameCount = minNormalFrameCount;
2287 }
2288 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2289 if (multiplier <= 1.0) {
2290 multiplier = 1.0;
2291 } else if (multiplier <= 2.0) {
2292 if (2 * mFrameCount <= maxNormalFrameCount) {
2293 multiplier = 2.0;
2294 } else {
2295 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2296 }
2297 } else {
2298 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002299 // 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 -08002300 // track, but we sometimes have to do this to satisfy the maximum frame count
2301 // constraint)
2302 // FIXME this rounding up should not be done if no HAL SRC
2303 uint32_t truncMult = (uint32_t) multiplier;
2304 if ((truncMult & 1)) {
2305 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2306 ++truncMult;
2307 }
2308 }
2309 multiplier = (double) truncMult;
2310 }
2311 }
2312 mNormalFrameCount = multiplier * mFrameCount;
2313 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002314 if (mType == MIXER || mType == DUPLICATING) {
2315 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2316 }
Andy Hung09a50072014-02-27 14:30:47 -08002317 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002318 mNormalFrameCount);
2319
Andy Hung08fb1742015-05-31 23:22:10 -07002320 // Check if we want to throttle the processing to no more than 2x normal rate
2321 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002322 mThreadThrottleTimeMs = 0;
2323 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002324 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2325
Andy Hung010a1a12014-03-13 13:57:33 -07002326 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2327 // Originally this was int16_t[] array, need to remove legacy implications.
2328 free(mSinkBuffer);
2329 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002330 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2331 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2332 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002333 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002334
Andy Hung69aed5f2014-02-25 17:24:40 -08002335 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2336 // drives the output.
2337 free(mMixerBuffer);
2338 mMixerBuffer = NULL;
2339 if (mMixerBufferEnabled) {
2340 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2341 mMixerBufferSize = mNormalFrameCount * mChannelCount
2342 * audio_bytes_per_sample(mMixerBufferFormat);
2343 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2344 }
Andy Hung98ef9782014-03-04 14:46:50 -08002345 free(mEffectBuffer);
2346 mEffectBuffer = NULL;
2347 if (mEffectBufferEnabled) {
2348 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2349 mEffectBufferSize = mNormalFrameCount * mChannelCount
2350 * audio_bytes_per_sample(mEffectBufferFormat);
2351 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2352 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002353
Eric Laurent81784c32012-11-19 14:55:58 -08002354 // force reconfiguration of effect chains and engines to take new buffer size and audio
2355 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002356 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002357 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2358 // matter.
2359 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2360 Vector< sp<EffectChain> > effectChains = mEffectChains;
2361 for (size_t i = 0; i < effectChains.size(); i ++) {
2362 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2363 }
2364}
2365
2366
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002367status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002368{
2369 if (halFrames == NULL || dspFrames == NULL) {
2370 return BAD_VALUE;
2371 }
2372 Mutex::Autolock _l(mLock);
2373 if (initCheck() != NO_ERROR) {
2374 return INVALID_OPERATION;
2375 }
Andy Hung818e7a32016-02-16 18:08:07 -08002376 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002377 *halFrames = framesWritten;
2378
2379 if (isSuspended()) {
2380 // return an estimation of rendered frames when the output is suspended
2381 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002382 *dspFrames = (uint32_t)
2383 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002384 return NO_ERROR;
2385 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002386 status_t status;
2387 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002388 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002389 *dspFrames = (size_t)frames;
2390 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002391 }
2392}
2393
2394uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2395{
2396 Mutex::Autolock _l(mLock);
2397 uint32_t result = 0;
2398 if (getEffectChain_l(sessionId) != 0) {
2399 result = EFFECT_SESSION;
2400 }
2401
2402 for (size_t i = 0; i < mTracks.size(); ++i) {
2403 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002404 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002405 result |= TRACK_SESSION;
2406 break;
2407 }
2408 }
2409
2410 return result;
2411}
2412
2413uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2414{
2415 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2416 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2417 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2418 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2419 }
2420 for (size_t i = 0; i < mTracks.size(); i++) {
2421 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002422 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002423 return AudioSystem::getStrategyForStream(track->streamType());
2424 }
2425 }
2426 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2427}
2428
2429
Phil Burk062e67a2015-02-11 13:40:50 -08002430AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002431{
2432 Mutex::Autolock _l(mLock);
2433 return mOutput;
2434}
2435
Phil Burk062e67a2015-02-11 13:40:50 -08002436AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002437{
2438 Mutex::Autolock _l(mLock);
2439 AudioStreamOut *output = mOutput;
2440 mOutput = NULL;
2441 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2442 // must push a NULL and wait for ack
2443 mOutputSink.clear();
2444 mPipeSink.clear();
2445 mNormalSink.clear();
2446 return output;
2447}
2448
2449// this method must always be called either with ThreadBase mLock held or inside the thread loop
2450audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2451{
2452 if (mOutput == NULL) {
2453 return NULL;
2454 }
2455 return &mOutput->stream->common;
2456}
2457
2458uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2459{
2460 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
2463status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2464{
2465 if (!isValidSyncEvent(event)) {
2466 return BAD_VALUE;
2467 }
2468
2469 Mutex::Autolock _l(mLock);
2470
2471 for (size_t i = 0; i < mTracks.size(); ++i) {
2472 sp<Track> track = mTracks[i];
2473 if (event->triggerSession() == track->sessionId()) {
2474 (void) track->setSyncEvent(event);
2475 return NO_ERROR;
2476 }
2477 }
2478
2479 return NAME_NOT_FOUND;
2480}
2481
2482bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2483{
2484 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2485}
2486
2487void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2488 const Vector< sp<Track> >& tracksToRemove)
2489{
2490 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002491 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002492 for (size_t i = 0 ; i < count ; i++) {
2493 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002494 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002495 AudioSystem::stopOutput(mId, track->streamType(),
2496 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497#ifdef ADD_BATTERY_DATA
2498 // to track the speaker usage
2499 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2500#endif
2501 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002502 AudioSystem::releaseOutput(mId, track->streamType(),
2503 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504 }
Eric Laurent81784c32012-11-19 14:55:58 -08002505 }
2506 }
2507 }
Eric Laurent81784c32012-11-19 14:55:58 -08002508}
2509
2510void AudioFlinger::PlaybackThread::checkSilentMode_l()
2511{
2512 if (!mMasterMute) {
2513 char value[PROPERTY_VALUE_MAX];
2514 if (property_get("ro.audio.silent", value, "0") > 0) {
2515 char *endptr;
2516 unsigned long ul = strtoul(value, &endptr, 0);
2517 if (*endptr == '\0' && ul != 0) {
2518 ALOGD("Silence is golden");
2519 // The setprop command will not allow a property to be changed after
2520 // the first time it is set, so we don't have to worry about un-muting.
2521 setMasterMute_l(true);
2522 }
2523 }
2524 }
2525}
2526
2527// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002528ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002529{
2530 // FIXME rewrite to reduce number of system calls
2531 mLastWriteTime = systemTime();
2532 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002533 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002534 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002535
2536 // If an NBAIO sink is present, use it to write the normal mixer's submix
2537 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002538
Andy Hung010a1a12014-03-13 13:57:33 -07002539 const size_t count = mBytesRemaining / mFrameSize;
2540
Simon Wilson2d590962012-11-29 15:18:50 -08002541 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002542 // update the setpoint when AudioFlinger::mScreenState changes
2543 uint32_t screenState = AudioFlinger::mScreenState;
2544 if (screenState != mScreenState) {
2545 mScreenState = screenState;
2546 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2547 if (pipe != NULL) {
2548 pipe->setAvgFrames((mScreenState & 1) ?
2549 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2550 }
2551 }
Andy Hung010a1a12014-03-13 13:57:33 -07002552 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002553 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002554 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002555 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002556 } else {
2557 bytesWritten = framesWritten;
2558 }
2559 // otherwise use the HAL / AudioStreamOut directly
2560 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002562
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002564 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2565 mWriteAckSequence += 2;
2566 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002568 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002569 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002570 // FIXME We should have an implementation of timestamps for direct output threads.
2571 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002572 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002573 if (mUseAsyncWrite &&
2574 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2575 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002576 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002578 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 }
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
2581
Eric Laurent81784c32012-11-19 14:55:58 -08002582 mNumWrites++;
2583 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002584 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 return bytesWritten;
2586}
2587
2588void AudioFlinger::PlaybackThread::threadLoop_drain()
2589{
2590 if (mOutput->stream->drain) {
2591 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2592 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002593 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2594 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002596 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 }
2598 mOutput->stream->drain(mOutput->stream,
2599 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2600 : AUDIO_DRAIN_ALL);
2601 }
2602}
2603
2604void AudioFlinger::PlaybackThread::threadLoop_exit()
2605{
Eric Laurent275e8e92014-11-30 15:14:47 -08002606 {
2607 Mutex::Autolock _l(mLock);
2608 for (size_t i = 0; i < mTracks.size(); i++) {
2609 sp<Track> track = mTracks[i];
2610 track->invalidate();
2611 }
2612 }
Eric Laurent81784c32012-11-19 14:55:58 -08002613}
2614
2615/*
2616The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002617 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002618 - mActiveSleepTimeUs from activeSleepTimeUs()
2619 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002620 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2621 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002622 - maxPeriod from frame count and sample rate (MIXER only)
2623
2624The parameters that affect these derived values are:
2625 - frame count
2626 - frame size
2627 - sample rate
2628 - device type: A2DP or not
2629 - device latency
2630 - format: PCM or not
2631 - active sleep time
2632 - idle sleep time
2633*/
2634
2635void AudioFlinger::PlaybackThread::cacheParameters_l()
2636{
Andy Hung25c2dac2014-02-27 14:56:00 -08002637 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002638 mActiveSleepTimeUs = activeSleepTimeUs();
2639 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002640
2641 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2642 // truncating audio when going to standby.
2643 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2644 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2645 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2646 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2647 }
2648 }
Eric Laurent81784c32012-11-19 14:55:58 -08002649}
2650
2651void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2652{
Glenn Kasten7c027242012-12-26 14:43:16 -08002653 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002654 this, streamType, mTracks.size());
2655 Mutex::Autolock _l(mLock);
2656
2657 size_t size = mTracks.size();
2658 for (size_t i = 0; i < size; i++) {
2659 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002660 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002661 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002662 }
2663 }
2664}
2665
2666status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2667{
2668 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002669 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2670 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002671 bool ownsBuffer = false;
2672
2673 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2674 if (session > 0) {
2675 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002676 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002677 if (mType != DIRECT) {
2678 size_t numSamples = mNormalFrameCount * mChannelCount;
2679 buffer = new int16_t[numSamples];
2680 memset(buffer, 0, numSamples * sizeof(int16_t));
2681 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2682 ownsBuffer = true;
2683 }
2684
2685 // Attach all tracks with same session ID to this chain.
2686 for (size_t i = 0; i < mTracks.size(); ++i) {
2687 sp<Track> track = mTracks[i];
2688 if (session == track->sessionId()) {
2689 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2690 buffer);
2691 track->setMainBuffer(buffer);
2692 chain->incTrackCnt();
2693 }
2694 }
2695
2696 // indicate all active tracks in the chain
2697 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2698 sp<Track> track = mActiveTracks[i].promote();
2699 if (track == 0) {
2700 continue;
2701 }
2702 if (session == track->sessionId()) {
2703 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2704 chain->incActiveTrackCnt();
2705 }
2706 }
2707 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002708 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002709 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002710 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2711 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002712 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2713 // chains list in order to be processed last as it contains output stage effects
2714 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2715 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2716 // after track specific effects and before output stage
2717 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2718 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2719 // Effect chain for other sessions are inserted at beginning of effect
2720 // chains list to be processed before output mix effects. Relative order between other
2721 // sessions is not important
2722 size_t size = mEffectChains.size();
2723 size_t i = 0;
2724 for (i = 0; i < size; i++) {
2725 if (mEffectChains[i]->sessionId() < session) {
2726 break;
2727 }
2728 }
2729 mEffectChains.insertAt(chain, i);
2730 checkSuspendOnAddEffectChain_l(chain);
2731
2732 return NO_ERROR;
2733}
2734
2735size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2736{
2737 int session = chain->sessionId();
2738
2739 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2740
2741 for (size_t i = 0; i < mEffectChains.size(); i++) {
2742 if (chain == mEffectChains[i]) {
2743 mEffectChains.removeAt(i);
2744 // detach all active tracks from the chain
2745 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2746 sp<Track> track = mActiveTracks[i].promote();
2747 if (track == 0) {
2748 continue;
2749 }
2750 if (session == track->sessionId()) {
2751 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2752 chain.get(), session);
2753 chain->decActiveTrackCnt();
2754 }
2755 }
2756
2757 // detach all tracks with same session ID from this chain
2758 for (size_t i = 0; i < mTracks.size(); ++i) {
2759 sp<Track> track = mTracks[i];
2760 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002761 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002762 chain->decTrackCnt();
2763 }
2764 }
2765 break;
2766 }
2767 }
2768 return mEffectChains.size();
2769}
2770
2771status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2772 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2773{
2774 Mutex::Autolock _l(mLock);
2775 return attachAuxEffect_l(track, EffectId);
2776}
2777
2778status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2779 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2780{
2781 status_t status = NO_ERROR;
2782
2783 if (EffectId == 0) {
2784 track->setAuxBuffer(0, NULL);
2785 } else {
2786 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2787 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2788 if (effect != 0) {
2789 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2790 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2791 } else {
2792 status = INVALID_OPERATION;
2793 }
2794 } else {
2795 status = BAD_VALUE;
2796 }
2797 }
2798 return status;
2799}
2800
2801void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2802{
2803 for (size_t i = 0; i < mTracks.size(); ++i) {
2804 sp<Track> track = mTracks[i];
2805 if (track->auxEffectId() == effectId) {
2806 attachAuxEffect_l(track, 0);
2807 }
2808 }
2809}
2810
2811bool AudioFlinger::PlaybackThread::threadLoop()
2812{
2813 Vector< sp<Track> > tracksToRemove;
2814
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002815 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002816
2817 // MIXER
2818 nsecs_t lastWarning = 0;
2819
2820 // DUPLICATING
2821 // FIXME could this be made local to while loop?
2822 writeFrames = 0;
2823
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002824 int lastGeneration = 0;
2825
Eric Laurent81784c32012-11-19 14:55:58 -08002826 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002827 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002828
2829 if (mType == MIXER) {
2830 sleepTimeShift = 0;
2831 }
2832
2833 CpuStats cpuStats;
2834 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2835
2836 acquireWakeLock();
2837
Glenn Kasten9e58b552013-01-18 15:09:48 -08002838 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2839 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2840 // and then that string will be logged at the next convenient opportunity.
2841 const char *logString = NULL;
2842
Eric Laurent664539d2013-09-23 18:24:31 -07002843 checkSilentMode_l();
2844
Eric Laurent81784c32012-11-19 14:55:58 -08002845 while (!exitPending())
2846 {
2847 cpuStats.sample(myName);
2848
2849 Vector< sp<EffectChain> > effectChains;
2850
Eric Laurent81784c32012-11-19 14:55:58 -08002851 { // scope for mLock
2852
2853 Mutex::Autolock _l(mLock);
2854
Eric Laurent021cf962014-05-13 10:18:14 -07002855 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002856
Glenn Kasten9e58b552013-01-18 15:09:48 -08002857 if (logString != NULL) {
2858 mNBLogWriter->logTimestamp();
2859 mNBLogWriter->log(logString);
2860 logString = NULL;
2861 }
2862
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002863 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002864 // and associate with the sink frames written out. We need
2865 // this to convert the sink timestamp to the track timestamp.
2866 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002867 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002868 // We always fetch the timestamp here because often the downstream
2869 // sink will block whie writing.
2870 ExtendedTimestamp timestamp; // use private copy to fetch
2871 (void) mNormalSink->getTimestamp(timestamp);
2872 // copy over kernel info
2873 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2874 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2875 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2876 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002877 }
2878 // mFramesWritten for non-offloaded tracks are contiguous
2879 // even after standby() is called. This is useful for the track frame
2880 // to sink frame mapping.
2881 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2882 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
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 mFramesWritten,
2890 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002891 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002892 }
2893
Eric Laurent81784c32012-11-19 14:55:58 -08002894 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 if (mSignalPending) {
2896 // A signal was raised while we were unlocked
2897 mSignalPending = false;
2898 } else if (waitingAsyncCallback_l()) {
2899 if (exitPending()) {
2900 break;
2901 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002902 bool released = false;
2903 // The following works around a bug in the offload driver. Ideally we would release
2904 // the wake lock every time, but that causes the last offload buffer(s) to be
2905 // dropped while the device is on battery, so we need to hold a wake lock during
2906 // the drain phase.
2907 if (mBytesRemaining && !(mDrainSequence & 1)) {
2908 releaseWakeLock_l();
2909 released = true;
2910 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002911 mWakeLockUids.clear();
2912 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 ALOGV("wait async completion");
2914 mWaitWorkCV.wait(mLock);
2915 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002916 if (released) {
2917 acquireWakeLock_l();
2918 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002919 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2920 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002921
2922 continue;
2923 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002924 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 isSuspended()) {
2926 // put audio hardware into standby after short delay
2927 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002928
2929 threadLoop_standby();
2930
2931 mStandby = true;
2932 }
2933
2934 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2935 // we're about to wait, flush the binder command buffer
2936 IPCThreadState::self()->flushCommands();
2937
2938 clearOutputTracks();
2939
2940 if (exitPending()) {
2941 break;
2942 }
2943
2944 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002945 mWakeLockUids.clear();
2946 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002947 // wait until we have something to do...
2948 ALOGV("%s going to sleep", myName.string());
2949 mWaitWorkCV.wait(mLock);
2950 ALOGV("%s waking up", myName.string());
2951 acquireWakeLock_l();
2952
2953 mMixerStatus = MIXER_IDLE;
2954 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2955 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002957 checkSilentMode_l();
2958
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002959 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2960 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002961 if (mType == MIXER) {
2962 sleepTimeShift = 0;
2963 }
2964
2965 continue;
2966 }
2967 }
Eric Laurent81784c32012-11-19 14:55:58 -08002968 // mMixerStatusIgnoringFastTracks is also updated internally
2969 mMixerStatus = prepareTracks_l(&tracksToRemove);
2970
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002971 // compare with previously applied list
2972 if (lastGeneration != mActiveTracksGeneration) {
2973 // update wakelock
2974 updateWakeLockUids_l(mWakeLockUids);
2975 lastGeneration = mActiveTracksGeneration;
2976 }
2977
Eric Laurent81784c32012-11-19 14:55:58 -08002978 // prevent any changes in effect chain list and in each effect chain
2979 // during mixing and effect process as the audio buffers could be deleted
2980 // or modified if an effect is created or deleted
2981 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002982 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002983
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984 if (mBytesRemaining == 0) {
2985 mCurrentWriteLength = 0;
2986 if (mMixerStatus == MIXER_TRACKS_READY) {
2987 // threadLoop_mix() sets mCurrentWriteLength
2988 threadLoop_mix();
2989 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2990 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002991 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 // must be written to HAL
2993 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002994 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002995 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002996 }
2997 }
Andy Hung98ef9782014-03-04 14:46:50 -08002998 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002999 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003000 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3001 // or mSinkBuffer (if there are no effects).
3002 //
3003 // This is done pre-effects computation; if effects change to
3004 // support higher precision, this needs to move.
3005 //
3006 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003007 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003008 if (mMixerBufferValid) {
3009 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3010 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3011
Andy Hung2ddee192015-12-18 17:34:44 -08003012 // mono blend occurs for mixer threads only (not direct or offloaded)
3013 // and is handled here if we're going directly to the sink.
3014 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003015 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3016 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003017 }
3018
Andy Hung98ef9782014-03-04 14:46:50 -08003019 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3020 mNormalFrameCount * mChannelCount);
3021 }
3022
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 mBytesRemaining = mCurrentWriteLength;
3024 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003025 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003027 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003028 mFramesWritten += mSinkBufferSize / mFrameSize;
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;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003079 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080 }
3081 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3082 (mMixerStatus == MIXER_DRAIN_ALL)) {
3083 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003084 }
Andy Hung08fb1742015-05-31 23:22:10 -07003085 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003086 // write blocked detection
3087 nsecs_t now = systemTime();
3088 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003089 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003090 mNumDelayedWrites++;
3091 if ((now - lastWarning) > kWarningThrottleNs) {
3092 ATRACE_NAME("underrun");
3093 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3094 ns2ms(delta), mNumDelayedWrites, this);
3095 lastWarning = now;
3096 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003097 }
Andy Hung08fb1742015-05-31 23:22:10 -07003098
3099 if (mThreadThrottle
3100 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3101 && ret > 0) { // we wrote something
3102 // Limit MixerThread data processing to no more than twice the
3103 // expected processing rate.
3104 //
3105 // This helps prevent underruns with NuPlayer and other applications
3106 // which may set up buffers that are close to the minimum size, or use
3107 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3108 //
3109 // The throttle smooths out sudden large data drains from the device,
3110 // e.g. when it comes out of standby, which often causes problems with
3111 // (1) mixer threads without a fast mixer (which has its own warm-up)
3112 // (2) minimum buffer sized tracks (even if the track is full,
3113 // the app won't fill fast enough to handle the sudden draw).
3114
3115 const int32_t deltaMs = delta / 1000000;
3116 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3117 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3118 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003119 // notify of throttle start on verbose log
3120 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3121 "mixer(%p) throttle begin:"
3122 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003123 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003124 mThreadThrottleTimeMs += throttleMs;
3125 } else {
3126 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3127 if (diff > 0) {
3128 // notify of throttle end on debug log
3129 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3130 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3131 }
Andy Hung08fb1742015-05-31 23:22:10 -07003132 }
3133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 }
Eric Laurent81784c32012-11-19 14:55:58 -08003135
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003137 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003138 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003139 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003140 }
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
3142
3143 // Finally let go of removed track(s), without the lock held
3144 // since we can't guarantee the destructors won't acquire that
3145 // same lock. This will also mutate and push a new fast mixer state.
3146 threadLoop_removeTracks(tracksToRemove);
3147 tracksToRemove.clear();
3148
3149 // FIXME I don't understand the need for this here;
3150 // it was in the original code but maybe the
3151 // assignment in saveOutputTracks() makes this unnecessary?
3152 clearOutputTracks();
3153
3154 // Effect chains will be actually deleted here if they were removed from
3155 // mEffectChains list during mixing or effects processing
3156 effectChains.clear();
3157
3158 // FIXME Note that the above .clear() is no longer necessary since effectChains
3159 // is now local to this block, but will keep it for now (at least until merge done).
3160 }
3161
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 threadLoop_exit();
3163
Eric Laurentcf817a22014-08-04 20:36:31 -07003164 if (!mStandby) {
3165 threadLoop_standby();
3166 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003167 }
3168
3169 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003170 mWakeLockUids.clear();
3171 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003172
3173 ALOGV("Thread %p type %d exiting", this, mType);
3174 return false;
3175}
3176
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177// removeTracks_l() must be called with ThreadBase::mLock held
3178void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3179{
3180 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003181 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 for (size_t i=0 ; i<count ; i++) {
3183 const sp<Track>& track = tracksToRemove.itemAt(i);
3184 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003185 mWakeLockUids.remove(track->uid());
3186 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3188 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3189 if (chain != 0) {
3190 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3191 track->sessionId());
3192 chain->decActiveTrackCnt();
3193 }
3194 if (track->isTerminated()) {
3195 removeTrack_l(track);
3196 }
3197 }
3198 }
3199
3200}
Eric Laurent81784c32012-11-19 14:55:58 -08003201
Eric Laurentaccc1472013-09-20 09:36:34 -07003202status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3203{
3204 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003205 ExtendedTimestamp ets;
3206 status_t status = mNormalSink->getTimestamp(ets);
3207 if (status == NO_ERROR) {
3208 status = ets.getBestTimestamp(&timestamp);
3209 }
3210 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003211 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003212 if ((mType == OFFLOAD || mType == DIRECT)
3213 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003214 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003215 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003216 if (ret == 0) {
3217 timestamp.mPosition = (uint32_t)position64;
3218 return NO_ERROR;
3219 }
3220 }
3221 return INVALID_OPERATION;
3222}
Eric Laurent1c333e22014-05-20 10:48:17 -07003223
Eric Laurent054d9d32015-04-24 08:48:48 -07003224status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3225 audio_patch_handle_t *handle)
3226{
3227 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3228 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3229 if (mFastMixer != 0) {
3230 FastMixerStateQueue *sq = mFastMixer->sq();
3231 FastMixerState *state = sq->begin();
3232 if (!(state->mCommand & FastMixerState::IDLE)) {
3233 previousCommand = state->mCommand;
3234 state->mCommand = FastMixerState::HOT_IDLE;
3235 sq->end();
3236 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3237 } else {
3238 sq->end(false /*didModify*/);
3239 }
3240 }
3241 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3242
3243 if (!(previousCommand & FastMixerState::IDLE)) {
3244 ALOG_ASSERT(mFastMixer != 0);
3245 FastMixerStateQueue *sq = mFastMixer->sq();
3246 FastMixerState *state = sq->begin();
3247 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3248 state->mCommand = previousCommand;
3249 sq->end();
3250 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3251 }
3252
3253 return status;
3254}
3255
Eric Laurent1c333e22014-05-20 10:48:17 -07003256status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3257 audio_patch_handle_t *handle)
3258{
3259 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003260
3261 // store new device and send to effects
3262 audio_devices_t type = AUDIO_DEVICE_NONE;
3263 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3264 type |= patch->sinks[i].ext.device.type;
3265 }
3266
3267#ifdef ADD_BATTERY_DATA
3268 // when changing the audio output device, call addBatteryData to notify
3269 // the change
3270 if (mOutDevice != type) {
3271 uint32_t params = 0;
3272 // check whether speaker is on
3273 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3274 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003275 }
3276
Eric Laurent054d9d32015-04-24 08:48:48 -07003277 audio_devices_t deviceWithoutSpeaker
3278 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3279 // check if any other device (except speaker) is on
3280 if (type & deviceWithoutSpeaker) {
3281 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3282 }
3283
3284 if (params != 0) {
3285 addBatteryData(params);
3286 }
3287 }
3288#endif
3289
3290 for (size_t i = 0; i < mEffectChains.size(); i++) {
3291 mEffectChains[i]->setDevice_l(type);
3292 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003293
3294 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3295 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3296 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003297 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003298 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003299
3300 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003301 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3302 status = hwDevice->create_audio_patch(hwDevice,
3303 patch->num_sources,
3304 patch->sources,
3305 patch->num_sinks,
3306 patch->sinks,
3307 handle);
3308 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003309 char *address;
3310 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3311 //FIXME: we only support address on first sink with HAL version < 3.0
3312 address = audio_device_address_to_parameter(
3313 patch->sinks[0].ext.device.type,
3314 patch->sinks[0].ext.device.address);
3315 } else {
3316 address = (char *)calloc(1, 1);
3317 }
3318 AudioParameter param = AudioParameter(String8(address));
3319 free(address);
3320 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3321 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3322 param.toString().string());
3323 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003324 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003325 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003326 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003327 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3328 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003329 return status;
3330}
3331
Eric Laurent054d9d32015-04-24 08:48:48 -07003332status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3333{
3334 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3335 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3336 if (mFastMixer != 0) {
3337 FastMixerStateQueue *sq = mFastMixer->sq();
3338 FastMixerState *state = sq->begin();
3339 if (!(state->mCommand & FastMixerState::IDLE)) {
3340 previousCommand = state->mCommand;
3341 state->mCommand = FastMixerState::HOT_IDLE;
3342 sq->end();
3343 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3344 } else {
3345 sq->end(false /*didModify*/);
3346 }
3347 }
3348
3349 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3350
3351 if (!(previousCommand & FastMixerState::IDLE)) {
3352 ALOG_ASSERT(mFastMixer != 0);
3353 FastMixerStateQueue *sq = mFastMixer->sq();
3354 FastMixerState *state = sq->begin();
3355 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3356 state->mCommand = previousCommand;
3357 sq->end();
3358 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3359 }
3360
3361 return status;
3362}
3363
Eric Laurent1c333e22014-05-20 10:48:17 -07003364status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3365{
3366 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003367
3368 mOutDevice = AUDIO_DEVICE_NONE;
3369
Eric Laurent1c333e22014-05-20 10:48:17 -07003370 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3371 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3372 status = hwDevice->release_audio_patch(hwDevice, handle);
3373 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003374 AudioParameter param;
3375 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3376 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3377 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003378 }
3379 return status;
3380}
3381
Eric Laurent83b88082014-06-20 18:31:16 -07003382void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3383{
3384 Mutex::Autolock _l(mLock);
3385 mTracks.add(track);
3386}
3387
3388void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3389{
3390 Mutex::Autolock _l(mLock);
3391 destroyTrack_l(track);
3392}
3393
3394void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3395{
3396 ThreadBase::getAudioPortConfig(config);
3397 config->role = AUDIO_PORT_ROLE_SOURCE;
3398 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3399 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3400}
3401
Eric Laurent81784c32012-11-19 14:55:58 -08003402// ----------------------------------------------------------------------------
3403
3404AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003405 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3406 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003407 // mAudioMixer below
3408 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003409 mFastMixerFutex(0),
3410 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003411 // mOutputSink below
3412 // mPipeSink below
3413 // mNormalSink below
3414{
3415 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003416 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003417 "mFrameCount=%d, mNormalFrameCount=%d",
3418 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3419 mNormalFrameCount);
3420 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3421
Andy Hungfbfc3952015-01-15 13:33:51 -08003422 if (type == DUPLICATING) {
3423 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3424 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3425 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3426 return;
3427 }
Eric Laurent81784c32012-11-19 14:55:58 -08003428 // create an NBAIO sink for the HAL output stream, and negotiate
3429 mOutputSink = new AudioStreamOutSink(output->stream);
3430 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003431 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003432 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3433 ALOG_ASSERT(index == 0);
3434
3435 // initialize fast mixer depending on configuration
3436 bool initFastMixer;
3437 switch (kUseFastMixer) {
3438 case FastMixer_Never:
3439 initFastMixer = false;
3440 break;
3441 case FastMixer_Always:
3442 initFastMixer = true;
3443 break;
3444 case FastMixer_Static:
3445 case FastMixer_Dynamic:
3446 initFastMixer = mFrameCount < mNormalFrameCount;
3447 break;
3448 }
3449 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003450 audio_format_t fastMixerFormat;
3451 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3452 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3453 } else {
3454 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3455 }
3456 if (mFormat != fastMixerFormat) {
3457 // change our Sink format to accept our intermediate precision
3458 mFormat = fastMixerFormat;
3459 free(mSinkBuffer);
3460 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3461 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3462 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3463 }
Eric Laurent81784c32012-11-19 14:55:58 -08003464
3465 // create a MonoPipe to connect our submix to FastMixer
3466 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003467 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003468 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003469 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003470 format.mFormat = fastMixerFormat;
3471 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3472
Eric Laurent81784c32012-11-19 14:55:58 -08003473 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3474 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3475 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3476 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3477 const NBAIO_Format offers[1] = {format};
3478 size_t numCounterOffers = 0;
3479 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3480 ALOG_ASSERT(index == 0);
3481 monoPipe->setAvgFrames((mScreenState & 1) ?
3482 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3483 mPipeSink = monoPipe;
3484
Glenn Kasten46909e72013-02-26 09:20:22 -08003485#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003486 if (mTeeSinkOutputEnabled) {
3487 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003488 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3489 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003490 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003491 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003492 ALOG_ASSERT(index == 0);
3493 mTeeSink = teeSink;
3494 PipeReader *teeSource = new PipeReader(*teeSink);
3495 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003496 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003497 ALOG_ASSERT(index == 0);
3498 mTeeSource = teeSource;
3499 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003500#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003501
3502 // create fast mixer and configure it initially with just one fast track for our submix
3503 mFastMixer = new FastMixer();
3504 FastMixerStateQueue *sq = mFastMixer->sq();
3505#ifdef STATE_QUEUE_DUMP
3506 sq->setObserverDump(&mStateQueueObserverDump);
3507 sq->setMutatorDump(&mStateQueueMutatorDump);
3508#endif
3509 FastMixerState *state = sq->begin();
3510 FastTrack *fastTrack = &state->mFastTracks[0];
3511 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3512 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3513 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003514 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3515 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003516 fastTrack->mGeneration++;
3517 state->mFastTracksGen++;
3518 state->mTrackMask = 1;
3519 // fast mixer will use the HAL output sink
3520 state->mOutputSink = mOutputSink.get();
3521 state->mOutputSinkGen++;
3522 state->mFrameCount = mFrameCount;
3523 state->mCommand = FastMixerState::COLD_IDLE;
3524 // already done in constructor initialization list
3525 //mFastMixerFutex = 0;
3526 state->mColdFutexAddr = &mFastMixerFutex;
3527 state->mColdGen++;
3528 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003529#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003530 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003531#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003532 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3533 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003534 sq->end();
3535 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3536
3537 // start the fast mixer
3538 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3539 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003540 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003541
3542#ifdef AUDIO_WATCHDOG
3543 // create and start the watchdog
3544 mAudioWatchdog = new AudioWatchdog();
3545 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3546 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3547 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003548 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003549#endif
3550
Eric Laurent81784c32012-11-19 14:55:58 -08003551 }
3552
3553 switch (kUseFastMixer) {
3554 case FastMixer_Never:
3555 case FastMixer_Dynamic:
3556 mNormalSink = mOutputSink;
3557 break;
3558 case FastMixer_Always:
3559 mNormalSink = mPipeSink;
3560 break;
3561 case FastMixer_Static:
3562 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3563 break;
3564 }
3565}
3566
3567AudioFlinger::MixerThread::~MixerThread()
3568{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003569 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003570 FastMixerStateQueue *sq = mFastMixer->sq();
3571 FastMixerState *state = sq->begin();
3572 if (state->mCommand == FastMixerState::COLD_IDLE) {
3573 int32_t old = android_atomic_inc(&mFastMixerFutex);
3574 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003575 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003576 }
3577 }
3578 state->mCommand = FastMixerState::EXIT;
3579 sq->end();
3580 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3581 mFastMixer->join();
3582 // Though the fast mixer thread has exited, it's state queue is still valid.
3583 // We'll use that extract the final state which contains one remaining fast track
3584 // corresponding to our sub-mix.
3585 state = sq->begin();
3586 ALOG_ASSERT(state->mTrackMask == 1);
3587 FastTrack *fastTrack = &state->mFastTracks[0];
3588 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3589 delete fastTrack->mBufferProvider;
3590 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003591 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003592#ifdef AUDIO_WATCHDOG
3593 if (mAudioWatchdog != 0) {
3594 mAudioWatchdog->requestExit();
3595 mAudioWatchdog->requestExitAndWait();
3596 mAudioWatchdog.clear();
3597 }
3598#endif
3599 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003600 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003601 delete mAudioMixer;
3602}
3603
3604
3605uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3606{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003607 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003608 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3609 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3610 }
3611 return latency;
3612}
3613
3614
3615void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3616{
3617 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3618}
3619
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003621{
3622 // FIXME we should only do one push per cycle; confirm this is true
3623 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003624 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003625 FastMixerStateQueue *sq = mFastMixer->sq();
3626 FastMixerState *state = sq->begin();
3627 if (state->mCommand != FastMixerState::MIX_WRITE &&
3628 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3629 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003630
3631 // FIXME workaround for first HAL write being CPU bound on some devices
3632 ATRACE_BEGIN("write");
3633 mOutput->write((char *)mSinkBuffer, 0);
3634 ATRACE_END();
3635
Eric Laurent81784c32012-11-19 14:55:58 -08003636 int32_t old = android_atomic_inc(&mFastMixerFutex);
3637 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003638 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003639 }
3640#ifdef AUDIO_WATCHDOG
3641 if (mAudioWatchdog != 0) {
3642 mAudioWatchdog->resume();
3643 }
3644#endif
3645 }
3646 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003647#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003648 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003649 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003650#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003651 sq->end();
3652 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3653 if (kUseFastMixer == FastMixer_Dynamic) {
3654 mNormalSink = mPipeSink;
3655 }
3656 } else {
3657 sq->end(false /*didModify*/);
3658 }
3659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003660 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003661}
3662
3663void AudioFlinger::MixerThread::threadLoop_standby()
3664{
3665 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003666 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003667 FastMixerStateQueue *sq = mFastMixer->sq();
3668 FastMixerState *state = sq->begin();
3669 if (!(state->mCommand & FastMixerState::IDLE)) {
3670 state->mCommand = FastMixerState::COLD_IDLE;
3671 state->mColdFutexAddr = &mFastMixerFutex;
3672 state->mColdGen++;
3673 mFastMixerFutex = 0;
3674 sq->end();
3675 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3676 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3677 if (kUseFastMixer == FastMixer_Dynamic) {
3678 mNormalSink = mOutputSink;
3679 }
3680#ifdef AUDIO_WATCHDOG
3681 if (mAudioWatchdog != 0) {
3682 mAudioWatchdog->pause();
3683 }
3684#endif
3685 } else {
3686 sq->end(false /*didModify*/);
3687 }
3688 }
3689 PlaybackThread::threadLoop_standby();
3690}
3691
Eric Laurentbfb1b832013-01-07 09:53:42 -08003692bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3693{
3694 return false;
3695}
3696
3697bool AudioFlinger::PlaybackThread::shouldStandby_l()
3698{
3699 return !mStandby;
3700}
3701
3702bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3703{
3704 Mutex::Autolock _l(mLock);
3705 return waitingAsyncCallback_l();
3706}
3707
Eric Laurent81784c32012-11-19 14:55:58 -08003708// shared by MIXER and DIRECT, overridden by DUPLICATING
3709void AudioFlinger::PlaybackThread::threadLoop_standby()
3710{
3711 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003712 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003713 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003714 // discard any pending drain or write ack by incrementing sequence
3715 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3716 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003718 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3719 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003721 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003722}
3723
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003724void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3725{
3726 ALOGV("signal playback thread");
3727 broadcast_l();
3728}
3729
Eric Laurent81784c32012-11-19 14:55:58 -08003730void AudioFlinger::MixerThread::threadLoop_mix()
3731{
Eric Laurent81784c32012-11-19 14:55:58 -08003732 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003733 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003734 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003735 // increase sleep time progressively when application underrun condition clears.
3736 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3737 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3738 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003739 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003740 sleepTimeShift--;
3741 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003742 mSleepTimeUs = 0;
3743 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003744 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003745
Eric Laurent81784c32012-11-19 14:55:58 -08003746}
3747
3748void AudioFlinger::MixerThread::threadLoop_sleepTime()
3749{
3750 // If no tracks are ready, sleep once for the duration of an output
3751 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003752 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003753 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003754 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3755 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3756 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003757 }
3758 // reduce sleep time in case of consecutive application underruns to avoid
3759 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3760 // duration we would end up writing less data than needed by the audio HAL if
3761 // the condition persists.
3762 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3763 sleepTimeShift++;
3764 }
3765 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003766 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003767 }
3768 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003769 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3770 // before effects processing or output.
3771 if (mMixerBufferValid) {
3772 memset(mMixerBuffer, 0, mMixerBufferSize);
3773 } else {
3774 memset(mSinkBuffer, 0, mSinkBufferSize);
3775 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003776 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003777 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3778 "anticipated start");
3779 }
3780 // TODO add standby time extension fct of effect tail
3781}
3782
3783// prepareTracks_l() must be called with ThreadBase::mLock held
3784AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3785 Vector< sp<Track> > *tracksToRemove)
3786{
3787
3788 mixer_state mixerStatus = MIXER_IDLE;
3789 // find out which tracks need to be processed
3790 size_t count = mActiveTracks.size();
3791 size_t mixedTracks = 0;
3792 size_t tracksWithEffect = 0;
3793 // counts only _active_ fast tracks
3794 size_t fastTracks = 0;
3795 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3796
3797 float masterVolume = mMasterVolume;
3798 bool masterMute = mMasterMute;
3799
3800 if (masterMute) {
3801 masterVolume = 0;
3802 }
3803 // Delegate master volume control to effect in output mix effect chain if needed
3804 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3805 if (chain != 0) {
3806 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3807 chain->setVolume_l(&v, &v);
3808 masterVolume = (float)((v + (1 << 23)) >> 24);
3809 chain.clear();
3810 }
3811
3812 // prepare a new state to push
3813 FastMixerStateQueue *sq = NULL;
3814 FastMixerState *state = NULL;
3815 bool didModify = false;
3816 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003817 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003818 sq = mFastMixer->sq();
3819 state = sq->begin();
3820 }
3821
Andy Hung69aed5f2014-02-25 17:24:40 -08003822 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003823 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003824
Eric Laurent81784c32012-11-19 14:55:58 -08003825 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003826 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003827 if (t == 0) {
3828 continue;
3829 }
3830
3831 // this const just means the local variable doesn't change
3832 Track* const track = t.get();
3833
3834 // process fast tracks
3835 if (track->isFastTrack()) {
3836
3837 // It's theoretically possible (though unlikely) for a fast track to be created
3838 // and then removed within the same normal mix cycle. This is not a problem, as
3839 // the track never becomes active so it's fast mixer slot is never touched.
3840 // The converse, of removing an (active) track and then creating a new track
3841 // at the identical fast mixer slot within the same normal mix cycle,
3842 // is impossible because the slot isn't marked available until the end of each cycle.
3843 int j = track->mFastIndex;
3844 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3845 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3846 FastTrack *fastTrack = &state->mFastTracks[j];
3847
3848 // Determine whether the track is currently in underrun condition,
3849 // and whether it had a recent underrun.
3850 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3851 FastTrackUnderruns underruns = ftDump->mUnderruns;
3852 uint32_t recentFull = (underruns.mBitFields.mFull -
3853 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3854 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3855 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3856 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3857 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3858 uint32_t recentUnderruns = recentPartial + recentEmpty;
3859 track->mObservedUnderruns = underruns;
3860 // don't count underruns that occur while stopping or pausing
3861 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003862 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3863 recentUnderruns > 0) {
3864 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3865 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003866 } else {
3867 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003868 }
3869
3870 // This is similar to the state machine for normal tracks,
3871 // with a few modifications for fast tracks.
3872 bool isActive = true;
3873 switch (track->mState) {
3874 case TrackBase::STOPPING_1:
3875 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003877 track->mState = TrackBase::STOPPING_2;
3878 }
3879 break;
3880 case TrackBase::PAUSING:
3881 // ramp down is not yet implemented
3882 track->setPaused();
3883 break;
3884 case TrackBase::RESUMING:
3885 // ramp up is not yet implemented
3886 track->mState = TrackBase::ACTIVE;
3887 break;
3888 case TrackBase::ACTIVE:
3889 if (recentFull > 0 || recentPartial > 0) {
3890 // track has provided at least some frames recently: reset retry count
3891 track->mRetryCount = kMaxTrackRetries;
3892 }
3893 if (recentUnderruns == 0) {
3894 // no recent underruns: stay active
3895 break;
3896 }
3897 // there has recently been an underrun of some kind
3898 if (track->sharedBuffer() == 0) {
3899 // were any of the recent underruns "empty" (no frames available)?
3900 if (recentEmpty == 0) {
3901 // no, then ignore the partial underruns as they are allowed indefinitely
3902 break;
3903 }
3904 // there has recently been an "empty" underrun: decrement the retry counter
3905 if (--(track->mRetryCount) > 0) {
3906 break;
3907 }
3908 // indicate to client process that the track was disabled because of underrun;
3909 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003910 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003911 // remove from active list, but state remains ACTIVE [confusing but true]
3912 isActive = false;
3913 break;
3914 }
3915 // fall through
3916 case TrackBase::STOPPING_2:
3917 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003918 case TrackBase::STOPPED:
3919 case TrackBase::FLUSHED: // flush() while active
3920 // Check for presentation complete if track is inactive
3921 // We have consumed all the buffers of this track.
3922 // This would be incomplete if we auto-paused on underrun
3923 {
3924 size_t audioHALFrames =
3925 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003926 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003927 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3928 // track stays in active list until presentation is complete
3929 break;
3930 }
3931 }
3932 if (track->isStopping_2()) {
3933 track->mState = TrackBase::STOPPED;
3934 }
3935 if (track->isStopped()) {
3936 // Can't reset directly, as fast mixer is still polling this track
3937 // track->reset();
3938 // So instead mark this track as needing to be reset after push with ack
3939 resetMask |= 1 << i;
3940 }
3941 isActive = false;
3942 break;
3943 case TrackBase::IDLE:
3944 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003945 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003946 }
3947
3948 if (isActive) {
3949 // was it previously inactive?
3950 if (!(state->mTrackMask & (1 << j))) {
3951 ExtendedAudioBufferProvider *eabp = track;
3952 VolumeProvider *vp = track;
3953 fastTrack->mBufferProvider = eabp;
3954 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003956 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003957 fastTrack->mGeneration++;
3958 state->mTrackMask |= 1 << j;
3959 didModify = true;
3960 // no acknowledgement required for newly active tracks
3961 }
3962 // cache the combined master volume and stream type volume for fast mixer; this
3963 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003964 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003965 ++fastTracks;
3966 } else {
3967 // was it previously active?
3968 if (state->mTrackMask & (1 << j)) {
3969 fastTrack->mBufferProvider = NULL;
3970 fastTrack->mGeneration++;
3971 state->mTrackMask &= ~(1 << j);
3972 didModify = true;
3973 // If any fast tracks were removed, we must wait for acknowledgement
3974 // because we're about to decrement the last sp<> on those tracks.
3975 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3976 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003977 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3978 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3979 j, track->mState, state->mTrackMask, recentUnderruns,
3980 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003981 }
3982 tracksToRemove->add(track);
3983 // Avoids a misleading display in dumpsys
3984 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3985 }
3986 continue;
3987 }
3988
3989 { // local variable scope to avoid goto warning
3990
3991 audio_track_cblk_t* cblk = track->cblk();
3992
3993 // The first time a track is added we wait
3994 // for all its buffers to be filled before processing it
3995 int name = track->name();
3996 // make sure that we have enough frames to mix one full buffer.
3997 // enforce this condition only once to enable draining the buffer in case the client
3998 // app does not call stop() and relies on underrun to stop:
3999 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4000 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004001 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004002 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004003 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004004
4005 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004006 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004007 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4008 // add frames already consumed but not yet released by the resampler
4009 // because mAudioTrackServerProxy->framesReady() will include these frames
4010 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4011
Eric Laurent81784c32012-11-19 14:55:58 -08004012 uint32_t minFrames = 1;
4013 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4014 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004015 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004017
4018 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004019 if (ATRACE_ENABLED()) {
4020 // I wish we had formatted trace names
4021 char traceName[16];
4022 strcpy(traceName, "nRdy");
4023 int name = track->name();
4024 if (AudioMixer::TRACK0 <= name &&
4025 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4026 name -= AudioMixer::TRACK0;
4027 traceName[4] = (name / 10) + '0';
4028 traceName[5] = (name % 10) + '0';
4029 } else {
4030 traceName[4] = '?';
4031 traceName[5] = '?';
4032 }
4033 traceName[6] = '\0';
4034 ATRACE_INT(traceName, framesReady);
4035 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004036 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004037 !track->isPaused() && !track->isTerminated())
4038 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004039 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004040
4041 mixedTracks++;
4042
Andy Hung69aed5f2014-02-25 17:24:40 -08004043 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4044 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004045 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004046 if (track->mainBuffer() != mSinkBuffer &&
4047 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004048 if (mEffectBufferEnabled) {
4049 mEffectBufferValid = true; // Later can set directly.
4050 }
Eric Laurent81784c32012-11-19 14:55:58 -08004051 chain = getEffectChain_l(track->sessionId());
4052 // Delegate volume control to effect in track effect chain if needed
4053 if (chain != 0) {
4054 tracksWithEffect++;
4055 } else {
4056 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4057 "session %d",
4058 name, track->sessionId());
4059 }
4060 }
4061
4062
4063 int param = AudioMixer::VOLUME;
4064 if (track->mFillingUpStatus == Track::FS_FILLED) {
4065 // no ramp for the first volume setting
4066 track->mFillingUpStatus = Track::FS_ACTIVE;
4067 if (track->mState == TrackBase::RESUMING) {
4068 track->mState = TrackBase::ACTIVE;
4069 param = AudioMixer::RAMP_VOLUME;
4070 }
4071 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004072 // FIXME should not make a decision based on mServer
4073 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 // If the track is stopped before the first frame was mixed,
4075 // do not apply ramp
4076 param = AudioMixer::RAMP_VOLUME;
4077 }
4078
4079 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004080 uint32_t vl, vr; // in U8.24 integer format
4081 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004082 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004083 vl = vr = 0;
4084 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004085 if (track->isPausing()) {
4086 track->setPaused();
4087 }
4088 } else {
4089
4090 // read original volumes with volume control
4091 float typeVolume = mStreamTypes[track->streamType()].volume;
4092 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004093 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004094 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004095 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4096 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004097 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004098 if (vlf > GAIN_FLOAT_UNITY) {
4099 ALOGV("Track left volume out of range: %.3g", vlf);
4100 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004101 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004102 if (vrf > GAIN_FLOAT_UNITY) {
4103 ALOGV("Track right volume out of range: %.3g", vrf);
4104 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004105 }
4106 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004107 vlf *= v;
4108 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004109 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004110 // then derive vl and vr as U8.24 versions for the effect chain
4111 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4112 vl = (uint32_t) (scaleto8_24 * vlf);
4113 vr = (uint32_t) (scaleto8_24 * vrf);
4114 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004115 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004116 // send level comes from shared memory and so may be corrupt
4117 if (sendLevel > MAX_GAIN_INT) {
4118 ALOGV("Track send level out of range: %04X", sendLevel);
4119 sendLevel = MAX_GAIN_INT;
4120 }
Andy Hung6be49402014-05-30 10:42:03 -07004121 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4122 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004123 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004124
Eric Laurent81784c32012-11-19 14:55:58 -08004125 // Delegate volume control to effect in track effect chain if needed
4126 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4127 // Do not ramp volume if volume is controlled by effect
4128 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004129 // Update remaining floating point volume levels
4130 vlf = (float)vl / (1 << 24);
4131 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004132 track->mHasVolumeController = true;
4133 } else {
4134 // force no volume ramp when volume controller was just disabled or removed
4135 // from effect chain to avoid volume spike
4136 if (track->mHasVolumeController) {
4137 param = AudioMixer::VOLUME;
4138 }
4139 track->mHasVolumeController = false;
4140 }
4141
Eric Laurent81784c32012-11-19 14:55:58 -08004142 // XXX: these things DON'T need to be done each time
4143 mAudioMixer->setBufferProvider(name, track);
4144 mAudioMixer->enable(name);
4145
Andy Hung6be49402014-05-30 10:42:03 -07004146 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4147 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4148 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004149 mAudioMixer->setParameter(
4150 name,
4151 AudioMixer::TRACK,
4152 AudioMixer::FORMAT, (void *)track->format());
4153 mAudioMixer->setParameter(
4154 name,
4155 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004156 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004157 mAudioMixer->setParameter(
4158 name,
4159 AudioMixer::TRACK,
4160 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004161 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004162 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004163 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004164 if (reqSampleRate == 0) {
4165 reqSampleRate = mSampleRate;
4166 } else if (reqSampleRate > maxSampleRate) {
4167 reqSampleRate = maxSampleRate;
4168 }
Eric Laurent81784c32012-11-19 14:55:58 -08004169 mAudioMixer->setParameter(
4170 name,
4171 AudioMixer::RESAMPLE,
4172 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004173 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004174
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004175 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004176 mAudioMixer->setParameter(
4177 name,
4178 AudioMixer::TIMESTRETCH,
4179 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004180 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004181
Andy Hung69aed5f2014-02-25 17:24:40 -08004182 /*
4183 * Select the appropriate output buffer for the track.
4184 *
Andy Hung98ef9782014-03-04 14:46:50 -08004185 * Tracks with effects go into their own effects chain buffer
4186 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004187 *
4188 * Other tracks can use mMixerBuffer for higher precision
4189 * channel accumulation. If this buffer is enabled
4190 * (mMixerBufferEnabled true), then selected tracks will accumulate
4191 * into it.
4192 *
4193 */
4194 if (mMixerBufferEnabled
4195 && (track->mainBuffer() == mSinkBuffer
4196 || track->mainBuffer() == mMixerBuffer)) {
4197 mAudioMixer->setParameter(
4198 name,
4199 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004200 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004201 mAudioMixer->setParameter(
4202 name,
4203 AudioMixer::TRACK,
4204 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4205 // TODO: override track->mainBuffer()?
4206 mMixerBufferValid = true;
4207 } else {
4208 mAudioMixer->setParameter(
4209 name,
4210 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004211 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004212 mAudioMixer->setParameter(
4213 name,
4214 AudioMixer::TRACK,
4215 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4216 }
Eric Laurent81784c32012-11-19 14:55:58 -08004217 mAudioMixer->setParameter(
4218 name,
4219 AudioMixer::TRACK,
4220 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4221
4222 // reset retry count
4223 track->mRetryCount = kMaxTrackRetries;
4224
4225 // If one track is ready, set the mixer ready if:
4226 // - the mixer was not ready during previous round OR
4227 // - no other track is not ready
4228 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4229 mixerStatus != MIXER_TRACKS_ENABLED) {
4230 mixerStatus = MIXER_TRACKS_READY;
4231 }
4232 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004233 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004234 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4235 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004236 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004237 } else {
4238 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004239 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004240
Eric Laurent81784c32012-11-19 14:55:58 -08004241 // clear effect chain input buffer if an active track underruns to avoid sending
4242 // previous audio buffer again to effects
4243 chain = getEffectChain_l(track->sessionId());
4244 if (chain != 0) {
4245 chain->clearInputBuffer();
4246 }
4247
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004248 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004249 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4250 track->isStopped() || track->isPaused()) {
4251 // We have consumed all the buffers of this track.
4252 // Remove it from the list of active tracks.
4253 // TODO: use actual buffer filling status instead of latency when available from
4254 // audio HAL
4255 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004256 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004257 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4258 if (track->isStopped()) {
4259 track->reset();
4260 }
4261 tracksToRemove->add(track);
4262 }
4263 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004264 // No buffers for this track. Give it a few chances to
4265 // fill a buffer, then remove it from active list.
4266 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004267 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004268 tracksToRemove->add(track);
4269 // indicate to client process that the track was disabled because of underrun;
4270 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004271 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004272 // If one track is not ready, mark the mixer also not ready if:
4273 // - the mixer was ready during previous round OR
4274 // - no other track is ready
4275 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4276 mixerStatus != MIXER_TRACKS_READY) {
4277 mixerStatus = MIXER_TRACKS_ENABLED;
4278 }
4279 }
4280 mAudioMixer->disable(name);
4281 }
4282
4283 } // local variable scope to avoid goto warning
4284track_is_ready: ;
4285
4286 }
4287
4288 // Push the new FastMixer state if necessary
4289 bool pauseAudioWatchdog = false;
4290 if (didModify) {
4291 state->mFastTracksGen++;
4292 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4293 if (kUseFastMixer == FastMixer_Dynamic &&
4294 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4295 state->mCommand = FastMixerState::COLD_IDLE;
4296 state->mColdFutexAddr = &mFastMixerFutex;
4297 state->mColdGen++;
4298 mFastMixerFutex = 0;
4299 if (kUseFastMixer == FastMixer_Dynamic) {
4300 mNormalSink = mOutputSink;
4301 }
4302 // If we go into cold idle, need to wait for acknowledgement
4303 // so that fast mixer stops doing I/O.
4304 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4305 pauseAudioWatchdog = true;
4306 }
Eric Laurent81784c32012-11-19 14:55:58 -08004307 }
4308 if (sq != NULL) {
4309 sq->end(didModify);
4310 sq->push(block);
4311 }
4312#ifdef AUDIO_WATCHDOG
4313 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4314 mAudioWatchdog->pause();
4315 }
4316#endif
4317
4318 // Now perform the deferred reset on fast tracks that have stopped
4319 while (resetMask != 0) {
4320 size_t i = __builtin_ctz(resetMask);
4321 ALOG_ASSERT(i < count);
4322 resetMask &= ~(1 << i);
4323 sp<Track> t = mActiveTracks[i].promote();
4324 if (t == 0) {
4325 continue;
4326 }
4327 Track* track = t.get();
4328 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4329 track->reset();
4330 }
4331
4332 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004334
Eric Laurent97d547d2014-09-02 14:45:53 -07004335 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4336 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004337 }
4338
4339 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004340 // as long as there are effects we should clear the effects buffer, to avoid
4341 // passing a non-clean buffer to the effect chain
4342 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004343 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004344 // sink or mix buffer must be cleared if all tracks are connected to an
4345 // effect chain as in this case the mixer will not write to the sink or mix buffer
4346 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4348 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004349 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004350 if (mMixerBufferValid) {
4351 memset(mMixerBuffer, 0, mMixerBufferSize);
4352 // TODO: In testing, mSinkBuffer below need not be cleared because
4353 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4354 // after mixing.
4355 //
4356 // To enforce this guarantee:
4357 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4358 // (mixedTracks == 0 && fastTracks > 0))
4359 // must imply MIXER_TRACKS_READY.
4360 // Later, we may clear buffers regardless, and skip much of this logic.
4361 }
Andy Hung98ef9782014-03-04 14:46:50 -08004362 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004363 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004364 }
4365
4366 // if any fast tracks, then status is ready
4367 mMixerStatusIgnoringFastTracks = mixerStatus;
4368 if (fastTracks > 0) {
4369 mixerStatus = MIXER_TRACKS_READY;
4370 }
4371 return mixerStatus;
4372}
4373
4374// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004375int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4376 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004377{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004378 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004379}
4380
4381// deleteTrackName_l() must be called with ThreadBase::mLock held
4382void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4383{
4384 ALOGV("remove track (%d) and delete from mixer", name);
4385 mAudioMixer->deleteTrackName(name);
4386}
4387
Eric Laurent10351942014-05-08 18:49:52 -07004388// checkForNewParameter_l() must be called with ThreadBase::mLock held
4389bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4390 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004391{
Eric Laurent81784c32012-11-19 14:55:58 -08004392 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004393 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004394
Eric Laurent10351942014-05-08 18:49:52 -07004395 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004396
Eric Laurent10351942014-05-08 18:49:52 -07004397 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4398 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004399 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004400 FastMixerStateQueue *sq = mFastMixer->sq();
4401 FastMixerState *state = sq->begin();
4402 if (!(state->mCommand & FastMixerState::IDLE)) {
4403 previousCommand = state->mCommand;
4404 state->mCommand = FastMixerState::HOT_IDLE;
4405 sq->end();
4406 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4407 } else {
4408 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004409 }
Eric Laurent10351942014-05-08 18:49:52 -07004410 }
Eric Laurent81784c32012-11-19 14:55:58 -08004411
Eric Laurent10351942014-05-08 18:49:52 -07004412 AudioParameter param = AudioParameter(keyValuePair);
4413 int value;
4414 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4415 reconfig = true;
4416 }
4417 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004418 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004419 status = BAD_VALUE;
4420 } else {
4421 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004422 reconfig = true;
4423 }
Eric Laurent10351942014-05-08 18:49:52 -07004424 }
4425 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004426 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004427 status = BAD_VALUE;
4428 } else {
4429 // no need to save value, since it's constant
4430 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004431 }
Eric Laurent10351942014-05-08 18:49:52 -07004432 }
4433 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4434 // do not accept frame count changes if tracks are open as the track buffer
4435 // size depends on frame count and correct behavior would not be guaranteed
4436 // if frame count is changed after track creation
4437 if (!mTracks.isEmpty()) {
4438 status = INVALID_OPERATION;
4439 } else {
4440 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004441 }
Eric Laurent10351942014-05-08 18:49:52 -07004442 }
4443 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004444#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004445 // when changing the audio output device, call addBatteryData to notify
4446 // the change
4447 if (mOutDevice != value) {
4448 uint32_t params = 0;
4449 // check whether speaker is on
4450 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4451 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004452 }
Eric Laurent10351942014-05-08 18:49:52 -07004453
4454 audio_devices_t deviceWithoutSpeaker
4455 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4456 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004457 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004458 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4459 }
4460
4461 if (params != 0) {
4462 addBatteryData(params);
4463 }
4464 }
Eric Laurent81784c32012-11-19 14:55:58 -08004465#endif
4466
Eric Laurent10351942014-05-08 18:49:52 -07004467 // forward device change to effects that have requested to be
4468 // aware of attached audio device.
4469 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004470 a2dpDeviceChanged =
4471 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004472 mOutDevice = value;
4473 for (size_t i = 0; i < mEffectChains.size(); i++) {
4474 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004475 }
4476 }
Eric Laurent10351942014-05-08 18:49:52 -07004477 }
Eric Laurent81784c32012-11-19 14:55:58 -08004478
Eric Laurent10351942014-05-08 18:49:52 -07004479 if (status == NO_ERROR) {
4480 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4481 keyValuePair.string());
4482 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004483 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004484 mStandby = true;
4485 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004486 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004487 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004488 }
Eric Laurent10351942014-05-08 18:49:52 -07004489 if (status == NO_ERROR && reconfig) {
4490 readOutputParameters_l();
4491 delete mAudioMixer;
4492 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4493 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004494 int name = getTrackName_l(mTracks[i]->mChannelMask,
4495 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004496 if (name < 0) {
4497 break;
4498 }
4499 mTracks[i]->mName = name;
4500 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004501 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004502 }
Eric Laurent81784c32012-11-19 14:55:58 -08004503 }
4504
4505 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004506 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004507 FastMixerStateQueue *sq = mFastMixer->sq();
4508 FastMixerState *state = sq->begin();
4509 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4510 state->mCommand = previousCommand;
4511 sq->end();
4512 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4513 }
4514
Eric Laurent42537be2016-01-08 17:16:42 -08004515 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004516}
4517
4518
4519void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4520{
4521 const size_t SIZE = 256;
4522 char buffer[SIZE];
4523 String8 result;
4524
4525 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004526 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004527 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004528 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004529
4530 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004531 // while we are dumping it. It may be inconsistent, but it won't mutate!
4532 // This is a large object so we place it on the heap.
4533 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4534 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4535 copy->dump(fd);
4536 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004537
4538#ifdef STATE_QUEUE_DUMP
4539 // Similar for state queue
4540 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4541 observerCopy.dump(fd);
4542 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4543 mutatorCopy.dump(fd);
4544#endif
4545
Glenn Kasten46909e72013-02-26 09:20:22 -08004546#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004547 // Write the tee output to a .wav file
4548 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004549#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004550
4551#ifdef AUDIO_WATCHDOG
4552 if (mAudioWatchdog != 0) {
4553 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4554 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4555 wdCopy.dump(fd);
4556 }
4557#endif
4558}
4559
4560uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4561{
4562 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4563}
4564
4565uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4566{
4567 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4568}
4569
4570void AudioFlinger::MixerThread::cacheParameters_l()
4571{
4572 PlaybackThread::cacheParameters_l();
4573
4574 // FIXME: Relaxed timing because of a certain device that can't meet latency
4575 // Should be reduced to 2x after the vendor fixes the driver issue
4576 // increase threshold again due to low power audio mode. The way this warning
4577 // threshold is calculated and its usefulness should be reconsidered anyway.
4578 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4579}
4580
4581// ----------------------------------------------------------------------------
4582
4583AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004584 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4585 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004586 // mLeftVolFloat, mRightVolFloat
4587{
4588}
4589
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4591 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004592 ThreadBase::type_t type, bool systemReady)
4593 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004594 // mLeftVolFloat, mRightVolFloat
4595{
4596}
4597
Eric Laurent81784c32012-11-19 14:55:58 -08004598AudioFlinger::DirectOutputThread::~DirectOutputThread()
4599{
4600}
4601
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4603{
4604 audio_track_cblk_t* cblk = track->cblk();
4605 float left, right;
4606
4607 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4608 left = right = 0;
4609 } else {
4610 float typeVolume = mStreamTypes[track->streamType()].volume;
4611 float v = mMasterVolume * typeVolume;
4612 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004613 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4614 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4615 if (left > GAIN_FLOAT_UNITY) {
4616 left = GAIN_FLOAT_UNITY;
4617 }
4618 left *= v;
4619 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4620 if (right > GAIN_FLOAT_UNITY) {
4621 right = GAIN_FLOAT_UNITY;
4622 }
4623 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004624 }
4625
4626 if (lastTrack) {
4627 if (left != mLeftVolFloat || right != mRightVolFloat) {
4628 mLeftVolFloat = left;
4629 mRightVolFloat = right;
4630
4631 // Convert volumes from float to 8.24
4632 uint32_t vl = (uint32_t)(left * (1 << 24));
4633 uint32_t vr = (uint32_t)(right * (1 << 24));
4634
4635 // Delegate volume control to effect in track effect chain if needed
4636 // only one effect chain can be present on DirectOutputThread, so if
4637 // there is one, the track is connected to it
4638 if (!mEffectChains.isEmpty()) {
4639 mEffectChains[0]->setVolume_l(&vl, &vr);
4640 left = (float)vl / (1 << 24);
4641 right = (float)vr / (1 << 24);
4642 }
4643 if (mOutput->stream->set_volume) {
4644 mOutput->stream->set_volume(mOutput->stream, left, right);
4645 }
4646 }
4647 }
4648}
4649
Phil Burk43b4dcc2015-06-09 16:53:44 -07004650void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4651{
4652 sp<Track> previousTrack = mPreviousTrack.promote();
4653 sp<Track> latestTrack = mLatestActiveTrack.promote();
4654
Eric Laurent0f0631e2015-07-06 18:01:25 -07004655 if (previousTrack != 0 && latestTrack != 0) {
4656 if (mType == DIRECT) {
4657 if (previousTrack.get() != latestTrack.get()) {
4658 mFlushPending = true;
4659 }
4660 } else /* mType == OFFLOAD */ {
4661 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4662 mFlushPending = true;
4663 }
4664 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004665 }
4666 PlaybackThread::onAddNewTrack_l();
4667}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668
Eric Laurent81784c32012-11-19 14:55:58 -08004669AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4670 Vector< sp<Track> > *tracksToRemove
4671)
4672{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004673 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004674 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004675 bool doHwPause = false;
4676 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004677
4678 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004679 for (size_t i = 0; i < count; i++) {
4680 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004681 // The track died recently
4682 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004683 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004684 }
4685
Phil Burk43b4dcc2015-06-09 16:53:44 -07004686 if (t->isInvalid()) {
4687 ALOGW("An invalidated track shouldn't be in active list");
4688 tracksToRemove->add(t);
4689 continue;
4690 }
4691
Eric Laurent81784c32012-11-19 14:55:58 -08004692 Track* const track = t.get();
4693 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004694 // Only consider last track started for volume and mixer state control.
4695 // In theory an older track could underrun and restart after the new one starts
4696 // but as we only care about the transition phase between two tracks on a
4697 // direct output, it is not a problem to ignore the underrun case.
4698 sp<Track> l = mLatestActiveTrack.promote();
4699 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004700
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004701 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004702 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004703 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004704 doHwPause = true;
4705 mHwPaused = true;
4706 }
4707 tracksToRemove->add(track);
4708 } else if (track->isFlushPending()) {
4709 track->flushAck();
4710 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004711 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004712 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004713 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004715 if (last && mHwPaused) {
4716 doHwResume = true;
4717 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004718 }
4719 }
4720
Eric Laurent81784c32012-11-19 14:55:58 -08004721 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004722 // for all its buffers to be filled before processing it.
4723 // Allow draining the buffer in case the client
4724 // app does not call stop() and relies on underrun to stop:
4725 // hence the test on (track->mRetryCount > 1).
4726 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004727 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004728 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004729 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004730 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004731 minFrames = mNormalFrameCount;
4732 } else {
4733 minFrames = 1;
4734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735
Eric Laurentab5cdba2014-06-09 17:22:27 -07004736 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4737 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004738 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004739 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004740
4741 if (track->mFillingUpStatus == Track::FS_FILLED) {
4742 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004743 // make sure processVolume_l() will apply new volume even if 0
4744 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004745 if (!mHwSupportsPause) {
4746 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004747 }
4748 }
4749
4750 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004751 processVolume_l(track, last);
4752 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004753 sp<Track> previousTrack = mPreviousTrack.promote();
4754 if (previousTrack != 0) {
4755 if (track != previousTrack.get()) {
4756 // Flush any data still being written from last track
4757 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004758 // Invalidate previous track to force a seek when resuming.
4759 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004760 }
4761 }
4762 mPreviousTrack = track;
4763
Eric Laurentd595b7c2013-04-03 17:27:56 -07004764 // reset retry count
4765 track->mRetryCount = kMaxTrackRetriesDirect;
4766 mActiveTrack = t;
4767 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004768 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004769 doHwResume = true;
4770 mHwPaused = false;
4771 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004772 }
Eric Laurent81784c32012-11-19 14:55:58 -08004773 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004774 // clear effect chain input buffer if the last active track started underruns
4775 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004776 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004777 mEffectChains[0]->clearInputBuffer();
4778 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004779 if (track->isStopping_1()) {
4780 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004781 if (last && mHwPaused) {
4782 doHwResume = true;
4783 mHwPaused = false;
4784 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004785 }
4786 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4787 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004788 // We have consumed all the buffers of this track.
4789 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004790 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004791 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004792 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4793 } else {
4794 audioHALFrames = 0;
4795 }
4796
Andy Hung818e7a32016-02-16 18:08:07 -08004797 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004798 if (mStandby || !last ||
4799 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004800 if (track->isStopping_2()) {
4801 track->mState = TrackBase::STOPPED;
4802 }
Eric Laurent81784c32012-11-19 14:55:58 -08004803 if (track->isStopped()) {
4804 track->reset();
4805 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004806 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004807 }
4808 } else {
4809 // No buffers for this track. Give it a few chances to
4810 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004811 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004812 if (--(track->mRetryCount) <= 0) {
4813 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004814 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004815 // indicate to client process that the track was disabled because of underrun;
4816 // it will then automatically call start() when data is available
4817 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004818 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004819 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4820 "minFrames = %u, mFormat = %#x",
4821 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004822 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004823 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004824 doHwPause = true;
4825 mHwPaused = true;
4826 }
Eric Laurent81784c32012-11-19 14:55:58 -08004827 }
4828 }
4829 }
4830 }
4831
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004833 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004834 for (size_t i = 0; i < mTracks.size(); i++) {
4835 if (mTracks[i]->isFlushPending()) {
4836 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004837 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004838 }
4839 }
4840 }
4841
4842 // make sure the pause/flush/resume sequence is executed in the right order.
4843 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4844 // before flush and then resume HW. This can happen in case of pause/flush/resume
4845 // if resume is received before pause is executed.
4846 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004847 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004848 mOutput->stream->pause(mOutput->stream);
4849 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004850 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004851 flushHw_l();
4852 }
4853 if (mHwSupportsPause && !mStandby && doHwResume) {
4854 mOutput->stream->resume(mOutput->stream);
4855 }
Eric Laurent81784c32012-11-19 14:55:58 -08004856 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004857 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004858
4859 return mixerStatus;
4860}
4861
4862void AudioFlinger::DirectOutputThread::threadLoop_mix()
4863{
Eric Laurent81784c32012-11-19 14:55:58 -08004864 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004865 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004866 // output audio to hardware
4867 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004868 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004869 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004870 status_t status = mActiveTrack->getNextBuffer(&buffer);
4871 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004872 memset(curBuf, 0, frameCount * mFrameSize);
4873 break;
4874 }
4875 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4876 frameCount -= buffer.frameCount;
4877 curBuf += buffer.frameCount * mFrameSize;
4878 mActiveTrack->releaseBuffer(&buffer);
4879 }
Andy Hung2098f272014-02-27 14:00:06 -08004880 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004881 mSleepTimeUs = 0;
4882 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004883 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004884}
4885
4886void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4887{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004888 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004889 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004890 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004891 return;
4892 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004893 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004894 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004897 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004898 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004899 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004900 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004901 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004902 }
4903}
4904
Eric Laurentd1f69b02014-12-15 14:33:13 -08004905void AudioFlinger::DirectOutputThread::threadLoop_exit()
4906{
4907 {
4908 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004909 for (size_t i = 0; i < mTracks.size(); i++) {
4910 if (mTracks[i]->isFlushPending()) {
4911 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004912 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004913 }
4914 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004915 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004916 flushHw_l();
4917 }
4918 }
4919 PlaybackThread::threadLoop_exit();
4920}
4921
4922// must be called with thread mutex locked
4923bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4924{
4925 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004926 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004927
4928 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4929 // after a timeout and we will enter standby then.
4930 if (mTracks.size() > 0) {
4931 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004932 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4933 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004934 }
4935
Eric Laurent5cff4032015-05-26 13:49:58 -07004936 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004937}
4938
Eric Laurent81784c32012-11-19 14:55:58 -08004939// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004940int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004941 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004942{
4943 return 0;
4944}
4945
4946// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004947void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004948{
4949}
4950
Eric Laurent10351942014-05-08 18:49:52 -07004951// checkForNewParameter_l() must be called with ThreadBase::mLock held
4952bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4953 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004954{
4955 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004956 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004957
Eric Laurent10351942014-05-08 18:49:52 -07004958 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004959
Eric Laurent10351942014-05-08 18:49:52 -07004960 AudioParameter param = AudioParameter(keyValuePair);
4961 int value;
4962 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4963 // forward device change to effects that have requested to be
4964 // aware of attached audio device.
4965 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004966 a2dpDeviceChanged =
4967 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004968 mOutDevice = value;
4969 for (size_t i = 0; i < mEffectChains.size(); i++) {
4970 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004971 }
4972 }
Eric Laurent81784c32012-11-19 14:55:58 -08004973 }
Eric Laurent10351942014-05-08 18:49:52 -07004974 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4975 // do not accept frame count changes if tracks are open as the track buffer
4976 // size depends on frame count and correct behavior would not be garantied
4977 // if frame count is changed after track creation
4978 if (!mTracks.isEmpty()) {
4979 status = INVALID_OPERATION;
4980 } else {
4981 reconfig = true;
4982 }
4983 }
4984 if (status == NO_ERROR) {
4985 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4986 keyValuePair.string());
4987 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004988 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004989 mStandby = true;
4990 mBytesWritten = 0;
4991 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4992 keyValuePair.string());
4993 }
4994 if (status == NO_ERROR && reconfig) {
4995 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004996 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004997 }
4998 }
4999
Eric Laurent42537be2016-01-08 17:16:42 -08005000 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005001}
5002
5003uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5004{
5005 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005006 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005007 time = PlaybackThread::activeSleepTimeUs();
5008 } else {
5009 time = 10000;
5010 }
5011 return time;
5012}
5013
5014uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5015{
5016 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005017 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005018 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5019 } else {
5020 time = 10000;
5021 }
5022 return time;
5023}
5024
5025uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5026{
5027 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005028 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005029 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5030 } else {
5031 time = 10000;
5032 }
5033 return time;
5034}
5035
5036void AudioFlinger::DirectOutputThread::cacheParameters_l()
5037{
5038 PlaybackThread::cacheParameters_l();
5039
5040 // use shorter standby delay as on normal output to release
5041 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005042 // no delay on outputs with HW A/V sync
5043 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005044 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005045 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005046 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005047 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005048 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005049 }
Eric Laurent81784c32012-11-19 14:55:58 -08005050}
5051
Eric Laurente659ef42014-09-29 13:06:46 -07005052void AudioFlinger::DirectOutputThread::flushHw_l()
5053{
Phil Burk062e67a2015-02-11 13:40:50 -08005054 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005056 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005057}
5058
Eric Laurent81784c32012-11-19 14:55:58 -08005059// ----------------------------------------------------------------------------
5060
Eric Laurentbfb1b832013-01-07 09:53:42 -08005061AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005062 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005063 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005064 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005065 mWriteAckSequence(0),
5066 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067{
5068}
5069
5070AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5071{
5072}
5073
5074void AudioFlinger::AsyncCallbackThread::onFirstRef()
5075{
5076 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5077}
5078
5079bool AudioFlinger::AsyncCallbackThread::threadLoop()
5080{
5081 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005082 uint32_t writeAckSequence;
5083 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005084
5085 {
5086 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005087 while (!((mWriteAckSequence & 1) ||
5088 (mDrainSequence & 1) ||
5089 exitPending())) {
5090 mWaitWorkCV.wait(mLock);
5091 }
5092
Eric Laurentbfb1b832013-01-07 09:53:42 -08005093 if (exitPending()) {
5094 break;
5095 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005096 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5097 mWriteAckSequence, mDrainSequence);
5098 writeAckSequence = mWriteAckSequence;
5099 mWriteAckSequence &= ~1;
5100 drainSequence = mDrainSequence;
5101 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005102 }
5103 {
Eric Laurent4de95592013-09-26 15:28:21 -07005104 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5105 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005106 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005107 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005108 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005109 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005110 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005111 }
5112 }
5113 }
5114 }
5115 return false;
5116}
5117
5118void AudioFlinger::AsyncCallbackThread::exit()
5119{
5120 ALOGV("AsyncCallbackThread::exit");
5121 Mutex::Autolock _l(mLock);
5122 requestExit();
5123 mWaitWorkCV.broadcast();
5124}
5125
Eric Laurent3b4529e2013-09-05 18:09:19 -07005126void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005127{
5128 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005129 // bit 0 is cleared
5130 mWriteAckSequence = sequence << 1;
5131}
5132
5133void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5134{
5135 Mutex::Autolock _l(mLock);
5136 // ignore unexpected callbacks
5137 if (mWriteAckSequence & 2) {
5138 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005139 mWaitWorkCV.signal();
5140 }
5141}
5142
Eric Laurent3b4529e2013-09-05 18:09:19 -07005143void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005144{
5145 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005146 // bit 0 is cleared
5147 mDrainSequence = sequence << 1;
5148}
5149
5150void AudioFlinger::AsyncCallbackThread::resetDraining()
5151{
5152 Mutex::Autolock _l(mLock);
5153 // ignore unexpected callbacks
5154 if (mDrainSequence & 2) {
5155 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005156 mWaitWorkCV.signal();
5157 }
5158}
5159
5160
5161// ----------------------------------------------------------------------------
5162AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005163 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5164 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005165 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166{
Eric Laurentfd477972013-10-25 18:10:40 -07005167 //FIXME: mStandby should be set to true by ThreadBase constructor
5168 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005169}
5170
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171void AudioFlinger::OffloadThread::threadLoop_exit()
5172{
5173 if (mFlushPending || mHwPaused) {
5174 // If a flush is pending or track was paused, just discard buffered data
5175 flushHw_l();
5176 } else {
5177 mMixerStatus = MIXER_DRAIN_ALL;
5178 threadLoop_drain();
5179 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005180 if (mUseAsyncWrite) {
5181 ALOG_ASSERT(mCallbackThread != 0);
5182 mCallbackThread->exit();
5183 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184 PlaybackThread::threadLoop_exit();
5185}
5186
5187AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5188 Vector< sp<Track> > *tracksToRemove
5189)
5190{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005191 size_t count = mActiveTracks.size();
5192
5193 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005194 bool doHwPause = false;
5195 bool doHwResume = false;
5196
Eric Laurentede6c3b2013-09-19 14:37:46 -07005197 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5198
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199 // find out which tracks need to be processed
5200 for (size_t i = 0; i < count; i++) {
5201 sp<Track> t = mActiveTracks[i].promote();
5202 // The track died recently
5203 if (t == 0) {
5204 continue;
5205 }
5206 Track* const track = t.get();
5207 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005208 // Only consider last track started for volume and mixer state control.
5209 // In theory an older track could underrun and restart after the new one starts
5210 // but as we only care about the transition phase between two tracks on a
5211 // direct output, it is not a problem to ignore the underrun case.
5212 sp<Track> l = mLatestActiveTrack.promote();
5213 bool last = l.get() == track;
5214
Haynes Mathew George7844f672014-01-15 12:32:55 -08005215 if (track->isInvalid()) {
5216 ALOGW("An invalidated track shouldn't be in active list");
5217 tracksToRemove->add(track);
5218 continue;
5219 }
5220
5221 if (track->mState == TrackBase::IDLE) {
5222 ALOGW("An idle track shouldn't be in active list");
5223 continue;
5224 }
5225
Eric Laurentbfb1b832013-01-07 09:53:42 -08005226 if (track->isPausing()) {
5227 track->setPaused();
5228 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005229 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005230 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 mHwPaused = true;
5232 }
5233 // If we were part way through writing the mixbuffer to
5234 // the HAL we must save this until we resume
5235 // BUG - this will be wrong if a different track is made active,
5236 // in that case we want to discard the pending data in the
5237 // mixbuffer and tell the client to present it again when the
5238 // track is resumed
5239 mPausedWriteLength = mCurrentWriteLength;
5240 mPausedBytesRemaining = mBytesRemaining;
5241 mBytesRemaining = 0; // stop writing
5242 }
5243 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005244 } else if (track->isFlushPending()) {
5245 track->flushAck();
5246 if (last) {
5247 mFlushPending = true;
5248 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005249 } else if (track->isResumePending()){
5250 track->resumeAck();
5251 if (last) {
5252 if (mPausedBytesRemaining) {
5253 // Need to continue write that was interrupted
5254 mCurrentWriteLength = mPausedWriteLength;
5255 mBytesRemaining = mPausedBytesRemaining;
5256 mPausedBytesRemaining = 0;
5257 }
5258 if (mHwPaused) {
5259 doHwResume = true;
5260 mHwPaused = false;
5261 // threadLoop_mix() will handle the case that we need to
5262 // resume an interrupted write
5263 }
5264 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005265 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005266
5267 // Do not handle new data in this iteration even if track->framesReady()
5268 mixerStatus = MIXER_TRACKS_ENABLED;
5269 }
5270 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005271 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005272 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005273 if (track->mFillingUpStatus == Track::FS_FILLED) {
5274 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005275 // make sure processVolume_l() will apply new volume even if 0
5276 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277 }
5278
5279 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005280 sp<Track> previousTrack = mPreviousTrack.promote();
5281 if (previousTrack != 0) {
5282 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005283 // Flush any data still being written from last track
5284 mBytesRemaining = 0;
5285 if (mPausedBytesRemaining) {
5286 // Last track was paused so we also need to flush saved
5287 // mixbuffer state and invalidate track so that it will
5288 // re-submit that unwritten data when it is next resumed
5289 mPausedBytesRemaining = 0;
5290 // Invalidate is a bit drastic - would be more efficient
5291 // to have a flag to tell client that some of the
5292 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005293 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005294 }
5295 // flush data already sent to the DSP if changing audio session as audio
5296 // comes from a different source. Also invalidate previous track to force a
5297 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005298 if (previousTrack->sessionId() != track->sessionId()) {
5299 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005300 }
5301 }
5302 }
5303 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 // reset retry count
5305 track->mRetryCount = kMaxTrackRetriesOffload;
5306 mActiveTrack = t;
5307 mixerStatus = MIXER_TRACKS_READY;
5308 }
5309 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005310 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 if (track->isStopping_1()) {
5312 // Hardware buffer can hold a large amount of audio so we must
5313 // wait for all current track's data to drain before we say
5314 // that the track is stopped.
5315 if (mBytesRemaining == 0) {
5316 // Only start draining when all data in mixbuffer
5317 // has been written
5318 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5319 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005320 // do not drain if no data was ever sent to HAL (mStandby == true)
5321 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005322 // do not modify drain sequence if we are already draining. This happens
5323 // when resuming from pause after drain.
5324 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005325 mSleepTimeUs = 0;
5326 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005327 mixerStatus = MIXER_DRAIN_TRACK;
5328 mDrainSequence += 2;
5329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005330 if (mHwPaused) {
5331 // It is possible to move from PAUSED to STOPPING_1 without
5332 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005333 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 mHwPaused = false;
5335 }
5336 }
5337 }
5338 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005339 // Drain has completed or we are in standby, signal presentation complete
5340 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 track->mState = TrackBase::STOPPED;
5342 size_t audioHALFrames =
5343 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005344 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005345 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 track->presentationComplete(framesWritten, audioHALFrames);
5347 track->reset();
5348 tracksToRemove->add(track);
5349 }
5350 } else {
5351 // No buffers for this track. Give it a few chances to
5352 // fill a buffer, then remove it from active list.
5353 if (--(track->mRetryCount) <= 0) {
5354 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5355 track->name());
5356 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005357 // indicate to client process that the track was disabled because of underrun;
5358 // it will then automatically call start() when data is available
5359 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360 } else if (last){
5361 mixerStatus = MIXER_TRACKS_ENABLED;
5362 }
5363 }
5364 }
5365 // compute volume for this track
5366 processVolume_l(track, last);
5367 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005368
Eric Laurentea0fade2013-10-04 16:23:48 -07005369 // make sure the pause/flush/resume sequence is executed in the right order.
5370 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5371 // before flush and then resume HW. This can happen in case of pause/flush/resume
5372 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005373 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005374 mOutput->stream->pause(mOutput->stream);
5375 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005376 if (mFlushPending) {
5377 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005378 }
Eric Laurentfd477972013-10-25 18:10:40 -07005379 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005380 mOutput->stream->resume(mOutput->stream);
5381 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005382
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 // remove all the tracks that need to be...
5384 removeTracks_l(*tracksToRemove);
5385
5386 return mixerStatus;
5387}
5388
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389// must be called with thread mutex locked
5390bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5391{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005392 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5393 mWriteAckSequence, mDrainSequence);
5394 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395 return true;
5396 }
5397 return false;
5398}
5399
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5401{
5402 Mutex::Autolock _l(mLock);
5403 return waitingAsyncCallback_l();
5404}
5405
5406void AudioFlinger::OffloadThread::flushHw_l()
5407{
Eric Laurente659ef42014-09-29 13:06:46 -07005408 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005409 // Flush anything still waiting in the mixbuffer
5410 mCurrentWriteLength = 0;
5411 mBytesRemaining = 0;
5412 mPausedWriteLength = 0;
5413 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005414
Eric Laurentbfb1b832013-01-07 09:53:42 -08005415 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005416 // discard any pending drain or write ack by incrementing sequence
5417 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5418 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005419 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005420 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5421 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 }
5423}
5424
5425// ----------------------------------------------------------------------------
5426
Eric Laurent81784c32012-11-19 14:55:58 -08005427AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005428 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005429 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005430 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005431 mWaitTimeMs(UINT_MAX)
5432{
5433 addOutputTrack(mainThread);
5434}
5435
5436AudioFlinger::DuplicatingThread::~DuplicatingThread()
5437{
5438 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5439 mOutputTracks[i]->destroy();
5440 }
5441}
5442
5443void AudioFlinger::DuplicatingThread::threadLoop_mix()
5444{
5445 // mix buffers...
5446 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005447 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005448 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005449 if (mMixerBufferValid) {
5450 memset(mMixerBuffer, 0, mMixerBufferSize);
5451 } else {
5452 memset(mSinkBuffer, 0, mSinkBufferSize);
5453 }
Eric Laurent81784c32012-11-19 14:55:58 -08005454 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005455 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005457 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005458 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005459}
5460
5461void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5462{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005463 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005464 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005465 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005466 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005467 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005468 }
5469 } else if (mBytesWritten != 0) {
5470 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5471 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005472 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005473 } else {
5474 // flush remaining overflow buffers in output tracks
5475 writeFrames = 0;
5476 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005477 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005478 }
5479}
5480
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005482{
5483 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005484 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005485 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005486 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005487 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005488}
5489
5490void AudioFlinger::DuplicatingThread::threadLoop_standby()
5491{
5492 // DuplicatingThread implements standby by stopping all tracks
5493 for (size_t i = 0; i < outputTracks.size(); i++) {
5494 outputTracks[i]->stop();
5495 }
5496}
5497
5498void AudioFlinger::DuplicatingThread::saveOutputTracks()
5499{
5500 outputTracks = mOutputTracks;
5501}
5502
5503void AudioFlinger::DuplicatingThread::clearOutputTracks()
5504{
5505 outputTracks.clear();
5506}
5507
5508void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5509{
5510 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005511 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5512 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5513 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5514 const size_t frameCount =
5515 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5516 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5517 // from different OutputTracks and their associated MixerThreads (e.g. one may
5518 // nearly empty and the other may be dropping data).
5519
5520 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005521 this,
5522 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005523 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005524 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005525 frameCount,
5526 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005527 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005528 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005529 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005530 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005531 updateWaitTime_l();
5532 }
5533}
5534
5535void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5536{
5537 Mutex::Autolock _l(mLock);
5538 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5539 if (mOutputTracks[i]->thread() == thread) {
5540 mOutputTracks[i]->destroy();
5541 mOutputTracks.removeAt(i);
5542 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005543 if (thread->getOutput() == mOutput) {
5544 mOutput = NULL;
5545 }
Eric Laurent81784c32012-11-19 14:55:58 -08005546 return;
5547 }
5548 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005549 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005550}
5551
5552// caller must hold mLock
5553void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5554{
5555 mWaitTimeMs = UINT_MAX;
5556 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5557 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5558 if (strong != 0) {
5559 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5560 if (waitTimeMs < mWaitTimeMs) {
5561 mWaitTimeMs = waitTimeMs;
5562 }
5563 }
5564 }
5565}
5566
5567
5568bool AudioFlinger::DuplicatingThread::outputsReady(
5569 const SortedVector< sp<OutputTrack> > &outputTracks)
5570{
5571 for (size_t i = 0; i < outputTracks.size(); i++) {
5572 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5573 if (thread == 0) {
5574 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5575 outputTracks[i].get());
5576 return false;
5577 }
5578 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5579 // see note at standby() declaration
5580 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5581 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5582 thread.get());
5583 return false;
5584 }
5585 }
5586 return true;
5587}
5588
5589uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5590{
5591 return (mWaitTimeMs * 1000) / 2;
5592}
5593
5594void AudioFlinger::DuplicatingThread::cacheParameters_l()
5595{
5596 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5597 updateWaitTime_l();
5598
5599 MixerThread::cacheParameters_l();
5600}
5601
5602// ----------------------------------------------------------------------------
5603// Record
5604// ----------------------------------------------------------------------------
5605
5606AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5607 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005608 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005609 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005610 audio_devices_t inDevice,
5611 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005612#ifdef TEE_SINK
5613 , const sp<NBAIO_Sink>& teeSink
5614#endif
5615 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005616 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005617 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005618 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005619 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005620#ifdef TEE_SINK
5621 , mTeeSink(teeSink)
5622#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005623 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5624 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005625 // mFastCapture below
5626 , mFastCaptureFutex(0)
5627 // mInputSource
5628 // mPipeSink
5629 // mPipeSource
5630 , mPipeFramesP2(0)
5631 // mPipeMemory
5632 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005633 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005634{
Glenn Kastend7dca052015-03-05 16:05:54 -08005635 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5636 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005637
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005638 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005639
5640 // create an NBAIO source for the HAL input stream, and negotiate
5641 mInputSource = new AudioStreamInSource(input->stream);
5642 size_t numCounterOffers = 0;
5643 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5644 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5645 ALOG_ASSERT(index == 0);
5646
5647 // initialize fast capture depending on configuration
5648 bool initFastCapture;
5649 switch (kUseFastCapture) {
5650 case FastCapture_Never:
5651 initFastCapture = false;
5652 break;
5653 case FastCapture_Always:
5654 initFastCapture = true;
5655 break;
5656 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005657 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005658 break;
5659 // case FastCapture_Dynamic:
5660 }
5661
5662 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005663 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005664 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005665 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005666 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5667 void *pipeBuffer;
5668 const sp<MemoryDealer> roHeap(readOnlyHeap());
5669 sp<IMemory> pipeMemory;
5670 if ((roHeap == 0) ||
5671 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5672 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5673 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5674 goto failed;
5675 }
5676 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5677 memset(pipeBuffer, 0, pipeSize);
5678 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5679 const NBAIO_Format offers[1] = {format};
5680 size_t numCounterOffers = 0;
5681 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5682 ALOG_ASSERT(index == 0);
5683 mPipeSink = pipe;
5684 PipeReader *pipeReader = new PipeReader(*pipe);
5685 numCounterOffers = 0;
5686 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5687 ALOG_ASSERT(index == 0);
5688 mPipeSource = pipeReader;
5689 mPipeFramesP2 = pipeFramesP2;
5690 mPipeMemory = pipeMemory;
5691
5692 // create fast capture
5693 mFastCapture = new FastCapture();
5694 FastCaptureStateQueue *sq = mFastCapture->sq();
5695#ifdef STATE_QUEUE_DUMP
5696 // FIXME
5697#endif
5698 FastCaptureState *state = sq->begin();
5699 state->mCblk = NULL;
5700 state->mInputSource = mInputSource.get();
5701 state->mInputSourceGen++;
5702 state->mPipeSink = pipe;
5703 state->mPipeSinkGen++;
5704 state->mFrameCount = mFrameCount;
5705 state->mCommand = FastCaptureState::COLD_IDLE;
5706 // already done in constructor initialization list
5707 //mFastCaptureFutex = 0;
5708 state->mColdFutexAddr = &mFastCaptureFutex;
5709 state->mColdGen++;
5710 state->mDumpState = &mFastCaptureDumpState;
5711#ifdef TEE_SINK
5712 // FIXME
5713#endif
5714 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5715 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5716 sq->end();
5717 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5718
5719 // start the fast capture
5720 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5721 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005722 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005723#ifdef AUDIO_WATCHDOG
5724 // FIXME
5725#endif
5726
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005727 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005728 }
5729failed: ;
5730
5731 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005732}
5733
Eric Laurent81784c32012-11-19 14:55:58 -08005734AudioFlinger::RecordThread::~RecordThread()
5735{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005736 if (mFastCapture != 0) {
5737 FastCaptureStateQueue *sq = mFastCapture->sq();
5738 FastCaptureState *state = sq->begin();
5739 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5740 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5741 if (old == -1) {
5742 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5743 }
5744 }
5745 state->mCommand = FastCaptureState::EXIT;
5746 sq->end();
5747 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5748 mFastCapture->join();
5749 mFastCapture.clear();
5750 }
5751 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005752 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005753 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005754}
5755
5756void AudioFlinger::RecordThread::onFirstRef()
5757{
Glenn Kastend7dca052015-03-05 16:05:54 -08005758 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005759}
5760
Eric Laurent81784c32012-11-19 14:55:58 -08005761bool AudioFlinger::RecordThread::threadLoop()
5762{
Eric Laurent81784c32012-11-19 14:55:58 -08005763 nsecs_t lastWarning = 0;
5764
5765 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005766
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005767reacquire_wakelock:
5768 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005769 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005770 {
5771 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005772 size_t size = mActiveTracks.size();
5773 activeTracksGen = mActiveTracksGen;
5774 if (size > 0) {
5775 // FIXME an arbitrary choice
5776 activeTrack = mActiveTracks[0];
5777 acquireWakeLock_l(activeTrack->uid());
5778 if (size > 1) {
5779 SortedVector<int> tmp;
5780 for (size_t i = 0; i < size; i++) {
5781 tmp.add(mActiveTracks[i]->uid());
5782 }
5783 updateWakeLockUids_l(tmp);
5784 }
5785 } else {
5786 acquireWakeLock_l(-1);
5787 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005788 }
5789
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005790 // used to request a deferred sleep, to be executed later while mutex is unlocked
5791 uint32_t sleepUs = 0;
5792
5793 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005794 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005795 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005796
Glenn Kasten5edadd42013-08-14 16:30:49 -07005797 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005798 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005799 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005801 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005803 }
5804
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005805 // activeTracks accumulates a copy of a subset of mActiveTracks
5806 Vector< sp<RecordTrack> > activeTracks;
5807
Glenn Kasten735f45f2014-08-18 15:51:59 -07005808 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005810
Glenn Kasten735f45f2014-08-18 15:51:59 -07005811 // reference to a fast track which is about to be removed
5812 sp<RecordTrack> fastTrackToRemove;
5813
Eric Laurent81784c32012-11-19 14:55:58 -08005814 { // scope for mLock
5815 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005816
Eric Laurent021cf962014-05-13 10:18:14 -07005817 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005818
Eric Laurent000a4192014-01-29 15:17:32 -08005819 // check exitPending here because checkForNewParameters_l() and
5820 // checkForNewParameters_l() can temporarily release mLock
5821 if (exitPending()) {
5822 break;
5823 }
5824
Glenn Kasten2b806402013-11-20 16:37:38 -08005825 // if no active track(s), then standby and release wakelock
5826 size_t size = mActiveTracks.size();
5827 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005828 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005829 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005830 releaseWakeLock_l();
5831 ALOGV("RecordThread: loop stopping");
5832 // go to sleep
5833 mWaitWorkCV.wait(mLock);
5834 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005835 goto reacquire_wakelock;
5836 }
5837
Glenn Kasten2b806402013-11-20 16:37:38 -08005838 if (mActiveTracksGen != activeTracksGen) {
5839 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005840 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005841 for (size_t i = 0; i < size; i++) {
5842 tmp.add(mActiveTracks[i]->uid());
5843 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005844 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005845 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005846
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005847 bool doBroadcast = false;
5848 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005849
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005850 activeTrack = mActiveTracks[i];
5851 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005852 if (activeTrack->isFastTrack()) {
5853 ALOG_ASSERT(fastTrackToRemove == 0);
5854 fastTrackToRemove = activeTrack;
5855 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005856 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005857 mActiveTracks.remove(activeTrack);
5858 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005859 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005860 continue;
5861 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005862
5863 TrackBase::track_state activeTrackState = activeTrack->mState;
5864 switch (activeTrackState) {
5865
5866 case TrackBase::PAUSING:
5867 mActiveTracks.remove(activeTrack);
5868 mActiveTracksGen++;
5869 doBroadcast = true;
5870 size--;
5871 continue;
5872
5873 case TrackBase::STARTING_1:
5874 sleepUs = 10000;
5875 i++;
5876 continue;
5877
5878 case TrackBase::STARTING_2:
5879 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005881 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 break;
5883
5884 case TrackBase::ACTIVE:
5885 break;
5886
5887 case TrackBase::IDLE:
5888 i++;
5889 continue;
5890
5891 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005892 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005893 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005894
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005895 activeTracks.add(activeTrack);
5896 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005897
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005898 if (activeTrack->isFastTrack()) {
5899 ALOG_ASSERT(!mFastTrackAvail);
5900 ALOG_ASSERT(fastTrack == 0);
5901 fastTrack = activeTrack;
5902 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005903 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904 if (doBroadcast) {
5905 mStartStopCond.broadcast();
5906 }
5907
5908 // sleep if there are no active tracks to process
5909 if (activeTracks.size() == 0) {
5910 if (sleepUs == 0) {
5911 sleepUs = kRecordThreadSleepUs;
5912 }
5913 continue;
5914 }
5915 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005916
Eric Laurent81784c32012-11-19 14:55:58 -08005917 lockEffectChains_l(effectChains);
5918 }
5919
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005921
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005922 size_t size = effectChains.size();
5923 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005924 // thread mutex is not locked, but effect chain is locked
5925 effectChains[i]->process_l();
5926 }
5927
Glenn Kasten735f45f2014-08-18 15:51:59 -07005928 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 if (mFastCapture != 0) {
5930 FastCaptureStateQueue *sq = mFastCapture->sq();
5931 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005932 bool didModify = false;
5933 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005934 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5935 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5936 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5937 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5938 if (old == -1) {
5939 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5940 }
5941 }
5942 state->mCommand = FastCaptureState::READ_WRITE;
5943#if 0 // FIXME
5944 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005945 FastThreadDumpState::kSamplingNforLowRamDevice :
5946 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005947#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005948 didModify = true;
5949 }
5950 audio_track_cblk_t *cblkOld = state->mCblk;
5951 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5952 if (cblkNew != cblkOld) {
5953 state->mCblk = cblkNew;
5954 // block until acked if removing a fast track
5955 if (cblkOld != NULL) {
5956 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5957 }
5958 didModify = true;
5959 }
5960 sq->end(didModify);
5961 if (didModify) {
5962 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005963#if 0
5964 if (kUseFastCapture == FastCapture_Dynamic) {
5965 mNormalSource = mPipeSource;
5966 }
5967#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005968 }
5969 }
5970
Glenn Kasten735f45f2014-08-18 15:51:59 -07005971 // now run the fast track destructor with thread mutex unlocked
5972 fastTrackToRemove.clear();
5973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005974 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5975 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5976 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5977 // If destination is non-contiguous, first read past the nominal end of buffer, then
5978 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005979
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005981 ssize_t framesRead;
5982
5983 // If an NBAIO source is present, use it to read the normal capture's data
5984 if (mPipeSource != 0) {
5985 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005986 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08005987 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005988 if (framesRead == 0) {
5989 // since pipe is non-blocking, simulate blocking input
5990 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5991 }
5992 // otherwise use the HAL / AudioStreamIn directly
5993 } else {
5994 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005995 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005996 if (bytesRead < 0) {
5997 framesRead = bytesRead;
5998 } else {
5999 framesRead = bytesRead / mFrameSize;
6000 }
6001 }
6002
Andy Hung3f0c9022016-01-15 17:49:46 -08006003 // Update server timestamp with server stats
6004 // systemTime() is optional if the hardware supports timestamps.
6005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6006 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6007
6008 // Update server timestamp with kernel stats
6009 if (mInput->stream->get_capture_position != nullptr) {
6010 int64_t position, time;
6011 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6012 if (ret == NO_ERROR) {
6013 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6014 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6015 // Note: In general record buffers should tend to be empty in
6016 // a properly running pipeline.
6017 //
6018 // Also, it is not advantageous to call get_presentation_position during the read
6019 // as the read obtains a lock, preventing the timestamp call from executing.
6020 }
6021 }
6022 // Use this to track timestamp information
6023 // ALOGD("%s", mTimestamp.toString().c_str());
6024
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006025 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6026 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 // Force input into standby so that it tries to recover at next read attempt
6028 inputStandBy();
6029 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006030 }
6031 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006032 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006035
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006037 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 }
6039 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006040 {
6041 size_t part1 = mRsmpInFramesP2 - rear;
6042 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006043 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006044 (framesRead - part1) * mFrameSize);
6045 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006046 }
6047 rear = mRsmpInRear += framesRead;
6048
6049 size = activeTracks.size();
6050 // loop over each active track
6051 for (size_t i = 0; i < size; i++) {
6052 activeTrack = activeTracks[i];
6053
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054 // skip fast tracks, as those are handled directly by FastCapture
6055 if (activeTrack->isFastTrack()) {
6056 continue;
6057 }
6058
Andy Hung73c02e42015-03-29 01:13:58 -07006059 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006060 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6061
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 enum {
6063 OVERRUN_UNKNOWN,
6064 OVERRUN_TRUE,
6065 OVERRUN_FALSE
6066 } overrun = OVERRUN_UNKNOWN;
6067
6068 // loop over getNextBuffer to handle circular sink
6069 for (;;) {
6070
6071 activeTrack->mSink.frameCount = ~0;
6072 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6073 size_t framesOut = activeTrack->mSink.frameCount;
6074 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6075
Andy Hung73c02e42015-03-29 01:13:58 -07006076 // check available frames and handle overrun conditions
6077 // if the record track isn't draining fast enough.
6078 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006079 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006080 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6081 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006082 overrun = OVERRUN_TRUE;
6083 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006084 if (framesOut == 0 || framesIn == 0) {
6085 break;
6086 }
6087
Andy Hung6770c6f2015-04-07 13:43:36 -07006088 // Don't allow framesOut to be larger than what is possible with resampling
6089 // from framesIn.
6090 // This isn't strictly necessary but helps limit buffer resizing in
6091 // RecordBufferConverter. TODO: remove when no longer needed.
6092 framesOut = min(framesOut,
6093 destinationFramesPossible(
6094 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006095 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6096 framesOut = activeTrack->mRecordBufferConverter->convert(
6097 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006098
6099 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6100 overrun = OVERRUN_FALSE;
6101 }
6102
6103 if (activeTrack->mFramesToDrop == 0) {
6104 if (framesOut > 0) {
6105 activeTrack->mSink.frameCount = framesOut;
6106 activeTrack->releaseBuffer(&activeTrack->mSink);
6107 }
6108 } else {
6109 // FIXME could do a partial drop of framesOut
6110 if (activeTrack->mFramesToDrop > 0) {
6111 activeTrack->mFramesToDrop -= framesOut;
6112 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006113 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006114 }
6115 } else {
6116 activeTrack->mFramesToDrop += framesOut;
6117 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6118 activeTrack->mSyncStartEvent->isCancelled()) {
6119 ALOGW("Synced record %s, session %d, trigger session %d",
6120 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6121 activeTrack->sessionId(),
6122 (activeTrack->mSyncStartEvent != 0) ?
6123 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006124 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 }
6126 }
6127 }
6128
6129 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006130 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006131 }
6132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133
6134 switch (overrun) {
6135 case OVERRUN_TRUE:
6136 // client isn't retrieving buffers fast enough
6137 if (!activeTrack->setOverflow()) {
6138 nsecs_t now = systemTime();
6139 // FIXME should lastWarning per track?
6140 if ((now - lastWarning) > kWarningThrottleNs) {
6141 ALOGW("RecordThread: buffer overflow");
6142 lastWarning = now;
6143 }
6144 }
6145 break;
6146 case OVERRUN_FALSE:
6147 activeTrack->clearOverflow();
6148 break;
6149 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006150 break;
6151 }
6152
Andy Hung3f0c9022016-01-15 17:49:46 -08006153 // update frame information and push timestamp out
6154 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006155 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006156 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6157 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006158 }
6159
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006160unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006161 // enable changes in effect chain
6162 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006163 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006164 }
6165
Glenn Kasten93e471f2013-08-19 08:40:07 -07006166 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006167
6168 {
6169 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006170 for (size_t i = 0; i < mTracks.size(); i++) {
6171 sp<RecordTrack> track = mTracks[i];
6172 track->invalidate();
6173 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006174 mActiveTracks.clear();
6175 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006176 mStartStopCond.broadcast();
6177 }
6178
6179 releaseWakeLock();
6180
6181 ALOGV("RecordThread %p exiting", this);
6182 return false;
6183}
6184
Glenn Kasten93e471f2013-08-19 08:40:07 -07006185void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006186{
6187 if (!mStandby) {
6188 inputStandBy();
6189 mStandby = true;
6190 }
6191}
6192
6193void AudioFlinger::RecordThread::inputStandBy()
6194{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006195 // Idle the fast capture if it's currently running
6196 if (mFastCapture != 0) {
6197 FastCaptureStateQueue *sq = mFastCapture->sq();
6198 FastCaptureState *state = sq->begin();
6199 if (!(state->mCommand & FastCaptureState::IDLE)) {
6200 state->mCommand = FastCaptureState::COLD_IDLE;
6201 state->mColdFutexAddr = &mFastCaptureFutex;
6202 state->mColdGen++;
6203 mFastCaptureFutex = 0;
6204 sq->end();
6205 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6206 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6207#if 0
6208 if (kUseFastCapture == FastCapture_Dynamic) {
6209 // FIXME
6210 }
6211#endif
6212#ifdef AUDIO_WATCHDOG
6213 // FIXME
6214#endif
6215 } else {
6216 sq->end(false /*didModify*/);
6217 }
6218 }
Eric Laurent81784c32012-11-19 14:55:58 -08006219 mInput->stream->common.standby(&mInput->stream->common);
6220}
6221
Glenn Kasten05997e22014-03-13 15:08:33 -07006222// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006223sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006224 const sp<AudioFlinger::Client>& client,
6225 uint32_t sampleRate,
6226 audio_format_t format,
6227 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006228 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006229 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006230 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006231 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006232 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006233 pid_t tid,
6234 status_t *status)
6235{
Glenn Kasten74935e42013-12-19 08:56:45 -08006236 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006237 sp<RecordTrack> track;
6238 status_t lStatus;
6239
Glenn Kasten90e58b12013-07-31 16:16:02 -07006240 // client expresses a preference for FAST, but we get the final say
6241 if (*flags & IAudioFlinger::TRACK_FAST) {
6242 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006243 // we formerly checked for a callback handler (non-0 tid),
6244 // but that is no longer required for TRANSFER_OBTAIN mode
6245 //
Glenn Kasten74105912014-07-03 12:28:53 -07006246 // frame count is not specified, or is exactly the pipe depth
6247 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006248 // PCM data
6249 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006250 // native format
6251 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006252 // native channel mask
6253 (channelMask == mChannelMask) &&
6254 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006255 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006256 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006257 hasFastCapture() &&
6258 // there are sufficient fast track slots available
6259 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006260 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006261 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006262 frameCount, mFrameCount);
6263 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006264 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6265 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006266 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006267 frameCount, mFrameCount, mPipeFramesP2,
6268 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6269 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006270 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006271 }
6272 }
6273
6274 // compute track buffer size in frames, and suggest the notification frame count
6275 if (*flags & IAudioFlinger::TRACK_FAST) {
6276 // fast track: frame count is exactly the pipe depth
6277 frameCount = mPipeFramesP2;
6278 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6279 *notificationFrames = mFrameCount;
6280 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006281 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6282 // or 20 ms if there is a fast capture
6283 // TODO This could be a roundupRatio inline, and const
6284 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6285 * sampleRate + mSampleRate - 1) / mSampleRate;
6286 // minimum number of notification periods is at least kMinNotifications,
6287 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6288 static const size_t kMinNotifications = 3;
6289 static const uint32_t kMinMs = 30;
6290 // TODO This could be a roundupRatio inline
6291 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6292 // TODO This could be a roundupRatio inline
6293 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6294 maxNotificationFrames;
6295 const size_t minFrameCount = maxNotificationFrames *
6296 max(kMinNotifications, minNotificationsByMs);
6297 frameCount = max(frameCount, minFrameCount);
6298 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6299 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006300 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006301 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006302 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006303
Glenn Kasten15e57982013-09-24 11:52:37 -07006304 lStatus = initCheck();
6305 if (lStatus != NO_ERROR) {
6306 ALOGE("createRecordTrack_l() audio driver not initialized");
6307 goto Exit;
6308 }
Eric Laurent81784c32012-11-19 14:55:58 -08006309
6310 { // scope for mLock
6311 Mutex::Autolock _l(mLock);
6312
6313 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006314 format, channelMask, frameCount, NULL, sessionId, uid,
6315 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006316
Glenn Kasten03003332013-08-06 15:40:54 -07006317 lStatus = track->initCheck();
6318 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006319 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006320 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006321 goto Exit;
6322 }
6323 mTracks.add(track);
6324
6325 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6326 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6327 mAudioFlinger->btNrecIsOff();
6328 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6329 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006330
6331 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6332 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6333 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6334 // so ask activity manager to do this on our behalf
6335 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6336 }
Eric Laurent81784c32012-11-19 14:55:58 -08006337 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006338
Eric Laurent81784c32012-11-19 14:55:58 -08006339 lStatus = NO_ERROR;
6340
6341Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006342 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006343 return track;
6344}
6345
6346status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6347 AudioSystem::sync_event_t event,
6348 int triggerSession)
6349{
6350 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6351 sp<ThreadBase> strongMe = this;
6352 status_t status = NO_ERROR;
6353
6354 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006355 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006356 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006357 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006358 triggerSession,
6359 recordTrack->sessionId(),
6360 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006361 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006362 // Sync event can be cancelled by the trigger session if the track is not in a
6363 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006364 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006365 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006366 } else {
6367 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006368 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006369 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006370 }
6371 }
6372
6373 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006374 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006375 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006376 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6377 if (recordTrack->mState == TrackBase::PAUSING) {
6378 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006379 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006380 } else {
6381 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006382 }
6383 return status;
6384 }
6385
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006386 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6387 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6388 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006390 mActiveTracks.add(recordTrack);
6391 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006392 status_t status = NO_ERROR;
6393 if (recordTrack->isExternalTrack()) {
6394 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006395 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006396 mLock.lock();
6397 // FIXME should verify that recordTrack is still in mActiveTracks
6398 if (status != NO_ERROR) {
6399 mActiveTracks.remove(recordTrack);
6400 mActiveTracksGen++;
6401 recordTrack->clearSyncStartEvent();
6402 ALOGV("RecordThread::start error %d", status);
6403 return status;
6404 }
Eric Laurent81784c32012-11-19 14:55:58 -08006405 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406 // Catch up with current buffer indices if thread is already running.
6407 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6408 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6409 // see previously buffered data before it called start(), but with greater risk of overrun.
6410
Andy Hung73c02e42015-03-29 01:13:58 -07006411 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006412 // clear any converter state as new data will be discontinuous
6413 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006414 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006415 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006416 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006417 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006418 ALOGV("Record failed to start");
6419 status = BAD_VALUE;
6420 goto startError;
6421 }
Eric Laurent81784c32012-11-19 14:55:58 -08006422 return status;
6423 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006424
Eric Laurent81784c32012-11-19 14:55:58 -08006425startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006426 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006427 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006428 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006429 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006430 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006431 return status;
6432}
6433
Eric Laurent81784c32012-11-19 14:55:58 -08006434void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6435{
6436 sp<SyncEvent> strongEvent = event.promote();
6437
6438 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006439 sp<RefBase> ptr = strongEvent->cookie().promote();
6440 if (ptr != 0) {
6441 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6442 recordTrack->handleSyncStartEvent(strongEvent);
6443 }
Eric Laurent81784c32012-11-19 14:55:58 -08006444 }
6445}
6446
Glenn Kastena8356f62013-07-25 14:37:52 -07006447bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006448 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006449 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006450 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006451 return false;
6452 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006453 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006454 recordTrack->mState = TrackBase::PAUSING;
6455 // do not wait for mStartStopCond if exiting
6456 if (exitPending()) {
6457 return true;
6458 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006459 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006460 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006461 // if we have been restarted, recordTrack is in mActiveTracks here
6462 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006463 ALOGV("Record stopped OK");
6464 return true;
6465 }
6466 return false;
6467}
6468
Glenn Kasten0f11b512014-01-31 16:18:54 -08006469bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006470{
6471 return false;
6472}
6473
Glenn Kasten0f11b512014-01-31 16:18:54 -08006474status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006475{
6476#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6477 if (!isValidSyncEvent(event)) {
6478 return BAD_VALUE;
6479 }
6480
6481 int eventSession = event->triggerSession();
6482 status_t ret = NAME_NOT_FOUND;
6483
6484 Mutex::Autolock _l(mLock);
6485
6486 for (size_t i = 0; i < mTracks.size(); i++) {
6487 sp<RecordTrack> track = mTracks[i];
6488 if (eventSession == track->sessionId()) {
6489 (void) track->setSyncEvent(event);
6490 ret = NO_ERROR;
6491 }
6492 }
6493 return ret;
6494#else
6495 return BAD_VALUE;
6496#endif
6497}
6498
6499// destroyTrack_l() must be called with ThreadBase::mLock held
6500void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6501{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006502 track->terminate();
6503 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006504 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006505 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006506 removeTrack_l(track);
6507 }
6508}
6509
6510void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6511{
6512 mTracks.remove(track);
6513 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006514 if (track->isFastTrack()) {
6515 ALOG_ASSERT(!mFastTrackAvail);
6516 mFastTrackAvail = true;
6517 }
Eric Laurent81784c32012-11-19 14:55:58 -08006518}
6519
6520void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6521{
6522 dumpInternals(fd, args);
6523 dumpTracks(fd, args);
6524 dumpEffectChains(fd, args);
6525}
6526
6527void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6528{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006529 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006530
Glenn Kasten44182c22015-03-05 17:12:23 -08006531 dumpBase(fd, args);
6532
6533 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006534 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006535 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006536 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006537 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006538
Glenn Kasten2f90c512015-12-02 11:40:09 -08006539 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6540 // while we are dumping it. It may be inconsistent, but it won't mutate!
6541 // This is a large object so we place it on the heap.
6542 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6543 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6544 copy->dump(fd);
6545 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006546}
6547
Glenn Kasten0f11b512014-01-31 16:18:54 -08006548void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006549{
6550 const size_t SIZE = 256;
6551 char buffer[SIZE];
6552 String8 result;
6553
Marco Nelissenb2208842014-02-07 14:00:50 -08006554 size_t numtracks = mTracks.size();
6555 size_t numactive = mActiveTracks.size();
6556 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006557 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006558 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006559 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006560 RecordTrack::appendDumpHeader(result);
6561 for (size_t i = 0; i < numtracks ; ++i) {
6562 sp<RecordTrack> track = mTracks[i];
6563 if (track != 0) {
6564 bool active = mActiveTracks.indexOf(track) >= 0;
6565 if (active) {
6566 numactiveseen++;
6567 }
6568 track->dump(buffer, SIZE, active);
6569 result.append(buffer);
6570 }
Eric Laurent81784c32012-11-19 14:55:58 -08006571 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006572 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006573 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006574 }
6575
Marco Nelissenb2208842014-02-07 14:00:50 -08006576 if (numactiveseen != numactive) {
6577 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6578 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006579 result.append(buffer);
6580 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006581 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006582 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006583 if (mTracks.indexOf(track) < 0) {
6584 track->dump(buffer, SIZE, true);
6585 result.append(buffer);
6586 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006587 }
Eric Laurent81784c32012-11-19 14:55:58 -08006588
6589 }
6590 write(fd, result.string(), result.size());
6591}
6592
Andy Hung73c02e42015-03-29 01:13:58 -07006593
6594void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6595{
6596 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6597 RecordThread *recordThread = (RecordThread *) threadBase.get();
6598 mRsmpInFront = recordThread->mRsmpInRear;
6599 mRsmpInUnrel = 0;
6600}
6601
6602void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6603 size_t *framesAvailable, bool *hasOverrun)
6604{
6605 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6606 RecordThread *recordThread = (RecordThread *) threadBase.get();
6607 const int32_t rear = recordThread->mRsmpInRear;
6608 const int32_t front = mRsmpInFront;
6609 const ssize_t filled = rear - front;
6610
6611 size_t framesIn;
6612 bool overrun = false;
6613 if (filled < 0) {
6614 // should not happen, but treat like a massive overrun and re-sync
6615 framesIn = 0;
6616 mRsmpInFront = rear;
6617 overrun = true;
6618 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6619 framesIn = (size_t) filled;
6620 } else {
6621 // client is not keeping up with server, but give it latest data
6622 framesIn = recordThread->mRsmpInFrames;
6623 mRsmpInFront = /* front = */ rear - framesIn;
6624 overrun = true;
6625 }
6626 if (framesAvailable != NULL) {
6627 *framesAvailable = framesIn;
6628 }
6629 if (hasOverrun != NULL) {
6630 *hasOverrun = overrun;
6631 }
6632}
6633
Eric Laurent81784c32012-11-19 14:55:58 -08006634// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006635status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006636 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006637{
Andy Hung73c02e42015-03-29 01:13:58 -07006638 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006639 if (threadBase == 0) {
6640 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006641 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006642 return NOT_ENOUGH_DATA;
6643 }
6644 RecordThread *recordThread = (RecordThread *) threadBase.get();
6645 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006646 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006647 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006648 // FIXME should not be P2 (don't want to increase latency)
6649 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006650 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006651 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006652 front &= recordThread->mRsmpInFramesP2 - 1;
6653 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006654 if (part1 > (size_t) filled) {
6655 part1 = filled;
6656 }
6657 size_t ask = buffer->frameCount;
6658 ALOG_ASSERT(ask > 0);
6659 if (part1 > ask) {
6660 part1 = ask;
6661 }
6662 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006663 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006664 buffer->raw = NULL;
6665 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006666 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006667 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006668 }
6669
Andy Hung57446612015-04-19 23:56:46 -07006670 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006671 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006672 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006673 return NO_ERROR;
6674}
6675
6676// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6678 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006679{
Glenn Kasten85948432013-08-19 12:09:05 -07006680 size_t stepCount = buffer->frameCount;
6681 if (stepCount == 0) {
6682 return;
6683 }
Andy Hung73c02e42015-03-29 01:13:58 -07006684 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6685 mRsmpInUnrel -= stepCount;
6686 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006687 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006688 buffer->frameCount = 0;
6689}
6690
Andy Hung97a893e2015-03-29 01:03:07 -07006691AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6692 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6693 uint32_t srcSampleRate,
6694 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6695 uint32_t dstSampleRate) :
6696 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6697 // mSrcFormat
6698 // mSrcSampleRate
6699 // mDstChannelMask
6700 // mDstFormat
6701 // mDstSampleRate
6702 // mSrcChannelCount
6703 // mDstChannelCount
6704 // mDstFrameSize
6705 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006706 mResampler(NULL),
6707 mIsLegacyDownmix(false),
6708 mIsLegacyUpmix(false),
6709 mRequiresFloat(false),
6710 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006711{
6712 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6713 dstChannelMask, dstFormat, dstSampleRate);
6714}
6715
6716AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6717 free(mBuf);
6718 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006719 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006720}
6721
6722size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6723 AudioBufferProvider *provider, size_t frames)
6724{
Andy Hungd330ee42015-04-20 13:23:41 -07006725 if (mInputConverterProvider != NULL) {
6726 mInputConverterProvider->setBufferProvider(provider);
6727 provider = mInputConverterProvider;
6728 }
6729
6730 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006731 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6732 mSrcSampleRate, mSrcFormat, mDstFormat);
6733
6734 AudioBufferProvider::Buffer buffer;
6735 for (size_t i = frames; i > 0; ) {
6736 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006737 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006738 if (status != OK || buffer.frameCount == 0) {
6739 frames -= i; // cannot fill request.
6740 break;
6741 }
Andy Hungd330ee42015-04-20 13:23:41 -07006742 // format convert to destination buffer
6743 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006744
6745 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6746 i -= buffer.frameCount;
6747 provider->releaseBuffer(&buffer);
6748 }
6749 } else {
6750 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6751 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6752
Andy Hungd330ee42015-04-20 13:23:41 -07006753 // reallocate buffer if needed
6754 if (mBufFrameSize != 0 && mBufFrames < frames) {
6755 free(mBuf);
6756 mBufFrames = frames;
6757 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6758 }
Andy Hung97a893e2015-03-29 01:03:07 -07006759 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006760 memset(mBuf, 0, frames * mBufFrameSize);
6761 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6762 // format convert to destination buffer
6763 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006764 }
6765 return frames;
6766}
6767
6768status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6769 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6770 uint32_t srcSampleRate,
6771 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6772 uint32_t dstSampleRate)
6773{
6774 // quick evaluation if there is any change.
6775 if (mSrcFormat == srcFormat
6776 && mSrcChannelMask == srcChannelMask
6777 && mSrcSampleRate == srcSampleRate
6778 && mDstFormat == dstFormat
6779 && mDstChannelMask == dstChannelMask
6780 && mDstSampleRate == dstSampleRate) {
6781 return NO_ERROR;
6782 }
6783
Andy Hungdb4c0312015-05-06 08:46:52 -07006784 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6785 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6786 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006787 const bool valid =
6788 audio_is_input_channel(srcChannelMask)
6789 && audio_is_input_channel(dstChannelMask)
6790 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6791 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6792 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6793 ; // no upsampling checks for now
6794 if (!valid) {
6795 return BAD_VALUE;
6796 }
6797
6798 mSrcFormat = srcFormat;
6799 mSrcChannelMask = srcChannelMask;
6800 mSrcSampleRate = srcSampleRate;
6801 mDstFormat = dstFormat;
6802 mDstChannelMask = dstChannelMask;
6803 mDstSampleRate = dstSampleRate;
6804
6805 // compute derived parameters
6806 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6807 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6808 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6809
Andy Hungd330ee42015-04-20 13:23:41 -07006810 // do we need to resample?
6811 delete mResampler;
6812 mResampler = NULL;
6813 if (mSrcSampleRate != mDstSampleRate) {
6814 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6815 mSrcChannelCount, mDstSampleRate);
6816 mResampler->setSampleRate(mSrcSampleRate);
6817 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6818 }
6819
6820 // are we running legacy channel conversion modes?
6821 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6822 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6823 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6824 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6825 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6826 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6827
6828 // do we need to process in float?
6829 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6830
6831 // do we need a staging buffer to convert for destination (we can still optimize this)?
6832 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6833 if (mResampler != NULL) {
6834 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6835 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006836 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006837 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6838 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006839 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6840 } else {
6841 mBufFrameSize = 0;
6842 }
6843 mBufFrames = 0; // force the buffer to be resized.
6844
Andy Hungd330ee42015-04-20 13:23:41 -07006845 // do we need an input converter buffer provider to give us float?
6846 delete mInputConverterProvider;
6847 mInputConverterProvider = NULL;
6848 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6849 mInputConverterProvider = new ReformatBufferProvider(
6850 audio_channel_count_from_in_mask(mSrcChannelMask),
6851 mSrcFormat,
6852 AUDIO_FORMAT_PCM_FLOAT,
6853 256 /* provider buffer frame count */);
6854 }
6855
6856 // do we need a remixer to do channel mask conversion
6857 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6858 (void) memcpy_by_index_array_initialization_from_channel_mask(
6859 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006860 }
6861 return NO_ERROR;
6862}
6863
Andy Hungd330ee42015-04-20 13:23:41 -07006864void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6865 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006866{
Andy Hungd330ee42015-04-20 13:23:41 -07006867 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006868 if (mBufFrameSize != 0 && mBufFrames < frames) {
6869 free(mBuf);
6870 mBufFrames = frames;
6871 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6872 }
Andy Hungd330ee42015-04-20 13:23:41 -07006873 // do we need to do legacy upmix and downmix?
6874 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006875 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006876 if (mIsLegacyUpmix) {
6877 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6878 (const float *)src, frames);
6879 } else /*mIsLegacyDownmix */ {
6880 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6881 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006882 }
Andy Hungd330ee42015-04-20 13:23:41 -07006883 if (mBuf != NULL) {
6884 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6885 frames * mDstChannelCount);
6886 }
6887 return;
6888 }
6889 // do we need to do channel mask conversion?
6890 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006891 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006892 memcpy_by_index_array(dstBuf, mDstChannelCount,
6893 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6894 if (dstBuf == dst) {
6895 return; // format is the same
6896 }
6897 }
6898 // convert to destination buffer
6899 const void *convertBuf = mBuf != NULL ? mBuf : src;
6900 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6901 frames * mDstChannelCount);
6902}
6903
6904void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6905 void *dst, /*not-a-const*/ void *src, size_t frames)
6906{
6907 // src buffer format is ALWAYS float when entering this routine
6908 if (mIsLegacyUpmix) {
6909 ; // mono to stereo already handled by resampler
6910 } else if (mIsLegacyDownmix
6911 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6912 // the resampler outputs stereo for mono input channel (a feature?)
6913 // must convert to mono
6914 downmix_to_mono_float_from_stereo_float((float *)src,
6915 (const float *)src, frames);
6916 } else if (mSrcChannelMask != mDstChannelMask) {
6917 // convert to mono channel again for channel mask conversion (could be skipped
6918 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006919 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006920 downmix_to_mono_float_from_stereo_float((float *)src,
6921 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006922 }
Andy Hungd330ee42015-04-20 13:23:41 -07006923 // convert to destination format (in place, OK as float is larger than other types)
6924 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6925 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6926 frames * mSrcChannelCount);
6927 }
6928 // channel convert and save to dst
6929 memcpy_by_index_array(dst, mDstChannelCount,
6930 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6931 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006932 }
Andy Hungd330ee42015-04-20 13:23:41 -07006933 // convert to destination format and save to dst
6934 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6935 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006936}
6937
Eric Laurent10351942014-05-08 18:49:52 -07006938bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6939 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006940{
6941 bool reconfig = false;
6942
Eric Laurent10351942014-05-08 18:49:52 -07006943 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006944
Eric Laurent10351942014-05-08 18:49:52 -07006945 audio_format_t reqFormat = mFormat;
6946 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006947 // 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 -07006948 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6949
6950 AudioParameter param = AudioParameter(keyValuePair);
6951 int value;
6952 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6953 // channel count change can be requested. Do we mandate the first client defines the
6954 // HAL sampling rate and channel count or do we allow changes on the fly?
6955 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6956 samplingRate = value;
6957 reconfig = true;
6958 }
6959 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006960 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006961 status = BAD_VALUE;
6962 } else {
6963 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006964 reconfig = true;
6965 }
Eric Laurent10351942014-05-08 18:49:52 -07006966 }
6967 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6968 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006969 if (!audio_is_input_channel(mask) ||
6970 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006971 status = BAD_VALUE;
6972 } else {
6973 channelMask = mask;
6974 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006975 }
Eric Laurent10351942014-05-08 18:49:52 -07006976 }
6977 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6978 // do not accept frame count changes if tracks are open as the track buffer
6979 // size depends on frame count and correct behavior would not be guaranteed
6980 // if frame count is changed after track creation
6981 if (mActiveTracks.size() > 0) {
6982 status = INVALID_OPERATION;
6983 } else {
6984 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006985 }
Eric Laurent10351942014-05-08 18:49:52 -07006986 }
6987 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6988 // forward device change to effects that have requested to be
6989 // aware of attached audio device.
6990 for (size_t i = 0; i < mEffectChains.size(); i++) {
6991 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006992 }
Eric Laurent81784c32012-11-19 14:55:58 -08006993
Eric Laurent10351942014-05-08 18:49:52 -07006994 // store input device and output device but do not forward output device to audio HAL.
6995 // Note that status is ignored by the caller for output device
6996 // (see AudioFlinger::setParameters()
6997 if (audio_is_output_devices(value)) {
6998 mOutDevice = value;
6999 status = BAD_VALUE;
7000 } else {
7001 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007002 if (value != AUDIO_DEVICE_NONE) {
7003 mPrevInDevice = value;
7004 }
Eric Laurent10351942014-05-08 18:49:52 -07007005 // disable AEC and NS if the device is a BT SCO headset supporting those
7006 // pre processings
7007 if (mTracks.size() > 0) {
7008 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7009 mAudioFlinger->btNrecIsOff();
7010 for (size_t i = 0; i < mTracks.size(); i++) {
7011 sp<RecordTrack> track = mTracks[i];
7012 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7013 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007014 }
7015 }
7016 }
Eric Laurent10351942014-05-08 18:49:52 -07007017 }
7018 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7019 mAudioSource != (audio_source_t)value) {
7020 // forward device change to effects that have requested to be
7021 // aware of attached audio device.
7022 for (size_t i = 0; i < mEffectChains.size(); i++) {
7023 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007024 }
Eric Laurent10351942014-05-08 18:49:52 -07007025 mAudioSource = (audio_source_t)value;
7026 }
Glenn Kastene198c362013-08-13 09:13:36 -07007027
Eric Laurent10351942014-05-08 18:49:52 -07007028 if (status == NO_ERROR) {
7029 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7030 keyValuePair.string());
7031 if (status == INVALID_OPERATION) {
7032 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007033 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7034 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007035 }
7036 if (reconfig) {
7037 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007038 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7039 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007040 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007041 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007042 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007043 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007044 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007045 }
Eric Laurent10351942014-05-08 18:49:52 -07007046 if (status == NO_ERROR) {
7047 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007048 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007049 }
7050 }
Eric Laurent81784c32012-11-19 14:55:58 -08007051 }
Eric Laurent10351942014-05-08 18:49:52 -07007052
Eric Laurent81784c32012-11-19 14:55:58 -08007053 return reconfig;
7054}
7055
7056String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7057{
Eric Laurent81784c32012-11-19 14:55:58 -08007058 Mutex::Autolock _l(mLock);
7059 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007060 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007061 }
7062
Glenn Kastend8ea6992013-07-16 14:17:15 -07007063 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7064 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007065 free(s);
7066 return out_s8;
7067}
7068
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007069void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007070 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7071
7072 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007073
7074 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007075 case AUDIO_INPUT_OPENED:
7076 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007077 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007078 desc->mChannelMask = mChannelMask;
7079 desc->mSamplingRate = mSampleRate;
7080 desc->mFormat = mFormat;
7081 desc->mFrameCount = mFrameCount;
7082 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007083 break;
7084
Eric Laurent73e26b62015-04-27 16:55:58 -07007085 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007086 default:
7087 break;
7088 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007089 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007090}
7091
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007092void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007093{
Eric Laurent81784c32012-11-19 14:55:58 -08007094 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7095 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007096 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007097 if (mChannelCount > FCC_8) {
7098 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7099 }
Andy Hung463be252014-07-10 16:56:07 -07007100 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7101 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007102 if (!audio_is_linear_pcm(mFormat)) {
7103 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007104 }
Eric Laurent665470b2014-07-03 16:37:08 -07007105 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007106 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7107 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007108 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007109 // 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 -07007110 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007111 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007112 // A larger value should allow more old data to be read after a track calls start(),
7113 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007114 //
7115 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007116 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007117 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007118 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007119 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007120
7121 // TODO optimize audio capture buffer sizes ...
7122 // Here we calculate the size of the sliding buffer used as a source
7123 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7124 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7125 // be better to have it derived from the pipe depth in the long term.
7126 // The current value is higher than necessary. However it should not add to latency.
7127
Glenn Kasten85948432013-08-19 12:09:05 -07007128 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007129 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7130 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7131 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007132
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007133 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7134 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007135}
7136
Glenn Kasten5f972c02014-01-13 09:59:31 -08007137uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007138{
7139 Mutex::Autolock _l(mLock);
7140 if (initCheck() != NO_ERROR) {
7141 return 0;
7142 }
7143
7144 return mInput->stream->get_input_frames_lost(mInput->stream);
7145}
7146
7147uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7148{
7149 Mutex::Autolock _l(mLock);
7150 uint32_t result = 0;
7151 if (getEffectChain_l(sessionId) != 0) {
7152 result = EFFECT_SESSION;
7153 }
7154
7155 for (size_t i = 0; i < mTracks.size(); ++i) {
7156 if (sessionId == mTracks[i]->sessionId()) {
7157 result |= TRACK_SESSION;
7158 break;
7159 }
7160 }
7161
7162 return result;
7163}
7164
7165KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7166{
7167 KeyedVector<int, bool> ids;
7168 Mutex::Autolock _l(mLock);
7169 for (size_t j = 0; j < mTracks.size(); ++j) {
7170 sp<RecordThread::RecordTrack> track = mTracks[j];
7171 int sessionId = track->sessionId();
7172 if (ids.indexOfKey(sessionId) < 0) {
7173 ids.add(sessionId, true);
7174 }
7175 }
7176 return ids;
7177}
7178
7179AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7180{
7181 Mutex::Autolock _l(mLock);
7182 AudioStreamIn *input = mInput;
7183 mInput = NULL;
7184 return input;
7185}
7186
7187// this method must always be called either with ThreadBase mLock held or inside the thread loop
7188audio_stream_t* AudioFlinger::RecordThread::stream() const
7189{
7190 if (mInput == NULL) {
7191 return NULL;
7192 }
7193 return &mInput->stream->common;
7194}
7195
7196status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7197{
7198 // only one chain per input thread
7199 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007200 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007201 return INVALID_OPERATION;
7202 }
7203 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007204 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007205 chain->setInBuffer(NULL);
7206 chain->setOutBuffer(NULL);
7207
7208 checkSuspendOnAddEffectChain_l(chain);
7209
Eric Laurent1b928682014-10-02 19:41:47 -07007210 // make sure enabled pre processing effects state is communicated to the HAL as we
7211 // just moved them to a new input stream.
7212 chain->syncHalEffectsState();
7213
Eric Laurent81784c32012-11-19 14:55:58 -08007214 mEffectChains.add(chain);
7215
7216 return NO_ERROR;
7217}
7218
7219size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7220{
7221 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7222 ALOGW_IF(mEffectChains.size() != 1,
7223 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7224 chain.get(), mEffectChains.size(), this);
7225 if (mEffectChains.size() == 1) {
7226 mEffectChains.removeAt(0);
7227 }
7228 return 0;
7229}
7230
Eric Laurent1c333e22014-05-20 10:48:17 -07007231status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7232 audio_patch_handle_t *handle)
7233{
7234 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007235
7236 // store new device and send to effects
7237 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007238 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007239 for (size_t i = 0; i < mEffectChains.size(); i++) {
7240 mEffectChains[i]->setDevice_l(mInDevice);
7241 }
7242
7243 // disable AEC and NS if the device is a BT SCO headset supporting those
7244 // pre processings
7245 if (mTracks.size() > 0) {
7246 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7247 mAudioFlinger->btNrecIsOff();
7248 for (size_t i = 0; i < mTracks.size(); i++) {
7249 sp<RecordTrack> track = mTracks[i];
7250 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7251 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7252 }
7253 }
7254
7255 // store new source and send to effects
7256 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7257 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007258 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007259 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007260 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007261 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007262
Eric Laurent054d9d32015-04-24 08:48:48 -07007263 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007264 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7265 status = hwDevice->create_audio_patch(hwDevice,
7266 patch->num_sources,
7267 patch->sources,
7268 patch->num_sinks,
7269 patch->sinks,
7270 handle);
7271 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007272 char *address;
7273 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7274 address = audio_device_address_to_parameter(
7275 patch->sources[0].ext.device.type,
7276 patch->sources[0].ext.device.address);
7277 } else {
7278 address = (char *)calloc(1, 1);
7279 }
7280 AudioParameter param = AudioParameter(String8(address));
7281 free(address);
7282 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7283 (int)patch->sources[0].ext.device.type);
7284 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7285 (int)patch->sinks[0].ext.mix.usecase.source);
7286 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7287 param.toString().string());
7288 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007289 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007290
Eric Laurente8726fe2015-06-26 09:39:24 -07007291 if (mInDevice != mPrevInDevice) {
7292 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7293 mPrevInDevice = mInDevice;
7294 }
Eric Laurent296fb132015-05-01 11:38:42 -07007295
Eric Laurent1c333e22014-05-20 10:48:17 -07007296 return status;
7297}
7298
7299status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7300{
7301 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007302
7303 mInDevice = AUDIO_DEVICE_NONE;
7304
Eric Laurent1c333e22014-05-20 10:48:17 -07007305 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7306 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7307 status = hwDevice->release_audio_patch(hwDevice, handle);
7308 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007309 AudioParameter param;
7310 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7311 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7312 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007313 }
7314 return status;
7315}
7316
Eric Laurent83b88082014-06-20 18:31:16 -07007317void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7318{
7319 Mutex::Autolock _l(mLock);
7320 mTracks.add(record);
7321}
7322
7323void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7324{
7325 Mutex::Autolock _l(mLock);
7326 destroyTrack_l(record);
7327}
7328
7329void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7330{
7331 ThreadBase::getAudioPortConfig(config);
7332 config->role = AUDIO_PORT_ROLE_SINK;
7333 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7334 config->ext.mix.usecase.source = mAudioSource;
7335}
Eric Laurent1c333e22014-05-20 10:48:17 -07007336
Glenn Kasten63238ef2015-03-02 15:50:29 -08007337} // namespace android