blob: 9540e0ac3a92e2990f16547a2d1b85e3cffa21fe [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>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
112// Whether to use fast mixer
113static const enum {
114 FastMixer_Never, // never initialize or use: for debugging only
115 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
116 // normal mixer multiplier is 1
117 FastMixer_Static, // initialize if needed, then use all the time if initialized,
118 // multiplier is calculated based on min & max normal mixer buffer size
119 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
120 // multiplier is calculated based on min & max normal mixer buffer size
121 // FIXME for FastMixer_Dynamic:
122 // Supporting this option will require fixing HALs that can't handle large writes.
123 // For example, one HAL implementation returns an error from a large write,
124 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
125 // We could either fix the HAL implementations, or provide a wrapper that breaks
126 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
127} kUseFastMixer = FastMixer_Static;
128
129// Priorities for requestPriority
130static const int kPriorityAudioApp = 2;
131static const int kPriorityFastMixer = 3;
132
133// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
134// for the track. The client then sub-divides this into smaller buffers for its use.
135// Currently the client uses double-buffering by default, but doesn't tell us about that.
136// So for now we just assume that client is double-buffered.
137// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
138// N-buffering, so AudioFlinger could allocate the right amount of memory.
139// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800140static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800141
142// ----------------------------------------------------------------------------
143
144#ifdef ADD_BATTERY_DATA
145// To collect the amplifier usage
146static void addBatteryData(uint32_t params) {
147 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
148 if (service == NULL) {
149 // it already logged
150 return;
151 }
152
153 service->addBatteryData(params);
154}
155#endif
156
157
158// ----------------------------------------------------------------------------
159// CPU Stats
160// ----------------------------------------------------------------------------
161
162class CpuStats {
163public:
164 CpuStats();
165 void sample(const String8 &title);
166#ifdef DEBUG_CPU_USAGE
167private:
168 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
169 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
170
171 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
172
173 int mCpuNum; // thread's current CPU number
174 int mCpukHz; // frequency of thread's current CPU in kHz
175#endif
176};
177
178CpuStats::CpuStats()
179#ifdef DEBUG_CPU_USAGE
180 : mCpuNum(-1), mCpukHz(-1)
181#endif
182{
183}
184
185void CpuStats::sample(const String8 &title) {
186#ifdef DEBUG_CPU_USAGE
187 // get current thread's delta CPU time in wall clock ns
188 double wcNs;
189 bool valid = mCpuUsage.sampleAndEnable(wcNs);
190
191 // record sample for wall clock statistics
192 if (valid) {
193 mWcStats.sample(wcNs);
194 }
195
196 // get the current CPU number
197 int cpuNum = sched_getcpu();
198
199 // get the current CPU frequency in kHz
200 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
201
202 // check if either CPU number or frequency changed
203 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
204 mCpuNum = cpuNum;
205 mCpukHz = cpukHz;
206 // ignore sample for purposes of cycles
207 valid = false;
208 }
209
210 // if no change in CPU number or frequency, then record sample for cycle statistics
211 if (valid && mCpukHz > 0) {
212 double cycles = wcNs * cpukHz * 0.000001;
213 mHzStats.sample(cycles);
214 }
215
216 unsigned n = mWcStats.n();
217 // mCpuUsage.elapsed() is expensive, so don't call it every loop
218 if ((n & 127) == 1) {
219 long long elapsed = mCpuUsage.elapsed();
220 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
221 double perLoop = elapsed / (double) n;
222 double perLoop100 = perLoop * 0.01;
223 double perLoop1k = perLoop * 0.001;
224 double mean = mWcStats.mean();
225 double stddev = mWcStats.stddev();
226 double minimum = mWcStats.minimum();
227 double maximum = mWcStats.maximum();
228 double meanCycles = mHzStats.mean();
229 double stddevCycles = mHzStats.stddev();
230 double minCycles = mHzStats.minimum();
231 double maxCycles = mHzStats.maximum();
232 mCpuUsage.resetElapsed();
233 mWcStats.reset();
234 mHzStats.reset();
235 ALOGD("CPU usage for %s over past %.1f secs\n"
236 " (%u mixer loops at %.1f mean ms per loop):\n"
237 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
238 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
239 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
240 title.string(),
241 elapsed * .000000001, n, perLoop * .000001,
242 mean * .001,
243 stddev * .001,
244 minimum * .001,
245 maximum * .001,
246 mean / perLoop100,
247 stddev / perLoop100,
248 minimum / perLoop100,
249 maximum / perLoop100,
250 meanCycles / perLoop1k,
251 stddevCycles / perLoop1k,
252 minCycles / perLoop1k,
253 maxCycles / perLoop1k);
254
255 }
256 }
257#endif
258};
259
260// ----------------------------------------------------------------------------
261// ThreadBase
262// ----------------------------------------------------------------------------
263
264AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
265 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
266 : Thread(false /*canCallJava*/),
267 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700268 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700269 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
270 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800271 mParamStatus(NO_ERROR),
272 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
273 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
274 // mName will be set by concrete (non-virtual) subclass
275 mDeathRecipient(new PMDeathRecipient(this))
276{
277}
278
279AudioFlinger::ThreadBase::~ThreadBase()
280{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700281 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
282 for (size_t i = 0; i < mConfigEvents.size(); i++) {
283 delete mConfigEvents[i];
284 }
285 mConfigEvents.clear();
286
Eric Laurent81784c32012-11-19 14:55:58 -0800287 mParamCond.broadcast();
288 // do not lock the mutex in destructor
289 releaseWakeLock_l();
290 if (mPowerManager != 0) {
291 sp<IBinder> binder = mPowerManager->asBinder();
292 binder->unlinkToDeath(mDeathRecipient);
293 }
294}
295
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700296status_t AudioFlinger::ThreadBase::readyToRun()
297{
298 status_t status = initCheck();
299 if (status == NO_ERROR) {
300 ALOGI("AudioFlinger's thread %p ready to run", this);
301 } else {
302 ALOGE("No working audio driver found.");
303 }
304 return status;
305}
306
Eric Laurent81784c32012-11-19 14:55:58 -0800307void AudioFlinger::ThreadBase::exit()
308{
309 ALOGV("ThreadBase::exit");
310 // do any cleanup required for exit to succeed
311 preExit();
312 {
313 // This lock prevents the following race in thread (uniprocessor for illustration):
314 // if (!exitPending()) {
315 // // context switch from here to exit()
316 // // exit() calls requestExit(), what exitPending() observes
317 // // exit() calls signal(), which is dropped since no waiters
318 // // context switch back from exit() to here
319 // mWaitWorkCV.wait(...);
320 // // now thread is hung
321 // }
322 AutoMutex lock(mLock);
323 requestExit();
324 mWaitWorkCV.broadcast();
325 }
326 // When Thread::requestExitAndWait is made virtual and this method is renamed to
327 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
328 requestExitAndWait();
329}
330
331status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
332{
333 status_t status;
334
335 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
336 Mutex::Autolock _l(mLock);
337
338 mNewParameters.add(keyValuePairs);
339 mWaitWorkCV.signal();
340 // wait condition with timeout in case the thread loop has exited
341 // before the request could be processed
342 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
343 status = mParamStatus;
344 mWaitWorkCV.signal();
345 } else {
346 status = TIMED_OUT;
347 }
348 return status;
349}
350
351void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
352{
353 Mutex::Autolock _l(mLock);
354 sendIoConfigEvent_l(event, param);
355}
356
357// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
358void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
359{
360 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
361 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
362 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
363 param);
364 mWaitWorkCV.signal();
365}
366
367// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
368void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
369{
370 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
371 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
372 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
373 mConfigEvents.size(), pid, tid, prio);
374 mWaitWorkCV.signal();
375}
376
377void AudioFlinger::ThreadBase::processConfigEvents()
378{
Glenn Kastenf7773312013-08-13 16:00:42 -0700379 Mutex::Autolock _l(mLock);
380 processConfigEvents_l();
381}
382
383void AudioFlinger::ThreadBase::processConfigEvents_l()
384{
Eric Laurent81784c32012-11-19 14:55:58 -0800385 while (!mConfigEvents.isEmpty()) {
386 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
387 ConfigEvent *event = mConfigEvents[0];
388 mConfigEvents.removeAt(0);
389 // release mLock before locking AudioFlinger mLock: lock order is always
390 // AudioFlinger then ThreadBase to avoid cross deadlock
391 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700392 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700393 case CFG_EVENT_PRIO: {
394 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
395 // FIXME Need to understand why this has be done asynchronously
396 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
397 true /*asynchronous*/);
398 if (err != 0) {
399 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
400 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
401 }
402 } break;
403 case CFG_EVENT_IO: {
404 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
405 mAudioFlinger->mLock.lock();
406 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
407 mAudioFlinger->mLock.unlock();
408 } break;
409 default:
410 ALOGE("processConfigEvents() unknown event type %d", event->type());
411 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800412 }
413 delete event;
414 mLock.lock();
415 }
Eric Laurent81784c32012-11-19 14:55:58 -0800416}
417
418void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
419{
420 const size_t SIZE = 256;
421 char buffer[SIZE];
422 String8 result;
423
424 bool locked = AudioFlinger::dumpTryLock(mLock);
425 if (!locked) {
426 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
427 write(fd, buffer, strlen(buffer));
428 }
429
430 snprintf(buffer, SIZE, "io handle: %d\n", mId);
431 result.append(buffer);
432 snprintf(buffer, SIZE, "TID: %d\n", getTid());
433 result.append(buffer);
434 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
435 result.append(buffer);
436 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
437 result.append(buffer);
438 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
439 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700440 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
441 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700442 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800443 result.append(buffer);
444 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
445 result.append(buffer);
446 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
447 result.append(buffer);
448 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
449 result.append(buffer);
450
451 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
452 result.append(buffer);
453 result.append(" Index Command");
454 for (size_t i = 0; i < mNewParameters.size(); ++i) {
455 snprintf(buffer, SIZE, "\n %02d ", i);
456 result.append(buffer);
457 result.append(mNewParameters[i]);
458 }
459
460 snprintf(buffer, SIZE, "\n\nPending config events: \n");
461 result.append(buffer);
462 for (size_t i = 0; i < mConfigEvents.size(); i++) {
463 mConfigEvents[i]->dump(buffer, SIZE);
464 result.append(buffer);
465 }
466 result.append("\n");
467
468 write(fd, result.string(), result.size());
469
470 if (locked) {
471 mLock.unlock();
472 }
473}
474
475void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
476{
477 const size_t SIZE = 256;
478 char buffer[SIZE];
479 String8 result;
480
481 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
482 write(fd, buffer, strlen(buffer));
483
484 for (size_t i = 0; i < mEffectChains.size(); ++i) {
485 sp<EffectChain> chain = mEffectChains[i];
486 if (chain != 0) {
487 chain->dump(fd, args);
488 }
489 }
490}
491
492void AudioFlinger::ThreadBase::acquireWakeLock()
493{
494 Mutex::Autolock _l(mLock);
495 acquireWakeLock_l();
496}
497
498void AudioFlinger::ThreadBase::acquireWakeLock_l()
499{
500 if (mPowerManager == 0) {
501 // use checkService() to avoid blocking if power service is not up yet
502 sp<IBinder> binder =
503 defaultServiceManager()->checkService(String16("power"));
504 if (binder == 0) {
505 ALOGW("Thread %s cannot connect to the power manager service", mName);
506 } else {
507 mPowerManager = interface_cast<IPowerManager>(binder);
508 binder->linkToDeath(mDeathRecipient);
509 }
510 }
511 if (mPowerManager != 0) {
512 sp<IBinder> binder = new BBinder();
513 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
514 binder,
Dianne Hackborn61d404e2013-05-20 11:22:20 -0700515 String16(mName),
516 String16("media"));
Eric Laurent81784c32012-11-19 14:55:58 -0800517 if (status == NO_ERROR) {
518 mWakeLockToken = binder;
519 }
520 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
521 }
522}
523
524void AudioFlinger::ThreadBase::releaseWakeLock()
525{
526 Mutex::Autolock _l(mLock);
527 releaseWakeLock_l();
528}
529
530void AudioFlinger::ThreadBase::releaseWakeLock_l()
531{
532 if (mWakeLockToken != 0) {
533 ALOGV("releaseWakeLock_l() %s", mName);
534 if (mPowerManager != 0) {
535 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
536 }
537 mWakeLockToken.clear();
538 }
539}
540
541void AudioFlinger::ThreadBase::clearPowerManager()
542{
543 Mutex::Autolock _l(mLock);
544 releaseWakeLock_l();
545 mPowerManager.clear();
546}
547
548void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
549{
550 sp<ThreadBase> thread = mThread.promote();
551 if (thread != 0) {
552 thread->clearPowerManager();
553 }
554 ALOGW("power manager service died !!!");
555}
556
557void AudioFlinger::ThreadBase::setEffectSuspended(
558 const effect_uuid_t *type, bool suspend, int sessionId)
559{
560 Mutex::Autolock _l(mLock);
561 setEffectSuspended_l(type, suspend, sessionId);
562}
563
564void AudioFlinger::ThreadBase::setEffectSuspended_l(
565 const effect_uuid_t *type, bool suspend, int sessionId)
566{
567 sp<EffectChain> chain = getEffectChain_l(sessionId);
568 if (chain != 0) {
569 if (type != NULL) {
570 chain->setEffectSuspended_l(type, suspend);
571 } else {
572 chain->setEffectSuspendedAll_l(suspend);
573 }
574 }
575
576 updateSuspendedSessions_l(type, suspend, sessionId);
577}
578
579void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
580{
581 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
582 if (index < 0) {
583 return;
584 }
585
586 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
587 mSuspendedSessions.valueAt(index);
588
589 for (size_t i = 0; i < sessionEffects.size(); i++) {
590 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
591 for (int j = 0; j < desc->mRefCount; j++) {
592 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
593 chain->setEffectSuspendedAll_l(true);
594 } else {
595 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
596 desc->mType.timeLow);
597 chain->setEffectSuspended_l(&desc->mType, true);
598 }
599 }
600 }
601}
602
603void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
604 bool suspend,
605 int sessionId)
606{
607 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
608
609 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
610
611 if (suspend) {
612 if (index >= 0) {
613 sessionEffects = mSuspendedSessions.valueAt(index);
614 } else {
615 mSuspendedSessions.add(sessionId, sessionEffects);
616 }
617 } else {
618 if (index < 0) {
619 return;
620 }
621 sessionEffects = mSuspendedSessions.valueAt(index);
622 }
623
624
625 int key = EffectChain::kKeyForSuspendAll;
626 if (type != NULL) {
627 key = type->timeLow;
628 }
629 index = sessionEffects.indexOfKey(key);
630
631 sp<SuspendedSessionDesc> desc;
632 if (suspend) {
633 if (index >= 0) {
634 desc = sessionEffects.valueAt(index);
635 } else {
636 desc = new SuspendedSessionDesc();
637 if (type != NULL) {
638 desc->mType = *type;
639 }
640 sessionEffects.add(key, desc);
641 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
642 }
643 desc->mRefCount++;
644 } else {
645 if (index < 0) {
646 return;
647 }
648 desc = sessionEffects.valueAt(index);
649 if (--desc->mRefCount == 0) {
650 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
651 sessionEffects.removeItemsAt(index);
652 if (sessionEffects.isEmpty()) {
653 ALOGV("updateSuspendedSessions_l() restore removing session %d",
654 sessionId);
655 mSuspendedSessions.removeItem(sessionId);
656 }
657 }
658 }
659 if (!sessionEffects.isEmpty()) {
660 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
661 }
662}
663
664void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
665 bool enabled,
666 int sessionId)
667{
668 Mutex::Autolock _l(mLock);
669 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
670}
671
672void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
673 bool enabled,
674 int sessionId)
675{
676 if (mType != RECORD) {
677 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
678 // another session. This gives the priority to well behaved effect control panels
679 // and applications not using global effects.
680 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
681 // global effects
682 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
683 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
684 }
685 }
686
687 sp<EffectChain> chain = getEffectChain_l(sessionId);
688 if (chain != 0) {
689 chain->checkSuspendOnEffectEnabled(effect, enabled);
690 }
691}
692
693// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
694sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
695 const sp<AudioFlinger::Client>& client,
696 const sp<IEffectClient>& effectClient,
697 int32_t priority,
698 int sessionId,
699 effect_descriptor_t *desc,
700 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700701 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800702{
703 sp<EffectModule> effect;
704 sp<EffectHandle> handle;
705 status_t lStatus;
706 sp<EffectChain> chain;
707 bool chainCreated = false;
708 bool effectCreated = false;
709 bool effectRegistered = false;
710
711 lStatus = initCheck();
712 if (lStatus != NO_ERROR) {
713 ALOGW("createEffect_l() Audio driver not initialized.");
714 goto Exit;
715 }
716
717 // Do not allow effects with session ID 0 on direct output or duplicating threads
718 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
719 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
720 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
721 desc->name, sessionId);
722 lStatus = BAD_VALUE;
723 goto Exit;
724 }
725 // Only Pre processor effects are allowed on input threads and only on input threads
726 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
727 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
728 desc->name, desc->flags, mType);
729 lStatus = BAD_VALUE;
730 goto Exit;
731 }
732
733 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
734
735 { // scope for mLock
736 Mutex::Autolock _l(mLock);
737
738 // check for existing effect chain with the requested audio session
739 chain = getEffectChain_l(sessionId);
740 if (chain == 0) {
741 // create a new chain for this session
742 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
743 chain = new EffectChain(this, sessionId);
744 addEffectChain_l(chain);
745 chain->setStrategy(getStrategyForSession_l(sessionId));
746 chainCreated = true;
747 } else {
748 effect = chain->getEffectFromDesc_l(desc);
749 }
750
751 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
752
753 if (effect == 0) {
754 int id = mAudioFlinger->nextUniqueId();
755 // Check CPU and memory usage
756 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
757 if (lStatus != NO_ERROR) {
758 goto Exit;
759 }
760 effectRegistered = true;
761 // create a new effect module if none present in the chain
762 effect = new EffectModule(this, chain, desc, id, sessionId);
763 lStatus = effect->status();
764 if (lStatus != NO_ERROR) {
765 goto Exit;
766 }
767 lStatus = chain->addEffect_l(effect);
768 if (lStatus != NO_ERROR) {
769 goto Exit;
770 }
771 effectCreated = true;
772
773 effect->setDevice(mOutDevice);
774 effect->setDevice(mInDevice);
775 effect->setMode(mAudioFlinger->getMode());
776 effect->setAudioSource(mAudioSource);
777 }
778 // create effect handle and connect it to effect module
779 handle = new EffectHandle(effect, client, effectClient, priority);
780 lStatus = effect->addHandle(handle.get());
781 if (enabled != NULL) {
782 *enabled = (int)effect->isEnabled();
783 }
784 }
785
786Exit:
787 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
788 Mutex::Autolock _l(mLock);
789 if (effectCreated) {
790 chain->removeEffect_l(effect);
791 }
792 if (effectRegistered) {
793 AudioSystem::unregisterEffect(effect->id());
794 }
795 if (chainCreated) {
796 removeEffectChain_l(chain);
797 }
798 handle.clear();
799 }
800
Glenn Kasten9156ef32013-08-06 15:39:08 -0700801 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800802 return handle;
803}
804
805sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
806{
807 Mutex::Autolock _l(mLock);
808 return getEffect_l(sessionId, effectId);
809}
810
811sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
812{
813 sp<EffectChain> chain = getEffectChain_l(sessionId);
814 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
815}
816
817// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
818// PlaybackThread::mLock held
819status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
820{
821 // check for existing effect chain with the requested audio session
822 int sessionId = effect->sessionId();
823 sp<EffectChain> chain = getEffectChain_l(sessionId);
824 bool chainCreated = false;
825
826 if (chain == 0) {
827 // create a new chain for this session
828 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
829 chain = new EffectChain(this, sessionId);
830 addEffectChain_l(chain);
831 chain->setStrategy(getStrategyForSession_l(sessionId));
832 chainCreated = true;
833 }
834 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
835
836 if (chain->getEffectFromId_l(effect->id()) != 0) {
837 ALOGW("addEffect_l() %p effect %s already present in chain %p",
838 this, effect->desc().name, chain.get());
839 return BAD_VALUE;
840 }
841
842 status_t status = chain->addEffect_l(effect);
843 if (status != NO_ERROR) {
844 if (chainCreated) {
845 removeEffectChain_l(chain);
846 }
847 return status;
848 }
849
850 effect->setDevice(mOutDevice);
851 effect->setDevice(mInDevice);
852 effect->setMode(mAudioFlinger->getMode());
853 effect->setAudioSource(mAudioSource);
854 return NO_ERROR;
855}
856
857void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
858
859 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
860 effect_descriptor_t desc = effect->desc();
861 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
862 detachAuxEffect_l(effect->id());
863 }
864
865 sp<EffectChain> chain = effect->chain().promote();
866 if (chain != 0) {
867 // remove effect chain if removing last effect
868 if (chain->removeEffect_l(effect) == 0) {
869 removeEffectChain_l(chain);
870 }
871 } else {
872 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
873 }
874}
875
876void AudioFlinger::ThreadBase::lockEffectChains_l(
877 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
878{
879 effectChains = mEffectChains;
880 for (size_t i = 0; i < mEffectChains.size(); i++) {
881 mEffectChains[i]->lock();
882 }
883}
884
885void AudioFlinger::ThreadBase::unlockEffectChains(
886 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
887{
888 for (size_t i = 0; i < effectChains.size(); i++) {
889 effectChains[i]->unlock();
890 }
891}
892
893sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
894{
895 Mutex::Autolock _l(mLock);
896 return getEffectChain_l(sessionId);
897}
898
899sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
900{
901 size_t size = mEffectChains.size();
902 for (size_t i = 0; i < size; i++) {
903 if (mEffectChains[i]->sessionId() == sessionId) {
904 return mEffectChains[i];
905 }
906 }
907 return 0;
908}
909
910void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
911{
912 Mutex::Autolock _l(mLock);
913 size_t size = mEffectChains.size();
914 for (size_t i = 0; i < size; i++) {
915 mEffectChains[i]->setMode_l(mode);
916 }
917}
918
919void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
920 EffectHandle *handle,
921 bool unpinIfLast) {
922
923 Mutex::Autolock _l(mLock);
924 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
925 // delete the effect module if removing last handle on it
926 if (effect->removeHandle(handle) == 0) {
927 if (!effect->isPinned() || unpinIfLast) {
928 removeEffect_l(effect);
929 AudioSystem::unregisterEffect(effect->id());
930 }
931 }
932}
933
934// ----------------------------------------------------------------------------
935// Playback
936// ----------------------------------------------------------------------------
937
938AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
939 AudioStreamOut* output,
940 audio_io_handle_t id,
941 audio_devices_t device,
942 type_t type)
943 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700944 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700945 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800946 // mStreamTypes[] initialized in constructor body
947 mOutput(output),
948 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
949 mMixerStatus(MIXER_IDLE),
950 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
951 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800952 mBytesRemaining(0),
953 mCurrentWriteLength(0),
954 mUseAsyncWrite(false),
955 mWriteBlocked(false),
956 mDraining(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800957 mScreenState(AudioFlinger::mScreenState),
958 // index 0 is reserved for normal mixer's submix
959 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
960{
961 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800962 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800963
964 // Assumes constructor is called by AudioFlinger with it's mLock held, but
965 // it would be safer to explicitly pass initial masterVolume/masterMute as
966 // parameter.
967 //
968 // If the HAL we are using has support for master volume or master mute,
969 // then do not attenuate or mute during mixing (just leave the volume at 1.0
970 // and the mute set to false).
971 mMasterVolume = audioFlinger->masterVolume_l();
972 mMasterMute = audioFlinger->masterMute_l();
973 if (mOutput && mOutput->audioHwDev) {
974 if (mOutput->audioHwDev->canSetMasterVolume()) {
975 mMasterVolume = 1.0;
976 }
977
978 if (mOutput->audioHwDev->canSetMasterMute()) {
979 mMasterMute = false;
980 }
981 }
982
983 readOutputParameters();
984
985 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
986 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
987 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
988 stream = (audio_stream_type_t) (stream + 1)) {
989 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
990 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
991 }
992 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
993 // because mAudioFlinger doesn't have one to copy from
994}
995
996AudioFlinger::PlaybackThread::~PlaybackThread()
997{
Glenn Kasten9e58b552013-01-18 15:09:48 -0800998 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -0700999 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001000}
1001
1002void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1003{
1004 dumpInternals(fd, args);
1005 dumpTracks(fd, args);
1006 dumpEffectChains(fd, args);
1007}
1008
1009void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1010{
1011 const size_t SIZE = 256;
1012 char buffer[SIZE];
1013 String8 result;
1014
1015 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1016 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1017 const stream_type_t *st = &mStreamTypes[i];
1018 if (i > 0) {
1019 result.appendFormat(", ");
1020 }
1021 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1022 if (st->mute) {
1023 result.append("M");
1024 }
1025 }
1026 result.append("\n");
1027 write(fd, result.string(), result.length());
1028 result.clear();
1029
1030 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1031 result.append(buffer);
1032 Track::appendDumpHeader(result);
1033 for (size_t i = 0; i < mTracks.size(); ++i) {
1034 sp<Track> track = mTracks[i];
1035 if (track != 0) {
1036 track->dump(buffer, SIZE);
1037 result.append(buffer);
1038 }
1039 }
1040
1041 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1042 result.append(buffer);
1043 Track::appendDumpHeader(result);
1044 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1045 sp<Track> track = mActiveTracks[i].promote();
1046 if (track != 0) {
1047 track->dump(buffer, SIZE);
1048 result.append(buffer);
1049 }
1050 }
1051 write(fd, result.string(), result.size());
1052
1053 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1054 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1055 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1056 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1057}
1058
1059void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1060{
1061 const size_t SIZE = 256;
1062 char buffer[SIZE];
1063 String8 result;
1064
1065 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1066 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001067 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1068 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001069 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1070 ns2ms(systemTime() - mLastWriteTime));
1071 result.append(buffer);
1072 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1073 result.append(buffer);
1074 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1075 result.append(buffer);
1076 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1077 result.append(buffer);
1078 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1079 result.append(buffer);
1080 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1081 result.append(buffer);
1082 write(fd, result.string(), result.size());
1083 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1084
1085 dumpBase(fd, args);
1086}
1087
1088// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001089
1090void AudioFlinger::PlaybackThread::onFirstRef()
1091{
1092 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1093}
1094
1095// ThreadBase virtuals
1096void AudioFlinger::PlaybackThread::preExit()
1097{
1098 ALOGV(" preExit()");
1099 // FIXME this is using hard-coded strings but in the future, this functionality will be
1100 // converted to use audio HAL extensions required to support tunneling
1101 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1102}
1103
1104// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1105sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1106 const sp<AudioFlinger::Client>& client,
1107 audio_stream_type_t streamType,
1108 uint32_t sampleRate,
1109 audio_format_t format,
1110 audio_channel_mask_t channelMask,
1111 size_t frameCount,
1112 const sp<IMemory>& sharedBuffer,
1113 int sessionId,
1114 IAudioFlinger::track_flags_t *flags,
1115 pid_t tid,
1116 status_t *status)
1117{
1118 sp<Track> track;
1119 status_t lStatus;
1120
1121 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1122
1123 // client expresses a preference for FAST, but we get the final say
1124 if (*flags & IAudioFlinger::TRACK_FAST) {
1125 if (
1126 // not timed
1127 (!isTimed) &&
1128 // either of these use cases:
1129 (
1130 // use case 1: shared buffer with any frame count
1131 (
1132 (sharedBuffer != 0)
1133 ) ||
1134 // use case 2: callback handler and frame count is default or at least as large as HAL
1135 (
1136 (tid != -1) &&
1137 ((frameCount == 0) ||
1138 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1139 )
1140 ) &&
1141 // PCM data
1142 audio_is_linear_pcm(format) &&
1143 // mono or stereo
1144 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1145 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1146#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1147 // hardware sample rate
1148 (sampleRate == mSampleRate) &&
1149#endif
1150 // normal mixer has an associated fast mixer
1151 hasFastMixer() &&
1152 // there are sufficient fast track slots available
1153 (mFastTrackAvailMask != 0)
1154 // FIXME test that MixerThread for this fast track has a capable output HAL
1155 // FIXME add a permission test also?
1156 ) {
1157 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1158 if (frameCount == 0) {
1159 frameCount = mFrameCount * kFastTrackMultiplier;
1160 }
1161 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1162 frameCount, mFrameCount);
1163 } else {
1164 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1165 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1166 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1167 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1168 audio_is_linear_pcm(format),
1169 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1170 *flags &= ~IAudioFlinger::TRACK_FAST;
1171 // For compatibility with AudioTrack calculation, buffer depth is forced
1172 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1173 // This is probably too conservative, but legacy application code may depend on it.
1174 // If you change this calculation, also review the start threshold which is related.
1175 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1176 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1177 if (minBufCount < 2) {
1178 minBufCount = 2;
1179 }
1180 size_t minFrameCount = mNormalFrameCount * minBufCount;
1181 if (frameCount < minFrameCount) {
1182 frameCount = minFrameCount;
1183 }
1184 }
1185 }
1186
1187 if (mType == DIRECT) {
1188 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1189 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1190 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1191 "for output %p with format %d",
1192 sampleRate, format, channelMask, mOutput, mFormat);
1193 lStatus = BAD_VALUE;
1194 goto Exit;
1195 }
1196 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001197 } else if (mType == OFFLOAD) {
1198 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1199 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1200 "for output %p with format %d",
1201 sampleRate, format, channelMask, mOutput, mFormat);
1202 lStatus = BAD_VALUE;
1203 goto Exit;
1204 }
Eric Laurent81784c32012-11-19 14:55:58 -08001205 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001206 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1207 ALOGE("createTrack_l() Bad parameter: format %d \""
1208 "for output %p with format %d",
1209 format, mOutput, mFormat);
1210 lStatus = BAD_VALUE;
1211 goto Exit;
1212 }
Eric Laurent81784c32012-11-19 14:55:58 -08001213 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1214 if (sampleRate > mSampleRate*2) {
1215 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1216 lStatus = BAD_VALUE;
1217 goto Exit;
1218 }
1219 }
1220
1221 lStatus = initCheck();
1222 if (lStatus != NO_ERROR) {
1223 ALOGE("Audio driver not initialized.");
1224 goto Exit;
1225 }
1226
1227 { // scope for mLock
1228 Mutex::Autolock _l(mLock);
1229
1230 // all tracks in same audio session must share the same routing strategy otherwise
1231 // conflicts will happen when tracks are moved from one output to another by audio policy
1232 // manager
1233 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1234 for (size_t i = 0; i < mTracks.size(); ++i) {
1235 sp<Track> t = mTracks[i];
1236 if (t != 0 && !t->isOutputTrack()) {
1237 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1238 if (sessionId == t->sessionId() && strategy != actual) {
1239 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1240 strategy, actual);
1241 lStatus = BAD_VALUE;
1242 goto Exit;
1243 }
1244 }
1245 }
1246
1247 if (!isTimed) {
1248 track = new Track(this, client, streamType, sampleRate, format,
1249 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1250 } else {
1251 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1252 channelMask, frameCount, sharedBuffer, sessionId);
1253 }
Glenn Kasten03003332013-08-06 15:40:54 -07001254
1255 // new Track always returns non-NULL,
1256 // but TimedTrack::create() is a factory that could fail by returning NULL
1257 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1258 if (lStatus != NO_ERROR) {
1259 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001260 goto Exit;
1261 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001262
Eric Laurent81784c32012-11-19 14:55:58 -08001263 mTracks.add(track);
1264
1265 sp<EffectChain> chain = getEffectChain_l(sessionId);
1266 if (chain != 0) {
1267 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1268 track->setMainBuffer(chain->inBuffer());
1269 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1270 chain->incTrackCnt();
1271 }
1272
1273 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1274 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1275 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1276 // so ask activity manager to do this on our behalf
1277 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1278 }
1279 }
1280
1281 lStatus = NO_ERROR;
1282
1283Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001284 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001285 return track;
1286}
1287
1288uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1289{
1290 return latency;
1291}
1292
1293uint32_t AudioFlinger::PlaybackThread::latency() const
1294{
1295 Mutex::Autolock _l(mLock);
1296 return latency_l();
1297}
1298uint32_t AudioFlinger::PlaybackThread::latency_l() const
1299{
1300 if (initCheck() == NO_ERROR) {
1301 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1302 } else {
1303 return 0;
1304 }
1305}
1306
1307void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1308{
1309 Mutex::Autolock _l(mLock);
1310 // Don't apply master volume in SW if our HAL can do it for us.
1311 if (mOutput && mOutput->audioHwDev &&
1312 mOutput->audioHwDev->canSetMasterVolume()) {
1313 mMasterVolume = 1.0;
1314 } else {
1315 mMasterVolume = value;
1316 }
1317}
1318
1319void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1320{
1321 Mutex::Autolock _l(mLock);
1322 // Don't apply master mute in SW if our HAL can do it for us.
1323 if (mOutput && mOutput->audioHwDev &&
1324 mOutput->audioHwDev->canSetMasterMute()) {
1325 mMasterMute = false;
1326 } else {
1327 mMasterMute = muted;
1328 }
1329}
1330
1331void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1332{
1333 Mutex::Autolock _l(mLock);
1334 mStreamTypes[stream].volume = value;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001335 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001336}
1337
1338void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1339{
1340 Mutex::Autolock _l(mLock);
1341 mStreamTypes[stream].mute = muted;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001342 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001343}
1344
1345float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1346{
1347 Mutex::Autolock _l(mLock);
1348 return mStreamTypes[stream].volume;
1349}
1350
1351// addTrack_l() must be called with ThreadBase::mLock held
1352status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1353{
1354 status_t status = ALREADY_EXISTS;
1355
1356 // set retry count for buffer fill
1357 track->mRetryCount = kMaxTrackStartupRetries;
1358 if (mActiveTracks.indexOf(track) < 0) {
1359 // the track is newly added, make sure it fills up all its
1360 // buffers before playing. This is to ensure the client will
1361 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001362 if (!track->isOutputTrack()) {
1363 TrackBase::track_state state = track->mState;
1364 mLock.unlock();
1365 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1366 mLock.lock();
1367 // abort track was stopped/paused while we released the lock
1368 if (state != track->mState) {
1369 if (status == NO_ERROR) {
1370 mLock.unlock();
1371 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1372 mLock.lock();
1373 }
1374 return INVALID_OPERATION;
1375 }
1376 // abort if start is rejected by audio policy manager
1377 if (status != NO_ERROR) {
1378 return PERMISSION_DENIED;
1379 }
1380#ifdef ADD_BATTERY_DATA
1381 // to track the speaker usage
1382 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1383#endif
1384 }
1385
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001386 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001387 track->mResetDone = false;
1388 track->mPresentationCompleteFrames = 0;
1389 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001390 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1391 if (chain != 0) {
1392 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1393 track->sessionId());
1394 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001395 }
1396
1397 status = NO_ERROR;
1398 }
1399
1400 ALOGV("mWaitWorkCV.broadcast");
1401 mWaitWorkCV.broadcast();
1402
1403 return status;
1404}
1405
Eric Laurentbfb1b832013-01-07 09:53:42 -08001406bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001408 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001409 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001410 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1411 track->mState = TrackBase::STOPPED;
1412 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001413 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001414 } else if (track->isFastTrack() || track->isOffloaded()) {
1415 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001416 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001417
1418 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001419}
1420
1421void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1422{
1423 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1424 mTracks.remove(track);
1425 deleteTrackName_l(track->name());
1426 // redundant as track is about to be destroyed, for dumpsys only
1427 track->mName = -1;
1428 if (track->isFastTrack()) {
1429 int index = track->mFastIndex;
1430 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1431 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1432 mFastTrackAvailMask |= 1 << index;
1433 // redundant as track is about to be destroyed, for dumpsys only
1434 track->mFastIndex = -1;
1435 }
1436 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1437 if (chain != 0) {
1438 chain->decTrackCnt();
1439 }
1440}
1441
Eric Laurentbfb1b832013-01-07 09:53:42 -08001442void AudioFlinger::PlaybackThread::signal_l()
1443{
1444 // Thread could be blocked waiting for async
1445 // so signal it to handle state changes immediately
1446 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1447 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1448 mSignalPending = true;
1449 mWaitWorkCV.signal();
1450}
1451
Eric Laurent81784c32012-11-19 14:55:58 -08001452String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1453{
Eric Laurent81784c32012-11-19 14:55:58 -08001454 Mutex::Autolock _l(mLock);
1455 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001456 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001457 }
1458
Glenn Kastend8ea6992013-07-16 14:17:15 -07001459 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1460 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001461 free(s);
1462 return out_s8;
1463}
1464
1465// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1466void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1467 AudioSystem::OutputDescriptor desc;
1468 void *param2 = NULL;
1469
1470 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1471 param);
1472
1473 switch (event) {
1474 case AudioSystem::OUTPUT_OPENED:
1475 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001476 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001477 desc.samplingRate = mSampleRate;
1478 desc.format = mFormat;
1479 desc.frameCount = mNormalFrameCount; // FIXME see
1480 // AudioFlinger::frameCount(audio_io_handle_t)
1481 desc.latency = latency();
1482 param2 = &desc;
1483 break;
1484
1485 case AudioSystem::STREAM_CONFIG_CHANGED:
1486 param2 = &param;
1487 case AudioSystem::OUTPUT_CLOSED:
1488 default:
1489 break;
1490 }
1491 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1492}
1493
Eric Laurentbfb1b832013-01-07 09:53:42 -08001494void AudioFlinger::PlaybackThread::writeCallback()
1495{
1496 ALOG_ASSERT(mCallbackThread != 0);
1497 mCallbackThread->setWriteBlocked(false);
1498}
1499
1500void AudioFlinger::PlaybackThread::drainCallback()
1501{
1502 ALOG_ASSERT(mCallbackThread != 0);
1503 mCallbackThread->setDraining(false);
1504}
1505
1506void AudioFlinger::PlaybackThread::setWriteBlocked(bool value)
1507{
1508 Mutex::Autolock _l(mLock);
1509 mWriteBlocked = value;
1510 if (!value) {
1511 mWaitWorkCV.signal();
1512 }
1513}
1514
1515void AudioFlinger::PlaybackThread::setDraining(bool value)
1516{
1517 Mutex::Autolock _l(mLock);
1518 mDraining = value;
1519 if (!value) {
1520 mWaitWorkCV.signal();
1521 }
1522}
1523
1524// static
1525int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1526 void *param,
1527 void *cookie)
1528{
1529 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1530 ALOGV("asyncCallback() event %d", event);
1531 switch (event) {
1532 case STREAM_CBK_EVENT_WRITE_READY:
1533 me->writeCallback();
1534 break;
1535 case STREAM_CBK_EVENT_DRAIN_READY:
1536 me->drainCallback();
1537 break;
1538 default:
1539 ALOGW("asyncCallback() unknown event %d", event);
1540 break;
1541 }
1542 return 0;
1543}
1544
Eric Laurent81784c32012-11-19 14:55:58 -08001545void AudioFlinger::PlaybackThread::readOutputParameters()
1546{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001547 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001548 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1549 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001550 if (!audio_is_output_channel(mChannelMask)) {
1551 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1552 }
1553 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1554 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1555 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1556 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001557 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001558 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001559 if (!audio_is_valid_format(mFormat)) {
1560 LOG_FATAL("HAL format %d not valid for output", mFormat);
1561 }
1562 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1563 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1564 mFormat);
1565 }
Eric Laurent81784c32012-11-19 14:55:58 -08001566 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001567 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1568 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001569 if (mFrameCount & 15) {
1570 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1571 mFrameCount);
1572 }
1573
Eric Laurentbfb1b832013-01-07 09:53:42 -08001574 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1575 (mOutput->stream->set_callback != NULL)) {
1576 if (mOutput->stream->set_callback(mOutput->stream,
1577 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1578 mUseAsyncWrite = true;
1579 }
1580 }
1581
Eric Laurent81784c32012-11-19 14:55:58 -08001582 // Calculate size of normal mix buffer relative to the HAL output buffer size
1583 double multiplier = 1.0;
1584 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1585 kUseFastMixer == FastMixer_Dynamic)) {
1586 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1587 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1588 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1589 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1590 maxNormalFrameCount = maxNormalFrameCount & ~15;
1591 if (maxNormalFrameCount < minNormalFrameCount) {
1592 maxNormalFrameCount = minNormalFrameCount;
1593 }
1594 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1595 if (multiplier <= 1.0) {
1596 multiplier = 1.0;
1597 } else if (multiplier <= 2.0) {
1598 if (2 * mFrameCount <= maxNormalFrameCount) {
1599 multiplier = 2.0;
1600 } else {
1601 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1602 }
1603 } else {
1604 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1605 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1606 // track, but we sometimes have to do this to satisfy the maximum frame count
1607 // constraint)
1608 // FIXME this rounding up should not be done if no HAL SRC
1609 uint32_t truncMult = (uint32_t) multiplier;
1610 if ((truncMult & 1)) {
1611 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1612 ++truncMult;
1613 }
1614 }
1615 multiplier = (double) truncMult;
1616 }
1617 }
1618 mNormalFrameCount = multiplier * mFrameCount;
1619 // round up to nearest 16 frames to satisfy AudioMixer
1620 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1621 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1622 mNormalFrameCount);
1623
Glenn Kastenc1fac192013-08-06 07:41:36 -07001624 delete[] mMixBuffer;
1625 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1626 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1627 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1628 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001629
1630 // force reconfiguration of effect chains and engines to take new buffer size and audio
1631 // parameters into account
1632 // Note that mLock is not held when readOutputParameters() is called from the constructor
1633 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1634 // matter.
1635 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1636 Vector< sp<EffectChain> > effectChains = mEffectChains;
1637 for (size_t i = 0; i < effectChains.size(); i ++) {
1638 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1639 }
1640}
1641
1642
1643status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1644{
1645 if (halFrames == NULL || dspFrames == NULL) {
1646 return BAD_VALUE;
1647 }
1648 Mutex::Autolock _l(mLock);
1649 if (initCheck() != NO_ERROR) {
1650 return INVALID_OPERATION;
1651 }
1652 size_t framesWritten = mBytesWritten / mFrameSize;
1653 *halFrames = framesWritten;
1654
1655 if (isSuspended()) {
1656 // return an estimation of rendered frames when the output is suspended
1657 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1658 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1659 return NO_ERROR;
1660 } else {
1661 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1662 }
1663}
1664
1665uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1666{
1667 Mutex::Autolock _l(mLock);
1668 uint32_t result = 0;
1669 if (getEffectChain_l(sessionId) != 0) {
1670 result = EFFECT_SESSION;
1671 }
1672
1673 for (size_t i = 0; i < mTracks.size(); ++i) {
1674 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001675 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001676 result |= TRACK_SESSION;
1677 break;
1678 }
1679 }
1680
1681 return result;
1682}
1683
1684uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1685{
1686 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1687 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1688 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1689 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1690 }
1691 for (size_t i = 0; i < mTracks.size(); i++) {
1692 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001693 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001694 return AudioSystem::getStrategyForStream(track->streamType());
1695 }
1696 }
1697 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1698}
1699
1700
1701AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1702{
1703 Mutex::Autolock _l(mLock);
1704 return mOutput;
1705}
1706
1707AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1708{
1709 Mutex::Autolock _l(mLock);
1710 AudioStreamOut *output = mOutput;
1711 mOutput = NULL;
1712 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1713 // must push a NULL and wait for ack
1714 mOutputSink.clear();
1715 mPipeSink.clear();
1716 mNormalSink.clear();
1717 return output;
1718}
1719
1720// this method must always be called either with ThreadBase mLock held or inside the thread loop
1721audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1722{
1723 if (mOutput == NULL) {
1724 return NULL;
1725 }
1726 return &mOutput->stream->common;
1727}
1728
1729uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1730{
1731 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1732}
1733
1734status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1735{
1736 if (!isValidSyncEvent(event)) {
1737 return BAD_VALUE;
1738 }
1739
1740 Mutex::Autolock _l(mLock);
1741
1742 for (size_t i = 0; i < mTracks.size(); ++i) {
1743 sp<Track> track = mTracks[i];
1744 if (event->triggerSession() == track->sessionId()) {
1745 (void) track->setSyncEvent(event);
1746 return NO_ERROR;
1747 }
1748 }
1749
1750 return NAME_NOT_FOUND;
1751}
1752
1753bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1754{
1755 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1756}
1757
1758void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1759 const Vector< sp<Track> >& tracksToRemove)
1760{
1761 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001762 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001763 for (size_t i = 0 ; i < count ; i++) {
1764 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001765 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001766 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767#ifdef ADD_BATTERY_DATA
1768 // to track the speaker usage
1769 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1770#endif
1771 if (track->isTerminated()) {
1772 AudioSystem::releaseOutput(mId);
1773 }
Eric Laurent81784c32012-11-19 14:55:58 -08001774 }
1775 }
1776 }
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
1779void AudioFlinger::PlaybackThread::checkSilentMode_l()
1780{
1781 if (!mMasterMute) {
1782 char value[PROPERTY_VALUE_MAX];
1783 if (property_get("ro.audio.silent", value, "0") > 0) {
1784 char *endptr;
1785 unsigned long ul = strtoul(value, &endptr, 0);
1786 if (*endptr == '\0' && ul != 0) {
1787 ALOGD("Silence is golden");
1788 // The setprop command will not allow a property to be changed after
1789 // the first time it is set, so we don't have to worry about un-muting.
1790 setMasterMute_l(true);
1791 }
1792 }
1793 }
1794}
1795
1796// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001798{
1799 // FIXME rewrite to reduce number of system calls
1800 mLastWriteTime = systemTime();
1801 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001802 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001803
1804 // If an NBAIO sink is present, use it to write the normal mixer's submix
1805 if (mNormalSink != 0) {
1806#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001807 size_t count = mBytesRemaining >> mBitShift;
1808 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001809 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001810 // update the setpoint when AudioFlinger::mScreenState changes
1811 uint32_t screenState = AudioFlinger::mScreenState;
1812 if (screenState != mScreenState) {
1813 mScreenState = screenState;
1814 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1815 if (pipe != NULL) {
1816 pipe->setAvgFrames((mScreenState & 1) ?
1817 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1818 }
1819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001820 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001821 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001822 if (framesWritten > 0) {
1823 bytesWritten = framesWritten << mBitShift;
1824 } else {
1825 bytesWritten = framesWritten;
1826 }
1827 // otherwise use the HAL / AudioStreamOut directly
1828 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001829 // Direct output and offload threads
1830 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1831 if (mUseAsyncWrite) {
1832 mWriteBlocked = true;
1833 ALOG_ASSERT(mCallbackThread != 0);
1834 mCallbackThread->setWriteBlocked(true);
1835 }
1836 bytesWritten = mOutput->stream->write(mOutput->stream,
1837 mMixBuffer + offset, mBytesRemaining);
1838 if (mUseAsyncWrite &&
1839 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1840 // do not wait for async callback in case of error of full write
1841 mWriteBlocked = false;
1842 ALOG_ASSERT(mCallbackThread != 0);
1843 mCallbackThread->setWriteBlocked(false);
1844 }
Eric Laurent81784c32012-11-19 14:55:58 -08001845 }
1846
Eric Laurent81784c32012-11-19 14:55:58 -08001847 mNumWrites++;
1848 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001849
1850 return bytesWritten;
1851}
1852
1853void AudioFlinger::PlaybackThread::threadLoop_drain()
1854{
1855 if (mOutput->stream->drain) {
1856 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1857 if (mUseAsyncWrite) {
1858 mDraining = true;
1859 ALOG_ASSERT(mCallbackThread != 0);
1860 mCallbackThread->setDraining(true);
1861 }
1862 mOutput->stream->drain(mOutput->stream,
1863 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1864 : AUDIO_DRAIN_ALL);
1865 }
1866}
1867
1868void AudioFlinger::PlaybackThread::threadLoop_exit()
1869{
1870 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873/*
1874The derived values that are cached:
1875 - mixBufferSize from frame count * frame size
1876 - activeSleepTime from activeSleepTimeUs()
1877 - idleSleepTime from idleSleepTimeUs()
1878 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1879 - maxPeriod from frame count and sample rate (MIXER only)
1880
1881The parameters that affect these derived values are:
1882 - frame count
1883 - frame size
1884 - sample rate
1885 - device type: A2DP or not
1886 - device latency
1887 - format: PCM or not
1888 - active sleep time
1889 - idle sleep time
1890*/
1891
1892void AudioFlinger::PlaybackThread::cacheParameters_l()
1893{
1894 mixBufferSize = mNormalFrameCount * mFrameSize;
1895 activeSleepTime = activeSleepTimeUs();
1896 idleSleepTime = idleSleepTimeUs();
1897}
1898
1899void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1900{
Glenn Kasten7c027242012-12-26 14:43:16 -08001901 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001902 this, streamType, mTracks.size());
1903 Mutex::Autolock _l(mLock);
1904
1905 size_t size = mTracks.size();
1906 for (size_t i = 0; i < size; i++) {
1907 sp<Track> t = mTracks[i];
1908 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001909 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001910 }
1911 }
1912}
1913
1914status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1915{
1916 int session = chain->sessionId();
1917 int16_t *buffer = mMixBuffer;
1918 bool ownsBuffer = false;
1919
1920 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1921 if (session > 0) {
1922 // Only one effect chain can be present in direct output thread and it uses
1923 // the mix buffer as input
1924 if (mType != DIRECT) {
1925 size_t numSamples = mNormalFrameCount * mChannelCount;
1926 buffer = new int16_t[numSamples];
1927 memset(buffer, 0, numSamples * sizeof(int16_t));
1928 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1929 ownsBuffer = true;
1930 }
1931
1932 // Attach all tracks with same session ID to this chain.
1933 for (size_t i = 0; i < mTracks.size(); ++i) {
1934 sp<Track> track = mTracks[i];
1935 if (session == track->sessionId()) {
1936 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1937 buffer);
1938 track->setMainBuffer(buffer);
1939 chain->incTrackCnt();
1940 }
1941 }
1942
1943 // indicate all active tracks in the chain
1944 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1945 sp<Track> track = mActiveTracks[i].promote();
1946 if (track == 0) {
1947 continue;
1948 }
1949 if (session == track->sessionId()) {
1950 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1951 chain->incActiveTrackCnt();
1952 }
1953 }
1954 }
1955
1956 chain->setInBuffer(buffer, ownsBuffer);
1957 chain->setOutBuffer(mMixBuffer);
1958 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1959 // chains list in order to be processed last as it contains output stage effects
1960 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1961 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1962 // after track specific effects and before output stage
1963 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1964 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1965 // Effect chain for other sessions are inserted at beginning of effect
1966 // chains list to be processed before output mix effects. Relative order between other
1967 // sessions is not important
1968 size_t size = mEffectChains.size();
1969 size_t i = 0;
1970 for (i = 0; i < size; i++) {
1971 if (mEffectChains[i]->sessionId() < session) {
1972 break;
1973 }
1974 }
1975 mEffectChains.insertAt(chain, i);
1976 checkSuspendOnAddEffectChain_l(chain);
1977
1978 return NO_ERROR;
1979}
1980
1981size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1982{
1983 int session = chain->sessionId();
1984
1985 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1986
1987 for (size_t i = 0; i < mEffectChains.size(); i++) {
1988 if (chain == mEffectChains[i]) {
1989 mEffectChains.removeAt(i);
1990 // detach all active tracks from the chain
1991 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1992 sp<Track> track = mActiveTracks[i].promote();
1993 if (track == 0) {
1994 continue;
1995 }
1996 if (session == track->sessionId()) {
1997 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1998 chain.get(), session);
1999 chain->decActiveTrackCnt();
2000 }
2001 }
2002
2003 // detach all tracks with same session ID from this chain
2004 for (size_t i = 0; i < mTracks.size(); ++i) {
2005 sp<Track> track = mTracks[i];
2006 if (session == track->sessionId()) {
2007 track->setMainBuffer(mMixBuffer);
2008 chain->decTrackCnt();
2009 }
2010 }
2011 break;
2012 }
2013 }
2014 return mEffectChains.size();
2015}
2016
2017status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2018 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2019{
2020 Mutex::Autolock _l(mLock);
2021 return attachAuxEffect_l(track, EffectId);
2022}
2023
2024status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2025 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2026{
2027 status_t status = NO_ERROR;
2028
2029 if (EffectId == 0) {
2030 track->setAuxBuffer(0, NULL);
2031 } else {
2032 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2033 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2034 if (effect != 0) {
2035 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2036 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2037 } else {
2038 status = INVALID_OPERATION;
2039 }
2040 } else {
2041 status = BAD_VALUE;
2042 }
2043 }
2044 return status;
2045}
2046
2047void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2048{
2049 for (size_t i = 0; i < mTracks.size(); ++i) {
2050 sp<Track> track = mTracks[i];
2051 if (track->auxEffectId() == effectId) {
2052 attachAuxEffect_l(track, 0);
2053 }
2054 }
2055}
2056
2057bool AudioFlinger::PlaybackThread::threadLoop()
2058{
2059 Vector< sp<Track> > tracksToRemove;
2060
2061 standbyTime = systemTime();
2062
2063 // MIXER
2064 nsecs_t lastWarning = 0;
2065
2066 // DUPLICATING
2067 // FIXME could this be made local to while loop?
2068 writeFrames = 0;
2069
2070 cacheParameters_l();
2071 sleepTime = idleSleepTime;
2072
2073 if (mType == MIXER) {
2074 sleepTimeShift = 0;
2075 }
2076
2077 CpuStats cpuStats;
2078 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2079
2080 acquireWakeLock();
2081
Glenn Kasten9e58b552013-01-18 15:09:48 -08002082 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2083 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2084 // and then that string will be logged at the next convenient opportunity.
2085 const char *logString = NULL;
2086
Eric Laurent81784c32012-11-19 14:55:58 -08002087 while (!exitPending())
2088 {
2089 cpuStats.sample(myName);
2090
2091 Vector< sp<EffectChain> > effectChains;
2092
2093 processConfigEvents();
2094
2095 { // scope for mLock
2096
2097 Mutex::Autolock _l(mLock);
2098
Glenn Kasten9e58b552013-01-18 15:09:48 -08002099 if (logString != NULL) {
2100 mNBLogWriter->logTimestamp();
2101 mNBLogWriter->log(logString);
2102 logString = NULL;
2103 }
2104
Eric Laurent81784c32012-11-19 14:55:58 -08002105 if (checkForNewParameters_l()) {
2106 cacheParameters_l();
2107 }
2108
2109 saveOutputTracks();
2110
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111 if (mSignalPending) {
2112 // A signal was raised while we were unlocked
2113 mSignalPending = false;
2114 } else if (waitingAsyncCallback_l()) {
2115 if (exitPending()) {
2116 break;
2117 }
2118 releaseWakeLock_l();
2119 ALOGV("wait async completion");
2120 mWaitWorkCV.wait(mLock);
2121 ALOGV("async completion/wake");
2122 acquireWakeLock_l();
2123 if (exitPending()) {
2124 break;
2125 }
2126 if (!mActiveTracks.size() && (systemTime() > standbyTime)) {
2127 continue;
2128 }
2129 sleepTime = 0;
2130 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2131 isSuspended()) {
2132 // put audio hardware into standby after short delay
2133 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002134
2135 threadLoop_standby();
2136
2137 mStandby = true;
2138 }
2139
2140 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2141 // we're about to wait, flush the binder command buffer
2142 IPCThreadState::self()->flushCommands();
2143
2144 clearOutputTracks();
2145
2146 if (exitPending()) {
2147 break;
2148 }
2149
2150 releaseWakeLock_l();
2151 // wait until we have something to do...
2152 ALOGV("%s going to sleep", myName.string());
2153 mWaitWorkCV.wait(mLock);
2154 ALOGV("%s waking up", myName.string());
2155 acquireWakeLock_l();
2156
2157 mMixerStatus = MIXER_IDLE;
2158 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2159 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002161 checkSilentMode_l();
2162
2163 standbyTime = systemTime() + standbyDelay;
2164 sleepTime = idleSleepTime;
2165 if (mType == MIXER) {
2166 sleepTimeShift = 0;
2167 }
2168
2169 continue;
2170 }
2171 }
2172
2173 // mMixerStatusIgnoringFastTracks is also updated internally
2174 mMixerStatus = prepareTracks_l(&tracksToRemove);
2175
2176 // prevent any changes in effect chain list and in each effect chain
2177 // during mixing and effect process as the audio buffers could be deleted
2178 // or modified if an effect is created or deleted
2179 lockEffectChains_l(effectChains);
2180 }
2181
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 if (mBytesRemaining == 0) {
2183 mCurrentWriteLength = 0;
2184 if (mMixerStatus == MIXER_TRACKS_READY) {
2185 // threadLoop_mix() sets mCurrentWriteLength
2186 threadLoop_mix();
2187 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2188 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2189 // threadLoop_sleepTime sets sleepTime to 0 if data
2190 // must be written to HAL
2191 threadLoop_sleepTime();
2192 if (sleepTime == 0) {
2193 mCurrentWriteLength = mixBufferSize;
2194 }
2195 }
2196 mBytesRemaining = mCurrentWriteLength;
2197 if (isSuspended()) {
2198 sleepTime = suspendSleepTimeUs();
2199 // simulate write to HAL when suspended
2200 mBytesWritten += mixBufferSize;
2201 mBytesRemaining = 0;
2202 }
Eric Laurent81784c32012-11-19 14:55:58 -08002203
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 // only process effects if we're going to write
2205 if (sleepTime == 0) {
2206 for (size_t i = 0; i < effectChains.size(); i ++) {
2207 effectChains[i]->process_l();
2208 }
Eric Laurent81784c32012-11-19 14:55:58 -08002209 }
2210 }
2211
2212 // enable changes in effect chain
2213 unlockEffectChains(effectChains);
2214
Eric Laurentbfb1b832013-01-07 09:53:42 -08002215 if (!waitingAsyncCallback()) {
2216 // sleepTime == 0 means we must write to audio hardware
2217 if (sleepTime == 0) {
2218 if (mBytesRemaining) {
2219 ssize_t ret = threadLoop_write();
2220 if (ret < 0) {
2221 mBytesRemaining = 0;
2222 } else {
2223 mBytesWritten += ret;
2224 mBytesRemaining -= ret;
2225 }
2226 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2227 (mMixerStatus == MIXER_DRAIN_ALL)) {
2228 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002229 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002230if (mType == MIXER) {
2231 // write blocked detection
2232 nsecs_t now = systemTime();
2233 nsecs_t delta = now - mLastWriteTime;
2234 if (!mStandby && delta > maxPeriod) {
2235 mNumDelayedWrites++;
2236 if ((now - lastWarning) > kWarningThrottleNs) {
2237 ATRACE_NAME("underrun");
2238 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2239 ns2ms(delta), mNumDelayedWrites, this);
2240 lastWarning = now;
2241 }
2242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 mStandby = false;
2246 } else {
2247 usleep(sleepTime);
2248 }
Eric Laurent81784c32012-11-19 14:55:58 -08002249 }
2250
2251 // Finally let go of removed track(s), without the lock held
2252 // since we can't guarantee the destructors won't acquire that
2253 // same lock. This will also mutate and push a new fast mixer state.
2254 threadLoop_removeTracks(tracksToRemove);
2255 tracksToRemove.clear();
2256
2257 // FIXME I don't understand the need for this here;
2258 // it was in the original code but maybe the
2259 // assignment in saveOutputTracks() makes this unnecessary?
2260 clearOutputTracks();
2261
2262 // Effect chains will be actually deleted here if they were removed from
2263 // mEffectChains list during mixing or effects processing
2264 effectChains.clear();
2265
2266 // FIXME Note that the above .clear() is no longer necessary since effectChains
2267 // is now local to this block, but will keep it for now (at least until merge done).
2268 }
2269
Eric Laurentbfb1b832013-01-07 09:53:42 -08002270 threadLoop_exit();
2271
Eric Laurent81784c32012-11-19 14:55:58 -08002272 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002274 // put output stream into standby mode
2275 if (!mStandby) {
2276 mOutput->stream->common.standby(&mOutput->stream->common);
2277 }
2278 }
2279
2280 releaseWakeLock();
2281
2282 ALOGV("Thread %p type %d exiting", this, mType);
2283 return false;
2284}
2285
Eric Laurentbfb1b832013-01-07 09:53:42 -08002286// removeTracks_l() must be called with ThreadBase::mLock held
2287void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2288{
2289 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002290 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291 for (size_t i=0 ; i<count ; i++) {
2292 const sp<Track>& track = tracksToRemove.itemAt(i);
2293 mActiveTracks.remove(track);
2294 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2295 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2296 if (chain != 0) {
2297 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2298 track->sessionId());
2299 chain->decActiveTrackCnt();
2300 }
2301 if (track->isTerminated()) {
2302 removeTrack_l(track);
2303 }
2304 }
2305 }
2306
2307}
Eric Laurent81784c32012-11-19 14:55:58 -08002308
2309// ----------------------------------------------------------------------------
2310
2311AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2312 audio_io_handle_t id, audio_devices_t device, type_t type)
2313 : PlaybackThread(audioFlinger, output, id, device, type),
2314 // mAudioMixer below
2315 // mFastMixer below
2316 mFastMixerFutex(0)
2317 // mOutputSink below
2318 // mPipeSink below
2319 // mNormalSink below
2320{
2321 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002322 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002323 "mFrameCount=%d, mNormalFrameCount=%d",
2324 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2325 mNormalFrameCount);
2326 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2327
2328 // FIXME - Current mixer implementation only supports stereo output
2329 if (mChannelCount != FCC_2) {
2330 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2331 }
2332
2333 // create an NBAIO sink for the HAL output stream, and negotiate
2334 mOutputSink = new AudioStreamOutSink(output->stream);
2335 size_t numCounterOffers = 0;
2336 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2337 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2338 ALOG_ASSERT(index == 0);
2339
2340 // initialize fast mixer depending on configuration
2341 bool initFastMixer;
2342 switch (kUseFastMixer) {
2343 case FastMixer_Never:
2344 initFastMixer = false;
2345 break;
2346 case FastMixer_Always:
2347 initFastMixer = true;
2348 break;
2349 case FastMixer_Static:
2350 case FastMixer_Dynamic:
2351 initFastMixer = mFrameCount < mNormalFrameCount;
2352 break;
2353 }
2354 if (initFastMixer) {
2355
2356 // create a MonoPipe to connect our submix to FastMixer
2357 NBAIO_Format format = mOutputSink->format();
2358 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2359 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2360 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2361 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2362 const NBAIO_Format offers[1] = {format};
2363 size_t numCounterOffers = 0;
2364 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2365 ALOG_ASSERT(index == 0);
2366 monoPipe->setAvgFrames((mScreenState & 1) ?
2367 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2368 mPipeSink = monoPipe;
2369
Glenn Kasten46909e72013-02-26 09:20:22 -08002370#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002371 if (mTeeSinkOutputEnabled) {
2372 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2373 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2374 numCounterOffers = 0;
2375 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2376 ALOG_ASSERT(index == 0);
2377 mTeeSink = teeSink;
2378 PipeReader *teeSource = new PipeReader(*teeSink);
2379 numCounterOffers = 0;
2380 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2381 ALOG_ASSERT(index == 0);
2382 mTeeSource = teeSource;
2383 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002385
2386 // create fast mixer and configure it initially with just one fast track for our submix
2387 mFastMixer = new FastMixer();
2388 FastMixerStateQueue *sq = mFastMixer->sq();
2389#ifdef STATE_QUEUE_DUMP
2390 sq->setObserverDump(&mStateQueueObserverDump);
2391 sq->setMutatorDump(&mStateQueueMutatorDump);
2392#endif
2393 FastMixerState *state = sq->begin();
2394 FastTrack *fastTrack = &state->mFastTracks[0];
2395 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2396 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2397 fastTrack->mVolumeProvider = NULL;
2398 fastTrack->mGeneration++;
2399 state->mFastTracksGen++;
2400 state->mTrackMask = 1;
2401 // fast mixer will use the HAL output sink
2402 state->mOutputSink = mOutputSink.get();
2403 state->mOutputSinkGen++;
2404 state->mFrameCount = mFrameCount;
2405 state->mCommand = FastMixerState::COLD_IDLE;
2406 // already done in constructor initialization list
2407 //mFastMixerFutex = 0;
2408 state->mColdFutexAddr = &mFastMixerFutex;
2409 state->mColdGen++;
2410 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002411#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002412 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002413#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002414 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2415 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002416 sq->end();
2417 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2418
2419 // start the fast mixer
2420 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2421 pid_t tid = mFastMixer->getTid();
2422 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2423 if (err != 0) {
2424 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2425 kPriorityFastMixer, getpid_cached, tid, err);
2426 }
2427
2428#ifdef AUDIO_WATCHDOG
2429 // create and start the watchdog
2430 mAudioWatchdog = new AudioWatchdog();
2431 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2432 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2433 tid = mAudioWatchdog->getTid();
2434 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2435 if (err != 0) {
2436 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2437 kPriorityFastMixer, getpid_cached, tid, err);
2438 }
2439#endif
2440
2441 } else {
2442 mFastMixer = NULL;
2443 }
2444
2445 switch (kUseFastMixer) {
2446 case FastMixer_Never:
2447 case FastMixer_Dynamic:
2448 mNormalSink = mOutputSink;
2449 break;
2450 case FastMixer_Always:
2451 mNormalSink = mPipeSink;
2452 break;
2453 case FastMixer_Static:
2454 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2455 break;
2456 }
2457}
2458
2459AudioFlinger::MixerThread::~MixerThread()
2460{
2461 if (mFastMixer != NULL) {
2462 FastMixerStateQueue *sq = mFastMixer->sq();
2463 FastMixerState *state = sq->begin();
2464 if (state->mCommand == FastMixerState::COLD_IDLE) {
2465 int32_t old = android_atomic_inc(&mFastMixerFutex);
2466 if (old == -1) {
2467 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2468 }
2469 }
2470 state->mCommand = FastMixerState::EXIT;
2471 sq->end();
2472 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2473 mFastMixer->join();
2474 // Though the fast mixer thread has exited, it's state queue is still valid.
2475 // We'll use that extract the final state which contains one remaining fast track
2476 // corresponding to our sub-mix.
2477 state = sq->begin();
2478 ALOG_ASSERT(state->mTrackMask == 1);
2479 FastTrack *fastTrack = &state->mFastTracks[0];
2480 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2481 delete fastTrack->mBufferProvider;
2482 sq->end(false /*didModify*/);
2483 delete mFastMixer;
2484#ifdef AUDIO_WATCHDOG
2485 if (mAudioWatchdog != 0) {
2486 mAudioWatchdog->requestExit();
2487 mAudioWatchdog->requestExitAndWait();
2488 mAudioWatchdog.clear();
2489 }
2490#endif
2491 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002492 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002493 delete mAudioMixer;
2494}
2495
2496
2497uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2498{
2499 if (mFastMixer != NULL) {
2500 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2501 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2502 }
2503 return latency;
2504}
2505
2506
2507void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2508{
2509 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2510}
2511
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002513{
2514 // FIXME we should only do one push per cycle; confirm this is true
2515 // Start the fast mixer if it's not already running
2516 if (mFastMixer != NULL) {
2517 FastMixerStateQueue *sq = mFastMixer->sq();
2518 FastMixerState *state = sq->begin();
2519 if (state->mCommand != FastMixerState::MIX_WRITE &&
2520 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2521 if (state->mCommand == FastMixerState::COLD_IDLE) {
2522 int32_t old = android_atomic_inc(&mFastMixerFutex);
2523 if (old == -1) {
2524 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2525 }
2526#ifdef AUDIO_WATCHDOG
2527 if (mAudioWatchdog != 0) {
2528 mAudioWatchdog->resume();
2529 }
2530#endif
2531 }
2532 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002533 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2534 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002535 sq->end();
2536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2537 if (kUseFastMixer == FastMixer_Dynamic) {
2538 mNormalSink = mPipeSink;
2539 }
2540 } else {
2541 sq->end(false /*didModify*/);
2542 }
2543 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002544 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002545}
2546
2547void AudioFlinger::MixerThread::threadLoop_standby()
2548{
2549 // Idle the fast mixer if it's currently running
2550 if (mFastMixer != NULL) {
2551 FastMixerStateQueue *sq = mFastMixer->sq();
2552 FastMixerState *state = sq->begin();
2553 if (!(state->mCommand & FastMixerState::IDLE)) {
2554 state->mCommand = FastMixerState::COLD_IDLE;
2555 state->mColdFutexAddr = &mFastMixerFutex;
2556 state->mColdGen++;
2557 mFastMixerFutex = 0;
2558 sq->end();
2559 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2560 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2561 if (kUseFastMixer == FastMixer_Dynamic) {
2562 mNormalSink = mOutputSink;
2563 }
2564#ifdef AUDIO_WATCHDOG
2565 if (mAudioWatchdog != 0) {
2566 mAudioWatchdog->pause();
2567 }
2568#endif
2569 } else {
2570 sq->end(false /*didModify*/);
2571 }
2572 }
2573 PlaybackThread::threadLoop_standby();
2574}
2575
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576// Empty implementation for standard mixer
2577// Overridden for offloaded playback
2578void AudioFlinger::PlaybackThread::flushOutput_l()
2579{
2580}
2581
2582bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2583{
2584 return false;
2585}
2586
2587bool AudioFlinger::PlaybackThread::shouldStandby_l()
2588{
2589 return !mStandby;
2590}
2591
2592bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2593{
2594 Mutex::Autolock _l(mLock);
2595 return waitingAsyncCallback_l();
2596}
2597
Eric Laurent81784c32012-11-19 14:55:58 -08002598// shared by MIXER and DIRECT, overridden by DUPLICATING
2599void AudioFlinger::PlaybackThread::threadLoop_standby()
2600{
2601 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2602 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 if (mUseAsyncWrite != 0) {
2604 mWriteBlocked = false;
2605 mDraining = false;
2606 ALOG_ASSERT(mCallbackThread != 0);
2607 mCallbackThread->setWriteBlocked(false);
2608 mCallbackThread->setDraining(false);
2609 }
Eric Laurent81784c32012-11-19 14:55:58 -08002610}
2611
2612void AudioFlinger::MixerThread::threadLoop_mix()
2613{
2614 // obtain the presentation timestamp of the next output buffer
2615 int64_t pts;
2616 status_t status = INVALID_OPERATION;
2617
2618 if (mNormalSink != 0) {
2619 status = mNormalSink->getNextWriteTimestamp(&pts);
2620 } else {
2621 status = mOutputSink->getNextWriteTimestamp(&pts);
2622 }
2623
2624 if (status != NO_ERROR) {
2625 pts = AudioBufferProvider::kInvalidPTS;
2626 }
2627
2628 // mix buffers...
2629 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002631 // increase sleep time progressively when application underrun condition clears.
2632 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2633 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2634 // such that we would underrun the audio HAL.
2635 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2636 sleepTimeShift--;
2637 }
2638 sleepTime = 0;
2639 standbyTime = systemTime() + standbyDelay;
2640 //TODO: delay standby when effects have a tail
2641}
2642
2643void AudioFlinger::MixerThread::threadLoop_sleepTime()
2644{
2645 // If no tracks are ready, sleep once for the duration of an output
2646 // buffer size, then write 0s to the output
2647 if (sleepTime == 0) {
2648 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2649 sleepTime = activeSleepTime >> sleepTimeShift;
2650 if (sleepTime < kMinThreadSleepTimeUs) {
2651 sleepTime = kMinThreadSleepTimeUs;
2652 }
2653 // reduce sleep time in case of consecutive application underruns to avoid
2654 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2655 // duration we would end up writing less data than needed by the audio HAL if
2656 // the condition persists.
2657 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2658 sleepTimeShift++;
2659 }
2660 } else {
2661 sleepTime = idleSleepTime;
2662 }
2663 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002664 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002665 sleepTime = 0;
2666 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2667 "anticipated start");
2668 }
2669 // TODO add standby time extension fct of effect tail
2670}
2671
2672// prepareTracks_l() must be called with ThreadBase::mLock held
2673AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2674 Vector< sp<Track> > *tracksToRemove)
2675{
2676
2677 mixer_state mixerStatus = MIXER_IDLE;
2678 // find out which tracks need to be processed
2679 size_t count = mActiveTracks.size();
2680 size_t mixedTracks = 0;
2681 size_t tracksWithEffect = 0;
2682 // counts only _active_ fast tracks
2683 size_t fastTracks = 0;
2684 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2685
2686 float masterVolume = mMasterVolume;
2687 bool masterMute = mMasterMute;
2688
2689 if (masterMute) {
2690 masterVolume = 0;
2691 }
2692 // Delegate master volume control to effect in output mix effect chain if needed
2693 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2694 if (chain != 0) {
2695 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2696 chain->setVolume_l(&v, &v);
2697 masterVolume = (float)((v + (1 << 23)) >> 24);
2698 chain.clear();
2699 }
2700
2701 // prepare a new state to push
2702 FastMixerStateQueue *sq = NULL;
2703 FastMixerState *state = NULL;
2704 bool didModify = false;
2705 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2706 if (mFastMixer != NULL) {
2707 sq = mFastMixer->sq();
2708 state = sq->begin();
2709 }
2710
2711 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002712 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002713 if (t == 0) {
2714 continue;
2715 }
2716
2717 // this const just means the local variable doesn't change
2718 Track* const track = t.get();
2719
2720 // process fast tracks
2721 if (track->isFastTrack()) {
2722
2723 // It's theoretically possible (though unlikely) for a fast track to be created
2724 // and then removed within the same normal mix cycle. This is not a problem, as
2725 // the track never becomes active so it's fast mixer slot is never touched.
2726 // The converse, of removing an (active) track and then creating a new track
2727 // at the identical fast mixer slot within the same normal mix cycle,
2728 // is impossible because the slot isn't marked available until the end of each cycle.
2729 int j = track->mFastIndex;
2730 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2731 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2732 FastTrack *fastTrack = &state->mFastTracks[j];
2733
2734 // Determine whether the track is currently in underrun condition,
2735 // and whether it had a recent underrun.
2736 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2737 FastTrackUnderruns underruns = ftDump->mUnderruns;
2738 uint32_t recentFull = (underruns.mBitFields.mFull -
2739 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2740 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2741 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2742 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2743 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2744 uint32_t recentUnderruns = recentPartial + recentEmpty;
2745 track->mObservedUnderruns = underruns;
2746 // don't count underruns that occur while stopping or pausing
2747 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002748 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2749 recentUnderruns > 0) {
2750 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2751 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002752 }
2753
2754 // This is similar to the state machine for normal tracks,
2755 // with a few modifications for fast tracks.
2756 bool isActive = true;
2757 switch (track->mState) {
2758 case TrackBase::STOPPING_1:
2759 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002761 track->mState = TrackBase::STOPPING_2;
2762 }
2763 break;
2764 case TrackBase::PAUSING:
2765 // ramp down is not yet implemented
2766 track->setPaused();
2767 break;
2768 case TrackBase::RESUMING:
2769 // ramp up is not yet implemented
2770 track->mState = TrackBase::ACTIVE;
2771 break;
2772 case TrackBase::ACTIVE:
2773 if (recentFull > 0 || recentPartial > 0) {
2774 // track has provided at least some frames recently: reset retry count
2775 track->mRetryCount = kMaxTrackRetries;
2776 }
2777 if (recentUnderruns == 0) {
2778 // no recent underruns: stay active
2779 break;
2780 }
2781 // there has recently been an underrun of some kind
2782 if (track->sharedBuffer() == 0) {
2783 // were any of the recent underruns "empty" (no frames available)?
2784 if (recentEmpty == 0) {
2785 // no, then ignore the partial underruns as they are allowed indefinitely
2786 break;
2787 }
2788 // there has recently been an "empty" underrun: decrement the retry counter
2789 if (--(track->mRetryCount) > 0) {
2790 break;
2791 }
2792 // indicate to client process that the track was disabled because of underrun;
2793 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002794 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002795 // remove from active list, but state remains ACTIVE [confusing but true]
2796 isActive = false;
2797 break;
2798 }
2799 // fall through
2800 case TrackBase::STOPPING_2:
2801 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002802 case TrackBase::STOPPED:
2803 case TrackBase::FLUSHED: // flush() while active
2804 // Check for presentation complete if track is inactive
2805 // We have consumed all the buffers of this track.
2806 // This would be incomplete if we auto-paused on underrun
2807 {
2808 size_t audioHALFrames =
2809 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2810 size_t framesWritten = mBytesWritten / mFrameSize;
2811 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2812 // track stays in active list until presentation is complete
2813 break;
2814 }
2815 }
2816 if (track->isStopping_2()) {
2817 track->mState = TrackBase::STOPPED;
2818 }
2819 if (track->isStopped()) {
2820 // Can't reset directly, as fast mixer is still polling this track
2821 // track->reset();
2822 // So instead mark this track as needing to be reset after push with ack
2823 resetMask |= 1 << i;
2824 }
2825 isActive = false;
2826 break;
2827 case TrackBase::IDLE:
2828 default:
2829 LOG_FATAL("unexpected track state %d", track->mState);
2830 }
2831
2832 if (isActive) {
2833 // was it previously inactive?
2834 if (!(state->mTrackMask & (1 << j))) {
2835 ExtendedAudioBufferProvider *eabp = track;
2836 VolumeProvider *vp = track;
2837 fastTrack->mBufferProvider = eabp;
2838 fastTrack->mVolumeProvider = vp;
2839 fastTrack->mSampleRate = track->mSampleRate;
2840 fastTrack->mChannelMask = track->mChannelMask;
2841 fastTrack->mGeneration++;
2842 state->mTrackMask |= 1 << j;
2843 didModify = true;
2844 // no acknowledgement required for newly active tracks
2845 }
2846 // cache the combined master volume and stream type volume for fast mixer; this
2847 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002848 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002849 ++fastTracks;
2850 } else {
2851 // was it previously active?
2852 if (state->mTrackMask & (1 << j)) {
2853 fastTrack->mBufferProvider = NULL;
2854 fastTrack->mGeneration++;
2855 state->mTrackMask &= ~(1 << j);
2856 didModify = true;
2857 // If any fast tracks were removed, we must wait for acknowledgement
2858 // because we're about to decrement the last sp<> on those tracks.
2859 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2860 } else {
2861 LOG_FATAL("fast track %d should have been active", j);
2862 }
2863 tracksToRemove->add(track);
2864 // Avoids a misleading display in dumpsys
2865 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2866 }
2867 continue;
2868 }
2869
2870 { // local variable scope to avoid goto warning
2871
2872 audio_track_cblk_t* cblk = track->cblk();
2873
2874 // The first time a track is added we wait
2875 // for all its buffers to be filled before processing it
2876 int name = track->name();
2877 // make sure that we have enough frames to mix one full buffer.
2878 // enforce this condition only once to enable draining the buffer in case the client
2879 // app does not call stop() and relies on underrun to stop:
2880 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2881 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002882 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002883 uint32_t sr = track->sampleRate();
2884 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002885 desiredFrames = mNormalFrameCount;
2886 } else {
2887 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002888 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002889 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002890 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002891 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2892 // the minimum track buffer size is normally twice the number of frames necessary
2893 // to fill one buffer and the resampler should not leave more than one buffer worth
2894 // of unreleased frames after each pass, but just in case...
2895 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2896 }
Eric Laurent81784c32012-11-19 14:55:58 -08002897 uint32_t minFrames = 1;
2898 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2899 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002900 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002902 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2903 size_t framesReady;
2904 if (track->sharedBuffer() == 0) {
2905 framesReady = track->framesReady();
2906 } else if (track->isStopped()) {
2907 framesReady = 0;
2908 } else {
2909 framesReady = 1;
2910 }
2911 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002912 !track->isPaused() && !track->isTerminated())
2913 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002914 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002915
2916 mixedTracks++;
2917
2918 // track->mainBuffer() != mMixBuffer means there is an effect chain
2919 // connected to the track
2920 chain.clear();
2921 if (track->mainBuffer() != mMixBuffer) {
2922 chain = getEffectChain_l(track->sessionId());
2923 // Delegate volume control to effect in track effect chain if needed
2924 if (chain != 0) {
2925 tracksWithEffect++;
2926 } else {
2927 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2928 "session %d",
2929 name, track->sessionId());
2930 }
2931 }
2932
2933
2934 int param = AudioMixer::VOLUME;
2935 if (track->mFillingUpStatus == Track::FS_FILLED) {
2936 // no ramp for the first volume setting
2937 track->mFillingUpStatus = Track::FS_ACTIVE;
2938 if (track->mState == TrackBase::RESUMING) {
2939 track->mState = TrackBase::ACTIVE;
2940 param = AudioMixer::RAMP_VOLUME;
2941 }
2942 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002943 // FIXME should not make a decision based on mServer
2944 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002945 // If the track is stopped before the first frame was mixed,
2946 // do not apply ramp
2947 param = AudioMixer::RAMP_VOLUME;
2948 }
2949
2950 // compute volume for this track
2951 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002952 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002953 vl = vr = va = 0;
2954 if (track->isPausing()) {
2955 track->setPaused();
2956 }
2957 } else {
2958
2959 // read original volumes with volume control
2960 float typeVolume = mStreamTypes[track->streamType()].volume;
2961 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002962 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002963 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002964 vl = vlr & 0xFFFF;
2965 vr = vlr >> 16;
2966 // track volumes come from shared memory, so can't be trusted and must be clamped
2967 if (vl > MAX_GAIN_INT) {
2968 ALOGV("Track left volume out of range: %04X", vl);
2969 vl = MAX_GAIN_INT;
2970 }
2971 if (vr > MAX_GAIN_INT) {
2972 ALOGV("Track right volume out of range: %04X", vr);
2973 vr = MAX_GAIN_INT;
2974 }
2975 // now apply the master volume and stream type volume
2976 vl = (uint32_t)(v * vl) << 12;
2977 vr = (uint32_t)(v * vr) << 12;
2978 // assuming master volume and stream type volume each go up to 1.0,
2979 // vl and vr are now in 8.24 format
2980
Glenn Kastene3aa6592012-12-04 12:22:46 -08002981 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08002982 // send level comes from shared memory and so may be corrupt
2983 if (sendLevel > MAX_GAIN_INT) {
2984 ALOGV("Track send level out of range: %04X", sendLevel);
2985 sendLevel = MAX_GAIN_INT;
2986 }
2987 va = (uint32_t)(v * sendLevel);
2988 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989
Eric Laurent81784c32012-11-19 14:55:58 -08002990 // Delegate volume control to effect in track effect chain if needed
2991 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2992 // Do not ramp volume if volume is controlled by effect
2993 param = AudioMixer::VOLUME;
2994 track->mHasVolumeController = true;
2995 } else {
2996 // force no volume ramp when volume controller was just disabled or removed
2997 // from effect chain to avoid volume spike
2998 if (track->mHasVolumeController) {
2999 param = AudioMixer::VOLUME;
3000 }
3001 track->mHasVolumeController = false;
3002 }
3003
3004 // Convert volumes from 8.24 to 4.12 format
3005 // This additional clamping is needed in case chain->setVolume_l() overshot
3006 vl = (vl + (1 << 11)) >> 12;
3007 if (vl > MAX_GAIN_INT) {
3008 vl = MAX_GAIN_INT;
3009 }
3010 vr = (vr + (1 << 11)) >> 12;
3011 if (vr > MAX_GAIN_INT) {
3012 vr = MAX_GAIN_INT;
3013 }
3014
3015 if (va > MAX_GAIN_INT) {
3016 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3017 }
3018
3019 // XXX: these things DON'T need to be done each time
3020 mAudioMixer->setBufferProvider(name, track);
3021 mAudioMixer->enable(name);
3022
3023 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3024 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3025 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3026 mAudioMixer->setParameter(
3027 name,
3028 AudioMixer::TRACK,
3029 AudioMixer::FORMAT, (void *)track->format());
3030 mAudioMixer->setParameter(
3031 name,
3032 AudioMixer::TRACK,
3033 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003034 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3035 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003036 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003037 if (reqSampleRate == 0) {
3038 reqSampleRate = mSampleRate;
3039 } else if (reqSampleRate > maxSampleRate) {
3040 reqSampleRate = maxSampleRate;
3041 }
Eric Laurent81784c32012-11-19 14:55:58 -08003042 mAudioMixer->setParameter(
3043 name,
3044 AudioMixer::RESAMPLE,
3045 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003046 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003047 mAudioMixer->setParameter(
3048 name,
3049 AudioMixer::TRACK,
3050 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3051 mAudioMixer->setParameter(
3052 name,
3053 AudioMixer::TRACK,
3054 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3055
3056 // reset retry count
3057 track->mRetryCount = kMaxTrackRetries;
3058
3059 // If one track is ready, set the mixer ready if:
3060 // - the mixer was not ready during previous round OR
3061 // - no other track is not ready
3062 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3063 mixerStatus != MIXER_TRACKS_ENABLED) {
3064 mixerStatus = MIXER_TRACKS_READY;
3065 }
3066 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003067 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003068 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070 // clear effect chain input buffer if an active track underruns to avoid sending
3071 // previous audio buffer again to effects
3072 chain = getEffectChain_l(track->sessionId());
3073 if (chain != 0) {
3074 chain->clearInputBuffer();
3075 }
3076
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003077 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003078 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3079 track->isStopped() || track->isPaused()) {
3080 // We have consumed all the buffers of this track.
3081 // Remove it from the list of active tracks.
3082 // TODO: use actual buffer filling status instead of latency when available from
3083 // audio HAL
3084 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3085 size_t framesWritten = mBytesWritten / mFrameSize;
3086 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3087 if (track->isStopped()) {
3088 track->reset();
3089 }
3090 tracksToRemove->add(track);
3091 }
3092 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // No buffers for this track. Give it a few chances to
3094 // fill a buffer, then remove it from active list.
3095 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003096 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003097 tracksToRemove->add(track);
3098 // indicate to client process that the track was disabled because of underrun;
3099 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003100 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003101 // If one track is not ready, mark the mixer also not ready if:
3102 // - the mixer was ready during previous round OR
3103 // - no other track is ready
3104 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3105 mixerStatus != MIXER_TRACKS_READY) {
3106 mixerStatus = MIXER_TRACKS_ENABLED;
3107 }
3108 }
3109 mAudioMixer->disable(name);
3110 }
3111
3112 } // local variable scope to avoid goto warning
3113track_is_ready: ;
3114
3115 }
3116
3117 // Push the new FastMixer state if necessary
3118 bool pauseAudioWatchdog = false;
3119 if (didModify) {
3120 state->mFastTracksGen++;
3121 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3122 if (kUseFastMixer == FastMixer_Dynamic &&
3123 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3124 state->mCommand = FastMixerState::COLD_IDLE;
3125 state->mColdFutexAddr = &mFastMixerFutex;
3126 state->mColdGen++;
3127 mFastMixerFutex = 0;
3128 if (kUseFastMixer == FastMixer_Dynamic) {
3129 mNormalSink = mOutputSink;
3130 }
3131 // If we go into cold idle, need to wait for acknowledgement
3132 // so that fast mixer stops doing I/O.
3133 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3134 pauseAudioWatchdog = true;
3135 }
Eric Laurent81784c32012-11-19 14:55:58 -08003136 }
3137 if (sq != NULL) {
3138 sq->end(didModify);
3139 sq->push(block);
3140 }
3141#ifdef AUDIO_WATCHDOG
3142 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3143 mAudioWatchdog->pause();
3144 }
3145#endif
3146
3147 // Now perform the deferred reset on fast tracks that have stopped
3148 while (resetMask != 0) {
3149 size_t i = __builtin_ctz(resetMask);
3150 ALOG_ASSERT(i < count);
3151 resetMask &= ~(1 << i);
3152 sp<Track> t = mActiveTracks[i].promote();
3153 if (t == 0) {
3154 continue;
3155 }
3156 Track* track = t.get();
3157 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3158 track->reset();
3159 }
3160
3161 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003163
3164 // mix buffer must be cleared if all tracks are connected to an
3165 // effect chain as in this case the mixer will not write to
3166 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003167 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3168 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003169 // FIXME as a performance optimization, should remember previous zero status
3170 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3171 }
3172
3173 // if any fast tracks, then status is ready
3174 mMixerStatusIgnoringFastTracks = mixerStatus;
3175 if (fastTracks > 0) {
3176 mixerStatus = MIXER_TRACKS_READY;
3177 }
3178 return mixerStatus;
3179}
3180
3181// getTrackName_l() must be called with ThreadBase::mLock held
3182int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3183{
3184 return mAudioMixer->getTrackName(channelMask, sessionId);
3185}
3186
3187// deleteTrackName_l() must be called with ThreadBase::mLock held
3188void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3189{
3190 ALOGV("remove track (%d) and delete from mixer", name);
3191 mAudioMixer->deleteTrackName(name);
3192}
3193
3194// checkForNewParameters_l() must be called with ThreadBase::mLock held
3195bool AudioFlinger::MixerThread::checkForNewParameters_l()
3196{
3197 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3198 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3199 bool reconfig = false;
3200
3201 while (!mNewParameters.isEmpty()) {
3202
3203 if (mFastMixer != NULL) {
3204 FastMixerStateQueue *sq = mFastMixer->sq();
3205 FastMixerState *state = sq->begin();
3206 if (!(state->mCommand & FastMixerState::IDLE)) {
3207 previousCommand = state->mCommand;
3208 state->mCommand = FastMixerState::HOT_IDLE;
3209 sq->end();
3210 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3211 } else {
3212 sq->end(false /*didModify*/);
3213 }
3214 }
3215
3216 status_t status = NO_ERROR;
3217 String8 keyValuePair = mNewParameters[0];
3218 AudioParameter param = AudioParameter(keyValuePair);
3219 int value;
3220
3221 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3222 reconfig = true;
3223 }
3224 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3225 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3226 status = BAD_VALUE;
3227 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003228 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003229 reconfig = true;
3230 }
3231 }
3232 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003233 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003234 status = BAD_VALUE;
3235 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003236 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003237 reconfig = true;
3238 }
3239 }
3240 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3241 // do not accept frame count changes if tracks are open as the track buffer
3242 // size depends on frame count and correct behavior would not be guaranteed
3243 // if frame count is changed after track creation
3244 if (!mTracks.isEmpty()) {
3245 status = INVALID_OPERATION;
3246 } else {
3247 reconfig = true;
3248 }
3249 }
3250 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3251#ifdef ADD_BATTERY_DATA
3252 // when changing the audio output device, call addBatteryData to notify
3253 // the change
3254 if (mOutDevice != value) {
3255 uint32_t params = 0;
3256 // check whether speaker is on
3257 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3258 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3259 }
3260
3261 audio_devices_t deviceWithoutSpeaker
3262 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3263 // check if any other device (except speaker) is on
3264 if (value & deviceWithoutSpeaker ) {
3265 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3266 }
3267
3268 if (params != 0) {
3269 addBatteryData(params);
3270 }
3271 }
3272#endif
3273
3274 // forward device change to effects that have requested to be
3275 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003276 if (value != AUDIO_DEVICE_NONE) {
3277 mOutDevice = value;
3278 for (size_t i = 0; i < mEffectChains.size(); i++) {
3279 mEffectChains[i]->setDevice_l(mOutDevice);
3280 }
Eric Laurent81784c32012-11-19 14:55:58 -08003281 }
3282 }
3283
3284 if (status == NO_ERROR) {
3285 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3286 keyValuePair.string());
3287 if (!mStandby && status == INVALID_OPERATION) {
3288 mOutput->stream->common.standby(&mOutput->stream->common);
3289 mStandby = true;
3290 mBytesWritten = 0;
3291 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3292 keyValuePair.string());
3293 }
3294 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003295 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003296 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003297 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3298 for (size_t i = 0; i < mTracks.size() ; i++) {
3299 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3300 if (name < 0) {
3301 break;
3302 }
3303 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003304 }
3305 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3306 }
3307 }
3308
3309 mNewParameters.removeAt(0);
3310
3311 mParamStatus = status;
3312 mParamCond.signal();
3313 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3314 // already timed out waiting for the status and will never signal the condition.
3315 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3316 }
3317
3318 if (!(previousCommand & FastMixerState::IDLE)) {
3319 ALOG_ASSERT(mFastMixer != NULL);
3320 FastMixerStateQueue *sq = mFastMixer->sq();
3321 FastMixerState *state = sq->begin();
3322 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3323 state->mCommand = previousCommand;
3324 sq->end();
3325 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3326 }
3327
3328 return reconfig;
3329}
3330
3331
3332void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3333{
3334 const size_t SIZE = 256;
3335 char buffer[SIZE];
3336 String8 result;
3337
3338 PlaybackThread::dumpInternals(fd, args);
3339
3340 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3341 result.append(buffer);
3342 write(fd, result.string(), result.size());
3343
3344 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003345 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003346 copy.dump(fd);
3347
3348#ifdef STATE_QUEUE_DUMP
3349 // Similar for state queue
3350 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3351 observerCopy.dump(fd);
3352 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3353 mutatorCopy.dump(fd);
3354#endif
3355
Glenn Kasten46909e72013-02-26 09:20:22 -08003356#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003357 // Write the tee output to a .wav file
3358 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003359#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003360
3361#ifdef AUDIO_WATCHDOG
3362 if (mAudioWatchdog != 0) {
3363 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3364 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3365 wdCopy.dump(fd);
3366 }
3367#endif
3368}
3369
3370uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3371{
3372 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3373}
3374
3375uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3376{
3377 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3378}
3379
3380void AudioFlinger::MixerThread::cacheParameters_l()
3381{
3382 PlaybackThread::cacheParameters_l();
3383
3384 // FIXME: Relaxed timing because of a certain device that can't meet latency
3385 // Should be reduced to 2x after the vendor fixes the driver issue
3386 // increase threshold again due to low power audio mode. The way this warning
3387 // threshold is calculated and its usefulness should be reconsidered anyway.
3388 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3389}
3390
3391// ----------------------------------------------------------------------------
3392
3393AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3394 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3395 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3396 // mLeftVolFloat, mRightVolFloat
3397{
3398}
3399
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3401 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3402 ThreadBase::type_t type)
3403 : PlaybackThread(audioFlinger, output, id, device, type)
3404 // mLeftVolFloat, mRightVolFloat
3405{
3406}
3407
Eric Laurent81784c32012-11-19 14:55:58 -08003408AudioFlinger::DirectOutputThread::~DirectOutputThread()
3409{
3410}
3411
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3413{
3414 audio_track_cblk_t* cblk = track->cblk();
3415 float left, right;
3416
3417 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3418 left = right = 0;
3419 } else {
3420 float typeVolume = mStreamTypes[track->streamType()].volume;
3421 float v = mMasterVolume * typeVolume;
3422 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3423 uint32_t vlr = proxy->getVolumeLR();
3424 float v_clamped = v * (vlr & 0xFFFF);
3425 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3426 left = v_clamped/MAX_GAIN;
3427 v_clamped = v * (vlr >> 16);
3428 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3429 right = v_clamped/MAX_GAIN;
3430 }
3431
3432 if (lastTrack) {
3433 if (left != mLeftVolFloat || right != mRightVolFloat) {
3434 mLeftVolFloat = left;
3435 mRightVolFloat = right;
3436
3437 // Convert volumes from float to 8.24
3438 uint32_t vl = (uint32_t)(left * (1 << 24));
3439 uint32_t vr = (uint32_t)(right * (1 << 24));
3440
3441 // Delegate volume control to effect in track effect chain if needed
3442 // only one effect chain can be present on DirectOutputThread, so if
3443 // there is one, the track is connected to it
3444 if (!mEffectChains.isEmpty()) {
3445 mEffectChains[0]->setVolume_l(&vl, &vr);
3446 left = (float)vl / (1 << 24);
3447 right = (float)vr / (1 << 24);
3448 }
3449 if (mOutput->stream->set_volume) {
3450 mOutput->stream->set_volume(mOutput->stream, left, right);
3451 }
3452 }
3453 }
3454}
3455
3456
Eric Laurent81784c32012-11-19 14:55:58 -08003457AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3458 Vector< sp<Track> > *tracksToRemove
3459)
3460{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003461 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003462 mixer_state mixerStatus = MIXER_IDLE;
3463
3464 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003465 for (size_t i = 0; i < count; i++) {
3466 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // The track died recently
3468 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003469 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003470 }
3471
3472 Track* const track = t.get();
3473 audio_track_cblk_t* cblk = track->cblk();
3474
3475 // The first time a track is added we wait
3476 // for all its buffers to be filled before processing it
3477 uint32_t minFrames;
3478 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3479 minFrames = mNormalFrameCount;
3480 } else {
3481 minFrames = 1;
3482 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003483 // Only consider last track started for volume and mixer state control.
3484 // This is the last entry in mActiveTracks unless a track underruns.
3485 // As we only care about the transition phase between two tracks on a
3486 // direct output, it is not a problem to ignore the underrun case.
3487 bool last = (i == (count - 1));
3488
Eric Laurent81784c32012-11-19 14:55:58 -08003489 if ((track->framesReady() >= minFrames) && track->isReady() &&
3490 !track->isPaused() && !track->isTerminated())
3491 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003492 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003493
3494 if (track->mFillingUpStatus == Track::FS_FILLED) {
3495 track->mFillingUpStatus = Track::FS_ACTIVE;
3496 mLeftVolFloat = mRightVolFloat = 0;
3497 if (track->mState == TrackBase::RESUMING) {
3498 track->mState = TrackBase::ACTIVE;
3499 }
3500 }
3501
3502 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 processVolume_l(track, last);
3504 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003505 // reset retry count
3506 track->mRetryCount = kMaxTrackRetriesDirect;
3507 mActiveTrack = t;
3508 mixerStatus = MIXER_TRACKS_READY;
3509 }
Eric Laurent81784c32012-11-19 14:55:58 -08003510 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003511 // clear effect chain input buffer if the last active track started underruns
3512 // to avoid sending previous audio buffer again to effects
3513 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003514 mEffectChains[0]->clearInputBuffer();
3515 }
3516
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003517 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003518 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3519 track->isStopped() || track->isPaused()) {
3520 // We have consumed all the buffers of this track.
3521 // Remove it from the list of active tracks.
3522 // TODO: implement behavior for compressed audio
3523 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3524 size_t framesWritten = mBytesWritten / mFrameSize;
3525 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3526 if (track->isStopped()) {
3527 track->reset();
3528 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003529 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003530 }
3531 } else {
3532 // No buffers for this track. Give it a few chances to
3533 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003534 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003535 if (--(track->mRetryCount) <= 0) {
3536 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003537 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003539 mixerStatus = MIXER_TRACKS_ENABLED;
3540 }
3541 }
3542 }
3543 }
3544
Eric Laurent81784c32012-11-19 14:55:58 -08003545 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003546 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003547
3548 return mixerStatus;
3549}
3550
3551void AudioFlinger::DirectOutputThread::threadLoop_mix()
3552{
Eric Laurent81784c32012-11-19 14:55:58 -08003553 size_t frameCount = mFrameCount;
3554 int8_t *curBuf = (int8_t *)mMixBuffer;
3555 // output audio to hardware
3556 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003557 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003558 buffer.frameCount = frameCount;
3559 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003560 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003561 memset(curBuf, 0, frameCount * mFrameSize);
3562 break;
3563 }
3564 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3565 frameCount -= buffer.frameCount;
3566 curBuf += buffer.frameCount * mFrameSize;
3567 mActiveTrack->releaseBuffer(&buffer);
3568 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003570 sleepTime = 0;
3571 standbyTime = systemTime() + standbyDelay;
3572 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003573}
3574
3575void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3576{
3577 if (sleepTime == 0) {
3578 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3579 sleepTime = activeSleepTime;
3580 } else {
3581 sleepTime = idleSleepTime;
3582 }
3583 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3584 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3585 sleepTime = 0;
3586 }
3587}
3588
3589// getTrackName_l() must be called with ThreadBase::mLock held
3590int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3591 int sessionId)
3592{
3593 return 0;
3594}
3595
3596// deleteTrackName_l() must be called with ThreadBase::mLock held
3597void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3598{
3599}
3600
3601// checkForNewParameters_l() must be called with ThreadBase::mLock held
3602bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3603{
3604 bool reconfig = false;
3605
3606 while (!mNewParameters.isEmpty()) {
3607 status_t status = NO_ERROR;
3608 String8 keyValuePair = mNewParameters[0];
3609 AudioParameter param = AudioParameter(keyValuePair);
3610 int value;
3611
3612 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3613 // do not accept frame count changes if tracks are open as the track buffer
3614 // size depends on frame count and correct behavior would not be garantied
3615 // if frame count is changed after track creation
3616 if (!mTracks.isEmpty()) {
3617 status = INVALID_OPERATION;
3618 } else {
3619 reconfig = true;
3620 }
3621 }
3622 if (status == NO_ERROR) {
3623 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3624 keyValuePair.string());
3625 if (!mStandby && status == INVALID_OPERATION) {
3626 mOutput->stream->common.standby(&mOutput->stream->common);
3627 mStandby = true;
3628 mBytesWritten = 0;
3629 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3630 keyValuePair.string());
3631 }
3632 if (status == NO_ERROR && reconfig) {
3633 readOutputParameters();
3634 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3635 }
3636 }
3637
3638 mNewParameters.removeAt(0);
3639
3640 mParamStatus = status;
3641 mParamCond.signal();
3642 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3643 // already timed out waiting for the status and will never signal the condition.
3644 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3645 }
3646 return reconfig;
3647}
3648
3649uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3650{
3651 uint32_t time;
3652 if (audio_is_linear_pcm(mFormat)) {
3653 time = PlaybackThread::activeSleepTimeUs();
3654 } else {
3655 time = 10000;
3656 }
3657 return time;
3658}
3659
3660uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3661{
3662 uint32_t time;
3663 if (audio_is_linear_pcm(mFormat)) {
3664 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3665 } else {
3666 time = 10000;
3667 }
3668 return time;
3669}
3670
3671uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3672{
3673 uint32_t time;
3674 if (audio_is_linear_pcm(mFormat)) {
3675 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3676 } else {
3677 time = 10000;
3678 }
3679 return time;
3680}
3681
3682void AudioFlinger::DirectOutputThread::cacheParameters_l()
3683{
3684 PlaybackThread::cacheParameters_l();
3685
3686 // use shorter standby delay as on normal output to release
3687 // hardware resources as soon as possible
3688 standbyDelay = microseconds(activeSleepTime*2);
3689}
3690
3691// ----------------------------------------------------------------------------
3692
Eric Laurentbfb1b832013-01-07 09:53:42 -08003693AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3694 const sp<AudioFlinger::OffloadThread>& offloadThread)
3695 : Thread(false /*canCallJava*/),
3696 mOffloadThread(offloadThread),
3697 mWriteBlocked(false),
3698 mDraining(false)
3699{
3700}
3701
3702AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3703{
3704}
3705
3706void AudioFlinger::AsyncCallbackThread::onFirstRef()
3707{
3708 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3709}
3710
3711bool AudioFlinger::AsyncCallbackThread::threadLoop()
3712{
3713 while (!exitPending()) {
3714 bool writeBlocked;
3715 bool draining;
3716
3717 {
3718 Mutex::Autolock _l(mLock);
3719 mWaitWorkCV.wait(mLock);
3720 if (exitPending()) {
3721 break;
3722 }
3723 writeBlocked = mWriteBlocked;
3724 draining = mDraining;
3725 ALOGV("AsyncCallbackThread mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3726 }
3727 {
3728 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3729 if (offloadThread != 0) {
3730 if (writeBlocked == false) {
3731 offloadThread->setWriteBlocked(false);
3732 }
3733 if (draining == false) {
3734 offloadThread->setDraining(false);
3735 }
3736 }
3737 }
3738 }
3739 return false;
3740}
3741
3742void AudioFlinger::AsyncCallbackThread::exit()
3743{
3744 ALOGV("AsyncCallbackThread::exit");
3745 Mutex::Autolock _l(mLock);
3746 requestExit();
3747 mWaitWorkCV.broadcast();
3748}
3749
3750void AudioFlinger::AsyncCallbackThread::setWriteBlocked(bool value)
3751{
3752 Mutex::Autolock _l(mLock);
3753 mWriteBlocked = value;
3754 if (!value) {
3755 mWaitWorkCV.signal();
3756 }
3757}
3758
3759void AudioFlinger::AsyncCallbackThread::setDraining(bool value)
3760{
3761 Mutex::Autolock _l(mLock);
3762 mDraining = value;
3763 if (!value) {
3764 mWaitWorkCV.signal();
3765 }
3766}
3767
3768
3769// ----------------------------------------------------------------------------
3770AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3771 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3772 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3773 mHwPaused(false),
3774 mPausedBytesRemaining(0)
3775{
3776 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3777}
3778
3779AudioFlinger::OffloadThread::~OffloadThread()
3780{
3781 mPreviousTrack.clear();
3782}
3783
3784void AudioFlinger::OffloadThread::threadLoop_exit()
3785{
3786 if (mFlushPending || mHwPaused) {
3787 // If a flush is pending or track was paused, just discard buffered data
3788 flushHw_l();
3789 } else {
3790 mMixerStatus = MIXER_DRAIN_ALL;
3791 threadLoop_drain();
3792 }
3793 mCallbackThread->exit();
3794 PlaybackThread::threadLoop_exit();
3795}
3796
3797AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3798 Vector< sp<Track> > *tracksToRemove
3799)
3800{
3801 ALOGV("OffloadThread::prepareTracks_l");
3802 size_t count = mActiveTracks.size();
3803
3804 mixer_state mixerStatus = MIXER_IDLE;
3805 if (mFlushPending) {
3806 flushHw_l();
3807 mFlushPending = false;
3808 }
3809 // find out which tracks need to be processed
3810 for (size_t i = 0; i < count; i++) {
3811 sp<Track> t = mActiveTracks[i].promote();
3812 // The track died recently
3813 if (t == 0) {
3814 continue;
3815 }
3816 Track* const track = t.get();
3817 audio_track_cblk_t* cblk = track->cblk();
3818 if (mPreviousTrack != NULL) {
3819 if (t != mPreviousTrack) {
3820 // Flush any data still being written from last track
3821 mBytesRemaining = 0;
3822 if (mPausedBytesRemaining) {
3823 // Last track was paused so we also need to flush saved
3824 // mixbuffer state and invalidate track so that it will
3825 // re-submit that unwritten data when it is next resumed
3826 mPausedBytesRemaining = 0;
3827 // Invalidate is a bit drastic - would be more efficient
3828 // to have a flag to tell client that some of the
3829 // previously written data was lost
3830 mPreviousTrack->invalidate();
3831 }
3832 }
3833 }
3834 mPreviousTrack = t;
3835 bool last = (i == (count - 1));
3836 if (track->isPausing()) {
3837 track->setPaused();
3838 if (last) {
3839 if (!mHwPaused) {
3840 mOutput->stream->pause(mOutput->stream);
3841 mHwPaused = true;
3842 }
3843 // If we were part way through writing the mixbuffer to
3844 // the HAL we must save this until we resume
3845 // BUG - this will be wrong if a different track is made active,
3846 // in that case we want to discard the pending data in the
3847 // mixbuffer and tell the client to present it again when the
3848 // track is resumed
3849 mPausedWriteLength = mCurrentWriteLength;
3850 mPausedBytesRemaining = mBytesRemaining;
3851 mBytesRemaining = 0; // stop writing
3852 }
3853 tracksToRemove->add(track);
3854 } else if (track->framesReady() && track->isReady() &&
3855 !track->isPaused() && !track->isTerminated()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003856 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857 if (track->mFillingUpStatus == Track::FS_FILLED) {
3858 track->mFillingUpStatus = Track::FS_ACTIVE;
3859 mLeftVolFloat = mRightVolFloat = 0;
3860 if (track->mState == TrackBase::RESUMING) {
Glenn Kastenfa319e62013-07-29 17:17:38 -07003861 if (mPausedBytesRemaining) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003862 // Need to continue write that was interrupted
3863 mCurrentWriteLength = mPausedWriteLength;
3864 mBytesRemaining = mPausedBytesRemaining;
3865 mPausedBytesRemaining = 0;
3866 }
3867 track->mState = TrackBase::ACTIVE;
3868 }
3869 }
3870
3871 if (last) {
3872 if (mHwPaused) {
3873 mOutput->stream->resume(mOutput->stream);
3874 mHwPaused = false;
3875 // threadLoop_mix() will handle the case that we need to
3876 // resume an interrupted write
3877 }
3878 // reset retry count
3879 track->mRetryCount = kMaxTrackRetriesOffload;
3880 mActiveTrack = t;
3881 mixerStatus = MIXER_TRACKS_READY;
3882 }
3883 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003884 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 if (track->isStopping_1()) {
3886 // Hardware buffer can hold a large amount of audio so we must
3887 // wait for all current track's data to drain before we say
3888 // that the track is stopped.
3889 if (mBytesRemaining == 0) {
3890 // Only start draining when all data in mixbuffer
3891 // has been written
3892 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3893 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3894 sleepTime = 0;
3895 standbyTime = systemTime() + standbyDelay;
3896 if (last) {
3897 mixerStatus = MIXER_DRAIN_TRACK;
3898 if (mHwPaused) {
3899 // It is possible to move from PAUSED to STOPPING_1 without
3900 // a resume so we must ensure hardware is running
3901 mOutput->stream->resume(mOutput->stream);
3902 mHwPaused = false;
3903 }
3904 }
3905 }
3906 } else if (track->isStopping_2()) {
3907 // Drain has completed, signal presentation complete
3908 if (!mDraining || !last) {
3909 track->mState = TrackBase::STOPPED;
3910 size_t audioHALFrames =
3911 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3912 size_t framesWritten =
3913 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3914 track->presentationComplete(framesWritten, audioHALFrames);
3915 track->reset();
3916 tracksToRemove->add(track);
3917 }
3918 } else {
3919 // No buffers for this track. Give it a few chances to
3920 // fill a buffer, then remove it from active list.
3921 if (--(track->mRetryCount) <= 0) {
3922 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3923 track->name());
3924 tracksToRemove->add(track);
3925 } else if (last){
3926 mixerStatus = MIXER_TRACKS_ENABLED;
3927 }
3928 }
3929 }
3930 // compute volume for this track
3931 processVolume_l(track, last);
3932 }
3933 // remove all the tracks that need to be...
3934 removeTracks_l(*tracksToRemove);
3935
3936 return mixerStatus;
3937}
3938
3939void AudioFlinger::OffloadThread::flushOutput_l()
3940{
3941 mFlushPending = true;
3942}
3943
3944// must be called with thread mutex locked
3945bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
3946{
3947 ALOGV("waitingAsyncCallback_l mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3948 if (mUseAsyncWrite && (mWriteBlocked || mDraining)) {
3949 return true;
3950 }
3951 return false;
3952}
3953
3954// must be called with thread mutex locked
3955bool AudioFlinger::OffloadThread::shouldStandby_l()
3956{
3957 bool TrackPaused = false;
3958
3959 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
3960 // after a timeout and we will enter standby then.
3961 if (mTracks.size() > 0) {
3962 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
3963 }
3964
3965 return !mStandby && !TrackPaused;
3966}
3967
3968
3969bool AudioFlinger::OffloadThread::waitingAsyncCallback()
3970{
3971 Mutex::Autolock _l(mLock);
3972 return waitingAsyncCallback_l();
3973}
3974
3975void AudioFlinger::OffloadThread::flushHw_l()
3976{
3977 mOutput->stream->flush(mOutput->stream);
3978 // Flush anything still waiting in the mixbuffer
3979 mCurrentWriteLength = 0;
3980 mBytesRemaining = 0;
3981 mPausedWriteLength = 0;
3982 mPausedBytesRemaining = 0;
3983 if (mUseAsyncWrite) {
3984 mWriteBlocked = false;
3985 mDraining = false;
3986 ALOG_ASSERT(mCallbackThread != 0);
3987 mCallbackThread->setWriteBlocked(false);
3988 mCallbackThread->setDraining(false);
3989 }
3990}
3991
3992// ----------------------------------------------------------------------------
3993
Eric Laurent81784c32012-11-19 14:55:58 -08003994AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3995 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3996 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3997 DUPLICATING),
3998 mWaitTimeMs(UINT_MAX)
3999{
4000 addOutputTrack(mainThread);
4001}
4002
4003AudioFlinger::DuplicatingThread::~DuplicatingThread()
4004{
4005 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4006 mOutputTracks[i]->destroy();
4007 }
4008}
4009
4010void AudioFlinger::DuplicatingThread::threadLoop_mix()
4011{
4012 // mix buffers...
4013 if (outputsReady(outputTracks)) {
4014 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4015 } else {
4016 memset(mMixBuffer, 0, mixBufferSize);
4017 }
4018 sleepTime = 0;
4019 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004021 standbyTime = systemTime() + standbyDelay;
4022}
4023
4024void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4025{
4026 if (sleepTime == 0) {
4027 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4028 sleepTime = activeSleepTime;
4029 } else {
4030 sleepTime = idleSleepTime;
4031 }
4032 } else if (mBytesWritten != 0) {
4033 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4034 writeFrames = mNormalFrameCount;
4035 memset(mMixBuffer, 0, mixBufferSize);
4036 } else {
4037 // flush remaining overflow buffers in output tracks
4038 writeFrames = 0;
4039 }
4040 sleepTime = 0;
4041 }
4042}
4043
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004045{
4046 for (size_t i = 0; i < outputTracks.size(); i++) {
4047 outputTracks[i]->write(mMixBuffer, writeFrames);
4048 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004050}
4051
4052void AudioFlinger::DuplicatingThread::threadLoop_standby()
4053{
4054 // DuplicatingThread implements standby by stopping all tracks
4055 for (size_t i = 0; i < outputTracks.size(); i++) {
4056 outputTracks[i]->stop();
4057 }
4058}
4059
4060void AudioFlinger::DuplicatingThread::saveOutputTracks()
4061{
4062 outputTracks = mOutputTracks;
4063}
4064
4065void AudioFlinger::DuplicatingThread::clearOutputTracks()
4066{
4067 outputTracks.clear();
4068}
4069
4070void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4071{
4072 Mutex::Autolock _l(mLock);
4073 // FIXME explain this formula
4074 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4075 OutputTrack *outputTrack = new OutputTrack(thread,
4076 this,
4077 mSampleRate,
4078 mFormat,
4079 mChannelMask,
4080 frameCount);
4081 if (outputTrack->cblk() != NULL) {
4082 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4083 mOutputTracks.add(outputTrack);
4084 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4085 updateWaitTime_l();
4086 }
4087}
4088
4089void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4090{
4091 Mutex::Autolock _l(mLock);
4092 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4093 if (mOutputTracks[i]->thread() == thread) {
4094 mOutputTracks[i]->destroy();
4095 mOutputTracks.removeAt(i);
4096 updateWaitTime_l();
4097 return;
4098 }
4099 }
4100 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4101}
4102
4103// caller must hold mLock
4104void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4105{
4106 mWaitTimeMs = UINT_MAX;
4107 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4108 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4109 if (strong != 0) {
4110 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4111 if (waitTimeMs < mWaitTimeMs) {
4112 mWaitTimeMs = waitTimeMs;
4113 }
4114 }
4115 }
4116}
4117
4118
4119bool AudioFlinger::DuplicatingThread::outputsReady(
4120 const SortedVector< sp<OutputTrack> > &outputTracks)
4121{
4122 for (size_t i = 0; i < outputTracks.size(); i++) {
4123 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4124 if (thread == 0) {
4125 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4126 outputTracks[i].get());
4127 return false;
4128 }
4129 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4130 // see note at standby() declaration
4131 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4132 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4133 thread.get());
4134 return false;
4135 }
4136 }
4137 return true;
4138}
4139
4140uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4141{
4142 return (mWaitTimeMs * 1000) / 2;
4143}
4144
4145void AudioFlinger::DuplicatingThread::cacheParameters_l()
4146{
4147 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4148 updateWaitTime_l();
4149
4150 MixerThread::cacheParameters_l();
4151}
4152
4153// ----------------------------------------------------------------------------
4154// Record
4155// ----------------------------------------------------------------------------
4156
4157AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4158 AudioStreamIn *input,
4159 uint32_t sampleRate,
4160 audio_channel_mask_t channelMask,
4161 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004162 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004163 audio_devices_t inDevice
4164#ifdef TEE_SINK
4165 , const sp<NBAIO_Sink>& teeSink
4166#endif
4167 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004168 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004169 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004170 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004171 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004172 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004173 // mBytesRead is only meaningful while active, and so is cleared in start()
4174 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004175#ifdef TEE_SINK
4176 , mTeeSink(teeSink)
4177#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004178{
4179 snprintf(mName, kNameLength, "AudioIn_%X", id);
4180
4181 readInputParameters();
4182
4183}
4184
4185
4186AudioFlinger::RecordThread::~RecordThread()
4187{
4188 delete[] mRsmpInBuffer;
4189 delete mResampler;
4190 delete[] mRsmpOutBuffer;
4191}
4192
4193void AudioFlinger::RecordThread::onFirstRef()
4194{
4195 run(mName, PRIORITY_URGENT_AUDIO);
4196}
4197
Eric Laurent81784c32012-11-19 14:55:58 -08004198bool AudioFlinger::RecordThread::threadLoop()
4199{
4200 AudioBufferProvider::Buffer buffer;
4201 sp<RecordTrack> activeTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004202
4203 nsecs_t lastWarning = 0;
4204
4205 inputStandBy();
4206 acquireWakeLock();
4207
4208 // used to verify we've read at least once before evaluating how many bytes were read
4209 bool readOnce = false;
4210
4211 // start recording
Glenn Kasten47c20702013-08-13 15:37:35 -07004212 // FIXME Race here: exitPending could become true immediately after testing.
4213 // It is only set to true while mLock held, but we don't hold mLock yet.
4214 // Probably a benign race, but it would be safer to check exitPending with mLock held.
Eric Laurent81784c32012-11-19 14:55:58 -08004215 while (!exitPending()) {
4216
4217 processConfigEvents();
4218
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004219 Vector< sp<EffectChain> > effectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08004220 { // scope for mLock
4221 Mutex::Autolock _l(mLock);
4222 checkForNewParameters_l();
4223 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4224 standby();
4225
4226 if (exitPending()) {
4227 break;
4228 }
4229
4230 releaseWakeLock_l();
4231 ALOGV("RecordThread: loop stopping");
4232 // go to sleep
4233 mWaitWorkCV.wait(mLock);
4234 ALOGV("RecordThread: loop starting");
4235 acquireWakeLock_l();
4236 continue;
4237 }
4238 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004239 if (mActiveTrack->isTerminated()) {
4240 removeTrack_l(mActiveTrack);
4241 mActiveTrack.clear();
Glenn Kasten2d944262013-08-13 13:54:08 -07004242 } else {
4243 switch (mActiveTrack->mState) {
4244 case TrackBase::PAUSING:
4245 standby();
Eric Laurent81784c32012-11-19 14:55:58 -08004246 mActiveTrack.clear();
4247 mStartStopCond.broadcast();
Glenn Kasten2d944262013-08-13 13:54:08 -07004248 break;
4249
4250 case TrackBase::RESUMING:
4251 if (mReqChannelCount != mActiveTrack->channelCount()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004252 mActiveTrack.clear();
Glenn Kasten2d944262013-08-13 13:54:08 -07004253 mStartStopCond.broadcast();
4254 } else if (readOnce) {
4255 // record start succeeds only if first read from audio input
4256 // succeeds
4257 if (mBytesRead >= 0) {
4258 mActiveTrack->mState = TrackBase::ACTIVE;
4259 } else {
4260 mActiveTrack.clear();
4261 }
4262 mStartStopCond.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08004263 }
Glenn Kasten2d944262013-08-13 13:54:08 -07004264 mStandby = false;
4265 break;
4266
4267 case TrackBase::ACTIVE:
4268 break;
4269
4270 case TrackBase::IDLE:
4271 break;
4272
4273 default:
4274 LOG_FATAL("Unexpected mActiveTrack->mState %d", mActiveTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004275 }
Glenn Kasten2d944262013-08-13 13:54:08 -07004276
Eric Laurent81784c32012-11-19 14:55:58 -08004277 }
4278 }
4279 lockEffectChains_l(effectChains);
4280 }
4281
Glenn Kasten47c20702013-08-13 15:37:35 -07004282 // thread mutex is now unlocked
4283 // FIXME RecordThread::start assigns to mActiveTrack under lock, but we read without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004284 if (mActiveTrack != 0) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004285 // FIXME RecordThread::stop assigns to mState under lock, but we read without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004286 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4287 mActiveTrack->mState != TrackBase::RESUMING) {
4288 unlockEffectChains(effectChains);
4289 usleep(kRecordThreadSleepUs);
4290 continue;
4291 }
4292 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004293 // thread mutex is not locked, but effect chain is locked
Eric Laurent81784c32012-11-19 14:55:58 -08004294 effectChains[i]->process_l();
4295 }
4296
4297 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004298 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004299 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004300 readOnce = true;
4301 size_t framesOut = buffer.frameCount;
4302 if (mResampler == NULL) {
4303 // no resampling
4304 while (framesOut) {
4305 size_t framesIn = mFrameCount - mRsmpInIndex;
Glenn Kasten34fca342013-08-13 09:48:14 -07004306 if (framesIn > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004307 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4308 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4309 mActiveTrack->mFrameSize;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004310 if (framesIn > framesOut) {
Eric Laurent81784c32012-11-19 14:55:58 -08004311 framesIn = framesOut;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004312 }
Eric Laurent81784c32012-11-19 14:55:58 -08004313 mRsmpInIndex += framesIn;
4314 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004315 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004316 memcpy(dst, src, framesIn * mFrameSize);
4317 } else {
4318 if (mChannelCount == 1) {
4319 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4320 (int16_t *)src, framesIn);
4321 } else {
4322 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4323 (int16_t *)src, framesIn);
4324 }
4325 }
4326 }
Glenn Kasten34fca342013-08-13 09:48:14 -07004327 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
Eric Laurent81784c32012-11-19 14:55:58 -08004328 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004329 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004330 readInto = buffer.raw;
4331 framesOut = 0;
4332 } else {
4333 readInto = mRsmpInBuffer;
4334 mRsmpInIndex = 0;
4335 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004336 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004337 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 if (mBytesRead <= 0) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004339 // FIXME read mState without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004340 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4341 {
4342 ALOGE("Error reading audio input");
4343 // Force input into standby so that it tries to
4344 // recover at next read attempt
4345 inputStandBy();
Glenn Kasten47c20702013-08-13 15:37:35 -07004346 // FIXME sleep with effect chains locked
Eric Laurent81784c32012-11-19 14:55:58 -08004347 usleep(kRecordThreadSleepUs);
4348 }
4349 mRsmpInIndex = mFrameCount;
4350 framesOut = 0;
4351 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004352 }
4353#ifdef TEE_SINK
4354 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004355 (void) mTeeSink->write(readInto,
4356 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4357 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004358#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004359 }
4360 }
4361 } else {
4362 // resampling
4363
Glenn Kasten34af0262013-07-30 11:52:39 -07004364 // resampler accumulates, but we only have one source track
4365 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004366 // alter output frame count as if we were expecting stereo samples
4367 if (mChannelCount == 1 && mReqChannelCount == 1) {
4368 framesOut >>= 1;
4369 }
4370 mResampler->resample(mRsmpOutBuffer, framesOut,
4371 this /* AudioBufferProvider* */);
4372 // ditherAndClamp() works as long as all buffers returned by
4373 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4374 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004375 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004376 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4377 // the resampler always outputs stereo samples:
4378 // do post stereo to mono conversion
4379 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4380 framesOut);
4381 } else {
4382 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4383 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004384 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004385
4386 }
4387 if (mFramestoDrop == 0) {
4388 mActiveTrack->releaseBuffer(&buffer);
4389 } else {
4390 if (mFramestoDrop > 0) {
4391 mFramestoDrop -= buffer.frameCount;
4392 if (mFramestoDrop <= 0) {
4393 clearSyncStartEvent();
4394 }
4395 } else {
4396 mFramestoDrop += buffer.frameCount;
4397 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4398 mSyncStartEvent->isCancelled()) {
4399 ALOGW("Synced record %s, session %d, trigger session %d",
4400 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4401 mActiveTrack->sessionId(),
4402 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4403 clearSyncStartEvent();
4404 }
4405 }
4406 }
4407 mActiveTrack->clearOverflow();
4408 }
4409 // client isn't retrieving buffers fast enough
4410 else {
4411 if (!mActiveTrack->setOverflow()) {
4412 nsecs_t now = systemTime();
4413 if ((now - lastWarning) > kWarningThrottleNs) {
4414 ALOGW("RecordThread: buffer overflow");
4415 lastWarning = now;
4416 }
4417 }
4418 // Release the processor for a while before asking for a new buffer.
4419 // This will give the application more chance to read from the buffer and
4420 // clear the overflow.
Glenn Kasten47c20702013-08-13 15:37:35 -07004421 // FIXME sleep with effect chains locked
Eric Laurent81784c32012-11-19 14:55:58 -08004422 usleep(kRecordThreadSleepUs);
4423 }
4424 }
4425 // enable changes in effect chain
4426 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004427 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004428 }
4429
4430 standby();
4431
4432 {
4433 Mutex::Autolock _l(mLock);
4434 mActiveTrack.clear();
4435 mStartStopCond.broadcast();
4436 }
4437
4438 releaseWakeLock();
4439
4440 ALOGV("RecordThread %p exiting", this);
4441 return false;
4442}
4443
4444void AudioFlinger::RecordThread::standby()
4445{
4446 if (!mStandby) {
4447 inputStandBy();
4448 mStandby = true;
4449 }
4450}
4451
4452void AudioFlinger::RecordThread::inputStandBy()
4453{
4454 mInput->stream->common.standby(&mInput->stream->common);
4455}
4456
Glenn Kastene198c362013-08-13 09:13:36 -07004457sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004458 const sp<AudioFlinger::Client>& client,
4459 uint32_t sampleRate,
4460 audio_format_t format,
4461 audio_channel_mask_t channelMask,
4462 size_t frameCount,
4463 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004464 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004465 pid_t tid,
4466 status_t *status)
4467{
4468 sp<RecordTrack> track;
4469 status_t lStatus;
4470
4471 lStatus = initCheck();
4472 if (lStatus != NO_ERROR) {
4473 ALOGE("Audio driver not initialized.");
4474 goto Exit;
4475 }
4476
Glenn Kasten90e58b12013-07-31 16:16:02 -07004477 // client expresses a preference for FAST, but we get the final say
4478 if (*flags & IAudioFlinger::TRACK_FAST) {
4479 if (
4480 // use case: callback handler and frame count is default or at least as large as HAL
4481 (
4482 (tid != -1) &&
4483 ((frameCount == 0) ||
4484 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4485 ) &&
4486 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4487 // mono or stereo
4488 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4489 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4490 // hardware sample rate
4491 (sampleRate == mSampleRate) &&
4492 // record thread has an associated fast recorder
4493 hasFastRecorder()
4494 // FIXME test that RecordThread for this fast track has a capable output HAL
4495 // FIXME add a permission test also?
4496 ) {
4497 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4498 if (frameCount == 0) {
4499 frameCount = mFrameCount * kFastTrackMultiplier;
4500 }
4501 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4502 frameCount, mFrameCount);
4503 } else {
4504 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4505 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4506 "hasFastRecorder=%d tid=%d",
4507 frameCount, mFrameCount, format,
4508 audio_is_linear_pcm(format),
4509 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4510 *flags &= ~IAudioFlinger::TRACK_FAST;
4511 // For compatibility with AudioRecord calculation, buffer depth is forced
4512 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4513 // This is probably too conservative, but legacy application code may depend on it.
4514 // If you change this calculation, also review the start threshold which is related.
4515 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4516 size_t mNormalFrameCount = 2048; // FIXME
4517 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4518 if (minBufCount < 2) {
4519 minBufCount = 2;
4520 }
4521 size_t minFrameCount = mNormalFrameCount * minBufCount;
4522 if (frameCount < minFrameCount) {
4523 frameCount = minFrameCount;
4524 }
4525 }
4526 }
4527
Eric Laurent81784c32012-11-19 14:55:58 -08004528 // FIXME use flags and tid similar to createTrack_l()
4529
4530 { // scope for mLock
4531 Mutex::Autolock _l(mLock);
4532
4533 track = new RecordTrack(this, client, sampleRate,
4534 format, channelMask, frameCount, sessionId);
4535
Glenn Kasten03003332013-08-06 15:40:54 -07004536 lStatus = track->initCheck();
4537 if (lStatus != NO_ERROR) {
4538 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004539 goto Exit;
4540 }
4541 mTracks.add(track);
4542
4543 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4544 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4545 mAudioFlinger->btNrecIsOff();
4546 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4547 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004548
4549 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4550 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4551 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4552 // so ask activity manager to do this on our behalf
4553 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4554 }
Eric Laurent81784c32012-11-19 14:55:58 -08004555 }
4556 lStatus = NO_ERROR;
4557
4558Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004559 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004560 return track;
4561}
4562
4563status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4564 AudioSystem::sync_event_t event,
4565 int triggerSession)
4566{
4567 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4568 sp<ThreadBase> strongMe = this;
4569 status_t status = NO_ERROR;
4570
4571 if (event == AudioSystem::SYNC_EVENT_NONE) {
4572 clearSyncStartEvent();
4573 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4574 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4575 triggerSession,
4576 recordTrack->sessionId(),
4577 syncStartEventCallback,
4578 this);
4579 // Sync event can be cancelled by the trigger session if the track is not in a
4580 // compatible state in which case we start record immediately
4581 if (mSyncStartEvent->isCancelled()) {
4582 clearSyncStartEvent();
4583 } else {
4584 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4585 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4586 }
4587 }
4588
4589 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004590 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004591 AutoMutex lock(mLock);
4592 if (mActiveTrack != 0) {
4593 if (recordTrack != mActiveTrack.get()) {
4594 status = -EBUSY;
4595 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4596 mActiveTrack->mState = TrackBase::ACTIVE;
4597 }
4598 return status;
4599 }
4600
Glenn Kasten47c20702013-08-13 15:37:35 -07004601 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004602 recordTrack->mState = TrackBase::IDLE;
4603 mActiveTrack = recordTrack;
4604 mLock.unlock();
4605 status_t status = AudioSystem::startInput(mId);
4606 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004607 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004608 if (status != NO_ERROR) {
4609 mActiveTrack.clear();
4610 clearSyncStartEvent();
4611 return status;
4612 }
4613 mRsmpInIndex = mFrameCount;
4614 mBytesRead = 0;
4615 if (mResampler != NULL) {
4616 mResampler->reset();
4617 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004618 // FIXME hijacking a playback track state name which was intended for start after pause;
4619 // here 'STARTING_2' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004620 mActiveTrack->mState = TrackBase::RESUMING;
4621 // signal thread to start
4622 ALOGV("Signal record thread");
4623 mWaitWorkCV.broadcast();
4624 // do not wait for mStartStopCond if exiting
4625 if (exitPending()) {
4626 mActiveTrack.clear();
4627 status = INVALID_OPERATION;
4628 goto startError;
4629 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004630 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004631 mStartStopCond.wait(mLock);
4632 if (mActiveTrack == 0) {
4633 ALOGV("Record failed to start");
4634 status = BAD_VALUE;
4635 goto startError;
4636 }
4637 ALOGV("Record started OK");
4638 return status;
4639 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004640
Eric Laurent81784c32012-11-19 14:55:58 -08004641startError:
4642 AudioSystem::stopInput(mId);
4643 clearSyncStartEvent();
4644 return status;
4645}
4646
4647void AudioFlinger::RecordThread::clearSyncStartEvent()
4648{
4649 if (mSyncStartEvent != 0) {
4650 mSyncStartEvent->cancel();
4651 }
4652 mSyncStartEvent.clear();
4653 mFramestoDrop = 0;
4654}
4655
4656void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4657{
4658 sp<SyncEvent> strongEvent = event.promote();
4659
4660 if (strongEvent != 0) {
4661 RecordThread *me = (RecordThread *)strongEvent->cookie();
4662 me->handleSyncStartEvent(strongEvent);
4663 }
4664}
4665
4666void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4667{
4668 if (event == mSyncStartEvent) {
4669 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4670 // from audio HAL
4671 mFramestoDrop = mFrameCount * 2;
4672 }
4673}
4674
Glenn Kastena8356f62013-07-25 14:37:52 -07004675bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004676 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004677 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004678 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4679 return false;
4680 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004681 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08004682 recordTrack->mState = TrackBase::PAUSING;
4683 // do not wait for mStartStopCond if exiting
4684 if (exitPending()) {
4685 return true;
4686 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004687 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004688 mStartStopCond.wait(mLock);
4689 // if we have been restarted, recordTrack == mActiveTrack.get() here
4690 if (exitPending() || recordTrack != mActiveTrack.get()) {
4691 ALOGV("Record stopped OK");
4692 return true;
4693 }
4694 return false;
4695}
4696
4697bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4698{
4699 return false;
4700}
4701
4702status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4703{
4704#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4705 if (!isValidSyncEvent(event)) {
4706 return BAD_VALUE;
4707 }
4708
4709 int eventSession = event->triggerSession();
4710 status_t ret = NAME_NOT_FOUND;
4711
4712 Mutex::Autolock _l(mLock);
4713
4714 for (size_t i = 0; i < mTracks.size(); i++) {
4715 sp<RecordTrack> track = mTracks[i];
4716 if (eventSession == track->sessionId()) {
4717 (void) track->setSyncEvent(event);
4718 ret = NO_ERROR;
4719 }
4720 }
4721 return ret;
4722#else
4723 return BAD_VALUE;
4724#endif
4725}
4726
4727// destroyTrack_l() must be called with ThreadBase::mLock held
4728void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4729{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004730 track->terminate();
4731 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004732 // active tracks are removed by threadLoop()
4733 if (mActiveTrack != track) {
4734 removeTrack_l(track);
4735 }
4736}
4737
4738void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4739{
4740 mTracks.remove(track);
4741 // need anything related to effects here?
4742}
4743
4744void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4745{
4746 dumpInternals(fd, args);
4747 dumpTracks(fd, args);
4748 dumpEffectChains(fd, args);
4749}
4750
4751void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4752{
4753 const size_t SIZE = 256;
4754 char buffer[SIZE];
4755 String8 result;
4756
4757 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4758 result.append(buffer);
4759
4760 if (mActiveTrack != 0) {
4761 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4762 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004763 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004764 result.append(buffer);
4765 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4766 result.append(buffer);
4767 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4768 result.append(buffer);
4769 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4770 result.append(buffer);
4771 } else {
4772 result.append("No active record client\n");
4773 }
4774
4775 write(fd, result.string(), result.size());
4776
4777 dumpBase(fd, args);
4778}
4779
4780void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4781{
4782 const size_t SIZE = 256;
4783 char buffer[SIZE];
4784 String8 result;
4785
4786 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4787 result.append(buffer);
4788 RecordTrack::appendDumpHeader(result);
4789 for (size_t i = 0; i < mTracks.size(); ++i) {
4790 sp<RecordTrack> track = mTracks[i];
4791 if (track != 0) {
4792 track->dump(buffer, SIZE);
4793 result.append(buffer);
4794 }
4795 }
4796
4797 if (mActiveTrack != 0) {
4798 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4799 result.append(buffer);
4800 RecordTrack::appendDumpHeader(result);
4801 mActiveTrack->dump(buffer, SIZE);
4802 result.append(buffer);
4803
4804 }
4805 write(fd, result.string(), result.size());
4806}
4807
4808// AudioBufferProvider interface
4809status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4810{
4811 size_t framesReq = buffer->frameCount;
4812 size_t framesReady = mFrameCount - mRsmpInIndex;
4813 int channelCount;
4814
4815 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004816 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004817 if (mBytesRead <= 0) {
4818 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4819 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4820 // Force input into standby so that it tries to
4821 // recover at next read attempt
4822 inputStandBy();
4823 usleep(kRecordThreadSleepUs);
4824 }
4825 buffer->raw = NULL;
4826 buffer->frameCount = 0;
4827 return NOT_ENOUGH_DATA;
4828 }
4829 mRsmpInIndex = 0;
4830 framesReady = mFrameCount;
4831 }
4832
4833 if (framesReq > framesReady) {
4834 framesReq = framesReady;
4835 }
4836
4837 if (mChannelCount == 1 && mReqChannelCount == 2) {
4838 channelCount = 1;
4839 } else {
4840 channelCount = 2;
4841 }
4842 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4843 buffer->frameCount = framesReq;
4844 return NO_ERROR;
4845}
4846
4847// AudioBufferProvider interface
4848void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4849{
4850 mRsmpInIndex += buffer->frameCount;
4851 buffer->frameCount = 0;
4852}
4853
4854bool AudioFlinger::RecordThread::checkForNewParameters_l()
4855{
4856 bool reconfig = false;
4857
4858 while (!mNewParameters.isEmpty()) {
4859 status_t status = NO_ERROR;
4860 String8 keyValuePair = mNewParameters[0];
4861 AudioParameter param = AudioParameter(keyValuePair);
4862 int value;
4863 audio_format_t reqFormat = mFormat;
4864 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07004865 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004866
4867 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4868 reqSamplingRate = value;
4869 reconfig = true;
4870 }
4871 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004872 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4873 status = BAD_VALUE;
4874 } else {
4875 reqFormat = (audio_format_t) value;
4876 reconfig = true;
4877 }
Eric Laurent81784c32012-11-19 14:55:58 -08004878 }
4879 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07004880 audio_channel_mask_t mask = (audio_channel_mask_t) value;
4881 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
4882 status = BAD_VALUE;
4883 } else {
4884 reqChannelMask = mask;
4885 reconfig = true;
4886 }
Eric Laurent81784c32012-11-19 14:55:58 -08004887 }
4888 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4889 // do not accept frame count changes if tracks are open as the track buffer
4890 // size depends on frame count and correct behavior would not be guaranteed
4891 // if frame count is changed after track creation
4892 if (mActiveTrack != 0) {
4893 status = INVALID_OPERATION;
4894 } else {
4895 reconfig = true;
4896 }
4897 }
4898 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4899 // forward device change to effects that have requested to be
4900 // aware of attached audio device.
4901 for (size_t i = 0; i < mEffectChains.size(); i++) {
4902 mEffectChains[i]->setDevice_l(value);
4903 }
4904
4905 // store input device and output device but do not forward output device to audio HAL.
4906 // Note that status is ignored by the caller for output device
4907 // (see AudioFlinger::setParameters()
4908 if (audio_is_output_devices(value)) {
4909 mOutDevice = value;
4910 status = BAD_VALUE;
4911 } else {
4912 mInDevice = value;
4913 // disable AEC and NS if the device is a BT SCO headset supporting those
4914 // pre processings
4915 if (mTracks.size() > 0) {
4916 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4917 mAudioFlinger->btNrecIsOff();
4918 for (size_t i = 0; i < mTracks.size(); i++) {
4919 sp<RecordTrack> track = mTracks[i];
4920 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4921 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4922 }
4923 }
4924 }
4925 }
4926 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4927 mAudioSource != (audio_source_t)value) {
4928 // forward device change to effects that have requested to be
4929 // aware of attached audio device.
4930 for (size_t i = 0; i < mEffectChains.size(); i++) {
4931 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4932 }
4933 mAudioSource = (audio_source_t)value;
4934 }
Glenn Kastene198c362013-08-13 09:13:36 -07004935
Eric Laurent81784c32012-11-19 14:55:58 -08004936 if (status == NO_ERROR) {
4937 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4938 keyValuePair.string());
4939 if (status == INVALID_OPERATION) {
4940 inputStandBy();
4941 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4942 keyValuePair.string());
4943 }
4944 if (reconfig) {
4945 if (status == BAD_VALUE &&
4946 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4947 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004948 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004949 <= (2 * reqSamplingRate)) &&
4950 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4951 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07004952 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
4953 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004954 status = NO_ERROR;
4955 }
4956 if (status == NO_ERROR) {
4957 readInputParameters();
4958 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4959 }
4960 }
4961 }
4962
4963 mNewParameters.removeAt(0);
4964
4965 mParamStatus = status;
4966 mParamCond.signal();
4967 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4968 // already timed out waiting for the status and will never signal the condition.
4969 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4970 }
4971 return reconfig;
4972}
4973
4974String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4975{
Eric Laurent81784c32012-11-19 14:55:58 -08004976 Mutex::Autolock _l(mLock);
4977 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07004978 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08004979 }
4980
Glenn Kastend8ea6992013-07-16 14:17:15 -07004981 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4982 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08004983 free(s);
4984 return out_s8;
4985}
4986
4987void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4988 AudioSystem::OutputDescriptor desc;
4989 void *param2 = NULL;
4990
4991 switch (event) {
4992 case AudioSystem::INPUT_OPENED:
4993 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07004994 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004995 desc.samplingRate = mSampleRate;
4996 desc.format = mFormat;
4997 desc.frameCount = mFrameCount;
4998 desc.latency = 0;
4999 param2 = &desc;
5000 break;
5001
5002 case AudioSystem::INPUT_CLOSED:
5003 default:
5004 break;
5005 }
5006 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5007}
5008
5009void AudioFlinger::RecordThread::readInputParameters()
5010{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005011 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005012 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005013 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005014 mRsmpOutBuffer = NULL;
5015 delete mResampler;
5016 mResampler = NULL;
5017
5018 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5019 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005020 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005021 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005022 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5023 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5024 }
Eric Laurent81784c32012-11-19 14:55:58 -08005025 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005026 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5027 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005028 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5029
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005030 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005031 int channelCount;
5032 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5033 // stereo to mono post process as the resampler always outputs stereo.
5034 if (mChannelCount == 1 && mReqChannelCount == 2) {
5035 channelCount = 1;
5036 } else {
5037 channelCount = 2;
5038 }
5039 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5040 mResampler->setSampleRate(mSampleRate);
5041 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005042 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005043
5044 // optmization: if mono to mono, alter input frame count as if we were inputing
5045 // stereo samples
5046 if (mChannelCount == 1 && mReqChannelCount == 1) {
5047 mFrameCount >>= 1;
5048 }
5049
5050 }
5051 mRsmpInIndex = mFrameCount;
5052}
5053
5054unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5055{
5056 Mutex::Autolock _l(mLock);
5057 if (initCheck() != NO_ERROR) {
5058 return 0;
5059 }
5060
5061 return mInput->stream->get_input_frames_lost(mInput->stream);
5062}
5063
5064uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5065{
5066 Mutex::Autolock _l(mLock);
5067 uint32_t result = 0;
5068 if (getEffectChain_l(sessionId) != 0) {
5069 result = EFFECT_SESSION;
5070 }
5071
5072 for (size_t i = 0; i < mTracks.size(); ++i) {
5073 if (sessionId == mTracks[i]->sessionId()) {
5074 result |= TRACK_SESSION;
5075 break;
5076 }
5077 }
5078
5079 return result;
5080}
5081
5082KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5083{
5084 KeyedVector<int, bool> ids;
5085 Mutex::Autolock _l(mLock);
5086 for (size_t j = 0; j < mTracks.size(); ++j) {
5087 sp<RecordThread::RecordTrack> track = mTracks[j];
5088 int sessionId = track->sessionId();
5089 if (ids.indexOfKey(sessionId) < 0) {
5090 ids.add(sessionId, true);
5091 }
5092 }
5093 return ids;
5094}
5095
5096AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5097{
5098 Mutex::Autolock _l(mLock);
5099 AudioStreamIn *input = mInput;
5100 mInput = NULL;
5101 return input;
5102}
5103
5104// this method must always be called either with ThreadBase mLock held or inside the thread loop
5105audio_stream_t* AudioFlinger::RecordThread::stream() const
5106{
5107 if (mInput == NULL) {
5108 return NULL;
5109 }
5110 return &mInput->stream->common;
5111}
5112
5113status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5114{
5115 // only one chain per input thread
5116 if (mEffectChains.size() != 0) {
5117 return INVALID_OPERATION;
5118 }
5119 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5120
5121 chain->setInBuffer(NULL);
5122 chain->setOutBuffer(NULL);
5123
5124 checkSuspendOnAddEffectChain_l(chain);
5125
5126 mEffectChains.add(chain);
5127
5128 return NO_ERROR;
5129}
5130
5131size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5132{
5133 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5134 ALOGW_IF(mEffectChains.size() != 1,
5135 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5136 chain.get(), mEffectChains.size(), this);
5137 if (mEffectChains.size() == 1) {
5138 mEffectChains.removeAt(0);
5139 }
5140 return 0;
5141}
5142
5143}; // namespace android