blob: 988176449852a9a8720a55194ce65fedf710ddfc [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>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#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"
62#include "SchedulingPolicyService.h"
63
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
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// ----------------------------------------------------------------------------
178
Glenn Kasten03490092014-05-27 12:30:54 -0700179static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
180
181static void sFastTrackMultiplierInit()
182{
183 char value[PROPERTY_VALUE_MAX];
184 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
185 char *endptr;
186 unsigned long ul = strtoul(value, &endptr, 0);
187 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
188 sFastTrackMultiplier = (int) ul;
189 }
190 }
191}
192
193// ----------------------------------------------------------------------------
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195#ifdef ADD_BATTERY_DATA
196// To collect the amplifier usage
197static void addBatteryData(uint32_t params) {
198 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
199 if (service == NULL) {
200 // it already logged
201 return;
202 }
203
204 service->addBatteryData(params);
205}
206#endif
207
208
209// ----------------------------------------------------------------------------
210// CPU Stats
211// ----------------------------------------------------------------------------
212
213class CpuStats {
214public:
215 CpuStats();
216 void sample(const String8 &title);
217#ifdef DEBUG_CPU_USAGE
218private:
219 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
220 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
221
222 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
223
224 int mCpuNum; // thread's current CPU number
225 int mCpukHz; // frequency of thread's current CPU in kHz
226#endif
227};
228
229CpuStats::CpuStats()
230#ifdef DEBUG_CPU_USAGE
231 : mCpuNum(-1), mCpukHz(-1)
232#endif
233{
234}
235
Glenn Kasten0f11b512014-01-31 16:18:54 -0800236void CpuStats::sample(const String8 &title
237#ifndef DEBUG_CPU_USAGE
238 __unused
239#endif
240 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800241#ifdef DEBUG_CPU_USAGE
242 // get current thread's delta CPU time in wall clock ns
243 double wcNs;
244 bool valid = mCpuUsage.sampleAndEnable(wcNs);
245
246 // record sample for wall clock statistics
247 if (valid) {
248 mWcStats.sample(wcNs);
249 }
250
251 // get the current CPU number
252 int cpuNum = sched_getcpu();
253
254 // get the current CPU frequency in kHz
255 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
256
257 // check if either CPU number or frequency changed
258 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
259 mCpuNum = cpuNum;
260 mCpukHz = cpukHz;
261 // ignore sample for purposes of cycles
262 valid = false;
263 }
264
265 // if no change in CPU number or frequency, then record sample for cycle statistics
266 if (valid && mCpukHz > 0) {
267 double cycles = wcNs * cpukHz * 0.000001;
268 mHzStats.sample(cycles);
269 }
270
271 unsigned n = mWcStats.n();
272 // mCpuUsage.elapsed() is expensive, so don't call it every loop
273 if ((n & 127) == 1) {
274 long long elapsed = mCpuUsage.elapsed();
275 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
276 double perLoop = elapsed / (double) n;
277 double perLoop100 = perLoop * 0.01;
278 double perLoop1k = perLoop * 0.001;
279 double mean = mWcStats.mean();
280 double stddev = mWcStats.stddev();
281 double minimum = mWcStats.minimum();
282 double maximum = mWcStats.maximum();
283 double meanCycles = mHzStats.mean();
284 double stddevCycles = mHzStats.stddev();
285 double minCycles = mHzStats.minimum();
286 double maxCycles = mHzStats.maximum();
287 mCpuUsage.resetElapsed();
288 mWcStats.reset();
289 mHzStats.reset();
290 ALOGD("CPU usage for %s over past %.1f secs\n"
291 " (%u mixer loops at %.1f mean ms per loop):\n"
292 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
293 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
294 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
295 title.string(),
296 elapsed * .000000001, n, perLoop * .000001,
297 mean * .001,
298 stddev * .001,
299 minimum * .001,
300 maximum * .001,
301 mean / perLoop100,
302 stddev / perLoop100,
303 minimum / perLoop100,
304 maximum / perLoop100,
305 meanCycles / perLoop1k,
306 stddevCycles / perLoop1k,
307 minCycles / perLoop1k,
308 maxCycles / perLoop1k);
309
310 }
311 }
312#endif
313};
314
315// ----------------------------------------------------------------------------
316// ThreadBase
317// ----------------------------------------------------------------------------
318
Glenn Kasten97b7b752014-09-28 13:04:24 -0700319// static
320const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
321{
322 switch (type) {
323 case MIXER:
324 return "MIXER";
325 case DIRECT:
326 return "DIRECT";
327 case DUPLICATING:
328 return "DUPLICATING";
329 case RECORD:
330 return "RECORD";
331 case OFFLOAD:
332 return "OFFLOAD";
333 default:
334 return "unknown";
335 }
336}
337
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800338String8 devicesToString(audio_devices_t devices)
339{
340 static const struct mapping {
341 audio_devices_t mDevices;
342 const char * mString;
343 } mappingsOut[] = {
344 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
345 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
346 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
347 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
348 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
349 AUDIO_DEVICE_NONE, "NONE", // must be last
350 }, mappingsIn[] = {
351 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
352 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
353 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
354 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
355 AUDIO_DEVICE_NONE, "NONE", // must be last
356 };
357 String8 result;
358 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
359 const mapping *entry;
360 if (devices & AUDIO_DEVICE_BIT_IN) {
361 devices &= ~AUDIO_DEVICE_BIT_IN;
362 entry = mappingsIn;
363 } else {
364 entry = mappingsOut;
365 }
366 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
367 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
368 if (devices & entry->mDevices) {
369 if (!result.isEmpty()) {
370 result.append("|");
371 }
372 result.append(entry->mString);
373 }
374 }
375 if (devices & ~allDevices) {
376 if (!result.isEmpty()) {
377 result.append("|");
378 }
379 result.appendFormat("0x%X", devices & ~allDevices);
380 }
381 if (result.isEmpty()) {
382 result.append(entry->mString);
383 }
384 return result;
385}
386
387String8 inputFlagsToString(audio_input_flags_t flags)
388{
389 static const struct mapping {
390 audio_input_flags_t mFlag;
391 const char * mString;
392 } mappings[] = {
393 AUDIO_INPUT_FLAG_FAST, "FAST",
394 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
395 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
396 };
397 String8 result;
398 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
399 const mapping *entry;
400 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
401 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
402 if (flags & entry->mFlag) {
403 if (!result.isEmpty()) {
404 result.append("|");
405 }
406 result.append(entry->mString);
407 }
408 }
409 if (flags & ~allFlags) {
410 if (!result.isEmpty()) {
411 result.append("|");
412 }
413 result.appendFormat("0x%X", flags & ~allFlags);
414 }
415 if (result.isEmpty()) {
416 result.append(entry->mString);
417 }
418 return result;
419}
420
421String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700422{
423 static const struct mapping {
424 audio_output_flags_t mFlag;
425 const char * mString;
426 } mappings[] = {
427 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
428 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
429 AUDIO_OUTPUT_FLAG_FAST, "FAST",
430 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800431 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
434 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
435 };
436 String8 result;
437 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
438 const mapping *entry;
439 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
440 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
441 if (flags & entry->mFlag) {
442 if (!result.isEmpty()) {
443 result.append("|");
444 }
445 result.append(entry->mString);
446 }
447 }
448 if (flags & ~allFlags) {
449 if (!result.isEmpty()) {
450 result.append("|");
451 }
452 result.appendFormat("0x%X", flags & ~allFlags);
453 }
454 if (result.isEmpty()) {
455 result.append(entry->mString);
456 }
457 return result;
458}
459
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460const char *sourceToString(audio_source_t source)
461{
462 switch (source) {
463 case AUDIO_SOURCE_DEFAULT: return "default";
464 case AUDIO_SOURCE_MIC: return "mic";
465 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
466 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
467 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
468 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
469 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
470 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
471 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
472 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
473 case AUDIO_SOURCE_HOTWORD: return "hotword";
474 default: return "unknown";
475 }
476}
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
479 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
480 : Thread(false /*canCallJava*/),
481 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700482 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700483 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800484 // are set by PlaybackThread::readOutputParameters_l() or
485 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700486 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800487 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
488 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
489 // mName will be set by concrete (non-virtual) subclass
490 mDeathRecipient(new PMDeathRecipient(this))
491{
492}
493
494AudioFlinger::ThreadBase::~ThreadBase()
495{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700496 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700497 mConfigEvents.clear();
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499 // do not lock the mutex in destructor
500 releaseWakeLock_l();
501 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800502 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800503 binder->unlinkToDeath(mDeathRecipient);
504 }
505}
506
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700507status_t AudioFlinger::ThreadBase::readyToRun()
508{
509 status_t status = initCheck();
510 if (status == NO_ERROR) {
511 ALOGI("AudioFlinger's thread %p ready to run", this);
512 } else {
513 ALOGE("No working audio driver found.");
514 }
515 return status;
516}
517
Eric Laurent81784c32012-11-19 14:55:58 -0800518void AudioFlinger::ThreadBase::exit()
519{
520 ALOGV("ThreadBase::exit");
521 // do any cleanup required for exit to succeed
522 preExit();
523 {
524 // This lock prevents the following race in thread (uniprocessor for illustration):
525 // if (!exitPending()) {
526 // // context switch from here to exit()
527 // // exit() calls requestExit(), what exitPending() observes
528 // // exit() calls signal(), which is dropped since no waiters
529 // // context switch back from exit() to here
530 // mWaitWorkCV.wait(...);
531 // // now thread is hung
532 // }
533 AutoMutex lock(mLock);
534 requestExit();
535 mWaitWorkCV.broadcast();
536 }
537 // When Thread::requestExitAndWait is made virtual and this method is renamed to
538 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
539 requestExitAndWait();
540}
541
542status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
543{
544 status_t status;
545
546 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
547 Mutex::Autolock _l(mLock);
548
Eric Laurent10351942014-05-08 18:49:52 -0700549 return sendSetParameterConfigEvent_l(keyValuePairs);
550}
551
552// sendConfigEvent_l() must be called with ThreadBase::mLock held
553// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
554status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
555{
556 status_t status = NO_ERROR;
557
558 mConfigEvents.add(event);
559 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800560 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700561 mLock.unlock();
562 {
563 Mutex::Autolock _l(event->mLock);
564 while (event->mWaitStatus) {
565 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
566 event->mStatus = TIMED_OUT;
567 event->mWaitStatus = false;
568 }
569 }
570 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800571 }
Eric Laurent10351942014-05-08 18:49:52 -0700572 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800573 return status;
574}
575
576void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
577{
578 Mutex::Autolock _l(mLock);
579 sendIoConfigEvent_l(event, param);
580}
581
582// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
583void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
584{
Eric Laurent10351942014-05-08 18:49:52 -0700585 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
586 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800587}
588
589// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
590void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
591{
Eric Laurent10351942014-05-08 18:49:52 -0700592 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
593 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800594}
595
Eric Laurent10351942014-05-08 18:49:52 -0700596// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
597status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800598{
Eric Laurent10351942014-05-08 18:49:52 -0700599 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
600 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700601}
602
Eric Laurent1c333e22014-05-20 10:48:17 -0700603status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
604 const struct audio_patch *patch,
605 audio_patch_handle_t *handle)
606{
607 Mutex::Autolock _l(mLock);
608 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
609 status_t status = sendConfigEvent_l(configEvent);
610 if (status == NO_ERROR) {
611 CreateAudioPatchConfigEventData *data =
612 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
613 *handle = data->mHandle;
614 }
615 return status;
616}
617
618status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
619 const audio_patch_handle_t handle)
620{
621 Mutex::Autolock _l(mLock);
622 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
623 return sendConfigEvent_l(configEvent);
624}
625
626
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700627// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700628void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700629{
Eric Laurent10351942014-05-08 18:49:52 -0700630 bool configChanged = false;
631
Eric Laurent81784c32012-11-19 14:55:58 -0800632 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700633 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
634 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800635 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700636 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700637 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700638 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
639 // FIXME Need to understand why this has to be done asynchronously
640 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700641 true /*asynchronous*/);
642 if (err != 0) {
643 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700644 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700645 }
646 } break;
647 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700648 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700649 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700650 } break;
651 case CFG_EVENT_SET_PARAMETER: {
652 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
653 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
654 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700655 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700656 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700657 case CFG_EVENT_CREATE_AUDIO_PATCH: {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)event->mData.get();
660 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
661 } break;
662 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
663 ReleaseAudioPatchConfigEventData *data =
664 (ReleaseAudioPatchConfigEventData *)event->mData.get();
665 event->mStatus = releaseAudioPatch_l(data->mHandle);
666 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700667 default:
Eric Laurent10351942014-05-08 18:49:52 -0700668 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700669 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800670 }
Eric Laurent10351942014-05-08 18:49:52 -0700671 {
672 Mutex::Autolock _l(event->mLock);
673 if (event->mWaitStatus) {
674 event->mWaitStatus = false;
675 event->mCond.signal();
676 }
677 }
678 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
679 }
680
681 if (configChanged) {
682 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800683 }
Eric Laurent81784c32012-11-19 14:55:58 -0800684}
685
Marco Nelissenb2208842014-02-07 14:00:50 -0800686String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
687 String8 s;
688 if (output) {
689 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
690 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
691 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
692 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
693 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
694 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
695 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
696 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
697 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
698 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
699 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
700 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
701 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
702 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
703 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
704 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
705 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
706 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
707 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
708 } else {
709 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
710 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
711 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
712 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
713 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
714 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
715 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
716 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
717 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
718 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
719 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
720 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
721 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
722 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
723 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
724 }
725 int len = s.length();
726 if (s.length() > 2) {
727 char *str = s.lockBuffer(len);
728 s.unlockBuffer(len - 2);
729 }
730 return s;
731}
732
Glenn Kasten0f11b512014-01-31 16:18:54 -0800733void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800734{
735 const size_t SIZE = 256;
736 char buffer[SIZE];
737 String8 result;
738
739 bool locked = AudioFlinger::dumpTryLock(mLock);
740 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700741 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
743
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800744 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700745 dprintf(fd, " I/O handle: %d\n", mId);
746 dprintf(fd, " TID: %d\n", getTid());
747 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700748 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700749 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700750 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700751 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700752 dprintf(fd, " Channel count: %u\n", mChannelCount);
753 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800754 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700755 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
756 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700757 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800758 size_t numConfig = mConfigEvents.size();
759 if (numConfig) {
760 for (size_t i = 0; i < numConfig; i++) {
761 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700762 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800763 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700764 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800765 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700766 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800768 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
769 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
770 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800771
772 if (locked) {
773 mLock.unlock();
774 }
775}
776
777void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
778{
779 const size_t SIZE = 256;
780 char buffer[SIZE];
781 String8 result;
782
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000784 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800785 write(fd, buffer, strlen(buffer));
786
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800788 sp<EffectChain> chain = mEffectChains[i];
789 if (chain != 0) {
790 chain->dump(fd, args);
791 }
792 }
793}
794
Marco Nelissene14a5d62013-10-03 08:51:24 -0700795void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800796{
797 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700798 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800799}
800
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100801String16 AudioFlinger::ThreadBase::getWakeLockTag()
802{
803 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800804 case MIXER:
805 return String16("AudioMix");
806 case DIRECT:
807 return String16("AudioDirectOut");
808 case DUPLICATING:
809 return String16("AudioDup");
810 case RECORD:
811 return String16("AudioIn");
812 case OFFLOAD:
813 return String16("AudioOffload");
814 default:
815 ALOG_ASSERT(false);
816 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100817 }
818}
819
Marco Nelissene14a5d62013-10-03 08:51:24 -0700820void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800821{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800822 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800823 if (mPowerManager != 0) {
824 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700825 status_t status;
826 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700827 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700828 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100829 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700830 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700831 uid,
832 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700833 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700834 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700835 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100836 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700837 String16("media"),
838 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700839 }
Eric Laurent81784c32012-11-19 14:55:58 -0800840 if (status == NO_ERROR) {
841 mWakeLockToken = binder;
842 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800843 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800844 }
845}
846
847void AudioFlinger::ThreadBase::releaseWakeLock()
848{
849 Mutex::Autolock _l(mLock);
850 releaseWakeLock_l();
851}
852
853void AudioFlinger::ThreadBase::releaseWakeLock_l()
854{
855 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800856 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700858 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
859 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800860 }
861 mWakeLockToken.clear();
862 }
863}
864
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800865void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
866 Mutex::Autolock _l(mLock);
867 updateWakeLockUids_l(uids);
868}
869
870void AudioFlinger::ThreadBase::getPowerManager_l() {
871
872 if (mPowerManager == 0) {
873 // use checkService() to avoid blocking if power service is not up yet
874 sp<IBinder> binder =
875 defaultServiceManager()->checkService(String16("power"));
876 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800877 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800878 } else {
879 mPowerManager = interface_cast<IPowerManager>(binder);
880 binder->linkToDeath(mDeathRecipient);
881 }
882 }
883}
884
885void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
886
887 getPowerManager_l();
888 if (mWakeLockToken == NULL) {
889 ALOGE("no wake lock to update!");
890 return;
891 }
892 if (mPowerManager != 0) {
893 sp<IBinder> binder = new BBinder();
894 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700895 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
896 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800897 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800898 }
899}
900
Eric Laurent81784c32012-11-19 14:55:58 -0800901void AudioFlinger::ThreadBase::clearPowerManager()
902{
903 Mutex::Autolock _l(mLock);
904 releaseWakeLock_l();
905 mPowerManager.clear();
906}
907
Glenn Kasten0f11b512014-01-31 16:18:54 -0800908void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800909{
910 sp<ThreadBase> thread = mThread.promote();
911 if (thread != 0) {
912 thread->clearPowerManager();
913 }
914 ALOGW("power manager service died !!!");
915}
916
917void AudioFlinger::ThreadBase::setEffectSuspended(
918 const effect_uuid_t *type, bool suspend, int sessionId)
919{
920 Mutex::Autolock _l(mLock);
921 setEffectSuspended_l(type, suspend, sessionId);
922}
923
924void AudioFlinger::ThreadBase::setEffectSuspended_l(
925 const effect_uuid_t *type, bool suspend, int sessionId)
926{
927 sp<EffectChain> chain = getEffectChain_l(sessionId);
928 if (chain != 0) {
929 if (type != NULL) {
930 chain->setEffectSuspended_l(type, suspend);
931 } else {
932 chain->setEffectSuspendedAll_l(suspend);
933 }
934 }
935
936 updateSuspendedSessions_l(type, suspend, sessionId);
937}
938
939void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
940{
941 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
942 if (index < 0) {
943 return;
944 }
945
946 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
947 mSuspendedSessions.valueAt(index);
948
949 for (size_t i = 0; i < sessionEffects.size(); i++) {
950 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
951 for (int j = 0; j < desc->mRefCount; j++) {
952 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
953 chain->setEffectSuspendedAll_l(true);
954 } else {
955 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
956 desc->mType.timeLow);
957 chain->setEffectSuspended_l(&desc->mType, true);
958 }
959 }
960 }
961}
962
963void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
964 bool suspend,
965 int sessionId)
966{
967 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
968
969 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
970
971 if (suspend) {
972 if (index >= 0) {
973 sessionEffects = mSuspendedSessions.valueAt(index);
974 } else {
975 mSuspendedSessions.add(sessionId, sessionEffects);
976 }
977 } else {
978 if (index < 0) {
979 return;
980 }
981 sessionEffects = mSuspendedSessions.valueAt(index);
982 }
983
984
985 int key = EffectChain::kKeyForSuspendAll;
986 if (type != NULL) {
987 key = type->timeLow;
988 }
989 index = sessionEffects.indexOfKey(key);
990
991 sp<SuspendedSessionDesc> desc;
992 if (suspend) {
993 if (index >= 0) {
994 desc = sessionEffects.valueAt(index);
995 } else {
996 desc = new SuspendedSessionDesc();
997 if (type != NULL) {
998 desc->mType = *type;
999 }
1000 sessionEffects.add(key, desc);
1001 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1002 }
1003 desc->mRefCount++;
1004 } else {
1005 if (index < 0) {
1006 return;
1007 }
1008 desc = sessionEffects.valueAt(index);
1009 if (--desc->mRefCount == 0) {
1010 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1011 sessionEffects.removeItemsAt(index);
1012 if (sessionEffects.isEmpty()) {
1013 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1014 sessionId);
1015 mSuspendedSessions.removeItem(sessionId);
1016 }
1017 }
1018 }
1019 if (!sessionEffects.isEmpty()) {
1020 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1021 }
1022}
1023
1024void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1025 bool enabled,
1026 int sessionId)
1027{
1028 Mutex::Autolock _l(mLock);
1029 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1030}
1031
1032void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1033 bool enabled,
1034 int sessionId)
1035{
1036 if (mType != RECORD) {
1037 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1038 // another session. This gives the priority to well behaved effect control panels
1039 // and applications not using global effects.
1040 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1041 // global effects
1042 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1043 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1044 }
1045 }
1046
1047 sp<EffectChain> chain = getEffectChain_l(sessionId);
1048 if (chain != 0) {
1049 chain->checkSuspendOnEffectEnabled(effect, enabled);
1050 }
1051}
1052
1053// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1054sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1055 const sp<AudioFlinger::Client>& client,
1056 const sp<IEffectClient>& effectClient,
1057 int32_t priority,
1058 int sessionId,
1059 effect_descriptor_t *desc,
1060 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001061 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001062{
1063 sp<EffectModule> effect;
1064 sp<EffectHandle> handle;
1065 status_t lStatus;
1066 sp<EffectChain> chain;
1067 bool chainCreated = false;
1068 bool effectCreated = false;
1069 bool effectRegistered = false;
1070
1071 lStatus = initCheck();
1072 if (lStatus != NO_ERROR) {
1073 ALOGW("createEffect_l() Audio driver not initialized.");
1074 goto Exit;
1075 }
1076
Andy Hung98ef9782014-03-04 14:46:50 -08001077 // Reject any effect on Direct output threads for now, since the format of
1078 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1079 if (mType == DIRECT) {
1080 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001081 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001082 lStatus = BAD_VALUE;
1083 goto Exit;
1084 }
1085
Andy Hung389cfdb2014-08-07 17:49:53 -07001086 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001087 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001088 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1089 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1090 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001091 lStatus = BAD_VALUE;
1092 goto Exit;
1093 }
1094
Eric Laurent5baf2af2013-09-12 17:37:00 -07001095 // Allow global effects only on offloaded and mixer threads
1096 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1097 switch (mType) {
1098 case MIXER:
1099 case OFFLOAD:
1100 break;
1101 case DIRECT:
1102 case DUPLICATING:
1103 case RECORD:
1104 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001105 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1106 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001107 lStatus = BAD_VALUE;
1108 goto Exit;
1109 }
Eric Laurent81784c32012-11-19 14:55:58 -08001110 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001111
Eric Laurent81784c32012-11-19 14:55:58 -08001112 // Only Pre processor effects are allowed on input threads and only on input threads
1113 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1114 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1115 desc->name, desc->flags, mType);
1116 lStatus = BAD_VALUE;
1117 goto Exit;
1118 }
1119
1120 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1121
1122 { // scope for mLock
1123 Mutex::Autolock _l(mLock);
1124
1125 // check for existing effect chain with the requested audio session
1126 chain = getEffectChain_l(sessionId);
1127 if (chain == 0) {
1128 // create a new chain for this session
1129 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1130 chain = new EffectChain(this, sessionId);
1131 addEffectChain_l(chain);
1132 chain->setStrategy(getStrategyForSession_l(sessionId));
1133 chainCreated = true;
1134 } else {
1135 effect = chain->getEffectFromDesc_l(desc);
1136 }
1137
1138 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1139
1140 if (effect == 0) {
1141 int id = mAudioFlinger->nextUniqueId();
1142 // Check CPU and memory usage
1143 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1144 if (lStatus != NO_ERROR) {
1145 goto Exit;
1146 }
1147 effectRegistered = true;
1148 // create a new effect module if none present in the chain
1149 effect = new EffectModule(this, chain, desc, id, sessionId);
1150 lStatus = effect->status();
1151 if (lStatus != NO_ERROR) {
1152 goto Exit;
1153 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001154 effect->setOffloaded(mType == OFFLOAD, mId);
1155
Eric Laurent81784c32012-11-19 14:55:58 -08001156 lStatus = chain->addEffect_l(effect);
1157 if (lStatus != NO_ERROR) {
1158 goto Exit;
1159 }
1160 effectCreated = true;
1161
1162 effect->setDevice(mOutDevice);
1163 effect->setDevice(mInDevice);
1164 effect->setMode(mAudioFlinger->getMode());
1165 effect->setAudioSource(mAudioSource);
1166 }
1167 // create effect handle and connect it to effect module
1168 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001169 lStatus = handle->initCheck();
1170 if (lStatus == OK) {
1171 lStatus = effect->addHandle(handle.get());
1172 }
Eric Laurent81784c32012-11-19 14:55:58 -08001173 if (enabled != NULL) {
1174 *enabled = (int)effect->isEnabled();
1175 }
1176 }
1177
1178Exit:
1179 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1180 Mutex::Autolock _l(mLock);
1181 if (effectCreated) {
1182 chain->removeEffect_l(effect);
1183 }
1184 if (effectRegistered) {
1185 AudioSystem::unregisterEffect(effect->id());
1186 }
1187 if (chainCreated) {
1188 removeEffectChain_l(chain);
1189 }
1190 handle.clear();
1191 }
1192
Glenn Kasten9156ef32013-08-06 15:39:08 -07001193 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001194 return handle;
1195}
1196
1197sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1198{
1199 Mutex::Autolock _l(mLock);
1200 return getEffect_l(sessionId, effectId);
1201}
1202
1203sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1204{
1205 sp<EffectChain> chain = getEffectChain_l(sessionId);
1206 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1207}
1208
1209// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1210// PlaybackThread::mLock held
1211status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1212{
1213 // check for existing effect chain with the requested audio session
1214 int sessionId = effect->sessionId();
1215 sp<EffectChain> chain = getEffectChain_l(sessionId);
1216 bool chainCreated = false;
1217
Eric Laurent5baf2af2013-09-12 17:37:00 -07001218 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1219 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1220 this, effect->desc().name, effect->desc().flags);
1221
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (chain == 0) {
1223 // create a new chain for this session
1224 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1225 chain = new EffectChain(this, sessionId);
1226 addEffectChain_l(chain);
1227 chain->setStrategy(getStrategyForSession_l(sessionId));
1228 chainCreated = true;
1229 }
1230 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1231
1232 if (chain->getEffectFromId_l(effect->id()) != 0) {
1233 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1234 this, effect->desc().name, chain.get());
1235 return BAD_VALUE;
1236 }
1237
Eric Laurent5baf2af2013-09-12 17:37:00 -07001238 effect->setOffloaded(mType == OFFLOAD, mId);
1239
Eric Laurent81784c32012-11-19 14:55:58 -08001240 status_t status = chain->addEffect_l(effect);
1241 if (status != NO_ERROR) {
1242 if (chainCreated) {
1243 removeEffectChain_l(chain);
1244 }
1245 return status;
1246 }
1247
1248 effect->setDevice(mOutDevice);
1249 effect->setDevice(mInDevice);
1250 effect->setMode(mAudioFlinger->getMode());
1251 effect->setAudioSource(mAudioSource);
1252 return NO_ERROR;
1253}
1254
1255void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1256
1257 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1258 effect_descriptor_t desc = effect->desc();
1259 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1260 detachAuxEffect_l(effect->id());
1261 }
1262
1263 sp<EffectChain> chain = effect->chain().promote();
1264 if (chain != 0) {
1265 // remove effect chain if removing last effect
1266 if (chain->removeEffect_l(effect) == 0) {
1267 removeEffectChain_l(chain);
1268 }
1269 } else {
1270 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1271 }
1272}
1273
1274void AudioFlinger::ThreadBase::lockEffectChains_l(
1275 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1276{
1277 effectChains = mEffectChains;
1278 for (size_t i = 0; i < mEffectChains.size(); i++) {
1279 mEffectChains[i]->lock();
1280 }
1281}
1282
1283void AudioFlinger::ThreadBase::unlockEffectChains(
1284 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1285{
1286 for (size_t i = 0; i < effectChains.size(); i++) {
1287 effectChains[i]->unlock();
1288 }
1289}
1290
1291sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1292{
1293 Mutex::Autolock _l(mLock);
1294 return getEffectChain_l(sessionId);
1295}
1296
1297sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1298{
1299 size_t size = mEffectChains.size();
1300 for (size_t i = 0; i < size; i++) {
1301 if (mEffectChains[i]->sessionId() == sessionId) {
1302 return mEffectChains[i];
1303 }
1304 }
1305 return 0;
1306}
1307
1308void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1309{
1310 Mutex::Autolock _l(mLock);
1311 size_t size = mEffectChains.size();
1312 for (size_t i = 0; i < size; i++) {
1313 mEffectChains[i]->setMode_l(mode);
1314 }
1315}
1316
Eric Laurent83b88082014-06-20 18:31:16 -07001317void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1318{
1319 config->type = AUDIO_PORT_TYPE_MIX;
1320 config->ext.mix.handle = mId;
1321 config->sample_rate = mSampleRate;
1322 config->format = mFormat;
1323 config->channel_mask = mChannelMask;
1324 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1325 AUDIO_PORT_CONFIG_FORMAT;
1326}
1327
1328
Eric Laurent81784c32012-11-19 14:55:58 -08001329// ----------------------------------------------------------------------------
1330// Playback
1331// ----------------------------------------------------------------------------
1332
1333AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1334 AudioStreamOut* output,
1335 audio_io_handle_t id,
1336 audio_devices_t device,
1337 type_t type)
1338 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001339 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001340 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001341 mMixerBuffer(NULL),
1342 mMixerBufferSize(0),
1343 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1344 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001345 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001346 mEffectBuffer(NULL),
1347 mEffectBufferSize(0),
1348 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1349 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001350 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001351 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001352 // mStreamTypes[] initialized in constructor body
1353 mOutput(output),
1354 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1355 mMixerStatus(MIXER_IDLE),
1356 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1357 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001358 mBytesRemaining(0),
1359 mCurrentWriteLength(0),
1360 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001361 mWriteAckSequence(0),
1362 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001363 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001364 mScreenState(AudioFlinger::mScreenState),
1365 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001366 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001367 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001368 // mLatchD, mLatchQ,
1369 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001370{
Glenn Kastend7dca052015-03-05 16:05:54 -08001371 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1372 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001373
1374 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1375 // it would be safer to explicitly pass initial masterVolume/masterMute as
1376 // parameter.
1377 //
1378 // If the HAL we are using has support for master volume or master mute,
1379 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1380 // and the mute set to false).
1381 mMasterVolume = audioFlinger->masterVolume_l();
1382 mMasterMute = audioFlinger->masterMute_l();
1383 if (mOutput && mOutput->audioHwDev) {
1384 if (mOutput->audioHwDev->canSetMasterVolume()) {
1385 mMasterVolume = 1.0;
1386 }
1387
1388 if (mOutput->audioHwDev->canSetMasterMute()) {
1389 mMasterMute = false;
1390 }
1391 }
1392
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001393 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001394
Eric Laurent223fd5c2014-11-11 13:43:36 -08001395 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001396 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001397 stream = (audio_stream_type_t) (stream + 1)) {
1398 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1399 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1400 }
Eric Laurent81784c32012-11-19 14:55:58 -08001401}
1402
1403AudioFlinger::PlaybackThread::~PlaybackThread()
1404{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001405 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001406 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001407 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001408 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001409}
1410
1411void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1412{
1413 dumpInternals(fd, args);
1414 dumpTracks(fd, args);
1415 dumpEffectChains(fd, args);
1416}
1417
Glenn Kasten0f11b512014-01-31 16:18:54 -08001418void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001419{
1420 const size_t SIZE = 256;
1421 char buffer[SIZE];
1422 String8 result;
1423
Marco Nelissenb2208842014-02-07 14:00:50 -08001424 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001425 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1426 const stream_type_t *st = &mStreamTypes[i];
1427 if (i > 0) {
1428 result.appendFormat(", ");
1429 }
1430 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1431 if (st->mute) {
1432 result.append("M");
1433 }
1434 }
1435 result.append("\n");
1436 write(fd, result.string(), result.length());
1437 result.clear();
1438
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1440 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001441 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001442 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001443
1444 size_t numtracks = mTracks.size();
1445 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001446 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001447 size_t numactiveseen = 0;
1448 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001449 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001450 Track::appendDumpHeader(result);
1451 for (size_t i = 0; i < numtracks; ++i) {
1452 sp<Track> track = mTracks[i];
1453 if (track != 0) {
1454 bool active = mActiveTracks.indexOf(track) >= 0;
1455 if (active) {
1456 numactiveseen++;
1457 }
1458 track->dump(buffer, SIZE, active);
1459 result.append(buffer);
1460 }
1461 }
1462 } else {
1463 result.append("\n");
1464 }
1465 if (numactiveseen != numactive) {
1466 // some tracks in the active list were not in the tracks list
1467 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1468 " not in the track list\n");
1469 result.append(buffer);
1470 Track::appendDumpHeader(result);
1471 for (size_t i = 0; i < numactive; ++i) {
1472 sp<Track> track = mActiveTracks[i].promote();
1473 if (track != 0 && mTracks.indexOf(track) < 0) {
1474 track->dump(buffer, SIZE, true);
1475 result.append(buffer);
1476 }
1477 }
1478 }
1479
1480 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001481}
1482
1483void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1484{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001485 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001486
1487 dumpBase(fd, args);
1488
Elliott Hughes87cebad2014-05-22 10:14:43 -07001489 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1490 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1491 dprintf(fd, " Total writes: %d\n", mNumWrites);
1492 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1493 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1494 dprintf(fd, " Suspend count: %d\n", mSuspended);
1495 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1496 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1497 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1498 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001499 AudioStreamOut *output = mOutput;
1500 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1501 String8 flagsAsString = outputFlagsToString(flags);
1502 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001503}
1504
1505// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001506
1507void AudioFlinger::PlaybackThread::onFirstRef()
1508{
Glenn Kastend7dca052015-03-05 16:05:54 -08001509 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001510}
1511
1512// ThreadBase virtuals
1513void AudioFlinger::PlaybackThread::preExit()
1514{
1515 ALOGV(" preExit()");
1516 // FIXME this is using hard-coded strings but in the future, this functionality will be
1517 // converted to use audio HAL extensions required to support tunneling
1518 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1519}
1520
1521// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1522sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1523 const sp<AudioFlinger::Client>& client,
1524 audio_stream_type_t streamType,
1525 uint32_t sampleRate,
1526 audio_format_t format,
1527 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001528 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001529 const sp<IMemory>& sharedBuffer,
1530 int sessionId,
1531 IAudioFlinger::track_flags_t *flags,
1532 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001533 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001534 status_t *status)
1535{
Glenn Kasten74935e42013-12-19 08:56:45 -08001536 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001537 sp<Track> track;
1538 status_t lStatus;
1539
1540 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1541
1542 // client expresses a preference for FAST, but we get the final say
1543 if (*flags & IAudioFlinger::TRACK_FAST) {
1544 if (
1545 // not timed
1546 (!isTimed) &&
1547 // either of these use cases:
1548 (
1549 // use case 1: shared buffer with any frame count
1550 (
1551 (sharedBuffer != 0)
1552 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001553 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001554 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001555 // we formerly checked for a callback handler (non-0 tid),
1556 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001557 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001558 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001559 )
1560 ) &&
1561 // PCM data
1562 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001563 // identical channel mask to sink, or mono in and stereo sink
1564 (channelMask == mChannelMask ||
1565 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1566 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001567 // hardware sample rate
1568 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001569 // normal mixer has an associated fast mixer
1570 hasFastMixer() &&
1571 // there are sufficient fast track slots available
1572 (mFastTrackAvailMask != 0)
1573 // FIXME test that MixerThread for this fast track has a capable output HAL
1574 // FIXME add a permission test also?
1575 ) {
1576 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1577 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001578 // read the fast track multiplier property the first time it is needed
1579 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1580 if (ok != 0) {
1581 ALOGE("%s pthread_once failed: %d", __func__, ok);
1582 }
1583 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001584 }
1585 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1586 frameCount, mFrameCount);
1587 } else {
1588 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001589 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1590 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001591 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001592 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001593 audio_is_linear_pcm(format),
1594 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1595 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001596 }
1597 }
1598 // For normal PCM streaming tracks, update minimum frame count.
1599 // For compatibility with AudioTrack calculation, buffer depth is forced
1600 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1601 // This is probably too conservative, but legacy application code may depend on it.
1602 // If you change this calculation, also review the start threshold which is related.
1603 if (!(*flags & IAudioFlinger::TRACK_FAST)
1604 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001605 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1606 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1607 if (minBufCount < 2) {
1608 minBufCount = 2;
1609 }
Andy Hung0e48d252015-01-26 11:43:15 -08001610 size_t minFrameCount =
1611 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1612 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001613 frameCount = minFrameCount;
1614 }
Eric Laurent81784c32012-11-19 14:55:58 -08001615 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001616 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001617
Glenn Kastenc3df8382014-03-13 15:05:25 -07001618 switch (mType) {
1619
1620 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001621 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001622 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001623 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1624 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001625 sampleRate, format, channelMask, mOutput, mFormat);
1626 lStatus = BAD_VALUE;
1627 goto Exit;
1628 }
1629 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001630 break;
1631
1632 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001633 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001634 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1635 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001636 sampleRate, format, channelMask, mOutput, mFormat);
1637 lStatus = BAD_VALUE;
1638 goto Exit;
1639 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001640 break;
1641
1642 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001643 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001644 ALOGE("createTrack_l() Bad parameter: format %#x \""
1645 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001646 format, mOutput, mFormat);
1647 lStatus = BAD_VALUE;
1648 goto Exit;
1649 }
Andy Hungcd044842014-08-07 11:04:34 -07001650 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001651 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1652 lStatus = BAD_VALUE;
1653 goto Exit;
1654 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001655 break;
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 }
1658
1659 lStatus = initCheck();
1660 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001661 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001662 goto Exit;
1663 }
1664
1665 { // scope for mLock
1666 Mutex::Autolock _l(mLock);
1667
1668 // all tracks in same audio session must share the same routing strategy otherwise
1669 // conflicts will happen when tracks are moved from one output to another by audio policy
1670 // manager
1671 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1672 for (size_t i = 0; i < mTracks.size(); ++i) {
1673 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001674 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001675 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1676 if (sessionId == t->sessionId() && strategy != actual) {
1677 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1678 strategy, actual);
1679 lStatus = BAD_VALUE;
1680 goto Exit;
1681 }
1682 }
1683 }
1684
1685 if (!isTimed) {
1686 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001687 channelMask, frameCount, NULL, sharedBuffer,
1688 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001689 } else {
1690 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001691 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001692 }
Glenn Kasten03003332013-08-06 15:40:54 -07001693
1694 // new Track always returns non-NULL,
1695 // but TimedTrack::create() is a factory that could fail by returning NULL
1696 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1697 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001698 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001699 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001700 goto Exit;
1701 }
1702 mTracks.add(track);
1703
1704 sp<EffectChain> chain = getEffectChain_l(sessionId);
1705 if (chain != 0) {
1706 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1707 track->setMainBuffer(chain->inBuffer());
1708 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1709 chain->incTrackCnt();
1710 }
1711
1712 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1713 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1714 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1715 // so ask activity manager to do this on our behalf
1716 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1717 }
1718 }
1719
1720 lStatus = NO_ERROR;
1721
1722Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001723 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001724 return track;
1725}
1726
1727uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1728{
1729 return latency;
1730}
1731
1732uint32_t AudioFlinger::PlaybackThread::latency() const
1733{
1734 Mutex::Autolock _l(mLock);
1735 return latency_l();
1736}
1737uint32_t AudioFlinger::PlaybackThread::latency_l() const
1738{
1739 if (initCheck() == NO_ERROR) {
1740 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1741 } else {
1742 return 0;
1743 }
1744}
1745
1746void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1747{
1748 Mutex::Autolock _l(mLock);
1749 // Don't apply master volume in SW if our HAL can do it for us.
1750 if (mOutput && mOutput->audioHwDev &&
1751 mOutput->audioHwDev->canSetMasterVolume()) {
1752 mMasterVolume = 1.0;
1753 } else {
1754 mMasterVolume = value;
1755 }
1756}
1757
1758void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1759{
1760 Mutex::Autolock _l(mLock);
1761 // Don't apply master mute in SW if our HAL can do it for us.
1762 if (mOutput && mOutput->audioHwDev &&
1763 mOutput->audioHwDev->canSetMasterMute()) {
1764 mMasterMute = false;
1765 } else {
1766 mMasterMute = muted;
1767 }
1768}
1769
1770void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1771{
1772 Mutex::Autolock _l(mLock);
1773 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001774 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001775}
1776
1777void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1778{
1779 Mutex::Autolock _l(mLock);
1780 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001781 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001782}
1783
1784float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1785{
1786 Mutex::Autolock _l(mLock);
1787 return mStreamTypes[stream].volume;
1788}
1789
1790// addTrack_l() must be called with ThreadBase::mLock held
1791status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1792{
1793 status_t status = ALREADY_EXISTS;
1794
1795 // set retry count for buffer fill
1796 track->mRetryCount = kMaxTrackStartupRetries;
1797 if (mActiveTracks.indexOf(track) < 0) {
1798 // the track is newly added, make sure it fills up all its
1799 // buffers before playing. This is to ensure the client will
1800 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001801 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001802 TrackBase::track_state state = track->mState;
1803 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001804 status = AudioSystem::startOutput(mId, track->streamType(),
1805 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001806 mLock.lock();
1807 // abort track was stopped/paused while we released the lock
1808 if (state != track->mState) {
1809 if (status == NO_ERROR) {
1810 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001811 AudioSystem::stopOutput(mId, track->streamType(),
1812 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001813 mLock.lock();
1814 }
1815 return INVALID_OPERATION;
1816 }
1817 // abort if start is rejected by audio policy manager
1818 if (status != NO_ERROR) {
1819 return PERMISSION_DENIED;
1820 }
1821#ifdef ADD_BATTERY_DATA
1822 // to track the speaker usage
1823 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1824#endif
1825 }
1826
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001828 track->mResetDone = false;
1829 track->mPresentationCompleteFrames = 0;
1830 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001831 mWakeLockUids.add(track->uid());
1832 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001833 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001834 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1835 if (chain != 0) {
1836 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1837 track->sessionId());
1838 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001839 }
1840
1841 status = NO_ERROR;
1842 }
1843
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001844 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001845 return status;
1846}
1847
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001849{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001851 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1853 track->mState = TrackBase::STOPPED;
1854 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001856 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859
1860 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001861}
1862
1863void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1864{
1865 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1866 mTracks.remove(track);
1867 deleteTrackName_l(track->name());
1868 // redundant as track is about to be destroyed, for dumpsys only
1869 track->mName = -1;
1870 if (track->isFastTrack()) {
1871 int index = track->mFastIndex;
1872 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1873 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1874 mFastTrackAvailMask |= 1 << index;
1875 // redundant as track is about to be destroyed, for dumpsys only
1876 track->mFastIndex = -1;
1877 }
1878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1879 if (chain != 0) {
1880 chain->decTrackCnt();
1881 }
1882}
1883
Eric Laurentede6c3b2013-09-19 14:37:46 -07001884void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885{
1886 // Thread could be blocked waiting for async
1887 // so signal it to handle state changes immediately
1888 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1889 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1890 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001891 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892}
1893
Eric Laurent81784c32012-11-19 14:55:58 -08001894String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1895{
Eric Laurent81784c32012-11-19 14:55:58 -08001896 Mutex::Autolock _l(mLock);
1897 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001898 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001899 }
1900
Glenn Kastend8ea6992013-07-16 14:17:15 -07001901 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1902 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001903 free(s);
1904 return out_s8;
1905}
1906
Eric Laurent021cf962014-05-13 10:18:14 -07001907void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001908 AudioSystem::OutputDescriptor desc;
1909 void *param2 = NULL;
1910
Eric Laurent021cf962014-05-13 10:18:14 -07001911 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001912 param);
1913
1914 switch (event) {
1915 case AudioSystem::OUTPUT_OPENED:
1916 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001917 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001918 desc.samplingRate = mSampleRate;
1919 desc.format = mFormat;
1920 desc.frameCount = mNormalFrameCount; // FIXME see
1921 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001922 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001923 param2 = &desc;
1924 break;
1925
1926 case AudioSystem::STREAM_CONFIG_CHANGED:
1927 param2 = &param;
1928 case AudioSystem::OUTPUT_CLOSED:
1929 default:
1930 break;
1931 }
Eric Laurent021cf962014-05-13 10:18:14 -07001932 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001933}
1934
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935void AudioFlinger::PlaybackThread::writeCallback()
1936{
1937 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001938 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939}
1940
1941void AudioFlinger::PlaybackThread::drainCallback()
1942{
1943 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001944 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945}
1946
Eric Laurent3b4529e2013-09-05 18:09:19 -07001947void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948{
1949 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950 // reject out of sequence requests
1951 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1952 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 mWaitWorkCV.signal();
1954 }
1955}
1956
Eric Laurent3b4529e2013-09-05 18:09:19 -07001957void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958{
1959 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001960 // reject out of sequence requests
1961 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1962 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 mWaitWorkCV.signal();
1964 }
1965}
1966
1967// static
1968int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001969 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 void *cookie)
1971{
1972 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1973 ALOGV("asyncCallback() event %d", event);
1974 switch (event) {
1975 case STREAM_CBK_EVENT_WRITE_READY:
1976 me->writeCallback();
1977 break;
1978 case STREAM_CBK_EVENT_DRAIN_READY:
1979 me->drainCallback();
1980 break;
1981 default:
1982 ALOGW("asyncCallback() unknown event %d", event);
1983 break;
1984 }
1985 return 0;
1986}
1987
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001988void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001989{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001990 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001991 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1992 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001993 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001994 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001995 }
Andy Hung9a592762014-07-21 21:56:01 -07001996 if ((mType == MIXER || mType == DUPLICATING)
1997 && !isValidPcmSinkChannelMask(mChannelMask)) {
1998 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1999 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002000 }
Andy Hunge5412692014-05-16 11:25:07 -07002001 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002002 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2003 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002004 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002005 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002006 }
Andy Hung6146c082014-03-18 11:56:15 -07002007 if ((mType == MIXER || mType == DUPLICATING)
2008 && !isValidPcmSinkFormat(mFormat)) {
2009 LOG_FATAL("HAL format %#x not supported for mixed output",
2010 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002011 }
Eric Laurent665470b2014-07-03 16:37:08 -07002012 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07002013 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2014 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002015 if (mFrameCount & 15) {
2016 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2017 mFrameCount);
2018 }
2019
Eric Laurentbfb1b832013-01-07 09:53:42 -08002020 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2021 (mOutput->stream->set_callback != NULL)) {
2022 if (mOutput->stream->set_callback(mOutput->stream,
2023 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2024 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002025 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002026 }
2027 }
2028
Eric Laurentd1f69b02014-12-15 14:33:13 -08002029 mHwSupportsPause = false;
2030 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2031 if (mOutput->stream->pause != NULL) {
2032 if (mOutput->stream->resume != NULL) {
2033 mHwSupportsPause = true;
2034 } else {
2035 ALOGW("direct output implements pause but not resume");
2036 }
2037 } else if (mOutput->stream->resume != NULL) {
2038 ALOGW("direct output implements resume but not pause");
2039 }
2040 }
2041
Andy Hungfbfc3952015-01-15 13:33:51 -08002042 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2043 // For best precision, we use float instead of the associated output
2044 // device format (typically PCM 16 bit).
2045
2046 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2047 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2048 mBufferSize = mFrameSize * mFrameCount;
2049
2050 // TODO: We currently use the associated output device channel mask and sample rate.
2051 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2052 // (if a valid mask) to avoid premature downmix.
2053 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2054 // instead of the output device sample rate to avoid loss of high frequency information.
2055 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2056 }
2057
Andy Hung09a50072014-02-27 14:30:47 -08002058 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002059 double multiplier = 1.0;
2060 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2061 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002062 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2063 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002064 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2065 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2066 maxNormalFrameCount = maxNormalFrameCount & ~15;
2067 if (maxNormalFrameCount < minNormalFrameCount) {
2068 maxNormalFrameCount = minNormalFrameCount;
2069 }
2070 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2071 if (multiplier <= 1.0) {
2072 multiplier = 1.0;
2073 } else if (multiplier <= 2.0) {
2074 if (2 * mFrameCount <= maxNormalFrameCount) {
2075 multiplier = 2.0;
2076 } else {
2077 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2078 }
2079 } else {
2080 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002081 // 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 -08002082 // track, but we sometimes have to do this to satisfy the maximum frame count
2083 // constraint)
2084 // FIXME this rounding up should not be done if no HAL SRC
2085 uint32_t truncMult = (uint32_t) multiplier;
2086 if ((truncMult & 1)) {
2087 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2088 ++truncMult;
2089 }
2090 }
2091 multiplier = (double) truncMult;
2092 }
2093 }
2094 mNormalFrameCount = multiplier * mFrameCount;
2095 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002096 if (mType == MIXER || mType == DUPLICATING) {
2097 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2098 }
Andy Hung09a50072014-02-27 14:30:47 -08002099 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002100 mNormalFrameCount);
2101
Andy Hung010a1a12014-03-13 13:57:33 -07002102 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2103 // Originally this was int16_t[] array, need to remove legacy implications.
2104 free(mSinkBuffer);
2105 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002106 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2107 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2108 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002109 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002110
Andy Hung69aed5f2014-02-25 17:24:40 -08002111 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2112 // drives the output.
2113 free(mMixerBuffer);
2114 mMixerBuffer = NULL;
2115 if (mMixerBufferEnabled) {
2116 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2117 mMixerBufferSize = mNormalFrameCount * mChannelCount
2118 * audio_bytes_per_sample(mMixerBufferFormat);
2119 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2120 }
Andy Hung98ef9782014-03-04 14:46:50 -08002121 free(mEffectBuffer);
2122 mEffectBuffer = NULL;
2123 if (mEffectBufferEnabled) {
2124 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2125 mEffectBufferSize = mNormalFrameCount * mChannelCount
2126 * audio_bytes_per_sample(mEffectBufferFormat);
2127 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2128 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002129
Eric Laurent81784c32012-11-19 14:55:58 -08002130 // force reconfiguration of effect chains and engines to take new buffer size and audio
2131 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002132 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002133 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2134 // matter.
2135 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2136 Vector< sp<EffectChain> > effectChains = mEffectChains;
2137 for (size_t i = 0; i < effectChains.size(); i ++) {
2138 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2139 }
2140}
2141
2142
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002143status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002144{
2145 if (halFrames == NULL || dspFrames == NULL) {
2146 return BAD_VALUE;
2147 }
2148 Mutex::Autolock _l(mLock);
2149 if (initCheck() != NO_ERROR) {
2150 return INVALID_OPERATION;
2151 }
2152 size_t framesWritten = mBytesWritten / mFrameSize;
2153 *halFrames = framesWritten;
2154
2155 if (isSuspended()) {
2156 // return an estimation of rendered frames when the output is suspended
2157 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2158 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2159 return NO_ERROR;
2160 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002161 status_t status;
2162 uint32_t frames;
2163 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2164 *dspFrames = (size_t)frames;
2165 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002166 }
2167}
2168
2169uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2170{
2171 Mutex::Autolock _l(mLock);
2172 uint32_t result = 0;
2173 if (getEffectChain_l(sessionId) != 0) {
2174 result = EFFECT_SESSION;
2175 }
2176
2177 for (size_t i = 0; i < mTracks.size(); ++i) {
2178 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002179 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002180 result |= TRACK_SESSION;
2181 break;
2182 }
2183 }
2184
2185 return result;
2186}
2187
2188uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2189{
2190 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2191 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2192 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2193 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2194 }
2195 for (size_t i = 0; i < mTracks.size(); i++) {
2196 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002197 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002198 return AudioSystem::getStrategyForStream(track->streamType());
2199 }
2200 }
2201 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2202}
2203
2204
2205AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2206{
2207 Mutex::Autolock _l(mLock);
2208 return mOutput;
2209}
2210
2211AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2212{
2213 Mutex::Autolock _l(mLock);
2214 AudioStreamOut *output = mOutput;
2215 mOutput = NULL;
2216 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2217 // must push a NULL and wait for ack
2218 mOutputSink.clear();
2219 mPipeSink.clear();
2220 mNormalSink.clear();
2221 return output;
2222}
2223
2224// this method must always be called either with ThreadBase mLock held or inside the thread loop
2225audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2226{
2227 if (mOutput == NULL) {
2228 return NULL;
2229 }
2230 return &mOutput->stream->common;
2231}
2232
2233uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2234{
2235 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2236}
2237
2238status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2239{
2240 if (!isValidSyncEvent(event)) {
2241 return BAD_VALUE;
2242 }
2243
2244 Mutex::Autolock _l(mLock);
2245
2246 for (size_t i = 0; i < mTracks.size(); ++i) {
2247 sp<Track> track = mTracks[i];
2248 if (event->triggerSession() == track->sessionId()) {
2249 (void) track->setSyncEvent(event);
2250 return NO_ERROR;
2251 }
2252 }
2253
2254 return NAME_NOT_FOUND;
2255}
2256
2257bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2258{
2259 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2260}
2261
2262void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2263 const Vector< sp<Track> >& tracksToRemove)
2264{
2265 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002266 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002267 for (size_t i = 0 ; i < count ; i++) {
2268 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002269 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002270 AudioSystem::stopOutput(mId, track->streamType(),
2271 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272#ifdef ADD_BATTERY_DATA
2273 // to track the speaker usage
2274 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2275#endif
2276 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002277 AudioSystem::releaseOutput(mId, track->streamType(),
2278 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279 }
Eric Laurent81784c32012-11-19 14:55:58 -08002280 }
2281 }
2282 }
Eric Laurent81784c32012-11-19 14:55:58 -08002283}
2284
2285void AudioFlinger::PlaybackThread::checkSilentMode_l()
2286{
2287 if (!mMasterMute) {
2288 char value[PROPERTY_VALUE_MAX];
2289 if (property_get("ro.audio.silent", value, "0") > 0) {
2290 char *endptr;
2291 unsigned long ul = strtoul(value, &endptr, 0);
2292 if (*endptr == '\0' && ul != 0) {
2293 ALOGD("Silence is golden");
2294 // The setprop command will not allow a property to be changed after
2295 // the first time it is set, so we don't have to worry about un-muting.
2296 setMasterMute_l(true);
2297 }
2298 }
2299 }
2300}
2301
2302// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002304{
2305 // FIXME rewrite to reduce number of system calls
2306 mLastWriteTime = systemTime();
2307 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002309 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002310
2311 // If an NBAIO sink is present, use it to write the normal mixer's submix
2312 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002313
Andy Hung010a1a12014-03-13 13:57:33 -07002314 const size_t count = mBytesRemaining / mFrameSize;
2315
Simon Wilson2d590962012-11-29 15:18:50 -08002316 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002317 // update the setpoint when AudioFlinger::mScreenState changes
2318 uint32_t screenState = AudioFlinger::mScreenState;
2319 if (screenState != mScreenState) {
2320 mScreenState = screenState;
2321 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2322 if (pipe != NULL) {
2323 pipe->setAvgFrames((mScreenState & 1) ?
2324 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2325 }
2326 }
Andy Hung010a1a12014-03-13 13:57:33 -07002327 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002328 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002329 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002330 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002331 } else {
2332 bytesWritten = framesWritten;
2333 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002334 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002335 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002336 if (status == NO_ERROR) {
2337 size_t totalFramesWritten = mNormalSink->framesWritten();
2338 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2339 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002340 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002341 mLatchDValid = true;
2342 }
2343 }
Eric Laurent81784c32012-11-19 14:55:58 -08002344 // otherwise use the HAL / AudioStreamOut directly
2345 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002347
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002349 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2350 mWriteAckSequence += 2;
2351 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002353 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002355 // FIXME We should have an implementation of timestamps for direct output threads.
2356 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002357 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002358 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002359 if (mUseAsyncWrite &&
2360 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2361 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002362 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002364 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 }
Eric Laurent81784c32012-11-19 14:55:58 -08002366 }
2367
Eric Laurent81784c32012-11-19 14:55:58 -08002368 mNumWrites++;
2369 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002370 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371 return bytesWritten;
2372}
2373
2374void AudioFlinger::PlaybackThread::threadLoop_drain()
2375{
2376 if (mOutput->stream->drain) {
2377 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2378 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002379 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2380 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002382 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 }
2384 mOutput->stream->drain(mOutput->stream,
2385 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2386 : AUDIO_DRAIN_ALL);
2387 }
2388}
2389
2390void AudioFlinger::PlaybackThread::threadLoop_exit()
2391{
Eric Laurent275e8e92014-11-30 15:14:47 -08002392 {
2393 Mutex::Autolock _l(mLock);
2394 for (size_t i = 0; i < mTracks.size(); i++) {
2395 sp<Track> track = mTracks[i];
2396 track->invalidate();
2397 }
2398 }
Eric Laurent81784c32012-11-19 14:55:58 -08002399}
2400
2401/*
2402The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002403 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002404 - activeSleepTime from activeSleepTimeUs()
2405 - idleSleepTime from idleSleepTimeUs()
2406 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2407 - maxPeriod from frame count and sample rate (MIXER only)
2408
2409The parameters that affect these derived values are:
2410 - frame count
2411 - frame size
2412 - sample rate
2413 - device type: A2DP or not
2414 - device latency
2415 - format: PCM or not
2416 - active sleep time
2417 - idle sleep time
2418*/
2419
2420void AudioFlinger::PlaybackThread::cacheParameters_l()
2421{
Andy Hung25c2dac2014-02-27 14:56:00 -08002422 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002423 activeSleepTime = activeSleepTimeUs();
2424 idleSleepTime = idleSleepTimeUs();
2425}
2426
2427void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2428{
Glenn Kasten7c027242012-12-26 14:43:16 -08002429 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002430 this, streamType, mTracks.size());
2431 Mutex::Autolock _l(mLock);
2432
2433 size_t size = mTracks.size();
2434 for (size_t i = 0; i < size; i++) {
2435 sp<Track> t = mTracks[i];
2436 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002437 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002438 }
2439 }
2440}
2441
2442status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2443{
2444 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002445 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2446 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002447 bool ownsBuffer = false;
2448
2449 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2450 if (session > 0) {
2451 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002452 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002453 if (mType != DIRECT) {
2454 size_t numSamples = mNormalFrameCount * mChannelCount;
2455 buffer = new int16_t[numSamples];
2456 memset(buffer, 0, numSamples * sizeof(int16_t));
2457 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2458 ownsBuffer = true;
2459 }
2460
2461 // Attach all tracks with same session ID to this chain.
2462 for (size_t i = 0; i < mTracks.size(); ++i) {
2463 sp<Track> track = mTracks[i];
2464 if (session == track->sessionId()) {
2465 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2466 buffer);
2467 track->setMainBuffer(buffer);
2468 chain->incTrackCnt();
2469 }
2470 }
2471
2472 // indicate all active tracks in the chain
2473 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2474 sp<Track> track = mActiveTracks[i].promote();
2475 if (track == 0) {
2476 continue;
2477 }
2478 if (session == track->sessionId()) {
2479 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2480 chain->incActiveTrackCnt();
2481 }
2482 }
2483 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002484 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002485 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002486 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2487 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002488 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2489 // chains list in order to be processed last as it contains output stage effects
2490 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2491 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2492 // after track specific effects and before output stage
2493 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2494 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2495 // Effect chain for other sessions are inserted at beginning of effect
2496 // chains list to be processed before output mix effects. Relative order between other
2497 // sessions is not important
2498 size_t size = mEffectChains.size();
2499 size_t i = 0;
2500 for (i = 0; i < size; i++) {
2501 if (mEffectChains[i]->sessionId() < session) {
2502 break;
2503 }
2504 }
2505 mEffectChains.insertAt(chain, i);
2506 checkSuspendOnAddEffectChain_l(chain);
2507
2508 return NO_ERROR;
2509}
2510
2511size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2512{
2513 int session = chain->sessionId();
2514
2515 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2516
2517 for (size_t i = 0; i < mEffectChains.size(); i++) {
2518 if (chain == mEffectChains[i]) {
2519 mEffectChains.removeAt(i);
2520 // detach all active tracks from the chain
2521 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2522 sp<Track> track = mActiveTracks[i].promote();
2523 if (track == 0) {
2524 continue;
2525 }
2526 if (session == track->sessionId()) {
2527 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2528 chain.get(), session);
2529 chain->decActiveTrackCnt();
2530 }
2531 }
2532
2533 // detach all tracks with same session ID from this chain
2534 for (size_t i = 0; i < mTracks.size(); ++i) {
2535 sp<Track> track = mTracks[i];
2536 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002537 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002538 chain->decTrackCnt();
2539 }
2540 }
2541 break;
2542 }
2543 }
2544 return mEffectChains.size();
2545}
2546
2547status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2548 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2549{
2550 Mutex::Autolock _l(mLock);
2551 return attachAuxEffect_l(track, EffectId);
2552}
2553
2554status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2555 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2556{
2557 status_t status = NO_ERROR;
2558
2559 if (EffectId == 0) {
2560 track->setAuxBuffer(0, NULL);
2561 } else {
2562 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2563 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2564 if (effect != 0) {
2565 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2566 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2567 } else {
2568 status = INVALID_OPERATION;
2569 }
2570 } else {
2571 status = BAD_VALUE;
2572 }
2573 }
2574 return status;
2575}
2576
2577void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2578{
2579 for (size_t i = 0; i < mTracks.size(); ++i) {
2580 sp<Track> track = mTracks[i];
2581 if (track->auxEffectId() == effectId) {
2582 attachAuxEffect_l(track, 0);
2583 }
2584 }
2585}
2586
2587bool AudioFlinger::PlaybackThread::threadLoop()
2588{
2589 Vector< sp<Track> > tracksToRemove;
2590
2591 standbyTime = systemTime();
2592
2593 // MIXER
2594 nsecs_t lastWarning = 0;
2595
2596 // DUPLICATING
2597 // FIXME could this be made local to while loop?
2598 writeFrames = 0;
2599
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002600 int lastGeneration = 0;
2601
Eric Laurent81784c32012-11-19 14:55:58 -08002602 cacheParameters_l();
2603 sleepTime = idleSleepTime;
2604
2605 if (mType == MIXER) {
2606 sleepTimeShift = 0;
2607 }
2608
2609 CpuStats cpuStats;
2610 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2611
2612 acquireWakeLock();
2613
Glenn Kasten9e58b552013-01-18 15:09:48 -08002614 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2615 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2616 // and then that string will be logged at the next convenient opportunity.
2617 const char *logString = NULL;
2618
Eric Laurent664539d2013-09-23 18:24:31 -07002619 checkSilentMode_l();
2620
Eric Laurent81784c32012-11-19 14:55:58 -08002621 while (!exitPending())
2622 {
2623 cpuStats.sample(myName);
2624
2625 Vector< sp<EffectChain> > effectChains;
2626
Eric Laurent81784c32012-11-19 14:55:58 -08002627 { // scope for mLock
2628
2629 Mutex::Autolock _l(mLock);
2630
Eric Laurent021cf962014-05-13 10:18:14 -07002631 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002632
Glenn Kasten9e58b552013-01-18 15:09:48 -08002633 if (logString != NULL) {
2634 mNBLogWriter->logTimestamp();
2635 mNBLogWriter->log(logString);
2636 logString = NULL;
2637 }
2638
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002639 // Gather the framesReleased counters for all active tracks,
2640 // and latch them atomically with the timestamp.
2641 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2642 mLatchD.mFramesReleased.clear();
2643 size_t size = mActiveTracks.size();
2644 for (size_t i = 0; i < size; i++) {
2645 sp<Track> t = mActiveTracks[i].promote();
2646 if (t != 0) {
2647 mLatchD.mFramesReleased.add(t.get(),
2648 t->mAudioTrackServerProxy->framesReleased());
2649 }
2650 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002651 if (mLatchDValid) {
2652 mLatchQ = mLatchD;
2653 mLatchDValid = false;
2654 mLatchQValid = true;
2655 }
2656
Eric Laurent81784c32012-11-19 14:55:58 -08002657 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 if (mSignalPending) {
2659 // A signal was raised while we were unlocked
2660 mSignalPending = false;
2661 } else if (waitingAsyncCallback_l()) {
2662 if (exitPending()) {
2663 break;
2664 }
2665 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002666 mWakeLockUids.clear();
2667 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 ALOGV("wait async completion");
2669 mWaitWorkCV.wait(mLock);
2670 ALOGV("async completion/wake");
2671 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002672 standbyTime = systemTime() + standbyDelay;
2673 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002674
2675 continue;
2676 }
2677 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 isSuspended()) {
2679 // put audio hardware into standby after short delay
2680 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002681
2682 threadLoop_standby();
2683
2684 mStandby = true;
2685 }
2686
2687 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2688 // we're about to wait, flush the binder command buffer
2689 IPCThreadState::self()->flushCommands();
2690
2691 clearOutputTracks();
2692
2693 if (exitPending()) {
2694 break;
2695 }
2696
2697 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002698 mWakeLockUids.clear();
2699 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002700 // wait until we have something to do...
2701 ALOGV("%s going to sleep", myName.string());
2702 mWaitWorkCV.wait(mLock);
2703 ALOGV("%s waking up", myName.string());
2704 acquireWakeLock_l();
2705
2706 mMixerStatus = MIXER_IDLE;
2707 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2708 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002710 checkSilentMode_l();
2711
2712 standbyTime = systemTime() + standbyDelay;
2713 sleepTime = idleSleepTime;
2714 if (mType == MIXER) {
2715 sleepTimeShift = 0;
2716 }
2717
2718 continue;
2719 }
2720 }
Eric Laurent81784c32012-11-19 14:55:58 -08002721 // mMixerStatusIgnoringFastTracks is also updated internally
2722 mMixerStatus = prepareTracks_l(&tracksToRemove);
2723
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002724 // compare with previously applied list
2725 if (lastGeneration != mActiveTracksGeneration) {
2726 // update wakelock
2727 updateWakeLockUids_l(mWakeLockUids);
2728 lastGeneration = mActiveTracksGeneration;
2729 }
2730
Eric Laurent81784c32012-11-19 14:55:58 -08002731 // prevent any changes in effect chain list and in each effect chain
2732 // during mixing and effect process as the audio buffers could be deleted
2733 // or modified if an effect is created or deleted
2734 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002735 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002736
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737 if (mBytesRemaining == 0) {
2738 mCurrentWriteLength = 0;
2739 if (mMixerStatus == MIXER_TRACKS_READY) {
2740 // threadLoop_mix() sets mCurrentWriteLength
2741 threadLoop_mix();
2742 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2743 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2744 // threadLoop_sleepTime sets sleepTime to 0 if data
2745 // must be written to HAL
2746 threadLoop_sleepTime();
2747 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002748 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 }
2750 }
Andy Hung98ef9782014-03-04 14:46:50 -08002751 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2752 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2753 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2754 // or mSinkBuffer (if there are no effects).
2755 //
2756 // This is done pre-effects computation; if effects change to
2757 // support higher precision, this needs to move.
2758 //
2759 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2760 // TODO use sleepTime == 0 as an additional condition.
2761 if (mMixerBufferValid) {
2762 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2763 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2764
2765 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2766 mNormalFrameCount * mChannelCount);
2767 }
2768
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 mBytesRemaining = mCurrentWriteLength;
2770 if (isSuspended()) {
2771 sleepTime = suspendSleepTimeUs();
2772 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002773 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 mBytesRemaining = 0;
2775 }
Eric Laurent81784c32012-11-19 14:55:58 -08002776
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002778 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 for (size_t i = 0; i < effectChains.size(); i ++) {
2780 effectChains[i]->process_l();
2781 }
Eric Laurent81784c32012-11-19 14:55:58 -08002782 }
2783 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002784 // Process effect chains for offloaded thread even if no audio
2785 // was read from audio track: process only updates effect state
2786 // and thus does have to be synchronized with audio writes but may have
2787 // to be called while waiting for async write callback
2788 if (mType == OFFLOAD) {
2789 for (size_t i = 0; i < effectChains.size(); i ++) {
2790 effectChains[i]->process_l();
2791 }
2792 }
Eric Laurent81784c32012-11-19 14:55:58 -08002793
Andy Hung98ef9782014-03-04 14:46:50 -08002794 // Only if the Effects buffer is enabled and there is data in the
2795 // Effects buffer (buffer valid), we need to
2796 // copy into the sink buffer.
2797 // TODO use sleepTime == 0 as an additional condition.
2798 if (mEffectBufferValid) {
2799 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2800 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2801 mNormalFrameCount * mChannelCount);
2802 }
2803
Eric Laurent81784c32012-11-19 14:55:58 -08002804 // enable changes in effect chain
2805 unlockEffectChains(effectChains);
2806
Eric Laurentbfb1b832013-01-07 09:53:42 -08002807 if (!waitingAsyncCallback()) {
2808 // sleepTime == 0 means we must write to audio hardware
2809 if (sleepTime == 0) {
2810 if (mBytesRemaining) {
2811 ssize_t ret = threadLoop_write();
2812 if (ret < 0) {
2813 mBytesRemaining = 0;
2814 } else {
2815 mBytesWritten += ret;
2816 mBytesRemaining -= ret;
2817 }
2818 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2819 (mMixerStatus == MIXER_DRAIN_ALL)) {
2820 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002821 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002822 if (mType == MIXER) {
2823 // write blocked detection
2824 nsecs_t now = systemTime();
2825 nsecs_t delta = now - mLastWriteTime;
2826 if (!mStandby && delta > maxPeriod) {
2827 mNumDelayedWrites++;
2828 if ((now - lastWarning) > kWarningThrottleNs) {
2829 ATRACE_NAME("underrun");
2830 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2831 ns2ms(delta), mNumDelayedWrites, this);
2832 lastWarning = now;
2833 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 }
2835 }
Eric Laurent81784c32012-11-19 14:55:58 -08002836
Eric Laurentbfb1b832013-01-07 09:53:42 -08002837 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002838 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002840 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002841 }
Eric Laurent81784c32012-11-19 14:55:58 -08002842 }
2843
2844 // Finally let go of removed track(s), without the lock held
2845 // since we can't guarantee the destructors won't acquire that
2846 // same lock. This will also mutate and push a new fast mixer state.
2847 threadLoop_removeTracks(tracksToRemove);
2848 tracksToRemove.clear();
2849
2850 // FIXME I don't understand the need for this here;
2851 // it was in the original code but maybe the
2852 // assignment in saveOutputTracks() makes this unnecessary?
2853 clearOutputTracks();
2854
2855 // Effect chains will be actually deleted here if they were removed from
2856 // mEffectChains list during mixing or effects processing
2857 effectChains.clear();
2858
2859 // FIXME Note that the above .clear() is no longer necessary since effectChains
2860 // is now local to this block, but will keep it for now (at least until merge done).
2861 }
2862
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 threadLoop_exit();
2864
Eric Laurentcf817a22014-08-04 20:36:31 -07002865 if (!mStandby) {
2866 threadLoop_standby();
2867 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002868 }
2869
2870 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002871 mWakeLockUids.clear();
2872 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002873
2874 ALOGV("Thread %p type %d exiting", this, mType);
2875 return false;
2876}
2877
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878// removeTracks_l() must be called with ThreadBase::mLock held
2879void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2880{
2881 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002882 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 for (size_t i=0 ; i<count ; i++) {
2884 const sp<Track>& track = tracksToRemove.itemAt(i);
2885 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002886 mWakeLockUids.remove(track->uid());
2887 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2889 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2890 if (chain != 0) {
2891 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2892 track->sessionId());
2893 chain->decActiveTrackCnt();
2894 }
2895 if (track->isTerminated()) {
2896 removeTrack_l(track);
2897 }
2898 }
2899 }
2900
2901}
Eric Laurent81784c32012-11-19 14:55:58 -08002902
Eric Laurentaccc1472013-09-20 09:36:34 -07002903status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2904{
2905 if (mNormalSink != 0) {
2906 return mNormalSink->getTimestamp(timestamp);
2907 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002908 if ((mType == OFFLOAD || mType == DIRECT)
2909 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002910 uint64_t position64;
2911 int ret = mOutput->stream->get_presentation_position(
2912 mOutput->stream, &position64, &timestamp.mTime);
2913 if (ret == 0) {
2914 timestamp.mPosition = (uint32_t)position64;
2915 return NO_ERROR;
2916 }
2917 }
2918 return INVALID_OPERATION;
2919}
Eric Laurent1c333e22014-05-20 10:48:17 -07002920
2921status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2922 audio_patch_handle_t *handle)
2923{
2924 status_t status = NO_ERROR;
2925 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2926 // store new device and send to effects
2927 audio_devices_t type = AUDIO_DEVICE_NONE;
2928 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2929 type |= patch->sinks[i].ext.device.type;
2930 }
2931 mOutDevice = type;
2932 for (size_t i = 0; i < mEffectChains.size(); i++) {
2933 mEffectChains[i]->setDevice_l(mOutDevice);
2934 }
2935
2936 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2937 status = hwDevice->create_audio_patch(hwDevice,
2938 patch->num_sources,
2939 patch->sources,
2940 patch->num_sinks,
2941 patch->sinks,
2942 handle);
2943 } else {
2944 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2945 }
2946 return status;
2947}
2948
2949status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2950{
2951 status_t status = NO_ERROR;
2952 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2953 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2954 status = hwDevice->release_audio_patch(hwDevice, handle);
2955 } else {
2956 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2957 }
2958 return status;
2959}
2960
Eric Laurent83b88082014-06-20 18:31:16 -07002961void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2962{
2963 Mutex::Autolock _l(mLock);
2964 mTracks.add(track);
2965}
2966
2967void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2968{
2969 Mutex::Autolock _l(mLock);
2970 destroyTrack_l(track);
2971}
2972
2973void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2974{
2975 ThreadBase::getAudioPortConfig(config);
2976 config->role = AUDIO_PORT_ROLE_SOURCE;
2977 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2978 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2979}
2980
Eric Laurent81784c32012-11-19 14:55:58 -08002981// ----------------------------------------------------------------------------
2982
2983AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2984 audio_io_handle_t id, audio_devices_t device, type_t type)
2985 : PlaybackThread(audioFlinger, output, id, device, type),
2986 // mAudioMixer below
2987 // mFastMixer below
2988 mFastMixerFutex(0)
2989 // mOutputSink below
2990 // mPipeSink below
2991 // mNormalSink below
2992{
2993 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002994 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002995 "mFrameCount=%d, mNormalFrameCount=%d",
2996 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2997 mNormalFrameCount);
2998 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2999
Andy Hungfbfc3952015-01-15 13:33:51 -08003000 if (type == DUPLICATING) {
3001 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3002 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3003 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3004 return;
3005 }
Eric Laurent81784c32012-11-19 14:55:58 -08003006 // create an NBAIO sink for the HAL output stream, and negotiate
3007 mOutputSink = new AudioStreamOutSink(output->stream);
3008 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003009 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003010 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3011 ALOG_ASSERT(index == 0);
3012
3013 // initialize fast mixer depending on configuration
3014 bool initFastMixer;
3015 switch (kUseFastMixer) {
3016 case FastMixer_Never:
3017 initFastMixer = false;
3018 break;
3019 case FastMixer_Always:
3020 initFastMixer = true;
3021 break;
3022 case FastMixer_Static:
3023 case FastMixer_Dynamic:
3024 initFastMixer = mFrameCount < mNormalFrameCount;
3025 break;
3026 }
3027 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003028 audio_format_t fastMixerFormat;
3029 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3030 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3031 } else {
3032 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3033 }
3034 if (mFormat != fastMixerFormat) {
3035 // change our Sink format to accept our intermediate precision
3036 mFormat = fastMixerFormat;
3037 free(mSinkBuffer);
3038 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3039 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3040 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3041 }
Eric Laurent81784c32012-11-19 14:55:58 -08003042
3043 // create a MonoPipe to connect our submix to FastMixer
3044 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003045 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003046 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003047 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003048 format.mFormat = fastMixerFormat;
3049 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3050
Eric Laurent81784c32012-11-19 14:55:58 -08003051 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3052 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3053 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3054 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3055 const NBAIO_Format offers[1] = {format};
3056 size_t numCounterOffers = 0;
3057 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3058 ALOG_ASSERT(index == 0);
3059 monoPipe->setAvgFrames((mScreenState & 1) ?
3060 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3061 mPipeSink = monoPipe;
3062
Glenn Kasten46909e72013-02-26 09:20:22 -08003063#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003064 if (mTeeSinkOutputEnabled) {
3065 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003066 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3067 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003068 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003069 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003070 ALOG_ASSERT(index == 0);
3071 mTeeSink = teeSink;
3072 PipeReader *teeSource = new PipeReader(*teeSink);
3073 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003074 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003075 ALOG_ASSERT(index == 0);
3076 mTeeSource = teeSource;
3077 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003078#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003079
3080 // create fast mixer and configure it initially with just one fast track for our submix
3081 mFastMixer = new FastMixer();
3082 FastMixerStateQueue *sq = mFastMixer->sq();
3083#ifdef STATE_QUEUE_DUMP
3084 sq->setObserverDump(&mStateQueueObserverDump);
3085 sq->setMutatorDump(&mStateQueueMutatorDump);
3086#endif
3087 FastMixerState *state = sq->begin();
3088 FastTrack *fastTrack = &state->mFastTracks[0];
3089 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3090 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3091 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003092 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3093 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003094 fastTrack->mGeneration++;
3095 state->mFastTracksGen++;
3096 state->mTrackMask = 1;
3097 // fast mixer will use the HAL output sink
3098 state->mOutputSink = mOutputSink.get();
3099 state->mOutputSinkGen++;
3100 state->mFrameCount = mFrameCount;
3101 state->mCommand = FastMixerState::COLD_IDLE;
3102 // already done in constructor initialization list
3103 //mFastMixerFutex = 0;
3104 state->mColdFutexAddr = &mFastMixerFutex;
3105 state->mColdGen++;
3106 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003107#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003108 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003109#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003110 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3111 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003112 sq->end();
3113 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3114
3115 // start the fast mixer
3116 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3117 pid_t tid = mFastMixer->getTid();
3118 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3119 if (err != 0) {
3120 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3121 kPriorityFastMixer, getpid_cached, tid, err);
3122 }
3123
3124#ifdef AUDIO_WATCHDOG
3125 // create and start the watchdog
3126 mAudioWatchdog = new AudioWatchdog();
3127 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3128 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3129 tid = mAudioWatchdog->getTid();
3130 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3131 if (err != 0) {
3132 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3133 kPriorityFastMixer, getpid_cached, tid, err);
3134 }
3135#endif
3136
Eric Laurent81784c32012-11-19 14:55:58 -08003137 }
3138
3139 switch (kUseFastMixer) {
3140 case FastMixer_Never:
3141 case FastMixer_Dynamic:
3142 mNormalSink = mOutputSink;
3143 break;
3144 case FastMixer_Always:
3145 mNormalSink = mPipeSink;
3146 break;
3147 case FastMixer_Static:
3148 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3149 break;
3150 }
3151}
3152
3153AudioFlinger::MixerThread::~MixerThread()
3154{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003155 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003156 FastMixerStateQueue *sq = mFastMixer->sq();
3157 FastMixerState *state = sq->begin();
3158 if (state->mCommand == FastMixerState::COLD_IDLE) {
3159 int32_t old = android_atomic_inc(&mFastMixerFutex);
3160 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003161 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003162 }
3163 }
3164 state->mCommand = FastMixerState::EXIT;
3165 sq->end();
3166 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3167 mFastMixer->join();
3168 // Though the fast mixer thread has exited, it's state queue is still valid.
3169 // We'll use that extract the final state which contains one remaining fast track
3170 // corresponding to our sub-mix.
3171 state = sq->begin();
3172 ALOG_ASSERT(state->mTrackMask == 1);
3173 FastTrack *fastTrack = &state->mFastTracks[0];
3174 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3175 delete fastTrack->mBufferProvider;
3176 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003177 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003178#ifdef AUDIO_WATCHDOG
3179 if (mAudioWatchdog != 0) {
3180 mAudioWatchdog->requestExit();
3181 mAudioWatchdog->requestExitAndWait();
3182 mAudioWatchdog.clear();
3183 }
3184#endif
3185 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003186 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003187 delete mAudioMixer;
3188}
3189
3190
3191uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3192{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003193 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003194 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3195 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3196 }
3197 return latency;
3198}
3199
3200
3201void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3202{
3203 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3204}
3205
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003207{
3208 // FIXME we should only do one push per cycle; confirm this is true
3209 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003210 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003211 FastMixerStateQueue *sq = mFastMixer->sq();
3212 FastMixerState *state = sq->begin();
3213 if (state->mCommand != FastMixerState::MIX_WRITE &&
3214 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3215 if (state->mCommand == FastMixerState::COLD_IDLE) {
3216 int32_t old = android_atomic_inc(&mFastMixerFutex);
3217 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003218 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
3220#ifdef AUDIO_WATCHDOG
3221 if (mAudioWatchdog != 0) {
3222 mAudioWatchdog->resume();
3223 }
3224#endif
3225 }
3226 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003227#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003228 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003229 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003230#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003231 sq->end();
3232 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3233 if (kUseFastMixer == FastMixer_Dynamic) {
3234 mNormalSink = mPipeSink;
3235 }
3236 } else {
3237 sq->end(false /*didModify*/);
3238 }
3239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003240 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003241}
3242
3243void AudioFlinger::MixerThread::threadLoop_standby()
3244{
3245 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003246 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003247 FastMixerStateQueue *sq = mFastMixer->sq();
3248 FastMixerState *state = sq->begin();
3249 if (!(state->mCommand & FastMixerState::IDLE)) {
3250 state->mCommand = FastMixerState::COLD_IDLE;
3251 state->mColdFutexAddr = &mFastMixerFutex;
3252 state->mColdGen++;
3253 mFastMixerFutex = 0;
3254 sq->end();
3255 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3256 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3257 if (kUseFastMixer == FastMixer_Dynamic) {
3258 mNormalSink = mOutputSink;
3259 }
3260#ifdef AUDIO_WATCHDOG
3261 if (mAudioWatchdog != 0) {
3262 mAudioWatchdog->pause();
3263 }
3264#endif
3265 } else {
3266 sq->end(false /*didModify*/);
3267 }
3268 }
3269 PlaybackThread::threadLoop_standby();
3270}
3271
Eric Laurentbfb1b832013-01-07 09:53:42 -08003272bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3273{
3274 return false;
3275}
3276
3277bool AudioFlinger::PlaybackThread::shouldStandby_l()
3278{
3279 return !mStandby;
3280}
3281
3282bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3283{
3284 Mutex::Autolock _l(mLock);
3285 return waitingAsyncCallback_l();
3286}
3287
Eric Laurent81784c32012-11-19 14:55:58 -08003288// shared by MIXER and DIRECT, overridden by DUPLICATING
3289void AudioFlinger::PlaybackThread::threadLoop_standby()
3290{
3291 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3292 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003294 // discard any pending drain or write ack by incrementing sequence
3295 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3296 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003298 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3299 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003300 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003301 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003302}
3303
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003304void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3305{
3306 ALOGV("signal playback thread");
3307 broadcast_l();
3308}
3309
Eric Laurent81784c32012-11-19 14:55:58 -08003310void AudioFlinger::MixerThread::threadLoop_mix()
3311{
3312 // obtain the presentation timestamp of the next output buffer
3313 int64_t pts;
3314 status_t status = INVALID_OPERATION;
3315
3316 if (mNormalSink != 0) {
3317 status = mNormalSink->getNextWriteTimestamp(&pts);
3318 } else {
3319 status = mOutputSink->getNextWriteTimestamp(&pts);
3320 }
3321
3322 if (status != NO_ERROR) {
3323 pts = AudioBufferProvider::kInvalidPTS;
3324 }
3325
3326 // mix buffers...
3327 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003328 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003329 // increase sleep time progressively when application underrun condition clears.
3330 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3331 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3332 // such that we would underrun the audio HAL.
3333 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3334 sleepTimeShift--;
3335 }
3336 sleepTime = 0;
3337 standbyTime = systemTime() + standbyDelay;
3338 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003339
Eric Laurent81784c32012-11-19 14:55:58 -08003340}
3341
3342void AudioFlinger::MixerThread::threadLoop_sleepTime()
3343{
3344 // If no tracks are ready, sleep once for the duration of an output
3345 // buffer size, then write 0s to the output
3346 if (sleepTime == 0) {
3347 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3348 sleepTime = activeSleepTime >> sleepTimeShift;
3349 if (sleepTime < kMinThreadSleepTimeUs) {
3350 sleepTime = kMinThreadSleepTimeUs;
3351 }
3352 // reduce sleep time in case of consecutive application underruns to avoid
3353 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3354 // duration we would end up writing less data than needed by the audio HAL if
3355 // the condition persists.
3356 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3357 sleepTimeShift++;
3358 }
3359 } else {
3360 sleepTime = idleSleepTime;
3361 }
3362 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003363 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3364 // before effects processing or output.
3365 if (mMixerBufferValid) {
3366 memset(mMixerBuffer, 0, mMixerBufferSize);
3367 } else {
3368 memset(mSinkBuffer, 0, mSinkBufferSize);
3369 }
Eric Laurent81784c32012-11-19 14:55:58 -08003370 sleepTime = 0;
3371 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3372 "anticipated start");
3373 }
3374 // TODO add standby time extension fct of effect tail
3375}
3376
3377// prepareTracks_l() must be called with ThreadBase::mLock held
3378AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3379 Vector< sp<Track> > *tracksToRemove)
3380{
3381
3382 mixer_state mixerStatus = MIXER_IDLE;
3383 // find out which tracks need to be processed
3384 size_t count = mActiveTracks.size();
3385 size_t mixedTracks = 0;
3386 size_t tracksWithEffect = 0;
3387 // counts only _active_ fast tracks
3388 size_t fastTracks = 0;
3389 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3390
3391 float masterVolume = mMasterVolume;
3392 bool masterMute = mMasterMute;
3393
3394 if (masterMute) {
3395 masterVolume = 0;
3396 }
3397 // Delegate master volume control to effect in output mix effect chain if needed
3398 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3399 if (chain != 0) {
3400 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3401 chain->setVolume_l(&v, &v);
3402 masterVolume = (float)((v + (1 << 23)) >> 24);
3403 chain.clear();
3404 }
3405
3406 // prepare a new state to push
3407 FastMixerStateQueue *sq = NULL;
3408 FastMixerState *state = NULL;
3409 bool didModify = false;
3410 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003411 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003412 sq = mFastMixer->sq();
3413 state = sq->begin();
3414 }
3415
Andy Hung69aed5f2014-02-25 17:24:40 -08003416 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003417 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003418
Eric Laurent81784c32012-11-19 14:55:58 -08003419 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003420 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003421 if (t == 0) {
3422 continue;
3423 }
3424
3425 // this const just means the local variable doesn't change
3426 Track* const track = t.get();
3427
3428 // process fast tracks
3429 if (track->isFastTrack()) {
3430
3431 // It's theoretically possible (though unlikely) for a fast track to be created
3432 // and then removed within the same normal mix cycle. This is not a problem, as
3433 // the track never becomes active so it's fast mixer slot is never touched.
3434 // The converse, of removing an (active) track and then creating a new track
3435 // at the identical fast mixer slot within the same normal mix cycle,
3436 // is impossible because the slot isn't marked available until the end of each cycle.
3437 int j = track->mFastIndex;
3438 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3439 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3440 FastTrack *fastTrack = &state->mFastTracks[j];
3441
3442 // Determine whether the track is currently in underrun condition,
3443 // and whether it had a recent underrun.
3444 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3445 FastTrackUnderruns underruns = ftDump->mUnderruns;
3446 uint32_t recentFull = (underruns.mBitFields.mFull -
3447 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3448 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3449 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3450 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3451 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3452 uint32_t recentUnderruns = recentPartial + recentEmpty;
3453 track->mObservedUnderruns = underruns;
3454 // don't count underruns that occur while stopping or pausing
3455 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003456 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3457 recentUnderruns > 0) {
3458 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3459 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003460 }
3461
3462 // This is similar to the state machine for normal tracks,
3463 // with a few modifications for fast tracks.
3464 bool isActive = true;
3465 switch (track->mState) {
3466 case TrackBase::STOPPING_1:
3467 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003469 track->mState = TrackBase::STOPPING_2;
3470 }
3471 break;
3472 case TrackBase::PAUSING:
3473 // ramp down is not yet implemented
3474 track->setPaused();
3475 break;
3476 case TrackBase::RESUMING:
3477 // ramp up is not yet implemented
3478 track->mState = TrackBase::ACTIVE;
3479 break;
3480 case TrackBase::ACTIVE:
3481 if (recentFull > 0 || recentPartial > 0) {
3482 // track has provided at least some frames recently: reset retry count
3483 track->mRetryCount = kMaxTrackRetries;
3484 }
3485 if (recentUnderruns == 0) {
3486 // no recent underruns: stay active
3487 break;
3488 }
3489 // there has recently been an underrun of some kind
3490 if (track->sharedBuffer() == 0) {
3491 // were any of the recent underruns "empty" (no frames available)?
3492 if (recentEmpty == 0) {
3493 // no, then ignore the partial underruns as they are allowed indefinitely
3494 break;
3495 }
3496 // there has recently been an "empty" underrun: decrement the retry counter
3497 if (--(track->mRetryCount) > 0) {
3498 break;
3499 }
3500 // indicate to client process that the track was disabled because of underrun;
3501 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003502 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003503 // remove from active list, but state remains ACTIVE [confusing but true]
3504 isActive = false;
3505 break;
3506 }
3507 // fall through
3508 case TrackBase::STOPPING_2:
3509 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003510 case TrackBase::STOPPED:
3511 case TrackBase::FLUSHED: // flush() while active
3512 // Check for presentation complete if track is inactive
3513 // We have consumed all the buffers of this track.
3514 // This would be incomplete if we auto-paused on underrun
3515 {
3516 size_t audioHALFrames =
3517 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3518 size_t framesWritten = mBytesWritten / mFrameSize;
3519 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3520 // track stays in active list until presentation is complete
3521 break;
3522 }
3523 }
3524 if (track->isStopping_2()) {
3525 track->mState = TrackBase::STOPPED;
3526 }
3527 if (track->isStopped()) {
3528 // Can't reset directly, as fast mixer is still polling this track
3529 // track->reset();
3530 // So instead mark this track as needing to be reset after push with ack
3531 resetMask |= 1 << i;
3532 }
3533 isActive = false;
3534 break;
3535 case TrackBase::IDLE:
3536 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003537 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 }
3539
3540 if (isActive) {
3541 // was it previously inactive?
3542 if (!(state->mTrackMask & (1 << j))) {
3543 ExtendedAudioBufferProvider *eabp = track;
3544 VolumeProvider *vp = track;
3545 fastTrack->mBufferProvider = eabp;
3546 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003547 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003548 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003549 fastTrack->mGeneration++;
3550 state->mTrackMask |= 1 << j;
3551 didModify = true;
3552 // no acknowledgement required for newly active tracks
3553 }
3554 // cache the combined master volume and stream type volume for fast mixer; this
3555 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003556 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003557 ++fastTracks;
3558 } else {
3559 // was it previously active?
3560 if (state->mTrackMask & (1 << j)) {
3561 fastTrack->mBufferProvider = NULL;
3562 fastTrack->mGeneration++;
3563 state->mTrackMask &= ~(1 << j);
3564 didModify = true;
3565 // If any fast tracks were removed, we must wait for acknowledgement
3566 // because we're about to decrement the last sp<> on those tracks.
3567 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3568 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003569 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003570 }
3571 tracksToRemove->add(track);
3572 // Avoids a misleading display in dumpsys
3573 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3574 }
3575 continue;
3576 }
3577
3578 { // local variable scope to avoid goto warning
3579
3580 audio_track_cblk_t* cblk = track->cblk();
3581
3582 // The first time a track is added we wait
3583 // for all its buffers to be filled before processing it
3584 int name = track->name();
3585 // make sure that we have enough frames to mix one full buffer.
3586 // enforce this condition only once to enable draining the buffer in case the client
3587 // app does not call stop() and relies on underrun to stop:
3588 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3589 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003590 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003591 uint32_t sr = track->sampleRate();
3592 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003593 desiredFrames = mNormalFrameCount;
3594 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003595 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003596 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003597 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003598 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003599#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003600 // the minimum track buffer size is normally twice the number of frames necessary
3601 // to fill one buffer and the resampler should not leave more than one buffer worth
3602 // of unreleased frames after each pass, but just in case...
3603 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003604#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003605 }
Eric Laurent81784c32012-11-19 14:55:58 -08003606 uint32_t minFrames = 1;
3607 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3608 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003609 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003610 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003611
3612 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003613 if (ATRACE_ENABLED()) {
3614 // I wish we had formatted trace names
3615 char traceName[16];
3616 strcpy(traceName, "nRdy");
3617 int name = track->name();
3618 if (AudioMixer::TRACK0 <= name &&
3619 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3620 name -= AudioMixer::TRACK0;
3621 traceName[4] = (name / 10) + '0';
3622 traceName[5] = (name % 10) + '0';
3623 } else {
3624 traceName[4] = '?';
3625 traceName[5] = '?';
3626 }
3627 traceName[6] = '\0';
3628 ATRACE_INT(traceName, framesReady);
3629 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003630 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003631 !track->isPaused() && !track->isTerminated())
3632 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003633 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003634
3635 mixedTracks++;
3636
Andy Hung69aed5f2014-02-25 17:24:40 -08003637 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3638 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003639 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003640 if (track->mainBuffer() != mSinkBuffer &&
3641 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003642 if (mEffectBufferEnabled) {
3643 mEffectBufferValid = true; // Later can set directly.
3644 }
Eric Laurent81784c32012-11-19 14:55:58 -08003645 chain = getEffectChain_l(track->sessionId());
3646 // Delegate volume control to effect in track effect chain if needed
3647 if (chain != 0) {
3648 tracksWithEffect++;
3649 } else {
3650 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3651 "session %d",
3652 name, track->sessionId());
3653 }
3654 }
3655
3656
3657 int param = AudioMixer::VOLUME;
3658 if (track->mFillingUpStatus == Track::FS_FILLED) {
3659 // no ramp for the first volume setting
3660 track->mFillingUpStatus = Track::FS_ACTIVE;
3661 if (track->mState == TrackBase::RESUMING) {
3662 track->mState = TrackBase::ACTIVE;
3663 param = AudioMixer::RAMP_VOLUME;
3664 }
3665 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003666 // FIXME should not make a decision based on mServer
3667 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003668 // If the track is stopped before the first frame was mixed,
3669 // do not apply ramp
3670 param = AudioMixer::RAMP_VOLUME;
3671 }
3672
3673 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003674 uint32_t vl, vr; // in U8.24 integer format
3675 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003676 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003677 vl = vr = 0;
3678 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003679 if (track->isPausing()) {
3680 track->setPaused();
3681 }
3682 } else {
3683
3684 // read original volumes with volume control
3685 float typeVolume = mStreamTypes[track->streamType()].volume;
3686 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003687 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003688 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003689 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3690 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003691 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003692 if (vlf > GAIN_FLOAT_UNITY) {
3693 ALOGV("Track left volume out of range: %.3g", vlf);
3694 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003695 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003696 if (vrf > GAIN_FLOAT_UNITY) {
3697 ALOGV("Track right volume out of range: %.3g", vrf);
3698 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003699 }
3700 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003701 vlf *= v;
3702 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003703 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003704 // then derive vl and vr as U8.24 versions for the effect chain
3705 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3706 vl = (uint32_t) (scaleto8_24 * vlf);
3707 vr = (uint32_t) (scaleto8_24 * vrf);
3708 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003709 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003710 // send level comes from shared memory and so may be corrupt
3711 if (sendLevel > MAX_GAIN_INT) {
3712 ALOGV("Track send level out of range: %04X", sendLevel);
3713 sendLevel = MAX_GAIN_INT;
3714 }
Andy Hung6be49402014-05-30 10:42:03 -07003715 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3716 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003717 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003718
Eric Laurent81784c32012-11-19 14:55:58 -08003719 // Delegate volume control to effect in track effect chain if needed
3720 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3721 // Do not ramp volume if volume is controlled by effect
3722 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003723 // Update remaining floating point volume levels
3724 vlf = (float)vl / (1 << 24);
3725 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003726 track->mHasVolumeController = true;
3727 } else {
3728 // force no volume ramp when volume controller was just disabled or removed
3729 // from effect chain to avoid volume spike
3730 if (track->mHasVolumeController) {
3731 param = AudioMixer::VOLUME;
3732 }
3733 track->mHasVolumeController = false;
3734 }
3735
Eric Laurent81784c32012-11-19 14:55:58 -08003736 // XXX: these things DON'T need to be done each time
3737 mAudioMixer->setBufferProvider(name, track);
3738 mAudioMixer->enable(name);
3739
Andy Hung6be49402014-05-30 10:42:03 -07003740 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3741 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3742 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003743 mAudioMixer->setParameter(
3744 name,
3745 AudioMixer::TRACK,
3746 AudioMixer::FORMAT, (void *)track->format());
3747 mAudioMixer->setParameter(
3748 name,
3749 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003750 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003751 mAudioMixer->setParameter(
3752 name,
3753 AudioMixer::TRACK,
3754 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003755 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003756 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003757 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003758 if (reqSampleRate == 0) {
3759 reqSampleRate = mSampleRate;
3760 } else if (reqSampleRate > maxSampleRate) {
3761 reqSampleRate = maxSampleRate;
3762 }
Eric Laurent81784c32012-11-19 14:55:58 -08003763 mAudioMixer->setParameter(
3764 name,
3765 AudioMixer::RESAMPLE,
3766 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003767 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003768 /*
3769 * Select the appropriate output buffer for the track.
3770 *
Andy Hung98ef9782014-03-04 14:46:50 -08003771 * Tracks with effects go into their own effects chain buffer
3772 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003773 *
3774 * Other tracks can use mMixerBuffer for higher precision
3775 * channel accumulation. If this buffer is enabled
3776 * (mMixerBufferEnabled true), then selected tracks will accumulate
3777 * into it.
3778 *
3779 */
3780 if (mMixerBufferEnabled
3781 && (track->mainBuffer() == mSinkBuffer
3782 || track->mainBuffer() == mMixerBuffer)) {
3783 mAudioMixer->setParameter(
3784 name,
3785 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003786 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003787 mAudioMixer->setParameter(
3788 name,
3789 AudioMixer::TRACK,
3790 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3791 // TODO: override track->mainBuffer()?
3792 mMixerBufferValid = true;
3793 } else {
3794 mAudioMixer->setParameter(
3795 name,
3796 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003797 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003798 mAudioMixer->setParameter(
3799 name,
3800 AudioMixer::TRACK,
3801 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3802 }
Eric Laurent81784c32012-11-19 14:55:58 -08003803 mAudioMixer->setParameter(
3804 name,
3805 AudioMixer::TRACK,
3806 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3807
3808 // reset retry count
3809 track->mRetryCount = kMaxTrackRetries;
3810
3811 // If one track is ready, set the mixer ready if:
3812 // - the mixer was not ready during previous round OR
3813 // - no other track is not ready
3814 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3815 mixerStatus != MIXER_TRACKS_ENABLED) {
3816 mixerStatus = MIXER_TRACKS_READY;
3817 }
3818 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003819 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003820 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003821 }
Eric Laurent81784c32012-11-19 14:55:58 -08003822 // clear effect chain input buffer if an active track underruns to avoid sending
3823 // previous audio buffer again to effects
3824 chain = getEffectChain_l(track->sessionId());
3825 if (chain != 0) {
3826 chain->clearInputBuffer();
3827 }
3828
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003829 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003830 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3831 track->isStopped() || track->isPaused()) {
3832 // We have consumed all the buffers of this track.
3833 // Remove it from the list of active tracks.
3834 // TODO: use actual buffer filling status instead of latency when available from
3835 // audio HAL
3836 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3837 size_t framesWritten = mBytesWritten / mFrameSize;
3838 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3839 if (track->isStopped()) {
3840 track->reset();
3841 }
3842 tracksToRemove->add(track);
3843 }
3844 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003845 // No buffers for this track. Give it a few chances to
3846 // fill a buffer, then remove it from active list.
3847 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003848 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003849 tracksToRemove->add(track);
3850 // indicate to client process that the track was disabled because of underrun;
3851 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003852 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003853 // If one track is not ready, mark the mixer also not ready if:
3854 // - the mixer was ready during previous round OR
3855 // - no other track is ready
3856 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3857 mixerStatus != MIXER_TRACKS_READY) {
3858 mixerStatus = MIXER_TRACKS_ENABLED;
3859 }
3860 }
3861 mAudioMixer->disable(name);
3862 }
3863
3864 } // local variable scope to avoid goto warning
3865track_is_ready: ;
3866
3867 }
3868
3869 // Push the new FastMixer state if necessary
3870 bool pauseAudioWatchdog = false;
3871 if (didModify) {
3872 state->mFastTracksGen++;
3873 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3874 if (kUseFastMixer == FastMixer_Dynamic &&
3875 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3876 state->mCommand = FastMixerState::COLD_IDLE;
3877 state->mColdFutexAddr = &mFastMixerFutex;
3878 state->mColdGen++;
3879 mFastMixerFutex = 0;
3880 if (kUseFastMixer == FastMixer_Dynamic) {
3881 mNormalSink = mOutputSink;
3882 }
3883 // If we go into cold idle, need to wait for acknowledgement
3884 // so that fast mixer stops doing I/O.
3885 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3886 pauseAudioWatchdog = true;
3887 }
Eric Laurent81784c32012-11-19 14:55:58 -08003888 }
3889 if (sq != NULL) {
3890 sq->end(didModify);
3891 sq->push(block);
3892 }
3893#ifdef AUDIO_WATCHDOG
3894 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3895 mAudioWatchdog->pause();
3896 }
3897#endif
3898
3899 // Now perform the deferred reset on fast tracks that have stopped
3900 while (resetMask != 0) {
3901 size_t i = __builtin_ctz(resetMask);
3902 ALOG_ASSERT(i < count);
3903 resetMask &= ~(1 << i);
3904 sp<Track> t = mActiveTracks[i].promote();
3905 if (t == 0) {
3906 continue;
3907 }
3908 Track* track = t.get();
3909 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3910 track->reset();
3911 }
3912
3913 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003914 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003915
Eric Laurent97d547d2014-09-02 14:45:53 -07003916 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3917 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003918 }
3919
3920 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003921 // as long as there are effects we should clear the effects buffer, to avoid
3922 // passing a non-clean buffer to the effect chain
3923 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003924 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003925 // sink or mix buffer must be cleared if all tracks are connected to an
3926 // effect chain as in this case the mixer will not write to the sink or mix buffer
3927 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3929 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003930 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003931 if (mMixerBufferValid) {
3932 memset(mMixerBuffer, 0, mMixerBufferSize);
3933 // TODO: In testing, mSinkBuffer below need not be cleared because
3934 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3935 // after mixing.
3936 //
3937 // To enforce this guarantee:
3938 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3939 // (mixedTracks == 0 && fastTracks > 0))
3940 // must imply MIXER_TRACKS_READY.
3941 // Later, we may clear buffers regardless, and skip much of this logic.
3942 }
Andy Hung98ef9782014-03-04 14:46:50 -08003943 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003944 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003945 }
3946
3947 // if any fast tracks, then status is ready
3948 mMixerStatusIgnoringFastTracks = mixerStatus;
3949 if (fastTracks > 0) {
3950 mixerStatus = MIXER_TRACKS_READY;
3951 }
3952 return mixerStatus;
3953}
3954
3955// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003956int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3957 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003958{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003959 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003960}
3961
3962// deleteTrackName_l() must be called with ThreadBase::mLock held
3963void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3964{
3965 ALOGV("remove track (%d) and delete from mixer", name);
3966 mAudioMixer->deleteTrackName(name);
3967}
3968
Eric Laurent10351942014-05-08 18:49:52 -07003969// checkForNewParameter_l() must be called with ThreadBase::mLock held
3970bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3971 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003972{
Eric Laurent81784c32012-11-19 14:55:58 -08003973 bool reconfig = false;
3974
Eric Laurent10351942014-05-08 18:49:52 -07003975 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003976
Eric Laurent10351942014-05-08 18:49:52 -07003977 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3978 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003979 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003980 FastMixerStateQueue *sq = mFastMixer->sq();
3981 FastMixerState *state = sq->begin();
3982 if (!(state->mCommand & FastMixerState::IDLE)) {
3983 previousCommand = state->mCommand;
3984 state->mCommand = FastMixerState::HOT_IDLE;
3985 sq->end();
3986 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3987 } else {
3988 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003989 }
Eric Laurent10351942014-05-08 18:49:52 -07003990 }
Eric Laurent81784c32012-11-19 14:55:58 -08003991
Eric Laurent10351942014-05-08 18:49:52 -07003992 AudioParameter param = AudioParameter(keyValuePair);
3993 int value;
3994 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3995 reconfig = true;
3996 }
3997 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003998 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003999 status = BAD_VALUE;
4000 } else {
4001 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004002 reconfig = true;
4003 }
Eric Laurent10351942014-05-08 18:49:52 -07004004 }
4005 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004006 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004007 status = BAD_VALUE;
4008 } else {
4009 // no need to save value, since it's constant
4010 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004011 }
Eric Laurent10351942014-05-08 18:49:52 -07004012 }
4013 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4014 // do not accept frame count changes if tracks are open as the track buffer
4015 // size depends on frame count and correct behavior would not be guaranteed
4016 // if frame count is changed after track creation
4017 if (!mTracks.isEmpty()) {
4018 status = INVALID_OPERATION;
4019 } else {
4020 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004021 }
Eric Laurent10351942014-05-08 18:49:52 -07004022 }
4023 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004024#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004025 // when changing the audio output device, call addBatteryData to notify
4026 // the change
4027 if (mOutDevice != value) {
4028 uint32_t params = 0;
4029 // check whether speaker is on
4030 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4031 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004032 }
Eric Laurent10351942014-05-08 18:49:52 -07004033
4034 audio_devices_t deviceWithoutSpeaker
4035 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4036 // check if any other device (except speaker) is on
4037 if (value & deviceWithoutSpeaker ) {
4038 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4039 }
4040
4041 if (params != 0) {
4042 addBatteryData(params);
4043 }
4044 }
Eric Laurent81784c32012-11-19 14:55:58 -08004045#endif
4046
Eric Laurent10351942014-05-08 18:49:52 -07004047 // forward device change to effects that have requested to be
4048 // aware of attached audio device.
4049 if (value != AUDIO_DEVICE_NONE) {
4050 mOutDevice = value;
4051 for (size_t i = 0; i < mEffectChains.size(); i++) {
4052 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004053 }
4054 }
Eric Laurent10351942014-05-08 18:49:52 -07004055 }
Eric Laurent81784c32012-11-19 14:55:58 -08004056
Eric Laurent10351942014-05-08 18:49:52 -07004057 if (status == NO_ERROR) {
4058 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4059 keyValuePair.string());
4060 if (!mStandby && status == INVALID_OPERATION) {
4061 mOutput->stream->common.standby(&mOutput->stream->common);
4062 mStandby = true;
4063 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004064 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004065 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004066 }
Eric Laurent10351942014-05-08 18:49:52 -07004067 if (status == NO_ERROR && reconfig) {
4068 readOutputParameters_l();
4069 delete mAudioMixer;
4070 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4071 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004072 int name = getTrackName_l(mTracks[i]->mChannelMask,
4073 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004074 if (name < 0) {
4075 break;
4076 }
4077 mTracks[i]->mName = name;
4078 }
4079 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4080 }
Eric Laurent81784c32012-11-19 14:55:58 -08004081 }
4082
4083 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004084 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004085 FastMixerStateQueue *sq = mFastMixer->sq();
4086 FastMixerState *state = sq->begin();
4087 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4088 state->mCommand = previousCommand;
4089 sq->end();
4090 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4091 }
4092
4093 return reconfig;
4094}
4095
4096
4097void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4098{
4099 const size_t SIZE = 256;
4100 char buffer[SIZE];
4101 String8 result;
4102
4103 PlaybackThread::dumpInternals(fd, args);
4104
Elliott Hughes87cebad2014-05-22 10:14:43 -07004105 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004106
4107 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004108 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004109 copy.dump(fd);
4110
4111#ifdef STATE_QUEUE_DUMP
4112 // Similar for state queue
4113 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4114 observerCopy.dump(fd);
4115 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4116 mutatorCopy.dump(fd);
4117#endif
4118
Glenn Kasten46909e72013-02-26 09:20:22 -08004119#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004120 // Write the tee output to a .wav file
4121 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004122#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004123
4124#ifdef AUDIO_WATCHDOG
4125 if (mAudioWatchdog != 0) {
4126 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4127 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4128 wdCopy.dump(fd);
4129 }
4130#endif
4131}
4132
4133uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4134{
4135 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4136}
4137
4138uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4139{
4140 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4141}
4142
4143void AudioFlinger::MixerThread::cacheParameters_l()
4144{
4145 PlaybackThread::cacheParameters_l();
4146
4147 // FIXME: Relaxed timing because of a certain device that can't meet latency
4148 // Should be reduced to 2x after the vendor fixes the driver issue
4149 // increase threshold again due to low power audio mode. The way this warning
4150 // threshold is calculated and its usefulness should be reconsidered anyway.
4151 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4152}
4153
4154// ----------------------------------------------------------------------------
4155
4156AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4157 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4158 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4159 // mLeftVolFloat, mRightVolFloat
4160{
4161}
4162
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4164 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4165 ThreadBase::type_t type)
4166 : PlaybackThread(audioFlinger, output, id, device, type)
4167 // mLeftVolFloat, mRightVolFloat
4168{
4169}
4170
Eric Laurent81784c32012-11-19 14:55:58 -08004171AudioFlinger::DirectOutputThread::~DirectOutputThread()
4172{
4173}
4174
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4176{
4177 audio_track_cblk_t* cblk = track->cblk();
4178 float left, right;
4179
4180 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4181 left = right = 0;
4182 } else {
4183 float typeVolume = mStreamTypes[track->streamType()].volume;
4184 float v = mMasterVolume * typeVolume;
4185 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004186 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4187 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4188 if (left > GAIN_FLOAT_UNITY) {
4189 left = GAIN_FLOAT_UNITY;
4190 }
4191 left *= v;
4192 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4193 if (right > GAIN_FLOAT_UNITY) {
4194 right = GAIN_FLOAT_UNITY;
4195 }
4196 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 }
4198
4199 if (lastTrack) {
4200 if (left != mLeftVolFloat || right != mRightVolFloat) {
4201 mLeftVolFloat = left;
4202 mRightVolFloat = right;
4203
4204 // Convert volumes from float to 8.24
4205 uint32_t vl = (uint32_t)(left * (1 << 24));
4206 uint32_t vr = (uint32_t)(right * (1 << 24));
4207
4208 // Delegate volume control to effect in track effect chain if needed
4209 // only one effect chain can be present on DirectOutputThread, so if
4210 // there is one, the track is connected to it
4211 if (!mEffectChains.isEmpty()) {
4212 mEffectChains[0]->setVolume_l(&vl, &vr);
4213 left = (float)vl / (1 << 24);
4214 right = (float)vr / (1 << 24);
4215 }
4216 if (mOutput->stream->set_volume) {
4217 mOutput->stream->set_volume(mOutput->stream, left, right);
4218 }
4219 }
4220 }
4221}
4222
4223
Eric Laurent81784c32012-11-19 14:55:58 -08004224AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4225 Vector< sp<Track> > *tracksToRemove
4226)
4227{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004228 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004229 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004230 bool doHwPause = false;
4231 bool doHwResume = false;
4232 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004233
4234 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004235 for (size_t i = 0; i < count; i++) {
4236 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004237 // The track died recently
4238 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004239 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004240 }
4241
4242 Track* const track = t.get();
4243 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004244 // Only consider last track started for volume and mixer state control.
4245 // In theory an older track could underrun and restart after the new one starts
4246 // but as we only care about the transition phase between two tracks on a
4247 // direct output, it is not a problem to ignore the underrun case.
4248 sp<Track> l = mLatestActiveTrack.promote();
4249 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004250
Eric Laurentd1f69b02014-12-15 14:33:13 -08004251 if (mHwSupportsPause && track->isPausing()) {
4252 track->setPaused();
4253 if (last && !mHwPaused) {
4254 doHwPause = true;
4255 mHwPaused = true;
4256 }
4257 tracksToRemove->add(track);
4258 } else if (track->isFlushPending()) {
4259 track->flushAck();
4260 if (last) {
4261 flushPending = true;
4262 }
4263 } else if (mHwSupportsPause && track->isResumePending()){
4264 track->resumeAck();
4265 if (last) {
4266 if (mHwPaused) {
4267 doHwResume = true;
4268 mHwPaused = false;
4269 }
4270 }
4271 }
4272
Eric Laurent81784c32012-11-19 14:55:58 -08004273 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004274 // for all its buffers to be filled before processing it.
4275 // Allow draining the buffer in case the client
4276 // app does not call stop() and relies on underrun to stop:
4277 // hence the test on (track->mRetryCount > 1).
4278 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004279 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004280 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4281 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004282 minFrames = mNormalFrameCount;
4283 } else {
4284 minFrames = 1;
4285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286
Eric Laurentab5cdba2014-06-09 17:22:27 -07004287 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4288 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004289 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004290 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004291
4292 if (track->mFillingUpStatus == Track::FS_FILLED) {
4293 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004294 // make sure processVolume_l() will apply new volume even if 0
4295 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004296 if (!mHwSupportsPause) {
4297 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004298 }
4299 }
4300
4301 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004302 processVolume_l(track, last);
4303 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004304 // reset retry count
4305 track->mRetryCount = kMaxTrackRetriesDirect;
4306 mActiveTrack = t;
4307 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004308 if (usesHwAvSync() && mHwPaused) {
4309 doHwResume = true;
4310 mHwPaused = false;
4311 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004312 }
Eric Laurent81784c32012-11-19 14:55:58 -08004313 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004314 // clear effect chain input buffer if the last active track started underruns
4315 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004316 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004317 mEffectChains[0]->clearInputBuffer();
4318 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004319 if (track->isStopping_1()) {
4320 track->mState = TrackBase::STOPPING_2;
4321 }
4322 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4323 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004324 // We have consumed all the buffers of this track.
4325 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004326 size_t audioHALFrames;
4327 if (audio_is_linear_pcm(mFormat)) {
4328 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4329 } else {
4330 audioHALFrames = 0;
4331 }
4332
Eric Laurent81784c32012-11-19 14:55:58 -08004333 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004334 if (mStandby || !last ||
4335 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004336 if (track->isStopping_2()) {
4337 track->mState = TrackBase::STOPPED;
4338 }
Eric Laurent81784c32012-11-19 14:55:58 -08004339 if (track->isStopped()) {
4340 track->reset();
4341 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004342 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004343 }
4344 } else {
4345 // No buffers for this track. Give it a few chances to
4346 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004347 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004348 if (--(track->mRetryCount) <= 0) {
4349 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004350 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004351 // indicate to client process that the track was disabled because of underrun;
4352 // it will then automatically call start() when data is available
4353 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004354 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004355 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004356 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4357 doHwPause = true;
4358 mHwPaused = true;
4359 }
Eric Laurent81784c32012-11-19 14:55:58 -08004360 }
4361 }
4362 }
4363 }
4364
Eric Laurentd1f69b02014-12-15 14:33:13 -08004365 // if an active track did not command a flush, check for pending flush on stopped tracks
4366 if (!flushPending) {
4367 for (size_t i = 0; i < mTracks.size(); i++) {
4368 if (mTracks[i]->isFlushPending()) {
4369 mTracks[i]->flushAck();
4370 flushPending = true;
4371 }
4372 }
4373 }
4374
4375 // make sure the pause/flush/resume sequence is executed in the right order.
4376 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4377 // before flush and then resume HW. This can happen in case of pause/flush/resume
4378 // if resume is received before pause is executed.
4379 if (mHwSupportsPause && !mStandby &&
4380 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4381 mOutput->stream->pause(mOutput->stream);
4382 }
4383 if (flushPending) {
4384 flushHw_l();
4385 }
4386 if (mHwSupportsPause && !mStandby && doHwResume) {
4387 mOutput->stream->resume(mOutput->stream);
4388 }
Eric Laurent81784c32012-11-19 14:55:58 -08004389 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004390 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004391
4392 return mixerStatus;
4393}
4394
4395void AudioFlinger::DirectOutputThread::threadLoop_mix()
4396{
Eric Laurent81784c32012-11-19 14:55:58 -08004397 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004398 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004399 // output audio to hardware
4400 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004401 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004402 buffer.frameCount = frameCount;
4403 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004404 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004405 memset(curBuf, 0, frameCount * mFrameSize);
4406 break;
4407 }
4408 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4409 frameCount -= buffer.frameCount;
4410 curBuf += buffer.frameCount * mFrameSize;
4411 mActiveTrack->releaseBuffer(&buffer);
4412 }
Andy Hung2098f272014-02-27 14:00:06 -08004413 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004414 sleepTime = 0;
4415 standbyTime = systemTime() + standbyDelay;
4416 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004417}
4418
4419void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4420{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004421 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004422 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004423 sleepTime = idleSleepTime;
4424 return;
4425 }
Eric Laurent81784c32012-11-19 14:55:58 -08004426 if (sleepTime == 0) {
4427 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4428 sleepTime = activeSleepTime;
4429 } else {
4430 sleepTime = idleSleepTime;
4431 }
4432 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004433 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004434 sleepTime = 0;
4435 }
4436}
4437
Eric Laurentd1f69b02014-12-15 14:33:13 -08004438void AudioFlinger::DirectOutputThread::threadLoop_exit()
4439{
4440 {
4441 Mutex::Autolock _l(mLock);
4442 bool flushPending = false;
4443 for (size_t i = 0; i < mTracks.size(); i++) {
4444 if (mTracks[i]->isFlushPending()) {
4445 mTracks[i]->flushAck();
4446 flushPending = true;
4447 }
4448 }
4449 if (flushPending) {
4450 flushHw_l();
4451 }
4452 }
4453 PlaybackThread::threadLoop_exit();
4454}
4455
4456// must be called with thread mutex locked
4457bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4458{
4459 bool trackPaused = false;
4460
4461 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4462 // after a timeout and we will enter standby then.
4463 if (mTracks.size() > 0) {
4464 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4465 }
4466
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004467 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004468}
4469
Eric Laurent81784c32012-11-19 14:55:58 -08004470// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004471int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004472 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004473{
4474 return 0;
4475}
4476
4477// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004478void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004479{
4480}
4481
Eric Laurent10351942014-05-08 18:49:52 -07004482// checkForNewParameter_l() must be called with ThreadBase::mLock held
4483bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4484 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004485{
4486 bool reconfig = false;
4487
Eric Laurent10351942014-05-08 18:49:52 -07004488 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004489
Eric Laurent10351942014-05-08 18:49:52 -07004490 AudioParameter param = AudioParameter(keyValuePair);
4491 int value;
4492 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4493 // forward device change to effects that have requested to be
4494 // aware of attached audio device.
4495 if (value != AUDIO_DEVICE_NONE) {
4496 mOutDevice = value;
4497 for (size_t i = 0; i < mEffectChains.size(); i++) {
4498 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004499 }
4500 }
Eric Laurent81784c32012-11-19 14:55:58 -08004501 }
Eric Laurent10351942014-05-08 18:49:52 -07004502 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4503 // do not accept frame count changes if tracks are open as the track buffer
4504 // size depends on frame count and correct behavior would not be garantied
4505 // if frame count is changed after track creation
4506 if (!mTracks.isEmpty()) {
4507 status = INVALID_OPERATION;
4508 } else {
4509 reconfig = true;
4510 }
4511 }
4512 if (status == NO_ERROR) {
4513 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4514 keyValuePair.string());
4515 if (!mStandby && status == INVALID_OPERATION) {
4516 mOutput->stream->common.standby(&mOutput->stream->common);
4517 mStandby = true;
4518 mBytesWritten = 0;
4519 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4520 keyValuePair.string());
4521 }
4522 if (status == NO_ERROR && reconfig) {
4523 readOutputParameters_l();
4524 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4525 }
4526 }
4527
Eric Laurent81784c32012-11-19 14:55:58 -08004528 return reconfig;
4529}
4530
4531uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4532{
4533 uint32_t time;
4534 if (audio_is_linear_pcm(mFormat)) {
4535 time = PlaybackThread::activeSleepTimeUs();
4536 } else {
4537 time = 10000;
4538 }
4539 return time;
4540}
4541
4542uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4543{
4544 uint32_t time;
4545 if (audio_is_linear_pcm(mFormat)) {
4546 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4547 } else {
4548 time = 10000;
4549 }
4550 return time;
4551}
4552
4553uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4554{
4555 uint32_t time;
4556 if (audio_is_linear_pcm(mFormat)) {
4557 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4558 } else {
4559 time = 10000;
4560 }
4561 return time;
4562}
4563
4564void AudioFlinger::DirectOutputThread::cacheParameters_l()
4565{
4566 PlaybackThread::cacheParameters_l();
4567
4568 // use shorter standby delay as on normal output to release
4569 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004570 if (audio_is_linear_pcm(mFormat)) {
4571 standbyDelay = microseconds(activeSleepTime*2);
4572 } else {
4573 standbyDelay = kOffloadStandbyDelayNs;
4574 }
Eric Laurent81784c32012-11-19 14:55:58 -08004575}
4576
Eric Laurente659ef42014-09-29 13:06:46 -07004577void AudioFlinger::DirectOutputThread::flushHw_l()
4578{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004579 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004580 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004581 }
4582 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004583}
4584
Eric Laurent81784c32012-11-19 14:55:58 -08004585// ----------------------------------------------------------------------------
4586
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004588 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004589 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004590 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004591 mWriteAckSequence(0),
4592 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593{
4594}
4595
4596AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4597{
4598}
4599
4600void AudioFlinger::AsyncCallbackThread::onFirstRef()
4601{
4602 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4603}
4604
4605bool AudioFlinger::AsyncCallbackThread::threadLoop()
4606{
4607 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004608 uint32_t writeAckSequence;
4609 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610
4611 {
4612 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004613 while (!((mWriteAckSequence & 1) ||
4614 (mDrainSequence & 1) ||
4615 exitPending())) {
4616 mWaitWorkCV.wait(mLock);
4617 }
4618
Eric Laurentbfb1b832013-01-07 09:53:42 -08004619 if (exitPending()) {
4620 break;
4621 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004622 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4623 mWriteAckSequence, mDrainSequence);
4624 writeAckSequence = mWriteAckSequence;
4625 mWriteAckSequence &= ~1;
4626 drainSequence = mDrainSequence;
4627 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628 }
4629 {
Eric Laurent4de95592013-09-26 15:28:21 -07004630 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4631 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004632 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004633 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004634 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004635 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004636 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004637 }
4638 }
4639 }
4640 }
4641 return false;
4642}
4643
4644void AudioFlinger::AsyncCallbackThread::exit()
4645{
4646 ALOGV("AsyncCallbackThread::exit");
4647 Mutex::Autolock _l(mLock);
4648 requestExit();
4649 mWaitWorkCV.broadcast();
4650}
4651
Eric Laurent3b4529e2013-09-05 18:09:19 -07004652void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004653{
4654 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004655 // bit 0 is cleared
4656 mWriteAckSequence = sequence << 1;
4657}
4658
4659void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4660{
4661 Mutex::Autolock _l(mLock);
4662 // ignore unexpected callbacks
4663 if (mWriteAckSequence & 2) {
4664 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665 mWaitWorkCV.signal();
4666 }
4667}
4668
Eric Laurent3b4529e2013-09-05 18:09:19 -07004669void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004670{
4671 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004672 // bit 0 is cleared
4673 mDrainSequence = sequence << 1;
4674}
4675
4676void AudioFlinger::AsyncCallbackThread::resetDraining()
4677{
4678 Mutex::Autolock _l(mLock);
4679 // ignore unexpected callbacks
4680 if (mDrainSequence & 2) {
4681 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682 mWaitWorkCV.signal();
4683 }
4684}
4685
4686
4687// ----------------------------------------------------------------------------
4688AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4689 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4690 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004691 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692{
Eric Laurentfd477972013-10-25 18:10:40 -07004693 //FIXME: mStandby should be set to true by ThreadBase constructor
4694 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695}
4696
Eric Laurentbfb1b832013-01-07 09:53:42 -08004697void AudioFlinger::OffloadThread::threadLoop_exit()
4698{
4699 if (mFlushPending || mHwPaused) {
4700 // If a flush is pending or track was paused, just discard buffered data
4701 flushHw_l();
4702 } else {
4703 mMixerStatus = MIXER_DRAIN_ALL;
4704 threadLoop_drain();
4705 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004706 if (mUseAsyncWrite) {
4707 ALOG_ASSERT(mCallbackThread != 0);
4708 mCallbackThread->exit();
4709 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004710 PlaybackThread::threadLoop_exit();
4711}
4712
4713AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4714 Vector< sp<Track> > *tracksToRemove
4715)
4716{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717 size_t count = mActiveTracks.size();
4718
4719 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004720 bool doHwPause = false;
4721 bool doHwResume = false;
4722
Eric Laurentede6c3b2013-09-19 14:37:46 -07004723 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4724
Eric Laurentbfb1b832013-01-07 09:53:42 -08004725 // find out which tracks need to be processed
4726 for (size_t i = 0; i < count; i++) {
4727 sp<Track> t = mActiveTracks[i].promote();
4728 // The track died recently
4729 if (t == 0) {
4730 continue;
4731 }
4732 Track* const track = t.get();
4733 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004734 // Only consider last track started for volume and mixer state control.
4735 // In theory an older track could underrun and restart after the new one starts
4736 // but as we only care about the transition phase between two tracks on a
4737 // direct output, it is not a problem to ignore the underrun case.
4738 sp<Track> l = mLatestActiveTrack.promote();
4739 bool last = l.get() == track;
4740
Haynes Mathew George7844f672014-01-15 12:32:55 -08004741 if (track->isInvalid()) {
4742 ALOGW("An invalidated track shouldn't be in active list");
4743 tracksToRemove->add(track);
4744 continue;
4745 }
4746
4747 if (track->mState == TrackBase::IDLE) {
4748 ALOGW("An idle track shouldn't be in active list");
4749 continue;
4750 }
4751
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752 if (track->isPausing()) {
4753 track->setPaused();
4754 if (last) {
4755 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004756 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757 mHwPaused = true;
4758 }
4759 // If we were part way through writing the mixbuffer to
4760 // the HAL we must save this until we resume
4761 // BUG - this will be wrong if a different track is made active,
4762 // in that case we want to discard the pending data in the
4763 // mixbuffer and tell the client to present it again when the
4764 // track is resumed
4765 mPausedWriteLength = mCurrentWriteLength;
4766 mPausedBytesRemaining = mBytesRemaining;
4767 mBytesRemaining = 0; // stop writing
4768 }
4769 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004770 } else if (track->isFlushPending()) {
4771 track->flushAck();
4772 if (last) {
4773 mFlushPending = true;
4774 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004775 } else if (track->isResumePending()){
4776 track->resumeAck();
4777 if (last) {
4778 if (mPausedBytesRemaining) {
4779 // Need to continue write that was interrupted
4780 mCurrentWriteLength = mPausedWriteLength;
4781 mBytesRemaining = mPausedBytesRemaining;
4782 mPausedBytesRemaining = 0;
4783 }
4784 if (mHwPaused) {
4785 doHwResume = true;
4786 mHwPaused = false;
4787 // threadLoop_mix() will handle the case that we need to
4788 // resume an interrupted write
4789 }
4790 // enable write to audio HAL
4791 sleepTime = 0;
4792
4793 // Do not handle new data in this iteration even if track->framesReady()
4794 mixerStatus = MIXER_TRACKS_ENABLED;
4795 }
4796 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004797 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004798 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799 if (track->mFillingUpStatus == Track::FS_FILLED) {
4800 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004801 // make sure processVolume_l() will apply new volume even if 0
4802 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004803 }
4804
4805 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004806 sp<Track> previousTrack = mPreviousTrack.promote();
4807 if (previousTrack != 0) {
4808 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004809 // Flush any data still being written from last track
4810 mBytesRemaining = 0;
4811 if (mPausedBytesRemaining) {
4812 // Last track was paused so we also need to flush saved
4813 // mixbuffer state and invalidate track so that it will
4814 // re-submit that unwritten data when it is next resumed
4815 mPausedBytesRemaining = 0;
4816 // Invalidate is a bit drastic - would be more efficient
4817 // to have a flag to tell client that some of the
4818 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004819 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004820 }
4821 // flush data already sent to the DSP if changing audio session as audio
4822 // comes from a different source. Also invalidate previous track to force a
4823 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004824 if (previousTrack->sessionId() != track->sessionId()) {
4825 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004826 }
4827 }
4828 }
4829 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 // reset retry count
4831 track->mRetryCount = kMaxTrackRetriesOffload;
4832 mActiveTrack = t;
4833 mixerStatus = MIXER_TRACKS_READY;
4834 }
4835 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004836 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837 if (track->isStopping_1()) {
4838 // Hardware buffer can hold a large amount of audio so we must
4839 // wait for all current track's data to drain before we say
4840 // that the track is stopped.
4841 if (mBytesRemaining == 0) {
4842 // Only start draining when all data in mixbuffer
4843 // has been written
4844 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4845 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004846 // do not drain if no data was ever sent to HAL (mStandby == true)
4847 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004848 // do not modify drain sequence if we are already draining. This happens
4849 // when resuming from pause after drain.
4850 if ((mDrainSequence & 1) == 0) {
4851 sleepTime = 0;
4852 standbyTime = systemTime() + standbyDelay;
4853 mixerStatus = MIXER_DRAIN_TRACK;
4854 mDrainSequence += 2;
4855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856 if (mHwPaused) {
4857 // It is possible to move from PAUSED to STOPPING_1 without
4858 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004859 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860 mHwPaused = false;
4861 }
4862 }
4863 }
4864 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004865 // Drain has completed or we are in standby, signal presentation complete
4866 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 track->mState = TrackBase::STOPPED;
4868 size_t audioHALFrames =
4869 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4870 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004871 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004872 track->presentationComplete(framesWritten, audioHALFrames);
4873 track->reset();
4874 tracksToRemove->add(track);
4875 }
4876 } else {
4877 // No buffers for this track. Give it a few chances to
4878 // fill a buffer, then remove it from active list.
4879 if (--(track->mRetryCount) <= 0) {
4880 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4881 track->name());
4882 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004883 // indicate to client process that the track was disabled because of underrun;
4884 // it will then automatically call start() when data is available
4885 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004886 } else if (last){
4887 mixerStatus = MIXER_TRACKS_ENABLED;
4888 }
4889 }
4890 }
4891 // compute volume for this track
4892 processVolume_l(track, last);
4893 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004894
Eric Laurentea0fade2013-10-04 16:23:48 -07004895 // make sure the pause/flush/resume sequence is executed in the right order.
4896 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4897 // before flush and then resume HW. This can happen in case of pause/flush/resume
4898 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004899 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004900 mOutput->stream->pause(mOutput->stream);
4901 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004902 if (mFlushPending) {
4903 flushHw_l();
4904 mFlushPending = false;
4905 }
Eric Laurentfd477972013-10-25 18:10:40 -07004906 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004907 mOutput->stream->resume(mOutput->stream);
4908 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004909
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910 // remove all the tracks that need to be...
4911 removeTracks_l(*tracksToRemove);
4912
4913 return mixerStatus;
4914}
4915
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916// must be called with thread mutex locked
4917bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4918{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004919 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4920 mWriteAckSequence, mDrainSequence);
4921 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922 return true;
4923 }
4924 return false;
4925}
4926
Eric Laurentbfb1b832013-01-07 09:53:42 -08004927bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4928{
4929 Mutex::Autolock _l(mLock);
4930 return waitingAsyncCallback_l();
4931}
4932
4933void AudioFlinger::OffloadThread::flushHw_l()
4934{
Eric Laurente659ef42014-09-29 13:06:46 -07004935 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936 // Flush anything still waiting in the mixbuffer
4937 mCurrentWriteLength = 0;
4938 mBytesRemaining = 0;
4939 mPausedWriteLength = 0;
4940 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004941
Eric Laurentbfb1b832013-01-07 09:53:42 -08004942 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004943 // discard any pending drain or write ack by incrementing sequence
4944 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4945 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004947 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4948 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004949 }
4950}
4951
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004952void AudioFlinger::OffloadThread::onAddNewTrack_l()
4953{
4954 sp<Track> previousTrack = mPreviousTrack.promote();
4955 sp<Track> latestTrack = mLatestActiveTrack.promote();
4956
4957 if (previousTrack != 0 && latestTrack != 0 &&
4958 (previousTrack->sessionId() != latestTrack->sessionId())) {
4959 mFlushPending = true;
4960 }
4961 PlaybackThread::onAddNewTrack_l();
4962}
4963
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964// ----------------------------------------------------------------------------
4965
Eric Laurent81784c32012-11-19 14:55:58 -08004966AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4967 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4968 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4969 DUPLICATING),
4970 mWaitTimeMs(UINT_MAX)
4971{
4972 addOutputTrack(mainThread);
4973}
4974
4975AudioFlinger::DuplicatingThread::~DuplicatingThread()
4976{
4977 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4978 mOutputTracks[i]->destroy();
4979 }
4980}
4981
4982void AudioFlinger::DuplicatingThread::threadLoop_mix()
4983{
4984 // mix buffers...
4985 if (outputsReady(outputTracks)) {
4986 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4987 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004988 if (mMixerBufferValid) {
4989 memset(mMixerBuffer, 0, mMixerBufferSize);
4990 } else {
4991 memset(mSinkBuffer, 0, mSinkBufferSize);
4992 }
Eric Laurent81784c32012-11-19 14:55:58 -08004993 }
4994 sleepTime = 0;
4995 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004996 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004997 standbyTime = systemTime() + standbyDelay;
4998}
4999
5000void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5001{
5002 if (sleepTime == 0) {
5003 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5004 sleepTime = activeSleepTime;
5005 } else {
5006 sleepTime = idleSleepTime;
5007 }
5008 } else if (mBytesWritten != 0) {
5009 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5010 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005011 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 } else {
5013 // flush remaining overflow buffers in output tracks
5014 writeFrames = 0;
5015 }
5016 sleepTime = 0;
5017 }
5018}
5019
Eric Laurentbfb1b832013-01-07 09:53:42 -08005020ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005021{
5022 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005023 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005024 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005025 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005026 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005027}
5028
5029void AudioFlinger::DuplicatingThread::threadLoop_standby()
5030{
5031 // DuplicatingThread implements standby by stopping all tracks
5032 for (size_t i = 0; i < outputTracks.size(); i++) {
5033 outputTracks[i]->stop();
5034 }
5035}
5036
5037void AudioFlinger::DuplicatingThread::saveOutputTracks()
5038{
5039 outputTracks = mOutputTracks;
5040}
5041
5042void AudioFlinger::DuplicatingThread::clearOutputTracks()
5043{
5044 outputTracks.clear();
5045}
5046
5047void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5048{
5049 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005050 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5051 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5052 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5053 const size_t frameCount =
5054 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5055 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5056 // from different OutputTracks and their associated MixerThreads (e.g. one may
5057 // nearly empty and the other may be dropping data).
5058
5059 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005060 this,
5061 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005062 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005063 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005064 frameCount,
5065 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005066 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005067 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005068 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005069 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005070 updateWaitTime_l();
5071 }
5072}
5073
5074void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5075{
5076 Mutex::Autolock _l(mLock);
5077 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5078 if (mOutputTracks[i]->thread() == thread) {
5079 mOutputTracks[i]->destroy();
5080 mOutputTracks.removeAt(i);
5081 updateWaitTime_l();
5082 return;
5083 }
5084 }
5085 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5086}
5087
5088// caller must hold mLock
5089void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5090{
5091 mWaitTimeMs = UINT_MAX;
5092 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5093 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5094 if (strong != 0) {
5095 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5096 if (waitTimeMs < mWaitTimeMs) {
5097 mWaitTimeMs = waitTimeMs;
5098 }
5099 }
5100 }
5101}
5102
5103
5104bool AudioFlinger::DuplicatingThread::outputsReady(
5105 const SortedVector< sp<OutputTrack> > &outputTracks)
5106{
5107 for (size_t i = 0; i < outputTracks.size(); i++) {
5108 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5109 if (thread == 0) {
5110 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5111 outputTracks[i].get());
5112 return false;
5113 }
5114 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5115 // see note at standby() declaration
5116 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5117 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5118 thread.get());
5119 return false;
5120 }
5121 }
5122 return true;
5123}
5124
5125uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5126{
5127 return (mWaitTimeMs * 1000) / 2;
5128}
5129
5130void AudioFlinger::DuplicatingThread::cacheParameters_l()
5131{
5132 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5133 updateWaitTime_l();
5134
5135 MixerThread::cacheParameters_l();
5136}
5137
5138// ----------------------------------------------------------------------------
5139// Record
5140// ----------------------------------------------------------------------------
5141
5142AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5143 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005144 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005145 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005146 audio_devices_t inDevice
5147#ifdef TEE_SINK
5148 , const sp<NBAIO_Sink>& teeSink
5149#endif
5150 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005151 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005152 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005153 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005154 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005155#ifdef TEE_SINK
5156 , mTeeSink(teeSink)
5157#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005158 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5159 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005160 // mFastCapture below
5161 , mFastCaptureFutex(0)
5162 // mInputSource
5163 // mPipeSink
5164 // mPipeSource
5165 , mPipeFramesP2(0)
5166 // mPipeMemory
5167 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005168 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005169{
Glenn Kastend7dca052015-03-05 16:05:54 -08005170 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5171 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005172
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005173 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005174
5175 // create an NBAIO source for the HAL input stream, and negotiate
5176 mInputSource = new AudioStreamInSource(input->stream);
5177 size_t numCounterOffers = 0;
5178 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5179 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5180 ALOG_ASSERT(index == 0);
5181
5182 // initialize fast capture depending on configuration
5183 bool initFastCapture;
5184 switch (kUseFastCapture) {
5185 case FastCapture_Never:
5186 initFastCapture = false;
5187 break;
5188 case FastCapture_Always:
5189 initFastCapture = true;
5190 break;
5191 case FastCapture_Static:
5192 uint32_t primaryOutputSampleRate;
5193 {
5194 AutoMutex _l(audioFlinger->mHardwareLock);
5195 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5196 }
5197 initFastCapture =
5198 // either capture sample rate is same as (a reasonable) primary output sample rate
5199 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5200 (mSampleRate == primaryOutputSampleRate)) ||
5201 // or primary output sample rate is unknown, and capture sample rate is reasonable
5202 ((primaryOutputSampleRate == 0) &&
5203 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005204 // and the buffer size is < 12 ms
5205 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005206 break;
5207 // case FastCapture_Dynamic:
5208 }
5209
5210 if (initFastCapture) {
5211 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5212 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005213 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005214 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5215 void *pipeBuffer;
5216 const sp<MemoryDealer> roHeap(readOnlyHeap());
5217 sp<IMemory> pipeMemory;
5218 if ((roHeap == 0) ||
5219 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5220 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5221 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5222 goto failed;
5223 }
5224 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5225 memset(pipeBuffer, 0, pipeSize);
5226 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5227 const NBAIO_Format offers[1] = {format};
5228 size_t numCounterOffers = 0;
5229 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5230 ALOG_ASSERT(index == 0);
5231 mPipeSink = pipe;
5232 PipeReader *pipeReader = new PipeReader(*pipe);
5233 numCounterOffers = 0;
5234 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5235 ALOG_ASSERT(index == 0);
5236 mPipeSource = pipeReader;
5237 mPipeFramesP2 = pipeFramesP2;
5238 mPipeMemory = pipeMemory;
5239
5240 // create fast capture
5241 mFastCapture = new FastCapture();
5242 FastCaptureStateQueue *sq = mFastCapture->sq();
5243#ifdef STATE_QUEUE_DUMP
5244 // FIXME
5245#endif
5246 FastCaptureState *state = sq->begin();
5247 state->mCblk = NULL;
5248 state->mInputSource = mInputSource.get();
5249 state->mInputSourceGen++;
5250 state->mPipeSink = pipe;
5251 state->mPipeSinkGen++;
5252 state->mFrameCount = mFrameCount;
5253 state->mCommand = FastCaptureState::COLD_IDLE;
5254 // already done in constructor initialization list
5255 //mFastCaptureFutex = 0;
5256 state->mColdFutexAddr = &mFastCaptureFutex;
5257 state->mColdGen++;
5258 state->mDumpState = &mFastCaptureDumpState;
5259#ifdef TEE_SINK
5260 // FIXME
5261#endif
5262 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5263 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5264 sq->end();
5265 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5266
5267 // start the fast capture
5268 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5269 pid_t tid = mFastCapture->getTid();
5270 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5271 if (err != 0) {
5272 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5273 kPriorityFastCapture, getpid_cached, tid, err);
5274 }
5275
5276#ifdef AUDIO_WATCHDOG
5277 // FIXME
5278#endif
5279
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005280 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005281 }
5282failed: ;
5283
5284 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005285}
5286
5287
5288AudioFlinger::RecordThread::~RecordThread()
5289{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005290 if (mFastCapture != 0) {
5291 FastCaptureStateQueue *sq = mFastCapture->sq();
5292 FastCaptureState *state = sq->begin();
5293 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5294 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5295 if (old == -1) {
5296 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5297 }
5298 }
5299 state->mCommand = FastCaptureState::EXIT;
5300 sq->end();
5301 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5302 mFastCapture->join();
5303 mFastCapture.clear();
5304 }
5305 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005306 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005307 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005308}
5309
5310void AudioFlinger::RecordThread::onFirstRef()
5311{
Glenn Kastend7dca052015-03-05 16:05:54 -08005312 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005313}
5314
Eric Laurent81784c32012-11-19 14:55:58 -08005315bool AudioFlinger::RecordThread::threadLoop()
5316{
Eric Laurent81784c32012-11-19 14:55:58 -08005317 nsecs_t lastWarning = 0;
5318
5319 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005320
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005321reacquire_wakelock:
5322 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005323 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005324 {
5325 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005326 size_t size = mActiveTracks.size();
5327 activeTracksGen = mActiveTracksGen;
5328 if (size > 0) {
5329 // FIXME an arbitrary choice
5330 activeTrack = mActiveTracks[0];
5331 acquireWakeLock_l(activeTrack->uid());
5332 if (size > 1) {
5333 SortedVector<int> tmp;
5334 for (size_t i = 0; i < size; i++) {
5335 tmp.add(mActiveTracks[i]->uid());
5336 }
5337 updateWakeLockUids_l(tmp);
5338 }
5339 } else {
5340 acquireWakeLock_l(-1);
5341 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005342 }
5343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005344 // used to request a deferred sleep, to be executed later while mutex is unlocked
5345 uint32_t sleepUs = 0;
5346
5347 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005348 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005349 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005350
Glenn Kasten5edadd42013-08-14 16:30:49 -07005351 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005353 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005354 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005355 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005356 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005357 }
5358
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005359 // activeTracks accumulates a copy of a subset of mActiveTracks
5360 Vector< sp<RecordTrack> > activeTracks;
5361
Glenn Kasten735f45f2014-08-18 15:51:59 -07005362 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005363 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005364
Glenn Kasten735f45f2014-08-18 15:51:59 -07005365 // reference to a fast track which is about to be removed
5366 sp<RecordTrack> fastTrackToRemove;
5367
Eric Laurent81784c32012-11-19 14:55:58 -08005368 { // scope for mLock
5369 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005370
Eric Laurent021cf962014-05-13 10:18:14 -07005371 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005372
Eric Laurent000a4192014-01-29 15:17:32 -08005373 // check exitPending here because checkForNewParameters_l() and
5374 // checkForNewParameters_l() can temporarily release mLock
5375 if (exitPending()) {
5376 break;
5377 }
5378
Glenn Kasten2b806402013-11-20 16:37:38 -08005379 // if no active track(s), then standby and release wakelock
5380 size_t size = mActiveTracks.size();
5381 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005382 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005383 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005384 releaseWakeLock_l();
5385 ALOGV("RecordThread: loop stopping");
5386 // go to sleep
5387 mWaitWorkCV.wait(mLock);
5388 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005389 goto reacquire_wakelock;
5390 }
5391
Glenn Kasten2b806402013-11-20 16:37:38 -08005392 if (mActiveTracksGen != activeTracksGen) {
5393 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005394 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005395 for (size_t i = 0; i < size; i++) {
5396 tmp.add(mActiveTracks[i]->uid());
5397 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005398 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005399 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005400
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005401 bool doBroadcast = false;
5402 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005403
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005404 activeTrack = mActiveTracks[i];
5405 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005406 if (activeTrack->isFastTrack()) {
5407 ALOG_ASSERT(fastTrackToRemove == 0);
5408 fastTrackToRemove = activeTrack;
5409 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005410 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005411 mActiveTracks.remove(activeTrack);
5412 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005413 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005414 continue;
5415 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005416
5417 TrackBase::track_state activeTrackState = activeTrack->mState;
5418 switch (activeTrackState) {
5419
5420 case TrackBase::PAUSING:
5421 mActiveTracks.remove(activeTrack);
5422 mActiveTracksGen++;
5423 doBroadcast = true;
5424 size--;
5425 continue;
5426
5427 case TrackBase::STARTING_1:
5428 sleepUs = 10000;
5429 i++;
5430 continue;
5431
5432 case TrackBase::STARTING_2:
5433 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005434 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005435 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005436 break;
5437
5438 case TrackBase::ACTIVE:
5439 break;
5440
5441 case TrackBase::IDLE:
5442 i++;
5443 continue;
5444
5445 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005446 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005447 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005448
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005449 activeTracks.add(activeTrack);
5450 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005451
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005452 if (activeTrack->isFastTrack()) {
5453 ALOG_ASSERT(!mFastTrackAvail);
5454 ALOG_ASSERT(fastTrack == 0);
5455 fastTrack = activeTrack;
5456 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005457 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 if (doBroadcast) {
5459 mStartStopCond.broadcast();
5460 }
5461
5462 // sleep if there are no active tracks to process
5463 if (activeTracks.size() == 0) {
5464 if (sleepUs == 0) {
5465 sleepUs = kRecordThreadSleepUs;
5466 }
5467 continue;
5468 }
5469 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005470
Eric Laurent81784c32012-11-19 14:55:58 -08005471 lockEffectChains_l(effectChains);
5472 }
5473
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005474 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005475
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005476 size_t size = effectChains.size();
5477 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005478 // thread mutex is not locked, but effect chain is locked
5479 effectChains[i]->process_l();
5480 }
5481
Glenn Kasten735f45f2014-08-18 15:51:59 -07005482 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005483 if (mFastCapture != 0) {
5484 FastCaptureStateQueue *sq = mFastCapture->sq();
5485 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005486 bool didModify = false;
5487 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005488 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5489 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5490 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5491 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5492 if (old == -1) {
5493 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5494 }
5495 }
5496 state->mCommand = FastCaptureState::READ_WRITE;
5497#if 0 // FIXME
5498 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005499 FastThreadDumpState::kSamplingNforLowRamDevice :
5500 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005501#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005502 didModify = true;
5503 }
5504 audio_track_cblk_t *cblkOld = state->mCblk;
5505 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5506 if (cblkNew != cblkOld) {
5507 state->mCblk = cblkNew;
5508 // block until acked if removing a fast track
5509 if (cblkOld != NULL) {
5510 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5511 }
5512 didModify = true;
5513 }
5514 sq->end(didModify);
5515 if (didModify) {
5516 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005517#if 0
5518 if (kUseFastCapture == FastCapture_Dynamic) {
5519 mNormalSource = mPipeSource;
5520 }
5521#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005522 }
5523 }
5524
Glenn Kasten735f45f2014-08-18 15:51:59 -07005525 // now run the fast track destructor with thread mutex unlocked
5526 fastTrackToRemove.clear();
5527
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005528 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5529 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5530 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5531 // If destination is non-contiguous, first read past the nominal end of buffer, then
5532 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005533
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005534 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005535 ssize_t framesRead;
5536
5537 // If an NBAIO source is present, use it to read the normal capture's data
5538 if (mPipeSource != 0) {
5539 size_t framesToRead = mBufferSize / mFrameSize;
5540 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5541 framesToRead, AudioBufferProvider::kInvalidPTS);
5542 if (framesRead == 0) {
5543 // since pipe is non-blocking, simulate blocking input
5544 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5545 }
5546 // otherwise use the HAL / AudioStreamIn directly
5547 } else {
5548 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5549 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5550 if (bytesRead < 0) {
5551 framesRead = bytesRead;
5552 } else {
5553 framesRead = bytesRead / mFrameSize;
5554 }
5555 }
5556
5557 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5558 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005559 // Force input into standby so that it tries to recover at next read attempt
5560 inputStandBy();
5561 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005562 }
5563 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005564 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005565 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005566 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005567
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005568 if (mTeeSink != 0) {
5569 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5570 }
5571 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005572 {
5573 size_t part1 = mRsmpInFramesP2 - rear;
5574 if ((size_t) framesRead > part1) {
5575 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5576 (framesRead - part1) * mFrameSize);
5577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005578 }
5579 rear = mRsmpInRear += framesRead;
5580
5581 size = activeTracks.size();
5582 // loop over each active track
5583 for (size_t i = 0; i < size; i++) {
5584 activeTrack = activeTracks[i];
5585
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005586 // skip fast tracks, as those are handled directly by FastCapture
5587 if (activeTrack->isFastTrack()) {
5588 continue;
5589 }
5590
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 enum {
5592 OVERRUN_UNKNOWN,
5593 OVERRUN_TRUE,
5594 OVERRUN_FALSE
5595 } overrun = OVERRUN_UNKNOWN;
5596
5597 // loop over getNextBuffer to handle circular sink
5598 for (;;) {
5599
5600 activeTrack->mSink.frameCount = ~0;
5601 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5602 size_t framesOut = activeTrack->mSink.frameCount;
5603 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5604
5605 int32_t front = activeTrack->mRsmpInFront;
5606 ssize_t filled = rear - front;
5607 size_t framesIn;
5608
5609 if (filled < 0) {
5610 // should not happen, but treat like a massive overrun and re-sync
5611 framesIn = 0;
5612 activeTrack->mRsmpInFront = rear;
5613 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005614 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005615 framesIn = (size_t) filled;
5616 } else {
5617 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005618 framesIn = mRsmpInFrames;
5619 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005620 overrun = OVERRUN_TRUE;
5621 }
5622
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005623 if (framesOut == 0 || framesIn == 0) {
5624 break;
5625 }
5626
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005627 if (activeTrack->mResampler == NULL) {
5628 // no resampling
5629 if (framesIn > framesOut) {
5630 framesIn = framesOut;
5631 } else {
5632 framesOut = framesIn;
5633 }
5634 int8_t *dst = activeTrack->mSink.i8;
5635 while (framesIn > 0) {
5636 front &= mRsmpInFramesP2 - 1;
5637 size_t part1 = mRsmpInFramesP2 - front;
5638 if (part1 > framesIn) {
5639 part1 = framesIn;
5640 }
5641 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005642 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005643 memcpy(dst, src, part1 * mFrameSize);
5644 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005645 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 part1);
5647 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005648 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5649 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 }
5651 dst += part1 * activeTrack->mFrameSize;
5652 front += part1;
5653 framesIn -= part1;
5654 }
5655 activeTrack->mRsmpInFront += framesOut;
5656
5657 } else {
5658 // resampling
5659 // FIXME framesInNeeded should really be part of resampler API, and should
5660 // depend on the SRC ratio
5661 // to keep mRsmpInBuffer full so resampler always has sufficient input
5662 size_t framesInNeeded;
5663 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005664 // Do not precompute in/out because floating point is not associative
5665 // e.g. a*b/c != a*(b/c).
5666 const double in(mSampleRate);
5667 const double out(activeTrack->mSampleRate);
5668 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005669 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005670 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005671 // Although we theoretically have framesIn in circular buffer, some of those are
5672 // unreleased frames, and thus must be discounted for purpose of budgeting.
5673 size_t unreleased = activeTrack->mRsmpInUnrel;
5674 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005675 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005676 ALOGV("not enough to resample: have %u frames in but need %u in to "
5677 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005678 framesIn, framesInNeeded, framesOut, in / out);
5679 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005680 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5681 if (newFramesOut == 0) {
5682 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005683 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005684 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005685 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005686 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005687 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5688 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5689 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005690 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005691 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005692 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005693 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005694 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005695 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005696 }
5697
5698 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5699 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005700 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005701 delete[] activeTrack->mRsmpOutBuffer;
5702 // resampler always outputs stereo
5703 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5704 activeTrack->mRsmpOutFrameCount = framesOut;
5705 }
5706
5707 // resampler accumulates, but we only have one source track
5708 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5709 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005710 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005711 activeTrack->mResamplerBufferProvider
5712 /*this*/ /* AudioBufferProvider* */);
5713 // ditherAndClamp() works as long as all buffers returned by
5714 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005715 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005716 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005717 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5718 framesOut);
5719 // the resampler always outputs stereo samples:
5720 // do post stereo to mono conversion
5721 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005722 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 } else {
5724 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5725 activeTrack->mRsmpOutBuffer, framesOut);
5726 }
5727 // now done with mRsmpOutBuffer
5728
5729 }
5730
5731 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5732 overrun = OVERRUN_FALSE;
5733 }
5734
5735 if (activeTrack->mFramesToDrop == 0) {
5736 if (framesOut > 0) {
5737 activeTrack->mSink.frameCount = framesOut;
5738 activeTrack->releaseBuffer(&activeTrack->mSink);
5739 }
5740 } else {
5741 // FIXME could do a partial drop of framesOut
5742 if (activeTrack->mFramesToDrop > 0) {
5743 activeTrack->mFramesToDrop -= framesOut;
5744 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005745 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005746 }
5747 } else {
5748 activeTrack->mFramesToDrop += framesOut;
5749 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5750 activeTrack->mSyncStartEvent->isCancelled()) {
5751 ALOGW("Synced record %s, session %d, trigger session %d",
5752 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5753 activeTrack->sessionId(),
5754 (activeTrack->mSyncStartEvent != 0) ?
5755 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005756 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005757 }
5758 }
5759 }
5760
5761 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005762 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005763 }
5764 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005765
5766 switch (overrun) {
5767 case OVERRUN_TRUE:
5768 // client isn't retrieving buffers fast enough
5769 if (!activeTrack->setOverflow()) {
5770 nsecs_t now = systemTime();
5771 // FIXME should lastWarning per track?
5772 if ((now - lastWarning) > kWarningThrottleNs) {
5773 ALOGW("RecordThread: buffer overflow");
5774 lastWarning = now;
5775 }
5776 }
5777 break;
5778 case OVERRUN_FALSE:
5779 activeTrack->clearOverflow();
5780 break;
5781 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005782 break;
5783 }
5784
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005785 }
5786
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005787unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005788 // enable changes in effect chain
5789 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005790 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005791 }
5792
Glenn Kasten93e471f2013-08-19 08:40:07 -07005793 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005794
5795 {
5796 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005797 for (size_t i = 0; i < mTracks.size(); i++) {
5798 sp<RecordTrack> track = mTracks[i];
5799 track->invalidate();
5800 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005801 mActiveTracks.clear();
5802 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005803 mStartStopCond.broadcast();
5804 }
5805
5806 releaseWakeLock();
5807
5808 ALOGV("RecordThread %p exiting", this);
5809 return false;
5810}
5811
Glenn Kasten93e471f2013-08-19 08:40:07 -07005812void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005813{
5814 if (!mStandby) {
5815 inputStandBy();
5816 mStandby = true;
5817 }
5818}
5819
5820void AudioFlinger::RecordThread::inputStandBy()
5821{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005822 // Idle the fast capture if it's currently running
5823 if (mFastCapture != 0) {
5824 FastCaptureStateQueue *sq = mFastCapture->sq();
5825 FastCaptureState *state = sq->begin();
5826 if (!(state->mCommand & FastCaptureState::IDLE)) {
5827 state->mCommand = FastCaptureState::COLD_IDLE;
5828 state->mColdFutexAddr = &mFastCaptureFutex;
5829 state->mColdGen++;
5830 mFastCaptureFutex = 0;
5831 sq->end();
5832 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5833 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5834#if 0
5835 if (kUseFastCapture == FastCapture_Dynamic) {
5836 // FIXME
5837 }
5838#endif
5839#ifdef AUDIO_WATCHDOG
5840 // FIXME
5841#endif
5842 } else {
5843 sq->end(false /*didModify*/);
5844 }
5845 }
Eric Laurent81784c32012-11-19 14:55:58 -08005846 mInput->stream->common.standby(&mInput->stream->common);
5847}
5848
Glenn Kasten05997e22014-03-13 15:08:33 -07005849// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005850sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005851 const sp<AudioFlinger::Client>& client,
5852 uint32_t sampleRate,
5853 audio_format_t format,
5854 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005855 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005856 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005857 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005858 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005859 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005860 pid_t tid,
5861 status_t *status)
5862{
Glenn Kasten74935e42013-12-19 08:56:45 -08005863 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005864 sp<RecordTrack> track;
5865 status_t lStatus;
5866
Glenn Kasten90e58b12013-07-31 16:16:02 -07005867 // client expresses a preference for FAST, but we get the final say
5868 if (*flags & IAudioFlinger::TRACK_FAST) {
5869 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005870 // use case: callback handler
5871 (tid != -1) &&
5872 // frame count is not specified, or is exactly the pipe depth
5873 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005874 // PCM data
5875 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005876 // native format
5877 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005878 // native channel mask
5879 (channelMask == mChannelMask) &&
5880 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005881 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005882 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 hasFastCapture() &&
5884 // there are sufficient fast track slots available
5885 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005886 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005887 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005888 frameCount, mFrameCount);
5889 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005890 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5891 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005892 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005893 frameCount, mFrameCount, mPipeFramesP2,
5894 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5895 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005896 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005897 }
5898 }
5899
5900 // compute track buffer size in frames, and suggest the notification frame count
5901 if (*flags & IAudioFlinger::TRACK_FAST) {
5902 // fast track: frame count is exactly the pipe depth
5903 frameCount = mPipeFramesP2;
5904 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5905 *notificationFrames = mFrameCount;
5906 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005907 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5908 // or 20 ms if there is a fast capture
5909 // TODO This could be a roundupRatio inline, and const
5910 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5911 * sampleRate + mSampleRate - 1) / mSampleRate;
5912 // minimum number of notification periods is at least kMinNotifications,
5913 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5914 static const size_t kMinNotifications = 3;
5915 static const uint32_t kMinMs = 30;
5916 // TODO This could be a roundupRatio inline
5917 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5918 // TODO This could be a roundupRatio inline
5919 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5920 maxNotificationFrames;
5921 const size_t minFrameCount = maxNotificationFrames *
5922 max(kMinNotifications, minNotificationsByMs);
5923 frameCount = max(frameCount, minFrameCount);
5924 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5925 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005926 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005927 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005928 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005929
Glenn Kasten15e57982013-09-24 11:52:37 -07005930 lStatus = initCheck();
5931 if (lStatus != NO_ERROR) {
5932 ALOGE("createRecordTrack_l() audio driver not initialized");
5933 goto Exit;
5934 }
Eric Laurent81784c32012-11-19 14:55:58 -08005935
5936 { // scope for mLock
5937 Mutex::Autolock _l(mLock);
5938
5939 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005940 format, channelMask, frameCount, NULL, sessionId, uid,
5941 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005942
Glenn Kasten03003332013-08-06 15:40:54 -07005943 lStatus = track->initCheck();
5944 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005945 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005946 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005947 goto Exit;
5948 }
5949 mTracks.add(track);
5950
5951 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5952 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5953 mAudioFlinger->btNrecIsOff();
5954 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5955 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005956
5957 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5958 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5959 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5960 // so ask activity manager to do this on our behalf
5961 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5962 }
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005964
Eric Laurent81784c32012-11-19 14:55:58 -08005965 lStatus = NO_ERROR;
5966
5967Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005968 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005969 return track;
5970}
5971
5972status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5973 AudioSystem::sync_event_t event,
5974 int triggerSession)
5975{
5976 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5977 sp<ThreadBase> strongMe = this;
5978 status_t status = NO_ERROR;
5979
5980 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005981 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005982 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005983 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005984 triggerSession,
5985 recordTrack->sessionId(),
5986 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005987 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005988 // Sync event can be cancelled by the trigger session if the track is not in a
5989 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005990 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005991 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005992 } else {
5993 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005994 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005995 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005996 }
5997 }
5998
5999 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006000 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006001 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006002 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6003 if (recordTrack->mState == TrackBase::PAUSING) {
6004 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006005 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006006 } else {
6007 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006008 }
6009 return status;
6010 }
6011
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006012 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6013 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6014 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006015 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006016 mActiveTracks.add(recordTrack);
6017 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006018 status_t status = NO_ERROR;
6019 if (recordTrack->isExternalTrack()) {
6020 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006021 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006022 mLock.lock();
6023 // FIXME should verify that recordTrack is still in mActiveTracks
6024 if (status != NO_ERROR) {
6025 mActiveTracks.remove(recordTrack);
6026 mActiveTracksGen++;
6027 recordTrack->clearSyncStartEvent();
6028 ALOGV("RecordThread::start error %d", status);
6029 return status;
6030 }
Eric Laurent81784c32012-11-19 14:55:58 -08006031 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006032 // Catch up with current buffer indices if thread is already running.
6033 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6034 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6035 // see previously buffered data before it called start(), but with greater risk of overrun.
6036
6037 recordTrack->mRsmpInFront = mRsmpInRear;
6038 recordTrack->mRsmpInUnrel = 0;
6039 // FIXME why reset?
6040 if (recordTrack->mResampler != NULL) {
6041 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08006042 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006043 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006044 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006045 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006046 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006047 ALOGV("Record failed to start");
6048 status = BAD_VALUE;
6049 goto startError;
6050 }
Eric Laurent81784c32012-11-19 14:55:58 -08006051 return status;
6052 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006053
Eric Laurent81784c32012-11-19 14:55:58 -08006054startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006055 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006056 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006057 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006058 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006059 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006060 return status;
6061}
6062
Eric Laurent81784c32012-11-19 14:55:58 -08006063void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6064{
6065 sp<SyncEvent> strongEvent = event.promote();
6066
6067 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006068 sp<RefBase> ptr = strongEvent->cookie().promote();
6069 if (ptr != 0) {
6070 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6071 recordTrack->handleSyncStartEvent(strongEvent);
6072 }
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074}
6075
Glenn Kastena8356f62013-07-25 14:37:52 -07006076bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006077 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006078 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006079 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006080 return false;
6081 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006082 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006083 recordTrack->mState = TrackBase::PAUSING;
6084 // do not wait for mStartStopCond if exiting
6085 if (exitPending()) {
6086 return true;
6087 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006088 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006089 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006090 // if we have been restarted, recordTrack is in mActiveTracks here
6091 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006092 ALOGV("Record stopped OK");
6093 return true;
6094 }
6095 return false;
6096}
6097
Glenn Kasten0f11b512014-01-31 16:18:54 -08006098bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006099{
6100 return false;
6101}
6102
Glenn Kasten0f11b512014-01-31 16:18:54 -08006103status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006104{
6105#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6106 if (!isValidSyncEvent(event)) {
6107 return BAD_VALUE;
6108 }
6109
6110 int eventSession = event->triggerSession();
6111 status_t ret = NAME_NOT_FOUND;
6112
6113 Mutex::Autolock _l(mLock);
6114
6115 for (size_t i = 0; i < mTracks.size(); i++) {
6116 sp<RecordTrack> track = mTracks[i];
6117 if (eventSession == track->sessionId()) {
6118 (void) track->setSyncEvent(event);
6119 ret = NO_ERROR;
6120 }
6121 }
6122 return ret;
6123#else
6124 return BAD_VALUE;
6125#endif
6126}
6127
6128// destroyTrack_l() must be called with ThreadBase::mLock held
6129void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6130{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006131 track->terminate();
6132 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006133 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006135 removeTrack_l(track);
6136 }
6137}
6138
6139void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6140{
6141 mTracks.remove(track);
6142 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006143 if (track->isFastTrack()) {
6144 ALOG_ASSERT(!mFastTrackAvail);
6145 mFastTrackAvail = true;
6146 }
Eric Laurent81784c32012-11-19 14:55:58 -08006147}
6148
6149void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6150{
6151 dumpInternals(fd, args);
6152 dumpTracks(fd, args);
6153 dumpEffectChains(fd, args);
6154}
6155
6156void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6157{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006158 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006159
Glenn Kasten44182c22015-03-05 17:12:23 -08006160 dumpBase(fd, args);
6161
6162 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006163 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006164 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006165 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006166 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006167
6168 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6169 const FastCaptureDumpState copy(mFastCaptureDumpState);
6170 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006171}
6172
Glenn Kasten0f11b512014-01-31 16:18:54 -08006173void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006174{
6175 const size_t SIZE = 256;
6176 char buffer[SIZE];
6177 String8 result;
6178
Marco Nelissenb2208842014-02-07 14:00:50 -08006179 size_t numtracks = mTracks.size();
6180 size_t numactive = mActiveTracks.size();
6181 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006182 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006183 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006184 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006185 RecordTrack::appendDumpHeader(result);
6186 for (size_t i = 0; i < numtracks ; ++i) {
6187 sp<RecordTrack> track = mTracks[i];
6188 if (track != 0) {
6189 bool active = mActiveTracks.indexOf(track) >= 0;
6190 if (active) {
6191 numactiveseen++;
6192 }
6193 track->dump(buffer, SIZE, active);
6194 result.append(buffer);
6195 }
Eric Laurent81784c32012-11-19 14:55:58 -08006196 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006197 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006198 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006199 }
6200
Marco Nelissenb2208842014-02-07 14:00:50 -08006201 if (numactiveseen != numactive) {
6202 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6203 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006204 result.append(buffer);
6205 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006206 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006207 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006208 if (mTracks.indexOf(track) < 0) {
6209 track->dump(buffer, SIZE, true);
6210 result.append(buffer);
6211 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006212 }
Eric Laurent81784c32012-11-19 14:55:58 -08006213
6214 }
6215 write(fd, result.string(), result.size());
6216}
6217
6218// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006219status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6220 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006221{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006222 RecordTrack *activeTrack = mRecordTrack;
6223 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6224 if (threadBase == 0) {
6225 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006226 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006227 return NOT_ENOUGH_DATA;
6228 }
6229 RecordThread *recordThread = (RecordThread *) threadBase.get();
6230 int32_t rear = recordThread->mRsmpInRear;
6231 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006232 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006233 // FIXME should not be P2 (don't want to increase latency)
6234 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006235 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006236 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006237 front &= recordThread->mRsmpInFramesP2 - 1;
6238 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006239 if (part1 > (size_t) filled) {
6240 part1 = filled;
6241 }
6242 size_t ask = buffer->frameCount;
6243 ALOG_ASSERT(ask > 0);
6244 if (part1 > ask) {
6245 part1 = ask;
6246 }
6247 if (part1 == 0) {
6248 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006249 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006250 buffer->raw = NULL;
6251 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006252 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006253 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006254 }
6255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006256 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006257 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006259 return NO_ERROR;
6260}
6261
6262// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006263void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6264 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006265{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006266 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006267 size_t stepCount = buffer->frameCount;
6268 if (stepCount == 0) {
6269 return;
6270 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006271 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6272 activeTrack->mRsmpInUnrel -= stepCount;
6273 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006274 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006275 buffer->frameCount = 0;
6276}
6277
Eric Laurent10351942014-05-08 18:49:52 -07006278bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6279 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006280{
6281 bool reconfig = false;
6282
Eric Laurent10351942014-05-08 18:49:52 -07006283 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006284
Eric Laurent10351942014-05-08 18:49:52 -07006285 audio_format_t reqFormat = mFormat;
6286 uint32_t samplingRate = mSampleRate;
6287 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6288
6289 AudioParameter param = AudioParameter(keyValuePair);
6290 int value;
6291 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6292 // channel count change can be requested. Do we mandate the first client defines the
6293 // HAL sampling rate and channel count or do we allow changes on the fly?
6294 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6295 samplingRate = value;
6296 reconfig = true;
6297 }
6298 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6299 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6300 status = BAD_VALUE;
6301 } else {
6302 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006303 reconfig = true;
6304 }
Eric Laurent10351942014-05-08 18:49:52 -07006305 }
6306 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6307 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6308 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6309 status = BAD_VALUE;
6310 } else {
6311 channelMask = mask;
6312 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006313 }
Eric Laurent10351942014-05-08 18:49:52 -07006314 }
6315 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6316 // do not accept frame count changes if tracks are open as the track buffer
6317 // size depends on frame count and correct behavior would not be guaranteed
6318 // if frame count is changed after track creation
6319 if (mActiveTracks.size() > 0) {
6320 status = INVALID_OPERATION;
6321 } else {
6322 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006323 }
Eric Laurent10351942014-05-08 18:49:52 -07006324 }
6325 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6326 // forward device change to effects that have requested to be
6327 // aware of attached audio device.
6328 for (size_t i = 0; i < mEffectChains.size(); i++) {
6329 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006330 }
Eric Laurent81784c32012-11-19 14:55:58 -08006331
Eric Laurent10351942014-05-08 18:49:52 -07006332 // store input device and output device but do not forward output device to audio HAL.
6333 // Note that status is ignored by the caller for output device
6334 // (see AudioFlinger::setParameters()
6335 if (audio_is_output_devices(value)) {
6336 mOutDevice = value;
6337 status = BAD_VALUE;
6338 } else {
6339 mInDevice = value;
6340 // disable AEC and NS if the device is a BT SCO headset supporting those
6341 // pre processings
6342 if (mTracks.size() > 0) {
6343 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6344 mAudioFlinger->btNrecIsOff();
6345 for (size_t i = 0; i < mTracks.size(); i++) {
6346 sp<RecordTrack> track = mTracks[i];
6347 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6348 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
6350 }
6351 }
Eric Laurent10351942014-05-08 18:49:52 -07006352 }
6353 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6354 mAudioSource != (audio_source_t)value) {
6355 // forward device change to effects that have requested to be
6356 // aware of attached audio device.
6357 for (size_t i = 0; i < mEffectChains.size(); i++) {
6358 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006359 }
Eric Laurent10351942014-05-08 18:49:52 -07006360 mAudioSource = (audio_source_t)value;
6361 }
Glenn Kastene198c362013-08-13 09:13:36 -07006362
Eric Laurent10351942014-05-08 18:49:52 -07006363 if (status == NO_ERROR) {
6364 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6365 keyValuePair.string());
6366 if (status == INVALID_OPERATION) {
6367 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006368 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6369 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006370 }
6371 if (reconfig) {
6372 if (status == BAD_VALUE &&
6373 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6374 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6375 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6376 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006377 audio_channel_count_from_in_mask(
6378 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006379 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6380 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6381 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006382 }
Eric Laurent10351942014-05-08 18:49:52 -07006383 if (status == NO_ERROR) {
6384 readInputParameters_l();
6385 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006386 }
6387 }
Eric Laurent81784c32012-11-19 14:55:58 -08006388 }
Eric Laurent10351942014-05-08 18:49:52 -07006389
Eric Laurent81784c32012-11-19 14:55:58 -08006390 return reconfig;
6391}
6392
6393String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6394{
Eric Laurent81784c32012-11-19 14:55:58 -08006395 Mutex::Autolock _l(mLock);
6396 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006397 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006398 }
6399
Glenn Kastend8ea6992013-07-16 14:17:15 -07006400 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6401 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006402 free(s);
6403 return out_s8;
6404}
6405
Eric Laurent021cf962014-05-13 10:18:14 -07006406void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006407 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006408 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006409
6410 switch (event) {
6411 case AudioSystem::INPUT_OPENED:
6412 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006413 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006414 desc.samplingRate = mSampleRate;
6415 desc.format = mFormat;
6416 desc.frameCount = mFrameCount;
6417 desc.latency = 0;
6418 param2 = &desc;
6419 break;
6420
6421 case AudioSystem::INPUT_CLOSED:
6422 default:
6423 break;
6424 }
Eric Laurent021cf962014-05-13 10:18:14 -07006425 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006426}
6427
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006428void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006429{
Eric Laurent81784c32012-11-19 14:55:58 -08006430 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6431 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006432 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006433 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6434 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006435 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006436 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006437 }
Eric Laurent665470b2014-07-03 16:37:08 -07006438 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006439 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6440 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006442 // 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 -07006443 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006444 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445 // A larger value should allow more old data to be read after a track calls start(),
6446 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006447 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006448 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006450
6451 // TODO optimize audio capture buffer sizes ...
6452 // Here we calculate the size of the sliding buffer used as a source
6453 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6454 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6455 // be better to have it derived from the pipe depth in the long term.
6456 // The current value is higher than necessary. However it should not add to latency.
6457
Glenn Kasten85948432013-08-19 12:09:05 -07006458 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6459 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006460
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006461 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6462 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006463}
6464
Glenn Kasten5f972c02014-01-13 09:59:31 -08006465uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006466{
6467 Mutex::Autolock _l(mLock);
6468 if (initCheck() != NO_ERROR) {
6469 return 0;
6470 }
6471
6472 return mInput->stream->get_input_frames_lost(mInput->stream);
6473}
6474
6475uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6476{
6477 Mutex::Autolock _l(mLock);
6478 uint32_t result = 0;
6479 if (getEffectChain_l(sessionId) != 0) {
6480 result = EFFECT_SESSION;
6481 }
6482
6483 for (size_t i = 0; i < mTracks.size(); ++i) {
6484 if (sessionId == mTracks[i]->sessionId()) {
6485 result |= TRACK_SESSION;
6486 break;
6487 }
6488 }
6489
6490 return result;
6491}
6492
6493KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6494{
6495 KeyedVector<int, bool> ids;
6496 Mutex::Autolock _l(mLock);
6497 for (size_t j = 0; j < mTracks.size(); ++j) {
6498 sp<RecordThread::RecordTrack> track = mTracks[j];
6499 int sessionId = track->sessionId();
6500 if (ids.indexOfKey(sessionId) < 0) {
6501 ids.add(sessionId, true);
6502 }
6503 }
6504 return ids;
6505}
6506
6507AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6508{
6509 Mutex::Autolock _l(mLock);
6510 AudioStreamIn *input = mInput;
6511 mInput = NULL;
6512 return input;
6513}
6514
6515// this method must always be called either with ThreadBase mLock held or inside the thread loop
6516audio_stream_t* AudioFlinger::RecordThread::stream() const
6517{
6518 if (mInput == NULL) {
6519 return NULL;
6520 }
6521 return &mInput->stream->common;
6522}
6523
6524status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6525{
6526 // only one chain per input thread
6527 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006528 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006529 return INVALID_OPERATION;
6530 }
6531 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006532 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006533 chain->setInBuffer(NULL);
6534 chain->setOutBuffer(NULL);
6535
6536 checkSuspendOnAddEffectChain_l(chain);
6537
Eric Laurent1b928682014-10-02 19:41:47 -07006538 // make sure enabled pre processing effects state is communicated to the HAL as we
6539 // just moved them to a new input stream.
6540 chain->syncHalEffectsState();
6541
Eric Laurent81784c32012-11-19 14:55:58 -08006542 mEffectChains.add(chain);
6543
6544 return NO_ERROR;
6545}
6546
6547size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6548{
6549 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6550 ALOGW_IF(mEffectChains.size() != 1,
6551 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6552 chain.get(), mEffectChains.size(), this);
6553 if (mEffectChains.size() == 1) {
6554 mEffectChains.removeAt(0);
6555 }
6556 return 0;
6557}
6558
Eric Laurent1c333e22014-05-20 10:48:17 -07006559status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6560 audio_patch_handle_t *handle)
6561{
6562 status_t status = NO_ERROR;
6563 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6564 // store new device and send to effects
6565 mInDevice = patch->sources[0].ext.device.type;
6566 for (size_t i = 0; i < mEffectChains.size(); i++) {
6567 mEffectChains[i]->setDevice_l(mInDevice);
6568 }
6569
6570 // disable AEC and NS if the device is a BT SCO headset supporting those
6571 // pre processings
6572 if (mTracks.size() > 0) {
6573 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6574 mAudioFlinger->btNrecIsOff();
6575 for (size_t i = 0; i < mTracks.size(); i++) {
6576 sp<RecordTrack> track = mTracks[i];
6577 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6578 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6579 }
6580 }
6581
6582 // store new source and send to effects
6583 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6584 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6585 for (size_t i = 0; i < mEffectChains.size(); i++) {
6586 mEffectChains[i]->setAudioSource_l(mAudioSource);
6587 }
6588 }
6589
6590 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6591 status = hwDevice->create_audio_patch(hwDevice,
6592 patch->num_sources,
6593 patch->sources,
6594 patch->num_sinks,
6595 patch->sinks,
6596 handle);
6597 } else {
6598 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6599 }
6600 return status;
6601}
6602
6603status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6604{
6605 status_t status = NO_ERROR;
6606 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6607 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6608 status = hwDevice->release_audio_patch(hwDevice, handle);
6609 } else {
6610 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6611 }
6612 return status;
6613}
6614
Eric Laurent83b88082014-06-20 18:31:16 -07006615void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6616{
6617 Mutex::Autolock _l(mLock);
6618 mTracks.add(record);
6619}
6620
6621void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6622{
6623 Mutex::Autolock _l(mLock);
6624 destroyTrack_l(record);
6625}
6626
6627void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6628{
6629 ThreadBase::getAudioPortConfig(config);
6630 config->role = AUDIO_PORT_ROLE_SINK;
6631 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6632 config->ext.mix.usecase.source = mAudioSource;
6633}
Eric Laurent1c333e22014-05-20 10:48:17 -07006634
Glenn Kasten63238ef2015-03-02 15:50:29 -08006635} // namespace android