blob: 58e3cbe0196deff7508d3fe8196884bbbb408718 [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
23#include <math.h>
24#include <fcntl.h>
25#include <sys/stat.h>
26#include <cutils/properties.h>
27#include <cutils/compiler.h>
28#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080029#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030
31#include <private/media/AudioTrackShared.h>
32#include <hardware/audio.h>
33#include <audio_effects/effect_ns.h>
34#include <audio_effects/effect_aec.h>
35#include <audio_utils/primitives.h>
36
37// NBAIO implementations
38#include <media/nbaio/AudioStreamOutSink.h>
39#include <media/nbaio/MonoPipe.h>
40#include <media/nbaio/MonoPipeReader.h>
41#include <media/nbaio/Pipe.h>
42#include <media/nbaio/PipeReader.h>
43#include <media/nbaio/SourceAudioBufferProvider.h>
44
45#include <powermanager/PowerManager.h>
46
47#include <common_time/cc_helper.h>
48#include <common_time/local_clock.h>
49
50#include "AudioFlinger.h"
51#include "AudioMixer.h"
52#include "FastMixer.h"
53#include "ServiceUtilities.h"
54#include "SchedulingPolicyService.h"
55
56#undef ADD_BATTERY_DATA
57
58#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62
63// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
64#ifdef DEBUG_CPU_USAGE
65#include <cpustats/CentralTendencyStatistics.h>
66#include <cpustats/ThreadCpuUsage.h>
67#endif
68
69// ----------------------------------------------------------------------------
70
71// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
83
84namespace android {
85
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95// don't warn about blocked writes or record buffer overflows more often than this
96static const nsecs_t kWarningThrottleNs = seconds(5);
97
98// RecordThread loop sleep time upon application overrun or audio HAL read error
99static const int kRecordThreadSleepUs = 5000;
100
101// maximum time to wait for setParameters to complete
102static const nsecs_t kSetParametersTimeoutNs = seconds(2);
103
104// minimum sleep time for the mixer thread loop when tracks are active but in underrun
105static const uint32_t kMinThreadSleepTimeUs = 5000;
106// maximum divider applied to the active sleep time in the mixer thread loop
107static const uint32_t kMaxThreadSleepTimeShift = 2;
108
109// minimum normal mix buffer size, expressed in milliseconds rather than frames
110static const uint32_t kMinNormalMixBufferSizeMs = 20;
111// maximum normal mix buffer size
112static const uint32_t kMaxNormalMixBufferSizeMs = 24;
113
114// Whether to use fast mixer
115static const enum {
116 FastMixer_Never, // never initialize or use: for debugging only
117 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
118 // normal mixer multiplier is 1
119 FastMixer_Static, // initialize if needed, then use all the time if initialized,
120 // multiplier is calculated based on min & max normal mixer buffer size
121 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
122 // multiplier is calculated based on min & max normal mixer buffer size
123 // FIXME for FastMixer_Dynamic:
124 // Supporting this option will require fixing HALs that can't handle large writes.
125 // For example, one HAL implementation returns an error from a large write,
126 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
127 // We could either fix the HAL implementations, or provide a wrapper that breaks
128 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
129} kUseFastMixer = FastMixer_Static;
130
131// Priorities for requestPriority
132static const int kPriorityAudioApp = 2;
133static const int kPriorityFastMixer = 3;
134
135// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
136// for the track. The client then sub-divides this into smaller buffers for its use.
137// Currently the client uses double-buffering by default, but doesn't tell us about that.
138// So for now we just assume that client is double-buffered.
139// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
140// N-buffering, so AudioFlinger could allocate the right amount of memory.
141// See the client's minBufCount and mNotificationFramesAct calculations for details.
142static const int kFastTrackMultiplier = 2;
143
144// ----------------------------------------------------------------------------
145
146#ifdef ADD_BATTERY_DATA
147// To collect the amplifier usage
148static void addBatteryData(uint32_t params) {
149 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
150 if (service == NULL) {
151 // it already logged
152 return;
153 }
154
155 service->addBatteryData(params);
156}
157#endif
158
159
160// ----------------------------------------------------------------------------
161// CPU Stats
162// ----------------------------------------------------------------------------
163
164class CpuStats {
165public:
166 CpuStats();
167 void sample(const String8 &title);
168#ifdef DEBUG_CPU_USAGE
169private:
170 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
171 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
172
173 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
174
175 int mCpuNum; // thread's current CPU number
176 int mCpukHz; // frequency of thread's current CPU in kHz
177#endif
178};
179
180CpuStats::CpuStats()
181#ifdef DEBUG_CPU_USAGE
182 : mCpuNum(-1), mCpukHz(-1)
183#endif
184{
185}
186
187void CpuStats::sample(const String8 &title) {
188#ifdef DEBUG_CPU_USAGE
189 // get current thread's delta CPU time in wall clock ns
190 double wcNs;
191 bool valid = mCpuUsage.sampleAndEnable(wcNs);
192
193 // record sample for wall clock statistics
194 if (valid) {
195 mWcStats.sample(wcNs);
196 }
197
198 // get the current CPU number
199 int cpuNum = sched_getcpu();
200
201 // get the current CPU frequency in kHz
202 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
203
204 // check if either CPU number or frequency changed
205 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
206 mCpuNum = cpuNum;
207 mCpukHz = cpukHz;
208 // ignore sample for purposes of cycles
209 valid = false;
210 }
211
212 // if no change in CPU number or frequency, then record sample for cycle statistics
213 if (valid && mCpukHz > 0) {
214 double cycles = wcNs * cpukHz * 0.000001;
215 mHzStats.sample(cycles);
216 }
217
218 unsigned n = mWcStats.n();
219 // mCpuUsage.elapsed() is expensive, so don't call it every loop
220 if ((n & 127) == 1) {
221 long long elapsed = mCpuUsage.elapsed();
222 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
223 double perLoop = elapsed / (double) n;
224 double perLoop100 = perLoop * 0.01;
225 double perLoop1k = perLoop * 0.001;
226 double mean = mWcStats.mean();
227 double stddev = mWcStats.stddev();
228 double minimum = mWcStats.minimum();
229 double maximum = mWcStats.maximum();
230 double meanCycles = mHzStats.mean();
231 double stddevCycles = mHzStats.stddev();
232 double minCycles = mHzStats.minimum();
233 double maxCycles = mHzStats.maximum();
234 mCpuUsage.resetElapsed();
235 mWcStats.reset();
236 mHzStats.reset();
237 ALOGD("CPU usage for %s over past %.1f secs\n"
238 " (%u mixer loops at %.1f mean ms per loop):\n"
239 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
240 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
241 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
242 title.string(),
243 elapsed * .000000001, n, perLoop * .000001,
244 mean * .001,
245 stddev * .001,
246 minimum * .001,
247 maximum * .001,
248 mean / perLoop100,
249 stddev / perLoop100,
250 minimum / perLoop100,
251 maximum / perLoop100,
252 meanCycles / perLoop1k,
253 stddevCycles / perLoop1k,
254 minCycles / perLoop1k,
255 maxCycles / perLoop1k);
256
257 }
258 }
259#endif
260};
261
262// ----------------------------------------------------------------------------
263// ThreadBase
264// ----------------------------------------------------------------------------
265
266AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
267 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
268 : Thread(false /*canCallJava*/),
269 mType(type),
270 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
271 // mChannelMask
272 mChannelCount(0),
273 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
274 mParamStatus(NO_ERROR),
275 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
276 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
277 // mName will be set by concrete (non-virtual) subclass
278 mDeathRecipient(new PMDeathRecipient(this))
279{
280}
281
282AudioFlinger::ThreadBase::~ThreadBase()
283{
284 mParamCond.broadcast();
285 // do not lock the mutex in destructor
286 releaseWakeLock_l();
287 if (mPowerManager != 0) {
288 sp<IBinder> binder = mPowerManager->asBinder();
289 binder->unlinkToDeath(mDeathRecipient);
290 }
291}
292
293void AudioFlinger::ThreadBase::exit()
294{
295 ALOGV("ThreadBase::exit");
296 // do any cleanup required for exit to succeed
297 preExit();
298 {
299 // This lock prevents the following race in thread (uniprocessor for illustration):
300 // if (!exitPending()) {
301 // // context switch from here to exit()
302 // // exit() calls requestExit(), what exitPending() observes
303 // // exit() calls signal(), which is dropped since no waiters
304 // // context switch back from exit() to here
305 // mWaitWorkCV.wait(...);
306 // // now thread is hung
307 // }
308 AutoMutex lock(mLock);
309 requestExit();
310 mWaitWorkCV.broadcast();
311 }
312 // When Thread::requestExitAndWait is made virtual and this method is renamed to
313 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
314 requestExitAndWait();
315}
316
317status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
318{
319 status_t status;
320
321 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
322 Mutex::Autolock _l(mLock);
323
324 mNewParameters.add(keyValuePairs);
325 mWaitWorkCV.signal();
326 // wait condition with timeout in case the thread loop has exited
327 // before the request could be processed
328 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
329 status = mParamStatus;
330 mWaitWorkCV.signal();
331 } else {
332 status = TIMED_OUT;
333 }
334 return status;
335}
336
337void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
338{
339 Mutex::Autolock _l(mLock);
340 sendIoConfigEvent_l(event, param);
341}
342
343// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
344void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
345{
346 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
347 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
348 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
349 param);
350 mWaitWorkCV.signal();
351}
352
353// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
354void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
355{
356 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
357 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
358 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
359 mConfigEvents.size(), pid, tid, prio);
360 mWaitWorkCV.signal();
361}
362
363void AudioFlinger::ThreadBase::processConfigEvents()
364{
365 mLock.lock();
366 while (!mConfigEvents.isEmpty()) {
367 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
368 ConfigEvent *event = mConfigEvents[0];
369 mConfigEvents.removeAt(0);
370 // release mLock before locking AudioFlinger mLock: lock order is always
371 // AudioFlinger then ThreadBase to avoid cross deadlock
372 mLock.unlock();
373 switch(event->type()) {
374 case CFG_EVENT_PRIO: {
375 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
376 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
377 if (err != 0) {
378 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
379 "error %d",
380 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
381 }
382 } break;
383 case CFG_EVENT_IO: {
384 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
385 mAudioFlinger->mLock.lock();
386 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
387 mAudioFlinger->mLock.unlock();
388 } break;
389 default:
390 ALOGE("processConfigEvents() unknown event type %d", event->type());
391 break;
392 }
393 delete event;
394 mLock.lock();
395 }
396 mLock.unlock();
397}
398
399void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
400{
401 const size_t SIZE = 256;
402 char buffer[SIZE];
403 String8 result;
404
405 bool locked = AudioFlinger::dumpTryLock(mLock);
406 if (!locked) {
407 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
408 write(fd, buffer, strlen(buffer));
409 }
410
411 snprintf(buffer, SIZE, "io handle: %d\n", mId);
412 result.append(buffer);
413 snprintf(buffer, SIZE, "TID: %d\n", getTid());
414 result.append(buffer);
415 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
416 result.append(buffer);
417 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
418 result.append(buffer);
419 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
420 result.append(buffer);
421 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
422 result.append(buffer);
423 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
424 result.append(buffer);
425 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
426 result.append(buffer);
427 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
428 result.append(buffer);
429 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
430 result.append(buffer);
431
432 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
433 result.append(buffer);
434 result.append(" Index Command");
435 for (size_t i = 0; i < mNewParameters.size(); ++i) {
436 snprintf(buffer, SIZE, "\n %02d ", i);
437 result.append(buffer);
438 result.append(mNewParameters[i]);
439 }
440
441 snprintf(buffer, SIZE, "\n\nPending config events: \n");
442 result.append(buffer);
443 for (size_t i = 0; i < mConfigEvents.size(); i++) {
444 mConfigEvents[i]->dump(buffer, SIZE);
445 result.append(buffer);
446 }
447 result.append("\n");
448
449 write(fd, result.string(), result.size());
450
451 if (locked) {
452 mLock.unlock();
453 }
454}
455
456void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
457{
458 const size_t SIZE = 256;
459 char buffer[SIZE];
460 String8 result;
461
462 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
463 write(fd, buffer, strlen(buffer));
464
465 for (size_t i = 0; i < mEffectChains.size(); ++i) {
466 sp<EffectChain> chain = mEffectChains[i];
467 if (chain != 0) {
468 chain->dump(fd, args);
469 }
470 }
471}
472
473void AudioFlinger::ThreadBase::acquireWakeLock()
474{
475 Mutex::Autolock _l(mLock);
476 acquireWakeLock_l();
477}
478
479void AudioFlinger::ThreadBase::acquireWakeLock_l()
480{
481 if (mPowerManager == 0) {
482 // use checkService() to avoid blocking if power service is not up yet
483 sp<IBinder> binder =
484 defaultServiceManager()->checkService(String16("power"));
485 if (binder == 0) {
486 ALOGW("Thread %s cannot connect to the power manager service", mName);
487 } else {
488 mPowerManager = interface_cast<IPowerManager>(binder);
489 binder->linkToDeath(mDeathRecipient);
490 }
491 }
492 if (mPowerManager != 0) {
493 sp<IBinder> binder = new BBinder();
494 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
495 binder,
496 String16(mName));
497 if (status == NO_ERROR) {
498 mWakeLockToken = binder;
499 }
500 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
501 }
502}
503
504void AudioFlinger::ThreadBase::releaseWakeLock()
505{
506 Mutex::Autolock _l(mLock);
507 releaseWakeLock_l();
508}
509
510void AudioFlinger::ThreadBase::releaseWakeLock_l()
511{
512 if (mWakeLockToken != 0) {
513 ALOGV("releaseWakeLock_l() %s", mName);
514 if (mPowerManager != 0) {
515 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
516 }
517 mWakeLockToken.clear();
518 }
519}
520
521void AudioFlinger::ThreadBase::clearPowerManager()
522{
523 Mutex::Autolock _l(mLock);
524 releaseWakeLock_l();
525 mPowerManager.clear();
526}
527
528void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
529{
530 sp<ThreadBase> thread = mThread.promote();
531 if (thread != 0) {
532 thread->clearPowerManager();
533 }
534 ALOGW("power manager service died !!!");
535}
536
537void AudioFlinger::ThreadBase::setEffectSuspended(
538 const effect_uuid_t *type, bool suspend, int sessionId)
539{
540 Mutex::Autolock _l(mLock);
541 setEffectSuspended_l(type, suspend, sessionId);
542}
543
544void AudioFlinger::ThreadBase::setEffectSuspended_l(
545 const effect_uuid_t *type, bool suspend, int sessionId)
546{
547 sp<EffectChain> chain = getEffectChain_l(sessionId);
548 if (chain != 0) {
549 if (type != NULL) {
550 chain->setEffectSuspended_l(type, suspend);
551 } else {
552 chain->setEffectSuspendedAll_l(suspend);
553 }
554 }
555
556 updateSuspendedSessions_l(type, suspend, sessionId);
557}
558
559void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
560{
561 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
562 if (index < 0) {
563 return;
564 }
565
566 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
567 mSuspendedSessions.valueAt(index);
568
569 for (size_t i = 0; i < sessionEffects.size(); i++) {
570 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
571 for (int j = 0; j < desc->mRefCount; j++) {
572 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
573 chain->setEffectSuspendedAll_l(true);
574 } else {
575 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
576 desc->mType.timeLow);
577 chain->setEffectSuspended_l(&desc->mType, true);
578 }
579 }
580 }
581}
582
583void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
584 bool suspend,
585 int sessionId)
586{
587 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
588
589 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
590
591 if (suspend) {
592 if (index >= 0) {
593 sessionEffects = mSuspendedSessions.valueAt(index);
594 } else {
595 mSuspendedSessions.add(sessionId, sessionEffects);
596 }
597 } else {
598 if (index < 0) {
599 return;
600 }
601 sessionEffects = mSuspendedSessions.valueAt(index);
602 }
603
604
605 int key = EffectChain::kKeyForSuspendAll;
606 if (type != NULL) {
607 key = type->timeLow;
608 }
609 index = sessionEffects.indexOfKey(key);
610
611 sp<SuspendedSessionDesc> desc;
612 if (suspend) {
613 if (index >= 0) {
614 desc = sessionEffects.valueAt(index);
615 } else {
616 desc = new SuspendedSessionDesc();
617 if (type != NULL) {
618 desc->mType = *type;
619 }
620 sessionEffects.add(key, desc);
621 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
622 }
623 desc->mRefCount++;
624 } else {
625 if (index < 0) {
626 return;
627 }
628 desc = sessionEffects.valueAt(index);
629 if (--desc->mRefCount == 0) {
630 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
631 sessionEffects.removeItemsAt(index);
632 if (sessionEffects.isEmpty()) {
633 ALOGV("updateSuspendedSessions_l() restore removing session %d",
634 sessionId);
635 mSuspendedSessions.removeItem(sessionId);
636 }
637 }
638 }
639 if (!sessionEffects.isEmpty()) {
640 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
641 }
642}
643
644void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
645 bool enabled,
646 int sessionId)
647{
648 Mutex::Autolock _l(mLock);
649 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
650}
651
652void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
653 bool enabled,
654 int sessionId)
655{
656 if (mType != RECORD) {
657 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
658 // another session. This gives the priority to well behaved effect control panels
659 // and applications not using global effects.
660 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
661 // global effects
662 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
663 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
664 }
665 }
666
667 sp<EffectChain> chain = getEffectChain_l(sessionId);
668 if (chain != 0) {
669 chain->checkSuspendOnEffectEnabled(effect, enabled);
670 }
671}
672
673// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
674sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
675 const sp<AudioFlinger::Client>& client,
676 const sp<IEffectClient>& effectClient,
677 int32_t priority,
678 int sessionId,
679 effect_descriptor_t *desc,
680 int *enabled,
681 status_t *status
682 )
683{
684 sp<EffectModule> effect;
685 sp<EffectHandle> handle;
686 status_t lStatus;
687 sp<EffectChain> chain;
688 bool chainCreated = false;
689 bool effectCreated = false;
690 bool effectRegistered = false;
691
692 lStatus = initCheck();
693 if (lStatus != NO_ERROR) {
694 ALOGW("createEffect_l() Audio driver not initialized.");
695 goto Exit;
696 }
697
698 // Do not allow effects with session ID 0 on direct output or duplicating threads
699 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
701 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
702 desc->name, sessionId);
703 lStatus = BAD_VALUE;
704 goto Exit;
705 }
706 // Only Pre processor effects are allowed on input threads and only on input threads
707 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
708 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
709 desc->name, desc->flags, mType);
710 lStatus = BAD_VALUE;
711 goto Exit;
712 }
713
714 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
715
716 { // scope for mLock
717 Mutex::Autolock _l(mLock);
718
719 // check for existing effect chain with the requested audio session
720 chain = getEffectChain_l(sessionId);
721 if (chain == 0) {
722 // create a new chain for this session
723 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
724 chain = new EffectChain(this, sessionId);
725 addEffectChain_l(chain);
726 chain->setStrategy(getStrategyForSession_l(sessionId));
727 chainCreated = true;
728 } else {
729 effect = chain->getEffectFromDesc_l(desc);
730 }
731
732 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
733
734 if (effect == 0) {
735 int id = mAudioFlinger->nextUniqueId();
736 // Check CPU and memory usage
737 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
738 if (lStatus != NO_ERROR) {
739 goto Exit;
740 }
741 effectRegistered = true;
742 // create a new effect module if none present in the chain
743 effect = new EffectModule(this, chain, desc, id, sessionId);
744 lStatus = effect->status();
745 if (lStatus != NO_ERROR) {
746 goto Exit;
747 }
748 lStatus = chain->addEffect_l(effect);
749 if (lStatus != NO_ERROR) {
750 goto Exit;
751 }
752 effectCreated = true;
753
754 effect->setDevice(mOutDevice);
755 effect->setDevice(mInDevice);
756 effect->setMode(mAudioFlinger->getMode());
757 effect->setAudioSource(mAudioSource);
758 }
759 // create effect handle and connect it to effect module
760 handle = new EffectHandle(effect, client, effectClient, priority);
761 lStatus = effect->addHandle(handle.get());
762 if (enabled != NULL) {
763 *enabled = (int)effect->isEnabled();
764 }
765 }
766
767Exit:
768 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
769 Mutex::Autolock _l(mLock);
770 if (effectCreated) {
771 chain->removeEffect_l(effect);
772 }
773 if (effectRegistered) {
774 AudioSystem::unregisterEffect(effect->id());
775 }
776 if (chainCreated) {
777 removeEffectChain_l(chain);
778 }
779 handle.clear();
780 }
781
782 if (status != NULL) {
783 *status = lStatus;
784 }
785 return handle;
786}
787
788sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
789{
790 Mutex::Autolock _l(mLock);
791 return getEffect_l(sessionId, effectId);
792}
793
794sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
795{
796 sp<EffectChain> chain = getEffectChain_l(sessionId);
797 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
798}
799
800// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
801// PlaybackThread::mLock held
802status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
803{
804 // check for existing effect chain with the requested audio session
805 int sessionId = effect->sessionId();
806 sp<EffectChain> chain = getEffectChain_l(sessionId);
807 bool chainCreated = false;
808
809 if (chain == 0) {
810 // create a new chain for this session
811 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
812 chain = new EffectChain(this, sessionId);
813 addEffectChain_l(chain);
814 chain->setStrategy(getStrategyForSession_l(sessionId));
815 chainCreated = true;
816 }
817 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
818
819 if (chain->getEffectFromId_l(effect->id()) != 0) {
820 ALOGW("addEffect_l() %p effect %s already present in chain %p",
821 this, effect->desc().name, chain.get());
822 return BAD_VALUE;
823 }
824
825 status_t status = chain->addEffect_l(effect);
826 if (status != NO_ERROR) {
827 if (chainCreated) {
828 removeEffectChain_l(chain);
829 }
830 return status;
831 }
832
833 effect->setDevice(mOutDevice);
834 effect->setDevice(mInDevice);
835 effect->setMode(mAudioFlinger->getMode());
836 effect->setAudioSource(mAudioSource);
837 return NO_ERROR;
838}
839
840void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
841
842 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
843 effect_descriptor_t desc = effect->desc();
844 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
845 detachAuxEffect_l(effect->id());
846 }
847
848 sp<EffectChain> chain = effect->chain().promote();
849 if (chain != 0) {
850 // remove effect chain if removing last effect
851 if (chain->removeEffect_l(effect) == 0) {
852 removeEffectChain_l(chain);
853 }
854 } else {
855 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
856 }
857}
858
859void AudioFlinger::ThreadBase::lockEffectChains_l(
860 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
861{
862 effectChains = mEffectChains;
863 for (size_t i = 0; i < mEffectChains.size(); i++) {
864 mEffectChains[i]->lock();
865 }
866}
867
868void AudioFlinger::ThreadBase::unlockEffectChains(
869 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
870{
871 for (size_t i = 0; i < effectChains.size(); i++) {
872 effectChains[i]->unlock();
873 }
874}
875
876sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
877{
878 Mutex::Autolock _l(mLock);
879 return getEffectChain_l(sessionId);
880}
881
882sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
883{
884 size_t size = mEffectChains.size();
885 for (size_t i = 0; i < size; i++) {
886 if (mEffectChains[i]->sessionId() == sessionId) {
887 return mEffectChains[i];
888 }
889 }
890 return 0;
891}
892
893void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
894{
895 Mutex::Autolock _l(mLock);
896 size_t size = mEffectChains.size();
897 for (size_t i = 0; i < size; i++) {
898 mEffectChains[i]->setMode_l(mode);
899 }
900}
901
902void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
903 EffectHandle *handle,
904 bool unpinIfLast) {
905
906 Mutex::Autolock _l(mLock);
907 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
908 // delete the effect module if removing last handle on it
909 if (effect->removeHandle(handle) == 0) {
910 if (!effect->isPinned() || unpinIfLast) {
911 removeEffect_l(effect);
912 AudioSystem::unregisterEffect(effect->id());
913 }
914 }
915}
916
917// ----------------------------------------------------------------------------
918// Playback
919// ----------------------------------------------------------------------------
920
921AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
922 AudioStreamOut* output,
923 audio_io_handle_t id,
924 audio_devices_t device,
925 type_t type)
926 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
927 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
928 // mStreamTypes[] initialized in constructor body
929 mOutput(output),
930 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
931 mMixerStatus(MIXER_IDLE),
932 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
933 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
934 mScreenState(AudioFlinger::mScreenState),
935 // index 0 is reserved for normal mixer's submix
936 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
937{
938 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800939 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800940
941 // Assumes constructor is called by AudioFlinger with it's mLock held, but
942 // it would be safer to explicitly pass initial masterVolume/masterMute as
943 // parameter.
944 //
945 // If the HAL we are using has support for master volume or master mute,
946 // then do not attenuate or mute during mixing (just leave the volume at 1.0
947 // and the mute set to false).
948 mMasterVolume = audioFlinger->masterVolume_l();
949 mMasterMute = audioFlinger->masterMute_l();
950 if (mOutput && mOutput->audioHwDev) {
951 if (mOutput->audioHwDev->canSetMasterVolume()) {
952 mMasterVolume = 1.0;
953 }
954
955 if (mOutput->audioHwDev->canSetMasterMute()) {
956 mMasterMute = false;
957 }
958 }
959
960 readOutputParameters();
961
962 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
963 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
964 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
965 stream = (audio_stream_type_t) (stream + 1)) {
966 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
967 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
968 }
969 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
970 // because mAudioFlinger doesn't have one to copy from
971}
972
973AudioFlinger::PlaybackThread::~PlaybackThread()
974{
Glenn Kasten9e58b552013-01-18 15:09:48 -0800975 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -0800976 delete [] mMixBuffer;
977}
978
979void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
980{
981 dumpInternals(fd, args);
982 dumpTracks(fd, args);
983 dumpEffectChains(fd, args);
984}
985
986void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
987{
988 const size_t SIZE = 256;
989 char buffer[SIZE];
990 String8 result;
991
992 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
993 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
994 const stream_type_t *st = &mStreamTypes[i];
995 if (i > 0) {
996 result.appendFormat(", ");
997 }
998 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
999 if (st->mute) {
1000 result.append("M");
1001 }
1002 }
1003 result.append("\n");
1004 write(fd, result.string(), result.length());
1005 result.clear();
1006
1007 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1008 result.append(buffer);
1009 Track::appendDumpHeader(result);
1010 for (size_t i = 0; i < mTracks.size(); ++i) {
1011 sp<Track> track = mTracks[i];
1012 if (track != 0) {
1013 track->dump(buffer, SIZE);
1014 result.append(buffer);
1015 }
1016 }
1017
1018 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1019 result.append(buffer);
1020 Track::appendDumpHeader(result);
1021 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1022 sp<Track> track = mActiveTracks[i].promote();
1023 if (track != 0) {
1024 track->dump(buffer, SIZE);
1025 result.append(buffer);
1026 }
1027 }
1028 write(fd, result.string(), result.size());
1029
1030 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1031 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1032 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1033 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1034}
1035
1036void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1037{
1038 const size_t SIZE = 256;
1039 char buffer[SIZE];
1040 String8 result;
1041
1042 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1043 result.append(buffer);
1044 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1045 ns2ms(systemTime() - mLastWriteTime));
1046 result.append(buffer);
1047 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1048 result.append(buffer);
1049 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1050 result.append(buffer);
1051 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1052 result.append(buffer);
1053 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1054 result.append(buffer);
1055 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1056 result.append(buffer);
1057 write(fd, result.string(), result.size());
1058 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1059
1060 dumpBase(fd, args);
1061}
1062
1063// Thread virtuals
1064status_t AudioFlinger::PlaybackThread::readyToRun()
1065{
1066 status_t status = initCheck();
1067 if (status == NO_ERROR) {
1068 ALOGI("AudioFlinger's thread %p ready to run", this);
1069 } else {
1070 ALOGE("No working audio driver found.");
1071 }
1072 return status;
1073}
1074
1075void AudioFlinger::PlaybackThread::onFirstRef()
1076{
1077 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1078}
1079
1080// ThreadBase virtuals
1081void AudioFlinger::PlaybackThread::preExit()
1082{
1083 ALOGV(" preExit()");
1084 // FIXME this is using hard-coded strings but in the future, this functionality will be
1085 // converted to use audio HAL extensions required to support tunneling
1086 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1087}
1088
1089// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1090sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1091 const sp<AudioFlinger::Client>& client,
1092 audio_stream_type_t streamType,
1093 uint32_t sampleRate,
1094 audio_format_t format,
1095 audio_channel_mask_t channelMask,
1096 size_t frameCount,
1097 const sp<IMemory>& sharedBuffer,
1098 int sessionId,
1099 IAudioFlinger::track_flags_t *flags,
1100 pid_t tid,
1101 status_t *status)
1102{
1103 sp<Track> track;
1104 status_t lStatus;
1105
1106 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1107
1108 // client expresses a preference for FAST, but we get the final say
1109 if (*flags & IAudioFlinger::TRACK_FAST) {
1110 if (
1111 // not timed
1112 (!isTimed) &&
1113 // either of these use cases:
1114 (
1115 // use case 1: shared buffer with any frame count
1116 (
1117 (sharedBuffer != 0)
1118 ) ||
1119 // use case 2: callback handler and frame count is default or at least as large as HAL
1120 (
1121 (tid != -1) &&
1122 ((frameCount == 0) ||
1123 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1124 )
1125 ) &&
1126 // PCM data
1127 audio_is_linear_pcm(format) &&
1128 // mono or stereo
1129 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1130 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1131#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1132 // hardware sample rate
1133 (sampleRate == mSampleRate) &&
1134#endif
1135 // normal mixer has an associated fast mixer
1136 hasFastMixer() &&
1137 // there are sufficient fast track slots available
1138 (mFastTrackAvailMask != 0)
1139 // FIXME test that MixerThread for this fast track has a capable output HAL
1140 // FIXME add a permission test also?
1141 ) {
1142 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1143 if (frameCount == 0) {
1144 frameCount = mFrameCount * kFastTrackMultiplier;
1145 }
1146 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1147 frameCount, mFrameCount);
1148 } else {
1149 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1150 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1151 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1152 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1153 audio_is_linear_pcm(format),
1154 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1155 *flags &= ~IAudioFlinger::TRACK_FAST;
1156 // For compatibility with AudioTrack calculation, buffer depth is forced
1157 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1158 // This is probably too conservative, but legacy application code may depend on it.
1159 // If you change this calculation, also review the start threshold which is related.
1160 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1161 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1162 if (minBufCount < 2) {
1163 minBufCount = 2;
1164 }
1165 size_t minFrameCount = mNormalFrameCount * minBufCount;
1166 if (frameCount < minFrameCount) {
1167 frameCount = minFrameCount;
1168 }
1169 }
1170 }
1171
1172 if (mType == DIRECT) {
1173 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1174 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1175 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1176 "for output %p with format %d",
1177 sampleRate, format, channelMask, mOutput, mFormat);
1178 lStatus = BAD_VALUE;
1179 goto Exit;
1180 }
1181 }
1182 } else {
1183 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1184 if (sampleRate > mSampleRate*2) {
1185 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189 }
1190
1191 lStatus = initCheck();
1192 if (lStatus != NO_ERROR) {
1193 ALOGE("Audio driver not initialized.");
1194 goto Exit;
1195 }
1196
1197 { // scope for mLock
1198 Mutex::Autolock _l(mLock);
Glenn Kasten32584a72013-02-13 14:46:45 -08001199 mNBLogWriter->logf("createTrack_l isFast=%d caller=%d",
1200 (*flags & IAudioFlinger::TRACK_FAST) != 0, IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001201
1202 // all tracks in same audio session must share the same routing strategy otherwise
1203 // conflicts will happen when tracks are moved from one output to another by audio policy
1204 // manager
1205 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1206 for (size_t i = 0; i < mTracks.size(); ++i) {
1207 sp<Track> t = mTracks[i];
1208 if (t != 0 && !t->isOutputTrack()) {
1209 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1210 if (sessionId == t->sessionId() && strategy != actual) {
1211 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1212 strategy, actual);
1213 lStatus = BAD_VALUE;
1214 goto Exit;
1215 }
1216 }
1217 }
1218
1219 if (!isTimed) {
1220 track = new Track(this, client, streamType, sampleRate, format,
1221 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1222 } else {
1223 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1224 channelMask, frameCount, sharedBuffer, sessionId);
1225 }
1226 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1227 lStatus = NO_MEMORY;
1228 goto Exit;
1229 }
1230 mTracks.add(track);
1231
1232 sp<EffectChain> chain = getEffectChain_l(sessionId);
1233 if (chain != 0) {
1234 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1235 track->setMainBuffer(chain->inBuffer());
1236 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1237 chain->incTrackCnt();
1238 }
1239
1240 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1241 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1242 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1243 // so ask activity manager to do this on our behalf
1244 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1245 }
1246 }
1247
1248 lStatus = NO_ERROR;
1249
1250Exit:
1251 if (status) {
1252 *status = lStatus;
1253 }
1254 return track;
1255}
1256
1257uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1258{
1259 return latency;
1260}
1261
1262uint32_t AudioFlinger::PlaybackThread::latency() const
1263{
1264 Mutex::Autolock _l(mLock);
1265 return latency_l();
1266}
1267uint32_t AudioFlinger::PlaybackThread::latency_l() const
1268{
1269 if (initCheck() == NO_ERROR) {
1270 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1271 } else {
1272 return 0;
1273 }
1274}
1275
1276void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1277{
1278 Mutex::Autolock _l(mLock);
1279 // Don't apply master volume in SW if our HAL can do it for us.
1280 if (mOutput && mOutput->audioHwDev &&
1281 mOutput->audioHwDev->canSetMasterVolume()) {
1282 mMasterVolume = 1.0;
1283 } else {
1284 mMasterVolume = value;
1285 }
1286}
1287
1288void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1289{
1290 Mutex::Autolock _l(mLock);
1291 // Don't apply master mute in SW if our HAL can do it for us.
1292 if (mOutput && mOutput->audioHwDev &&
1293 mOutput->audioHwDev->canSetMasterMute()) {
1294 mMasterMute = false;
1295 } else {
1296 mMasterMute = muted;
1297 }
1298}
1299
1300void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1301{
1302 Mutex::Autolock _l(mLock);
1303 mStreamTypes[stream].volume = value;
1304}
1305
1306void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1307{
1308 Mutex::Autolock _l(mLock);
1309 mStreamTypes[stream].mute = muted;
1310}
1311
1312float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1313{
1314 Mutex::Autolock _l(mLock);
1315 return mStreamTypes[stream].volume;
1316}
1317
1318// addTrack_l() must be called with ThreadBase::mLock held
1319status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1320{
Glenn Kasten32584a72013-02-13 14:46:45 -08001321 mNBLogWriter->logf("addTrack_l mName=%d mFastIndex=%d caller=%d", track->mName,
1322 track->mFastIndex, IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001323 status_t status = ALREADY_EXISTS;
1324
1325 // set retry count for buffer fill
1326 track->mRetryCount = kMaxTrackStartupRetries;
1327 if (mActiveTracks.indexOf(track) < 0) {
1328 // the track is newly added, make sure it fills up all its
1329 // buffers before playing. This is to ensure the client will
1330 // effectively get the latency it requested.
1331 track->mFillingUpStatus = Track::FS_FILLING;
1332 track->mResetDone = false;
1333 track->mPresentationCompleteFrames = 0;
1334 mActiveTracks.add(track);
1335 if (track->mainBuffer() != mMixBuffer) {
1336 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1337 if (chain != 0) {
1338 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1339 track->sessionId());
1340 chain->incActiveTrackCnt();
1341 }
1342 }
1343
1344 status = NO_ERROR;
1345 }
1346
1347 ALOGV("mWaitWorkCV.broadcast");
1348 mWaitWorkCV.broadcast();
1349
1350 return status;
1351}
1352
1353// destroyTrack_l() must be called with ThreadBase::mLock held
1354void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1355{
Glenn Kasten32584a72013-02-13 14:46:45 -08001356 mNBLogWriter->logTimestamp();
1357 mNBLogWriter->logf("destroyTrack_l mName=%d mFastIndex=%d mClientPid=%d", track->mName,
1358 track->mFastIndex, track->mClient != 0 ? track->mClient->pid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08001359 track->mState = TrackBase::TERMINATED;
1360 // active tracks are removed by threadLoop()
1361 if (mActiveTracks.indexOf(track) < 0) {
1362 removeTrack_l(track);
1363 }
1364}
1365
1366void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1367{
Glenn Kasten32584a72013-02-13 14:46:45 -08001368 mNBLogWriter->logTimestamp();
1369 mNBLogWriter->logf("removeTrack_l mName=%d mFastIndex=%d clientPid=%d", track->mName,
1370 track->mFastIndex, track->mClient != 0 ? track->mClient->pid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08001371 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1372 mTracks.remove(track);
1373 deleteTrackName_l(track->name());
1374 // redundant as track is about to be destroyed, for dumpsys only
1375 track->mName = -1;
1376 if (track->isFastTrack()) {
1377 int index = track->mFastIndex;
1378 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1379 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1380 mFastTrackAvailMask |= 1 << index;
1381 // redundant as track is about to be destroyed, for dumpsys only
1382 track->mFastIndex = -1;
1383 }
1384 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1385 if (chain != 0) {
1386 chain->decTrackCnt();
1387 }
1388}
1389
1390String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1391{
1392 String8 out_s8 = String8("");
1393 char *s;
1394
1395 Mutex::Autolock _l(mLock);
1396 if (initCheck() != NO_ERROR) {
1397 return out_s8;
1398 }
1399
1400 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1401 out_s8 = String8(s);
1402 free(s);
1403 return out_s8;
1404}
1405
1406// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1407void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1408 AudioSystem::OutputDescriptor desc;
1409 void *param2 = NULL;
1410
1411 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1412 param);
1413
1414 switch (event) {
1415 case AudioSystem::OUTPUT_OPENED:
1416 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1417 desc.channels = mChannelMask;
1418 desc.samplingRate = mSampleRate;
1419 desc.format = mFormat;
1420 desc.frameCount = mNormalFrameCount; // FIXME see
1421 // AudioFlinger::frameCount(audio_io_handle_t)
1422 desc.latency = latency();
1423 param2 = &desc;
1424 break;
1425
1426 case AudioSystem::STREAM_CONFIG_CHANGED:
1427 param2 = &param;
1428 case AudioSystem::OUTPUT_CLOSED:
1429 default:
1430 break;
1431 }
1432 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1433}
1434
1435void AudioFlinger::PlaybackThread::readOutputParameters()
1436{
1437 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1438 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1439 mChannelCount = (uint16_t)popcount(mChannelMask);
1440 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1441 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1442 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1443 if (mFrameCount & 15) {
1444 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1445 mFrameCount);
1446 }
1447
1448 // Calculate size of normal mix buffer relative to the HAL output buffer size
1449 double multiplier = 1.0;
1450 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1451 kUseFastMixer == FastMixer_Dynamic)) {
1452 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1453 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1454 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1455 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1456 maxNormalFrameCount = maxNormalFrameCount & ~15;
1457 if (maxNormalFrameCount < minNormalFrameCount) {
1458 maxNormalFrameCount = minNormalFrameCount;
1459 }
1460 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1461 if (multiplier <= 1.0) {
1462 multiplier = 1.0;
1463 } else if (multiplier <= 2.0) {
1464 if (2 * mFrameCount <= maxNormalFrameCount) {
1465 multiplier = 2.0;
1466 } else {
1467 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1468 }
1469 } else {
1470 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1471 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1472 // track, but we sometimes have to do this to satisfy the maximum frame count
1473 // constraint)
1474 // FIXME this rounding up should not be done if no HAL SRC
1475 uint32_t truncMult = (uint32_t) multiplier;
1476 if ((truncMult & 1)) {
1477 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1478 ++truncMult;
1479 }
1480 }
1481 multiplier = (double) truncMult;
1482 }
1483 }
1484 mNormalFrameCount = multiplier * mFrameCount;
1485 // round up to nearest 16 frames to satisfy AudioMixer
1486 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1487 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1488 mNormalFrameCount);
1489
1490 delete[] mMixBuffer;
1491 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
1492 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
1493
1494 // force reconfiguration of effect chains and engines to take new buffer size and audio
1495 // parameters into account
1496 // Note that mLock is not held when readOutputParameters() is called from the constructor
1497 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1498 // matter.
1499 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1500 Vector< sp<EffectChain> > effectChains = mEffectChains;
1501 for (size_t i = 0; i < effectChains.size(); i ++) {
1502 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1503 }
1504}
1505
1506
1507status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1508{
1509 if (halFrames == NULL || dspFrames == NULL) {
1510 return BAD_VALUE;
1511 }
1512 Mutex::Autolock _l(mLock);
1513 if (initCheck() != NO_ERROR) {
1514 return INVALID_OPERATION;
1515 }
1516 size_t framesWritten = mBytesWritten / mFrameSize;
1517 *halFrames = framesWritten;
1518
1519 if (isSuspended()) {
1520 // return an estimation of rendered frames when the output is suspended
1521 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1522 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1523 return NO_ERROR;
1524 } else {
1525 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1526 }
1527}
1528
1529uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1530{
1531 Mutex::Autolock _l(mLock);
1532 uint32_t result = 0;
1533 if (getEffectChain_l(sessionId) != 0) {
1534 result = EFFECT_SESSION;
1535 }
1536
1537 for (size_t i = 0; i < mTracks.size(); ++i) {
1538 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001539 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001540 result |= TRACK_SESSION;
1541 break;
1542 }
1543 }
1544
1545 return result;
1546}
1547
1548uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1549{
1550 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1551 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1552 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1553 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1554 }
1555 for (size_t i = 0; i < mTracks.size(); i++) {
1556 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001557 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001558 return AudioSystem::getStrategyForStream(track->streamType());
1559 }
1560 }
1561 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1562}
1563
1564
1565AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1566{
1567 Mutex::Autolock _l(mLock);
1568 return mOutput;
1569}
1570
1571AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1572{
1573 Mutex::Autolock _l(mLock);
1574 AudioStreamOut *output = mOutput;
1575 mOutput = NULL;
1576 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1577 // must push a NULL and wait for ack
1578 mOutputSink.clear();
1579 mPipeSink.clear();
1580 mNormalSink.clear();
1581 return output;
1582}
1583
1584// this method must always be called either with ThreadBase mLock held or inside the thread loop
1585audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1586{
1587 if (mOutput == NULL) {
1588 return NULL;
1589 }
1590 return &mOutput->stream->common;
1591}
1592
1593uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1594{
1595 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1596}
1597
1598status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1599{
1600 if (!isValidSyncEvent(event)) {
1601 return BAD_VALUE;
1602 }
1603
1604 Mutex::Autolock _l(mLock);
1605
1606 for (size_t i = 0; i < mTracks.size(); ++i) {
1607 sp<Track> track = mTracks[i];
1608 if (event->triggerSession() == track->sessionId()) {
1609 (void) track->setSyncEvent(event);
1610 return NO_ERROR;
1611 }
1612 }
1613
1614 return NAME_NOT_FOUND;
1615}
1616
1617bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1618{
1619 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1620}
1621
1622void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1623 const Vector< sp<Track> >& tracksToRemove)
1624{
1625 size_t count = tracksToRemove.size();
1626 if (CC_UNLIKELY(count)) {
1627 for (size_t i = 0 ; i < count ; i++) {
1628 const sp<Track>& track = tracksToRemove.itemAt(i);
1629 if ((track->sharedBuffer() != 0) &&
1630 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
1631 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1632 }
1633 }
1634 }
1635
1636}
1637
1638void AudioFlinger::PlaybackThread::checkSilentMode_l()
1639{
1640 if (!mMasterMute) {
1641 char value[PROPERTY_VALUE_MAX];
1642 if (property_get("ro.audio.silent", value, "0") > 0) {
1643 char *endptr;
1644 unsigned long ul = strtoul(value, &endptr, 0);
1645 if (*endptr == '\0' && ul != 0) {
1646 ALOGD("Silence is golden");
1647 // The setprop command will not allow a property to be changed after
1648 // the first time it is set, so we don't have to worry about un-muting.
1649 setMasterMute_l(true);
1650 }
1651 }
1652 }
1653}
1654
1655// shared by MIXER and DIRECT, overridden by DUPLICATING
1656void AudioFlinger::PlaybackThread::threadLoop_write()
1657{
1658 // FIXME rewrite to reduce number of system calls
1659 mLastWriteTime = systemTime();
1660 mInWrite = true;
1661 int bytesWritten;
1662
1663 // If an NBAIO sink is present, use it to write the normal mixer's submix
1664 if (mNormalSink != 0) {
1665#define mBitShift 2 // FIXME
1666 size_t count = mixBufferSize >> mBitShift;
Simon Wilson2d590962012-11-29 15:18:50 -08001667 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001668 // update the setpoint when AudioFlinger::mScreenState changes
1669 uint32_t screenState = AudioFlinger::mScreenState;
1670 if (screenState != mScreenState) {
1671 mScreenState = screenState;
1672 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1673 if (pipe != NULL) {
1674 pipe->setAvgFrames((mScreenState & 1) ?
1675 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1676 }
1677 }
1678 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001679 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001680 if (framesWritten > 0) {
1681 bytesWritten = framesWritten << mBitShift;
1682 } else {
1683 bytesWritten = framesWritten;
1684 }
1685 // otherwise use the HAL / AudioStreamOut directly
1686 } else {
1687 // Direct output thread.
1688 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
1689 }
1690
1691 if (bytesWritten > 0) {
1692 mBytesWritten += mixBufferSize;
1693 }
1694 mNumWrites++;
1695 mInWrite = false;
1696}
1697
1698/*
1699The derived values that are cached:
1700 - mixBufferSize from frame count * frame size
1701 - activeSleepTime from activeSleepTimeUs()
1702 - idleSleepTime from idleSleepTimeUs()
1703 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1704 - maxPeriod from frame count and sample rate (MIXER only)
1705
1706The parameters that affect these derived values are:
1707 - frame count
1708 - frame size
1709 - sample rate
1710 - device type: A2DP or not
1711 - device latency
1712 - format: PCM or not
1713 - active sleep time
1714 - idle sleep time
1715*/
1716
1717void AudioFlinger::PlaybackThread::cacheParameters_l()
1718{
1719 mixBufferSize = mNormalFrameCount * mFrameSize;
1720 activeSleepTime = activeSleepTimeUs();
1721 idleSleepTime = idleSleepTimeUs();
1722}
1723
1724void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1725{
1726 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1727 this, streamType, mTracks.size());
1728 Mutex::Autolock _l(mLock);
1729
1730 size_t size = mTracks.size();
1731 for (size_t i = 0; i < size; i++) {
1732 sp<Track> t = mTracks[i];
1733 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001734 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001735 }
1736 }
1737}
1738
1739status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1740{
1741 int session = chain->sessionId();
1742 int16_t *buffer = mMixBuffer;
1743 bool ownsBuffer = false;
1744
1745 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1746 if (session > 0) {
1747 // Only one effect chain can be present in direct output thread and it uses
1748 // the mix buffer as input
1749 if (mType != DIRECT) {
1750 size_t numSamples = mNormalFrameCount * mChannelCount;
1751 buffer = new int16_t[numSamples];
1752 memset(buffer, 0, numSamples * sizeof(int16_t));
1753 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1754 ownsBuffer = true;
1755 }
1756
1757 // Attach all tracks with same session ID to this chain.
1758 for (size_t i = 0; i < mTracks.size(); ++i) {
1759 sp<Track> track = mTracks[i];
1760 if (session == track->sessionId()) {
1761 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1762 buffer);
1763 track->setMainBuffer(buffer);
1764 chain->incTrackCnt();
1765 }
1766 }
1767
1768 // indicate all active tracks in the chain
1769 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1770 sp<Track> track = mActiveTracks[i].promote();
1771 if (track == 0) {
1772 continue;
1773 }
1774 if (session == track->sessionId()) {
1775 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1776 chain->incActiveTrackCnt();
1777 }
1778 }
1779 }
1780
1781 chain->setInBuffer(buffer, ownsBuffer);
1782 chain->setOutBuffer(mMixBuffer);
1783 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1784 // chains list in order to be processed last as it contains output stage effects
1785 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1786 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1787 // after track specific effects and before output stage
1788 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1789 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1790 // Effect chain for other sessions are inserted at beginning of effect
1791 // chains list to be processed before output mix effects. Relative order between other
1792 // sessions is not important
1793 size_t size = mEffectChains.size();
1794 size_t i = 0;
1795 for (i = 0; i < size; i++) {
1796 if (mEffectChains[i]->sessionId() < session) {
1797 break;
1798 }
1799 }
1800 mEffectChains.insertAt(chain, i);
1801 checkSuspendOnAddEffectChain_l(chain);
1802
1803 return NO_ERROR;
1804}
1805
1806size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1807{
1808 int session = chain->sessionId();
1809
1810 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1811
1812 for (size_t i = 0; i < mEffectChains.size(); i++) {
1813 if (chain == mEffectChains[i]) {
1814 mEffectChains.removeAt(i);
1815 // detach all active tracks from the chain
1816 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1817 sp<Track> track = mActiveTracks[i].promote();
1818 if (track == 0) {
1819 continue;
1820 }
1821 if (session == track->sessionId()) {
1822 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1823 chain.get(), session);
1824 chain->decActiveTrackCnt();
1825 }
1826 }
1827
1828 // detach all tracks with same session ID from this chain
1829 for (size_t i = 0; i < mTracks.size(); ++i) {
1830 sp<Track> track = mTracks[i];
1831 if (session == track->sessionId()) {
1832 track->setMainBuffer(mMixBuffer);
1833 chain->decTrackCnt();
1834 }
1835 }
1836 break;
1837 }
1838 }
1839 return mEffectChains.size();
1840}
1841
1842status_t AudioFlinger::PlaybackThread::attachAuxEffect(
1843 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
1844{
1845 Mutex::Autolock _l(mLock);
1846 return attachAuxEffect_l(track, EffectId);
1847}
1848
1849status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
1850 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
1851{
1852 status_t status = NO_ERROR;
1853
1854 if (EffectId == 0) {
1855 track->setAuxBuffer(0, NULL);
1856 } else {
1857 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
1858 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
1859 if (effect != 0) {
1860 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1861 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
1862 } else {
1863 status = INVALID_OPERATION;
1864 }
1865 } else {
1866 status = BAD_VALUE;
1867 }
1868 }
1869 return status;
1870}
1871
1872void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
1873{
1874 for (size_t i = 0; i < mTracks.size(); ++i) {
1875 sp<Track> track = mTracks[i];
1876 if (track->auxEffectId() == effectId) {
1877 attachAuxEffect_l(track, 0);
1878 }
1879 }
1880}
1881
1882bool AudioFlinger::PlaybackThread::threadLoop()
1883{
1884 Vector< sp<Track> > tracksToRemove;
1885
1886 standbyTime = systemTime();
1887
1888 // MIXER
1889 nsecs_t lastWarning = 0;
1890
1891 // DUPLICATING
1892 // FIXME could this be made local to while loop?
1893 writeFrames = 0;
1894
1895 cacheParameters_l();
1896 sleepTime = idleSleepTime;
1897
1898 if (mType == MIXER) {
1899 sleepTimeShift = 0;
1900 }
1901
1902 CpuStats cpuStats;
1903 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
1904
1905 acquireWakeLock();
1906
Glenn Kasten9e58b552013-01-18 15:09:48 -08001907 // mNBLogWriter->log can only be called while thread mutex mLock is held.
1908 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
1909 // and then that string will be logged at the next convenient opportunity.
1910 const char *logString = NULL;
1911
Eric Laurent81784c32012-11-19 14:55:58 -08001912 while (!exitPending())
1913 {
1914 cpuStats.sample(myName);
1915
1916 Vector< sp<EffectChain> > effectChains;
1917
1918 processConfigEvents();
1919
1920 { // scope for mLock
1921
1922 Mutex::Autolock _l(mLock);
1923
Glenn Kasten9e58b552013-01-18 15:09:48 -08001924 if (logString != NULL) {
1925 mNBLogWriter->logTimestamp();
1926 mNBLogWriter->log(logString);
1927 logString = NULL;
1928 }
1929
Eric Laurent81784c32012-11-19 14:55:58 -08001930 if (checkForNewParameters_l()) {
1931 cacheParameters_l();
1932 }
1933
1934 saveOutputTracks();
1935
1936 // put audio hardware into standby after short delay
1937 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1938 isSuspended())) {
1939 if (!mStandby) {
1940
1941 threadLoop_standby();
1942
Glenn Kasten9e58b552013-01-18 15:09:48 -08001943 mNBLogWriter->log("standby");
Eric Laurent81784c32012-11-19 14:55:58 -08001944 mStandby = true;
1945 }
1946
1947 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1948 // we're about to wait, flush the binder command buffer
1949 IPCThreadState::self()->flushCommands();
1950
1951 clearOutputTracks();
1952
1953 if (exitPending()) {
1954 break;
1955 }
1956
1957 releaseWakeLock_l();
1958 // wait until we have something to do...
1959 ALOGV("%s going to sleep", myName.string());
1960 mWaitWorkCV.wait(mLock);
1961 ALOGV("%s waking up", myName.string());
1962 acquireWakeLock_l();
1963
1964 mMixerStatus = MIXER_IDLE;
1965 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
1966 mBytesWritten = 0;
1967
1968 checkSilentMode_l();
1969
1970 standbyTime = systemTime() + standbyDelay;
1971 sleepTime = idleSleepTime;
1972 if (mType == MIXER) {
1973 sleepTimeShift = 0;
1974 }
1975
1976 continue;
1977 }
1978 }
1979
1980 // mMixerStatusIgnoringFastTracks is also updated internally
1981 mMixerStatus = prepareTracks_l(&tracksToRemove);
1982
1983 // prevent any changes in effect chain list and in each effect chain
1984 // during mixing and effect process as the audio buffers could be deleted
1985 // or modified if an effect is created or deleted
1986 lockEffectChains_l(effectChains);
1987 }
1988
1989 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
1990 threadLoop_mix();
1991 } else {
1992 threadLoop_sleepTime();
1993 }
1994
1995 if (isSuspended()) {
1996 sleepTime = suspendSleepTimeUs();
1997 mBytesWritten += mixBufferSize;
1998 }
1999
2000 // only process effects if we're going to write
2001 if (sleepTime == 0) {
2002 for (size_t i = 0; i < effectChains.size(); i ++) {
2003 effectChains[i]->process_l();
2004 }
2005 }
2006
2007 // enable changes in effect chain
2008 unlockEffectChains(effectChains);
2009
2010 // sleepTime == 0 means we must write to audio hardware
2011 if (sleepTime == 0) {
2012
2013 threadLoop_write();
2014
2015if (mType == MIXER) {
2016 // write blocked detection
2017 nsecs_t now = systemTime();
2018 nsecs_t delta = now - mLastWriteTime;
2019 if (!mStandby && delta > maxPeriod) {
2020 mNumDelayedWrites++;
2021 if ((now - lastWarning) > kWarningThrottleNs) {
Alex Ray371eb972012-11-30 11:11:54 -08002022 ATRACE_NAME("underrun");
Eric Laurent81784c32012-11-19 14:55:58 -08002023 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2024 ns2ms(delta), mNumDelayedWrites, this);
2025 lastWarning = now;
2026 }
2027 }
2028}
2029
2030 mStandby = false;
2031 } else {
2032 usleep(sleepTime);
2033 }
2034
2035 // Finally let go of removed track(s), without the lock held
2036 // since we can't guarantee the destructors won't acquire that
2037 // same lock. This will also mutate and push a new fast mixer state.
2038 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten9e58b552013-01-18 15:09:48 -08002039 if (tracksToRemove.size() > 0) {
2040 logString = "remove";
2041 }
Eric Laurent81784c32012-11-19 14:55:58 -08002042 tracksToRemove.clear();
2043
2044 // FIXME I don't understand the need for this here;
2045 // it was in the original code but maybe the
2046 // assignment in saveOutputTracks() makes this unnecessary?
2047 clearOutputTracks();
2048
2049 // Effect chains will be actually deleted here if they were removed from
2050 // mEffectChains list during mixing or effects processing
2051 effectChains.clear();
2052
2053 // FIXME Note that the above .clear() is no longer necessary since effectChains
2054 // is now local to this block, but will keep it for now (at least until merge done).
2055 }
2056
2057 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2058 if (mType == MIXER || mType == DIRECT) {
2059 // put output stream into standby mode
2060 if (!mStandby) {
2061 mOutput->stream->common.standby(&mOutput->stream->common);
2062 }
2063 }
2064
2065 releaseWakeLock();
2066
2067 ALOGV("Thread %p type %d exiting", this, mType);
2068 return false;
2069}
2070
2071
2072// ----------------------------------------------------------------------------
2073
2074AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2075 audio_io_handle_t id, audio_devices_t device, type_t type)
2076 : PlaybackThread(audioFlinger, output, id, device, type),
2077 // mAudioMixer below
2078 // mFastMixer below
2079 mFastMixerFutex(0)
2080 // mOutputSink below
2081 // mPipeSink below
2082 // mNormalSink below
2083{
2084 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2085 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, "
2086 "mFrameCount=%d, mNormalFrameCount=%d",
2087 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2088 mNormalFrameCount);
2089 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2090
2091 // FIXME - Current mixer implementation only supports stereo output
2092 if (mChannelCount != FCC_2) {
2093 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2094 }
2095
2096 // create an NBAIO sink for the HAL output stream, and negotiate
2097 mOutputSink = new AudioStreamOutSink(output->stream);
2098 size_t numCounterOffers = 0;
2099 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2100 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2101 ALOG_ASSERT(index == 0);
2102
2103 // initialize fast mixer depending on configuration
2104 bool initFastMixer;
2105 switch (kUseFastMixer) {
2106 case FastMixer_Never:
2107 initFastMixer = false;
2108 break;
2109 case FastMixer_Always:
2110 initFastMixer = true;
2111 break;
2112 case FastMixer_Static:
2113 case FastMixer_Dynamic:
2114 initFastMixer = mFrameCount < mNormalFrameCount;
2115 break;
2116 }
2117 if (initFastMixer) {
2118
2119 // create a MonoPipe to connect our submix to FastMixer
2120 NBAIO_Format format = mOutputSink->format();
2121 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2122 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2123 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2124 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2125 const NBAIO_Format offers[1] = {format};
2126 size_t numCounterOffers = 0;
2127 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2128 ALOG_ASSERT(index == 0);
2129 monoPipe->setAvgFrames((mScreenState & 1) ?
2130 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2131 mPipeSink = monoPipe;
2132
2133#ifdef TEE_SINK_FRAMES
2134 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2135 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2136 numCounterOffers = 0;
2137 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2138 ALOG_ASSERT(index == 0);
2139 mTeeSink = teeSink;
2140 PipeReader *teeSource = new PipeReader(*teeSink);
2141 numCounterOffers = 0;
2142 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2143 ALOG_ASSERT(index == 0);
2144 mTeeSource = teeSource;
2145#endif
2146
2147 // create fast mixer and configure it initially with just one fast track for our submix
2148 mFastMixer = new FastMixer();
2149 FastMixerStateQueue *sq = mFastMixer->sq();
2150#ifdef STATE_QUEUE_DUMP
2151 sq->setObserverDump(&mStateQueueObserverDump);
2152 sq->setMutatorDump(&mStateQueueMutatorDump);
2153#endif
2154 FastMixerState *state = sq->begin();
2155 FastTrack *fastTrack = &state->mFastTracks[0];
2156 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2157 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
Glenn Kasten32584a72013-02-13 14:46:45 -08002158 mNBLogWriter->logf("fastTrack0 bp=%p", fastTrack->mBufferProvider);
Eric Laurent81784c32012-11-19 14:55:58 -08002159 fastTrack->mVolumeProvider = NULL;
2160 fastTrack->mGeneration++;
2161 state->mFastTracksGen++;
2162 state->mTrackMask = 1;
2163 // fast mixer will use the HAL output sink
2164 state->mOutputSink = mOutputSink.get();
2165 state->mOutputSinkGen++;
2166 state->mFrameCount = mFrameCount;
2167 state->mCommand = FastMixerState::COLD_IDLE;
2168 // already done in constructor initialization list
2169 //mFastMixerFutex = 0;
2170 state->mColdFutexAddr = &mFastMixerFutex;
2171 state->mColdGen++;
2172 state->mDumpState = &mFastMixerDumpState;
2173 state->mTeeSink = mTeeSink.get();
Glenn Kasten9e58b552013-01-18 15:09:48 -08002174 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2175 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002176 sq->end();
2177 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2178
2179 // start the fast mixer
2180 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2181 pid_t tid = mFastMixer->getTid();
2182 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2183 if (err != 0) {
2184 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2185 kPriorityFastMixer, getpid_cached, tid, err);
2186 }
2187
2188#ifdef AUDIO_WATCHDOG
2189 // create and start the watchdog
2190 mAudioWatchdog = new AudioWatchdog();
2191 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2192 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2193 tid = mAudioWatchdog->getTid();
2194 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2195 if (err != 0) {
2196 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2197 kPriorityFastMixer, getpid_cached, tid, err);
2198 }
2199#endif
2200
2201 } else {
2202 mFastMixer = NULL;
2203 }
2204
2205 switch (kUseFastMixer) {
2206 case FastMixer_Never:
2207 case FastMixer_Dynamic:
2208 mNormalSink = mOutputSink;
2209 break;
2210 case FastMixer_Always:
2211 mNormalSink = mPipeSink;
2212 break;
2213 case FastMixer_Static:
2214 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2215 break;
2216 }
2217}
2218
2219AudioFlinger::MixerThread::~MixerThread()
2220{
2221 if (mFastMixer != NULL) {
2222 FastMixerStateQueue *sq = mFastMixer->sq();
2223 FastMixerState *state = sq->begin();
2224 if (state->mCommand == FastMixerState::COLD_IDLE) {
2225 int32_t old = android_atomic_inc(&mFastMixerFutex);
2226 if (old == -1) {
2227 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2228 }
2229 }
2230 state->mCommand = FastMixerState::EXIT;
2231 sq->end();
2232 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2233 mFastMixer->join();
2234 // Though the fast mixer thread has exited, it's state queue is still valid.
2235 // We'll use that extract the final state which contains one remaining fast track
2236 // corresponding to our sub-mix.
2237 state = sq->begin();
2238 ALOG_ASSERT(state->mTrackMask == 1);
2239 FastTrack *fastTrack = &state->mFastTracks[0];
2240 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2241 delete fastTrack->mBufferProvider;
2242 sq->end(false /*didModify*/);
2243 delete mFastMixer;
2244#ifdef AUDIO_WATCHDOG
2245 if (mAudioWatchdog != 0) {
2246 mAudioWatchdog->requestExit();
2247 mAudioWatchdog->requestExitAndWait();
2248 mAudioWatchdog.clear();
2249 }
2250#endif
2251 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002252 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002253 delete mAudioMixer;
2254}
2255
2256
2257uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2258{
2259 if (mFastMixer != NULL) {
2260 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2261 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2262 }
2263 return latency;
2264}
2265
2266
2267void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2268{
2269 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2270}
2271
2272void AudioFlinger::MixerThread::threadLoop_write()
2273{
2274 // FIXME we should only do one push per cycle; confirm this is true
2275 // Start the fast mixer if it's not already running
2276 if (mFastMixer != NULL) {
2277 FastMixerStateQueue *sq = mFastMixer->sq();
2278 FastMixerState *state = sq->begin();
2279 if (state->mCommand != FastMixerState::MIX_WRITE &&
2280 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2281 if (state->mCommand == FastMixerState::COLD_IDLE) {
2282 int32_t old = android_atomic_inc(&mFastMixerFutex);
2283 if (old == -1) {
2284 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2285 }
2286#ifdef AUDIO_WATCHDOG
2287 if (mAudioWatchdog != 0) {
2288 mAudioWatchdog->resume();
2289 }
2290#endif
2291 }
2292 state->mCommand = FastMixerState::MIX_WRITE;
2293 sq->end();
2294 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2295 if (kUseFastMixer == FastMixer_Dynamic) {
2296 mNormalSink = mPipeSink;
2297 }
2298 } else {
2299 sq->end(false /*didModify*/);
2300 }
2301 }
2302 PlaybackThread::threadLoop_write();
2303}
2304
2305void AudioFlinger::MixerThread::threadLoop_standby()
2306{
2307 // Idle the fast mixer if it's currently running
2308 if (mFastMixer != NULL) {
2309 FastMixerStateQueue *sq = mFastMixer->sq();
2310 FastMixerState *state = sq->begin();
2311 if (!(state->mCommand & FastMixerState::IDLE)) {
2312 state->mCommand = FastMixerState::COLD_IDLE;
2313 state->mColdFutexAddr = &mFastMixerFutex;
2314 state->mColdGen++;
2315 mFastMixerFutex = 0;
2316 sq->end();
2317 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2318 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2319 if (kUseFastMixer == FastMixer_Dynamic) {
2320 mNormalSink = mOutputSink;
2321 }
2322#ifdef AUDIO_WATCHDOG
2323 if (mAudioWatchdog != 0) {
2324 mAudioWatchdog->pause();
2325 }
2326#endif
2327 } else {
2328 sq->end(false /*didModify*/);
2329 }
2330 }
2331 PlaybackThread::threadLoop_standby();
2332}
2333
2334// shared by MIXER and DIRECT, overridden by DUPLICATING
2335void AudioFlinger::PlaybackThread::threadLoop_standby()
2336{
2337 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2338 mOutput->stream->common.standby(&mOutput->stream->common);
2339}
2340
2341void AudioFlinger::MixerThread::threadLoop_mix()
2342{
2343 // obtain the presentation timestamp of the next output buffer
2344 int64_t pts;
2345 status_t status = INVALID_OPERATION;
2346
2347 if (mNormalSink != 0) {
2348 status = mNormalSink->getNextWriteTimestamp(&pts);
2349 } else {
2350 status = mOutputSink->getNextWriteTimestamp(&pts);
2351 }
2352
2353 if (status != NO_ERROR) {
2354 pts = AudioBufferProvider::kInvalidPTS;
2355 }
2356
2357 // mix buffers...
2358 mAudioMixer->process(pts);
2359 // increase sleep time progressively when application underrun condition clears.
2360 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2361 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2362 // such that we would underrun the audio HAL.
2363 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2364 sleepTimeShift--;
2365 }
2366 sleepTime = 0;
2367 standbyTime = systemTime() + standbyDelay;
2368 //TODO: delay standby when effects have a tail
2369}
2370
2371void AudioFlinger::MixerThread::threadLoop_sleepTime()
2372{
2373 // If no tracks are ready, sleep once for the duration of an output
2374 // buffer size, then write 0s to the output
2375 if (sleepTime == 0) {
2376 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2377 sleepTime = activeSleepTime >> sleepTimeShift;
2378 if (sleepTime < kMinThreadSleepTimeUs) {
2379 sleepTime = kMinThreadSleepTimeUs;
2380 }
2381 // reduce sleep time in case of consecutive application underruns to avoid
2382 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2383 // duration we would end up writing less data than needed by the audio HAL if
2384 // the condition persists.
2385 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2386 sleepTimeShift++;
2387 }
2388 } else {
2389 sleepTime = idleSleepTime;
2390 }
2391 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2392 memset (mMixBuffer, 0, mixBufferSize);
2393 sleepTime = 0;
2394 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2395 "anticipated start");
2396 }
2397 // TODO add standby time extension fct of effect tail
2398}
2399
2400// prepareTracks_l() must be called with ThreadBase::mLock held
2401AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2402 Vector< sp<Track> > *tracksToRemove)
2403{
2404
2405 mixer_state mixerStatus = MIXER_IDLE;
2406 // find out which tracks need to be processed
2407 size_t count = mActiveTracks.size();
2408 size_t mixedTracks = 0;
2409 size_t tracksWithEffect = 0;
2410 // counts only _active_ fast tracks
2411 size_t fastTracks = 0;
2412 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2413
2414 float masterVolume = mMasterVolume;
2415 bool masterMute = mMasterMute;
2416
2417 if (masterMute) {
2418 masterVolume = 0;
2419 }
2420 // Delegate master volume control to effect in output mix effect chain if needed
2421 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2422 if (chain != 0) {
2423 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2424 chain->setVolume_l(&v, &v);
2425 masterVolume = (float)((v + (1 << 23)) >> 24);
2426 chain.clear();
2427 }
2428
2429 // prepare a new state to push
2430 FastMixerStateQueue *sq = NULL;
2431 FastMixerState *state = NULL;
2432 bool didModify = false;
2433 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2434 if (mFastMixer != NULL) {
2435 sq = mFastMixer->sq();
2436 state = sq->begin();
2437 }
2438
2439 for (size_t i=0 ; i<count ; i++) {
2440 sp<Track> t = mActiveTracks[i].promote();
2441 if (t == 0) {
2442 continue;
2443 }
2444
2445 // this const just means the local variable doesn't change
2446 Track* const track = t.get();
2447
2448 // process fast tracks
2449 if (track->isFastTrack()) {
2450
2451 // It's theoretically possible (though unlikely) for a fast track to be created
2452 // and then removed within the same normal mix cycle. This is not a problem, as
2453 // the track never becomes active so it's fast mixer slot is never touched.
2454 // The converse, of removing an (active) track and then creating a new track
2455 // at the identical fast mixer slot within the same normal mix cycle,
2456 // is impossible because the slot isn't marked available until the end of each cycle.
2457 int j = track->mFastIndex;
2458 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2459 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2460 FastTrack *fastTrack = &state->mFastTracks[j];
2461
2462 // Determine whether the track is currently in underrun condition,
2463 // and whether it had a recent underrun.
2464 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2465 FastTrackUnderruns underruns = ftDump->mUnderruns;
2466 uint32_t recentFull = (underruns.mBitFields.mFull -
2467 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2468 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2469 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2470 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2471 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2472 uint32_t recentUnderruns = recentPartial + recentEmpty;
2473 track->mObservedUnderruns = underruns;
2474 // don't count underruns that occur while stopping or pausing
2475 // or stopped which can occur when flush() is called while active
2476 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2477 track->mUnderrunCount += recentUnderruns;
2478 }
2479
2480 // This is similar to the state machine for normal tracks,
2481 // with a few modifications for fast tracks.
2482 bool isActive = true;
2483 switch (track->mState) {
2484 case TrackBase::STOPPING_1:
2485 // track stays active in STOPPING_1 state until first underrun
2486 if (recentUnderruns > 0) {
2487 track->mState = TrackBase::STOPPING_2;
2488 }
2489 break;
2490 case TrackBase::PAUSING:
2491 // ramp down is not yet implemented
2492 track->setPaused();
2493 break;
2494 case TrackBase::RESUMING:
2495 // ramp up is not yet implemented
2496 track->mState = TrackBase::ACTIVE;
2497 break;
2498 case TrackBase::ACTIVE:
2499 if (recentFull > 0 || recentPartial > 0) {
2500 // track has provided at least some frames recently: reset retry count
2501 track->mRetryCount = kMaxTrackRetries;
2502 }
2503 if (recentUnderruns == 0) {
2504 // no recent underruns: stay active
2505 break;
2506 }
2507 // there has recently been an underrun of some kind
2508 if (track->sharedBuffer() == 0) {
2509 // were any of the recent underruns "empty" (no frames available)?
2510 if (recentEmpty == 0) {
2511 // no, then ignore the partial underruns as they are allowed indefinitely
2512 break;
2513 }
2514 // there has recently been an "empty" underrun: decrement the retry counter
2515 if (--(track->mRetryCount) > 0) {
2516 break;
2517 }
2518 // indicate to client process that the track was disabled because of underrun;
2519 // it will then automatically call start() when data is available
2520 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
2521 // remove from active list, but state remains ACTIVE [confusing but true]
2522 isActive = false;
2523 break;
2524 }
2525 // fall through
2526 case TrackBase::STOPPING_2:
2527 case TrackBase::PAUSED:
2528 case TrackBase::TERMINATED:
2529 case TrackBase::STOPPED:
2530 case TrackBase::FLUSHED: // flush() while active
2531 // Check for presentation complete if track is inactive
2532 // We have consumed all the buffers of this track.
2533 // This would be incomplete if we auto-paused on underrun
2534 {
2535 size_t audioHALFrames =
2536 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2537 size_t framesWritten = mBytesWritten / mFrameSize;
2538 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2539 // track stays in active list until presentation is complete
2540 break;
2541 }
2542 }
2543 if (track->isStopping_2()) {
2544 track->mState = TrackBase::STOPPED;
2545 }
2546 if (track->isStopped()) {
2547 // Can't reset directly, as fast mixer is still polling this track
2548 // track->reset();
2549 // So instead mark this track as needing to be reset after push with ack
2550 resetMask |= 1 << i;
2551 }
2552 isActive = false;
2553 break;
2554 case TrackBase::IDLE:
2555 default:
2556 LOG_FATAL("unexpected track state %d", track->mState);
2557 }
2558
2559 if (isActive) {
2560 // was it previously inactive?
2561 if (!(state->mTrackMask & (1 << j))) {
2562 ExtendedAudioBufferProvider *eabp = track;
Glenn Kasten32584a72013-02-13 14:46:45 -08002563 mNBLogWriter->logf("fastTrack j=%d bp=%p", j, eabp);
Eric Laurent81784c32012-11-19 14:55:58 -08002564 VolumeProvider *vp = track;
2565 fastTrack->mBufferProvider = eabp;
2566 fastTrack->mVolumeProvider = vp;
2567 fastTrack->mSampleRate = track->mSampleRate;
2568 fastTrack->mChannelMask = track->mChannelMask;
2569 fastTrack->mGeneration++;
2570 state->mTrackMask |= 1 << j;
2571 didModify = true;
2572 // no acknowledgement required for newly active tracks
2573 }
2574 // cache the combined master volume and stream type volume for fast mixer; this
2575 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002576 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002577 ++fastTracks;
2578 } else {
2579 // was it previously active?
2580 if (state->mTrackMask & (1 << j)) {
2581 fastTrack->mBufferProvider = NULL;
2582 fastTrack->mGeneration++;
2583 state->mTrackMask &= ~(1 << j);
2584 didModify = true;
2585 // If any fast tracks were removed, we must wait for acknowledgement
2586 // because we're about to decrement the last sp<> on those tracks.
2587 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2588 } else {
2589 LOG_FATAL("fast track %d should have been active", j);
2590 }
2591 tracksToRemove->add(track);
2592 // Avoids a misleading display in dumpsys
2593 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2594 }
2595 continue;
2596 }
2597
2598 { // local variable scope to avoid goto warning
2599
2600 audio_track_cblk_t* cblk = track->cblk();
2601
2602 // The first time a track is added we wait
2603 // for all its buffers to be filled before processing it
2604 int name = track->name();
2605 // make sure that we have enough frames to mix one full buffer.
2606 // enforce this condition only once to enable draining the buffer in case the client
2607 // app does not call stop() and relies on underrun to stop:
2608 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2609 // during last round
2610 uint32_t minFrames = 1;
2611 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2612 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
2613 if (t->sampleRate() == mSampleRate) {
2614 minFrames = mNormalFrameCount;
2615 } else {
2616 // +1 for rounding and +1 for additional sample needed for interpolation
2617 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2618 // add frames already consumed but not yet released by the resampler
2619 // because cblk->framesReady() will include these frames
2620 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2621 // the minimum track buffer size is normally twice the number of frames necessary
2622 // to fill one buffer and the resampler should not leave more than one buffer worth
2623 // of unreleased frames after each pass, but just in case...
Eric Laurent2592f6e2013-01-17 17:36:00 -08002624 ALOG_ASSERT(minFrames <= cblk->frameCount_);
Eric Laurent81784c32012-11-19 14:55:58 -08002625 }
2626 }
2627 if ((track->framesReady() >= minFrames) && track->isReady() &&
2628 !track->isPaused() && !track->isTerminated())
2629 {
2630 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
2631 this);
2632
2633 mixedTracks++;
2634
2635 // track->mainBuffer() != mMixBuffer means there is an effect chain
2636 // connected to the track
2637 chain.clear();
2638 if (track->mainBuffer() != mMixBuffer) {
2639 chain = getEffectChain_l(track->sessionId());
2640 // Delegate volume control to effect in track effect chain if needed
2641 if (chain != 0) {
2642 tracksWithEffect++;
2643 } else {
2644 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2645 "session %d",
2646 name, track->sessionId());
2647 }
2648 }
2649
2650
2651 int param = AudioMixer::VOLUME;
2652 if (track->mFillingUpStatus == Track::FS_FILLED) {
2653 // no ramp for the first volume setting
2654 track->mFillingUpStatus = Track::FS_ACTIVE;
2655 if (track->mState == TrackBase::RESUMING) {
2656 track->mState = TrackBase::ACTIVE;
2657 param = AudioMixer::RAMP_VOLUME;
2658 }
2659 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2660 } else if (cblk->server != 0) {
2661 // If the track is stopped before the first frame was mixed,
2662 // do not apply ramp
2663 param = AudioMixer::RAMP_VOLUME;
2664 }
2665
2666 // compute volume for this track
2667 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002668 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002669 vl = vr = va = 0;
2670 if (track->isPausing()) {
2671 track->setPaused();
2672 }
2673 } else {
2674
2675 // read original volumes with volume control
2676 float typeVolume = mStreamTypes[track->streamType()].volume;
2677 float v = masterVolume * typeVolume;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002678 ServerProxy *proxy = track->mServerProxy;
2679 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002680 vl = vlr & 0xFFFF;
2681 vr = vlr >> 16;
2682 // track volumes come from shared memory, so can't be trusted and must be clamped
2683 if (vl > MAX_GAIN_INT) {
2684 ALOGV("Track left volume out of range: %04X", vl);
2685 vl = MAX_GAIN_INT;
2686 }
2687 if (vr > MAX_GAIN_INT) {
2688 ALOGV("Track right volume out of range: %04X", vr);
2689 vr = MAX_GAIN_INT;
2690 }
2691 // now apply the master volume and stream type volume
2692 vl = (uint32_t)(v * vl) << 12;
2693 vr = (uint32_t)(v * vr) << 12;
2694 // assuming master volume and stream type volume each go up to 1.0,
2695 // vl and vr are now in 8.24 format
2696
Glenn Kastene3aa6592012-12-04 12:22:46 -08002697 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08002698 // send level comes from shared memory and so may be corrupt
2699 if (sendLevel > MAX_GAIN_INT) {
2700 ALOGV("Track send level out of range: %04X", sendLevel);
2701 sendLevel = MAX_GAIN_INT;
2702 }
2703 va = (uint32_t)(v * sendLevel);
2704 }
2705 // Delegate volume control to effect in track effect chain if needed
2706 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2707 // Do not ramp volume if volume is controlled by effect
2708 param = AudioMixer::VOLUME;
2709 track->mHasVolumeController = true;
2710 } else {
2711 // force no volume ramp when volume controller was just disabled or removed
2712 // from effect chain to avoid volume spike
2713 if (track->mHasVolumeController) {
2714 param = AudioMixer::VOLUME;
2715 }
2716 track->mHasVolumeController = false;
2717 }
2718
2719 // Convert volumes from 8.24 to 4.12 format
2720 // This additional clamping is needed in case chain->setVolume_l() overshot
2721 vl = (vl + (1 << 11)) >> 12;
2722 if (vl > MAX_GAIN_INT) {
2723 vl = MAX_GAIN_INT;
2724 }
2725 vr = (vr + (1 << 11)) >> 12;
2726 if (vr > MAX_GAIN_INT) {
2727 vr = MAX_GAIN_INT;
2728 }
2729
2730 if (va > MAX_GAIN_INT) {
2731 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
2732 }
2733
2734 // XXX: these things DON'T need to be done each time
2735 mAudioMixer->setBufferProvider(name, track);
2736 mAudioMixer->enable(name);
2737
2738 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2739 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2740 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
2741 mAudioMixer->setParameter(
2742 name,
2743 AudioMixer::TRACK,
2744 AudioMixer::FORMAT, (void *)track->format());
2745 mAudioMixer->setParameter(
2746 name,
2747 AudioMixer::TRACK,
2748 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08002749 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
2750 uint32_t maxSampleRate = mSampleRate * 2;
2751 uint32_t reqSampleRate = track->mServerProxy->getSampleRate();
2752 if (reqSampleRate == 0) {
2753 reqSampleRate = mSampleRate;
2754 } else if (reqSampleRate > maxSampleRate) {
2755 reqSampleRate = maxSampleRate;
2756 }
Eric Laurent81784c32012-11-19 14:55:58 -08002757 mAudioMixer->setParameter(
2758 name,
2759 AudioMixer::RESAMPLE,
2760 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08002761 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08002762 mAudioMixer->setParameter(
2763 name,
2764 AudioMixer::TRACK,
2765 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2766 mAudioMixer->setParameter(
2767 name,
2768 AudioMixer::TRACK,
2769 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2770
2771 // reset retry count
2772 track->mRetryCount = kMaxTrackRetries;
2773
2774 // If one track is ready, set the mixer ready if:
2775 // - the mixer was not ready during previous round OR
2776 // - no other track is not ready
2777 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
2778 mixerStatus != MIXER_TRACKS_ENABLED) {
2779 mixerStatus = MIXER_TRACKS_READY;
2780 }
2781 } else {
2782 // clear effect chain input buffer if an active track underruns to avoid sending
2783 // previous audio buffer again to effects
2784 chain = getEffectChain_l(track->sessionId());
2785 if (chain != 0) {
2786 chain->clearInputBuffer();
2787 }
2788
2789 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
2790 cblk->server, this);
2791 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
2792 track->isStopped() || track->isPaused()) {
2793 // We have consumed all the buffers of this track.
2794 // Remove it from the list of active tracks.
2795 // TODO: use actual buffer filling status instead of latency when available from
2796 // audio HAL
2797 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
2798 size_t framesWritten = mBytesWritten / mFrameSize;
2799 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
2800 if (track->isStopped()) {
2801 track->reset();
2802 }
2803 tracksToRemove->add(track);
2804 }
2805 } else {
2806 track->mUnderrunCount++;
2807 // No buffers for this track. Give it a few chances to
2808 // fill a buffer, then remove it from active list.
2809 if (--(track->mRetryCount) <= 0) {
2810 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
2811 tracksToRemove->add(track);
2812 // indicate to client process that the track was disabled because of underrun;
2813 // it will then automatically call start() when data is available
2814 android_atomic_or(CBLK_DISABLED, &cblk->flags);
2815 // If one track is not ready, mark the mixer also not ready if:
2816 // - the mixer was ready during previous round OR
2817 // - no other track is ready
2818 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
2819 mixerStatus != MIXER_TRACKS_READY) {
2820 mixerStatus = MIXER_TRACKS_ENABLED;
2821 }
2822 }
2823 mAudioMixer->disable(name);
2824 }
2825
2826 } // local variable scope to avoid goto warning
2827track_is_ready: ;
2828
2829 }
2830
2831 // Push the new FastMixer state if necessary
2832 bool pauseAudioWatchdog = false;
2833 if (didModify) {
2834 state->mFastTracksGen++;
2835 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2836 if (kUseFastMixer == FastMixer_Dynamic &&
2837 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2838 state->mCommand = FastMixerState::COLD_IDLE;
2839 state->mColdFutexAddr = &mFastMixerFutex;
2840 state->mColdGen++;
2841 mFastMixerFutex = 0;
2842 if (kUseFastMixer == FastMixer_Dynamic) {
2843 mNormalSink = mOutputSink;
2844 }
2845 // If we go into cold idle, need to wait for acknowledgement
2846 // so that fast mixer stops doing I/O.
2847 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2848 pauseAudioWatchdog = true;
2849 }
Eric Laurent81784c32012-11-19 14:55:58 -08002850 }
2851 if (sq != NULL) {
Glenn Kasten32584a72013-02-13 14:46:45 -08002852 unsigned trackMask = state->mTrackMask;
Eric Laurent81784c32012-11-19 14:55:58 -08002853 sq->end(didModify);
Glenn Kasten32584a72013-02-13 14:46:45 -08002854 if (didModify) {
2855 mNBLogWriter->logTimestamp();
2856 mNBLogWriter->logf("push trackMask=%#x block=%d", trackMask, block);
2857 }
Eric Laurent81784c32012-11-19 14:55:58 -08002858 sq->push(block);
Glenn Kasten32584a72013-02-13 14:46:45 -08002859 if (didModify) {
2860 mNBLogWriter->logTimestamp();
2861 mNBLogWriter->log("pushed");
2862 }
Eric Laurent81784c32012-11-19 14:55:58 -08002863 }
2864#ifdef AUDIO_WATCHDOG
2865 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
2866 mAudioWatchdog->pause();
2867 }
2868#endif
2869
2870 // Now perform the deferred reset on fast tracks that have stopped
2871 while (resetMask != 0) {
2872 size_t i = __builtin_ctz(resetMask);
2873 ALOG_ASSERT(i < count);
2874 resetMask &= ~(1 << i);
2875 sp<Track> t = mActiveTracks[i].promote();
2876 if (t == 0) {
2877 continue;
2878 }
2879 Track* track = t.get();
2880 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
2881 track->reset();
2882 }
2883
2884 // remove all the tracks that need to be...
2885 count = tracksToRemove->size();
2886 if (CC_UNLIKELY(count)) {
2887 for (size_t i=0 ; i<count ; i++) {
2888 const sp<Track>& track = tracksToRemove->itemAt(i);
Glenn Kasten32584a72013-02-13 14:46:45 -08002889 mNBLogWriter->logTimestamp();
2890 mNBLogWriter->logf("prepareTracks_l remove name=%u mFastIndex=%d", track->name(),
2891 track->mFastIndex);
Eric Laurent81784c32012-11-19 14:55:58 -08002892 mActiveTracks.remove(track);
2893 if (track->mainBuffer() != mMixBuffer) {
2894 chain = getEffectChain_l(track->sessionId());
2895 if (chain != 0) {
2896 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2897 track->sessionId());
2898 chain->decActiveTrackCnt();
2899 }
2900 }
2901 if (track->isTerminated()) {
2902 removeTrack_l(track);
2903 }
2904 }
2905 }
2906
2907 // mix buffer must be cleared if all tracks are connected to an
2908 // effect chain as in this case the mixer will not write to
2909 // mix buffer and track effects will accumulate into it
2910 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
2911 (mixedTracks == 0 && fastTracks > 0)) {
2912 // FIXME as a performance optimization, should remember previous zero status
2913 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2914 }
2915
2916 // if any fast tracks, then status is ready
2917 mMixerStatusIgnoringFastTracks = mixerStatus;
2918 if (fastTracks > 0) {
2919 mixerStatus = MIXER_TRACKS_READY;
2920 }
2921 return mixerStatus;
2922}
2923
2924// getTrackName_l() must be called with ThreadBase::mLock held
2925int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
2926{
2927 return mAudioMixer->getTrackName(channelMask, sessionId);
2928}
2929
2930// deleteTrackName_l() must be called with ThreadBase::mLock held
2931void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2932{
2933 ALOGV("remove track (%d) and delete from mixer", name);
2934 mAudioMixer->deleteTrackName(name);
2935}
2936
2937// checkForNewParameters_l() must be called with ThreadBase::mLock held
2938bool AudioFlinger::MixerThread::checkForNewParameters_l()
2939{
2940 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2941 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2942 bool reconfig = false;
2943
2944 while (!mNewParameters.isEmpty()) {
2945
2946 if (mFastMixer != NULL) {
2947 FastMixerStateQueue *sq = mFastMixer->sq();
2948 FastMixerState *state = sq->begin();
2949 if (!(state->mCommand & FastMixerState::IDLE)) {
2950 previousCommand = state->mCommand;
2951 state->mCommand = FastMixerState::HOT_IDLE;
2952 sq->end();
2953 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2954 } else {
2955 sq->end(false /*didModify*/);
2956 }
2957 }
2958
2959 status_t status = NO_ERROR;
2960 String8 keyValuePair = mNewParameters[0];
2961 AudioParameter param = AudioParameter(keyValuePair);
2962 int value;
2963
2964 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2965 reconfig = true;
2966 }
2967 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
2968 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
2969 status = BAD_VALUE;
2970 } else {
2971 reconfig = true;
2972 }
2973 }
2974 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
2975 if (value != AUDIO_CHANNEL_OUT_STEREO) {
2976 status = BAD_VALUE;
2977 } else {
2978 reconfig = true;
2979 }
2980 }
2981 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2982 // do not accept frame count changes if tracks are open as the track buffer
2983 // size depends on frame count and correct behavior would not be guaranteed
2984 // if frame count is changed after track creation
2985 if (!mTracks.isEmpty()) {
2986 status = INVALID_OPERATION;
2987 } else {
2988 reconfig = true;
2989 }
2990 }
2991 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
2992#ifdef ADD_BATTERY_DATA
2993 // when changing the audio output device, call addBatteryData to notify
2994 // the change
2995 if (mOutDevice != value) {
2996 uint32_t params = 0;
2997 // check whether speaker is on
2998 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
2999 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3000 }
3001
3002 audio_devices_t deviceWithoutSpeaker
3003 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3004 // check if any other device (except speaker) is on
3005 if (value & deviceWithoutSpeaker ) {
3006 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3007 }
3008
3009 if (params != 0) {
3010 addBatteryData(params);
3011 }
3012 }
3013#endif
3014
3015 // forward device change to effects that have requested to be
3016 // aware of attached audio device.
3017 mOutDevice = value;
3018 for (size_t i = 0; i < mEffectChains.size(); i++) {
3019 mEffectChains[i]->setDevice_l(mOutDevice);
3020 }
3021 }
3022
3023 if (status == NO_ERROR) {
3024 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3025 keyValuePair.string());
3026 if (!mStandby && status == INVALID_OPERATION) {
3027 mOutput->stream->common.standby(&mOutput->stream->common);
3028 mStandby = true;
3029 mBytesWritten = 0;
3030 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3031 keyValuePair.string());
3032 }
3033 if (status == NO_ERROR && reconfig) {
3034 delete mAudioMixer;
3035 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3036 mAudioMixer = NULL;
3037 readOutputParameters();
3038 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3039 for (size_t i = 0; i < mTracks.size() ; i++) {
3040 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3041 if (name < 0) {
3042 break;
3043 }
3044 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003045 }
3046 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3047 }
3048 }
3049
3050 mNewParameters.removeAt(0);
3051
3052 mParamStatus = status;
3053 mParamCond.signal();
3054 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3055 // already timed out waiting for the status and will never signal the condition.
3056 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3057 }
3058
3059 if (!(previousCommand & FastMixerState::IDLE)) {
3060 ALOG_ASSERT(mFastMixer != NULL);
3061 FastMixerStateQueue *sq = mFastMixer->sq();
3062 FastMixerState *state = sq->begin();
3063 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3064 state->mCommand = previousCommand;
3065 sq->end();
3066 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3067 }
3068
3069 return reconfig;
3070}
3071
3072
3073void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3074{
3075 const size_t SIZE = 256;
3076 char buffer[SIZE];
3077 String8 result;
3078
3079 PlaybackThread::dumpInternals(fd, args);
3080
3081 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3082 result.append(buffer);
3083 write(fd, result.string(), result.size());
3084
3085 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3086 FastMixerDumpState copy = mFastMixerDumpState;
3087 copy.dump(fd);
3088
3089#ifdef STATE_QUEUE_DUMP
3090 // Similar for state queue
3091 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3092 observerCopy.dump(fd);
3093 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3094 mutatorCopy.dump(fd);
3095#endif
3096
3097 // Write the tee output to a .wav file
3098 dumpTee(fd, mTeeSource, mId);
3099
3100#ifdef AUDIO_WATCHDOG
3101 if (mAudioWatchdog != 0) {
3102 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3103 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3104 wdCopy.dump(fd);
3105 }
3106#endif
3107}
3108
3109uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3110{
3111 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3112}
3113
3114uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3115{
3116 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3117}
3118
3119void AudioFlinger::MixerThread::cacheParameters_l()
3120{
3121 PlaybackThread::cacheParameters_l();
3122
3123 // FIXME: Relaxed timing because of a certain device that can't meet latency
3124 // Should be reduced to 2x after the vendor fixes the driver issue
3125 // increase threshold again due to low power audio mode. The way this warning
3126 // threshold is calculated and its usefulness should be reconsidered anyway.
3127 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3128}
3129
3130// ----------------------------------------------------------------------------
3131
3132AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3133 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3134 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3135 // mLeftVolFloat, mRightVolFloat
3136{
3137}
3138
3139AudioFlinger::DirectOutputThread::~DirectOutputThread()
3140{
3141}
3142
3143AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3144 Vector< sp<Track> > *tracksToRemove
3145)
3146{
3147 sp<Track> trackToRemove;
3148
3149 mixer_state mixerStatus = MIXER_IDLE;
3150
3151 // find out which tracks need to be processed
3152 if (mActiveTracks.size() != 0) {
3153 sp<Track> t = mActiveTracks[0].promote();
3154 // The track died recently
3155 if (t == 0) {
3156 return MIXER_IDLE;
3157 }
3158
3159 Track* const track = t.get();
3160 audio_track_cblk_t* cblk = track->cblk();
3161
3162 // The first time a track is added we wait
3163 // for all its buffers to be filled before processing it
3164 uint32_t minFrames;
3165 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3166 minFrames = mNormalFrameCount;
3167 } else {
3168 minFrames = 1;
3169 }
3170 if ((track->framesReady() >= minFrames) && track->isReady() &&
3171 !track->isPaused() && !track->isTerminated())
3172 {
3173 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3174
3175 if (track->mFillingUpStatus == Track::FS_FILLED) {
3176 track->mFillingUpStatus = Track::FS_ACTIVE;
3177 mLeftVolFloat = mRightVolFloat = 0;
3178 if (track->mState == TrackBase::RESUMING) {
3179 track->mState = TrackBase::ACTIVE;
3180 }
3181 }
3182
3183 // compute volume for this track
3184 float left, right;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003185 if (mMasterMute || track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003186 left = right = 0;
3187 if (track->isPausing()) {
3188 track->setPaused();
3189 }
3190 } else {
3191 float typeVolume = mStreamTypes[track->streamType()].volume;
3192 float v = mMasterVolume * typeVolume;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003193 uint32_t vlr = track->mServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003194 float v_clamped = v * (vlr & 0xFFFF);
3195 if (v_clamped > MAX_GAIN) {
3196 v_clamped = MAX_GAIN;
3197 }
3198 left = v_clamped/MAX_GAIN;
3199 v_clamped = v * (vlr >> 16);
3200 if (v_clamped > MAX_GAIN) {
3201 v_clamped = MAX_GAIN;
3202 }
3203 right = v_clamped/MAX_GAIN;
3204 }
3205
3206 if (left != mLeftVolFloat || right != mRightVolFloat) {
3207 mLeftVolFloat = left;
3208 mRightVolFloat = right;
3209
3210 // Convert volumes from float to 8.24
3211 uint32_t vl = (uint32_t)(left * (1 << 24));
3212 uint32_t vr = (uint32_t)(right * (1 << 24));
3213
3214 // Delegate volume control to effect in track effect chain if needed
3215 // only one effect chain can be present on DirectOutputThread, so if
3216 // there is one, the track is connected to it
3217 if (!mEffectChains.isEmpty()) {
3218 // Do not ramp volume if volume is controlled by effect
3219 mEffectChains[0]->setVolume_l(&vl, &vr);
3220 left = (float)vl / (1 << 24);
3221 right = (float)vr / (1 << 24);
3222 }
3223 mOutput->stream->set_volume(mOutput->stream, left, right);
3224 }
3225
3226 // reset retry count
3227 track->mRetryCount = kMaxTrackRetriesDirect;
3228 mActiveTrack = t;
3229 mixerStatus = MIXER_TRACKS_READY;
3230 } else {
3231 // clear effect chain input buffer if an active track underruns to avoid sending
3232 // previous audio buffer again to effects
3233 if (!mEffectChains.isEmpty()) {
3234 mEffectChains[0]->clearInputBuffer();
3235 }
3236
3237 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3238 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3239 track->isStopped() || track->isPaused()) {
3240 // We have consumed all the buffers of this track.
3241 // Remove it from the list of active tracks.
3242 // TODO: implement behavior for compressed audio
3243 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3244 size_t framesWritten = mBytesWritten / mFrameSize;
3245 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3246 if (track->isStopped()) {
3247 track->reset();
3248 }
3249 trackToRemove = track;
3250 }
3251 } else {
3252 // No buffers for this track. Give it a few chances to
3253 // fill a buffer, then remove it from active list.
3254 if (--(track->mRetryCount) <= 0) {
3255 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3256 trackToRemove = track;
3257 } else {
3258 mixerStatus = MIXER_TRACKS_ENABLED;
3259 }
3260 }
3261 }
3262 }
3263
3264 // FIXME merge this with similar code for removing multiple tracks
3265 // remove all the tracks that need to be...
3266 if (CC_UNLIKELY(trackToRemove != 0)) {
3267 tracksToRemove->add(trackToRemove);
Glenn Kasten9e58b552013-01-18 15:09:48 -08003268#if 0
3269 mNBLogWriter->logf("prepareTracks_l remove name=%u", trackToRemove->name());
3270#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003271 mActiveTracks.remove(trackToRemove);
3272 if (!mEffectChains.isEmpty()) {
3273 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3274 trackToRemove->sessionId());
3275 mEffectChains[0]->decActiveTrackCnt();
3276 }
3277 if (trackToRemove->isTerminated()) {
3278 removeTrack_l(trackToRemove);
3279 }
3280 }
3281
3282 return mixerStatus;
3283}
3284
3285void AudioFlinger::DirectOutputThread::threadLoop_mix()
3286{
3287 AudioBufferProvider::Buffer buffer;
3288 size_t frameCount = mFrameCount;
3289 int8_t *curBuf = (int8_t *)mMixBuffer;
3290 // output audio to hardware
3291 while (frameCount) {
3292 buffer.frameCount = frameCount;
3293 mActiveTrack->getNextBuffer(&buffer);
3294 if (CC_UNLIKELY(buffer.raw == NULL)) {
3295 memset(curBuf, 0, frameCount * mFrameSize);
3296 break;
3297 }
3298 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3299 frameCount -= buffer.frameCount;
3300 curBuf += buffer.frameCount * mFrameSize;
3301 mActiveTrack->releaseBuffer(&buffer);
3302 }
3303 sleepTime = 0;
3304 standbyTime = systemTime() + standbyDelay;
3305 mActiveTrack.clear();
3306
3307}
3308
3309void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3310{
3311 if (sleepTime == 0) {
3312 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3313 sleepTime = activeSleepTime;
3314 } else {
3315 sleepTime = idleSleepTime;
3316 }
3317 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3318 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3319 sleepTime = 0;
3320 }
3321}
3322
3323// getTrackName_l() must be called with ThreadBase::mLock held
3324int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3325 int sessionId)
3326{
3327 return 0;
3328}
3329
3330// deleteTrackName_l() must be called with ThreadBase::mLock held
3331void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3332{
3333}
3334
3335// checkForNewParameters_l() must be called with ThreadBase::mLock held
3336bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3337{
3338 bool reconfig = false;
3339
3340 while (!mNewParameters.isEmpty()) {
3341 status_t status = NO_ERROR;
3342 String8 keyValuePair = mNewParameters[0];
3343 AudioParameter param = AudioParameter(keyValuePair);
3344 int value;
3345
3346 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3347 // do not accept frame count changes if tracks are open as the track buffer
3348 // size depends on frame count and correct behavior would not be garantied
3349 // if frame count is changed after track creation
3350 if (!mTracks.isEmpty()) {
3351 status = INVALID_OPERATION;
3352 } else {
3353 reconfig = true;
3354 }
3355 }
3356 if (status == NO_ERROR) {
3357 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3358 keyValuePair.string());
3359 if (!mStandby && status == INVALID_OPERATION) {
3360 mOutput->stream->common.standby(&mOutput->stream->common);
3361 mStandby = true;
3362 mBytesWritten = 0;
3363 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3364 keyValuePair.string());
3365 }
3366 if (status == NO_ERROR && reconfig) {
3367 readOutputParameters();
3368 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3369 }
3370 }
3371
3372 mNewParameters.removeAt(0);
3373
3374 mParamStatus = status;
3375 mParamCond.signal();
3376 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3377 // already timed out waiting for the status and will never signal the condition.
3378 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3379 }
3380 return reconfig;
3381}
3382
3383uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3384{
3385 uint32_t time;
3386 if (audio_is_linear_pcm(mFormat)) {
3387 time = PlaybackThread::activeSleepTimeUs();
3388 } else {
3389 time = 10000;
3390 }
3391 return time;
3392}
3393
3394uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3395{
3396 uint32_t time;
3397 if (audio_is_linear_pcm(mFormat)) {
3398 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3399 } else {
3400 time = 10000;
3401 }
3402 return time;
3403}
3404
3405uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3406{
3407 uint32_t time;
3408 if (audio_is_linear_pcm(mFormat)) {
3409 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3410 } else {
3411 time = 10000;
3412 }
3413 return time;
3414}
3415
3416void AudioFlinger::DirectOutputThread::cacheParameters_l()
3417{
3418 PlaybackThread::cacheParameters_l();
3419
3420 // use shorter standby delay as on normal output to release
3421 // hardware resources as soon as possible
3422 standbyDelay = microseconds(activeSleepTime*2);
3423}
3424
3425// ----------------------------------------------------------------------------
3426
3427AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3428 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3429 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3430 DUPLICATING),
3431 mWaitTimeMs(UINT_MAX)
3432{
3433 addOutputTrack(mainThread);
3434}
3435
3436AudioFlinger::DuplicatingThread::~DuplicatingThread()
3437{
3438 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3439 mOutputTracks[i]->destroy();
3440 }
3441}
3442
3443void AudioFlinger::DuplicatingThread::threadLoop_mix()
3444{
3445 // mix buffers...
3446 if (outputsReady(outputTracks)) {
3447 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3448 } else {
3449 memset(mMixBuffer, 0, mixBufferSize);
3450 }
3451 sleepTime = 0;
3452 writeFrames = mNormalFrameCount;
3453 standbyTime = systemTime() + standbyDelay;
3454}
3455
3456void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3457{
3458 if (sleepTime == 0) {
3459 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3460 sleepTime = activeSleepTime;
3461 } else {
3462 sleepTime = idleSleepTime;
3463 }
3464 } else if (mBytesWritten != 0) {
3465 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3466 writeFrames = mNormalFrameCount;
3467 memset(mMixBuffer, 0, mixBufferSize);
3468 } else {
3469 // flush remaining overflow buffers in output tracks
3470 writeFrames = 0;
3471 }
3472 sleepTime = 0;
3473 }
3474}
3475
3476void AudioFlinger::DuplicatingThread::threadLoop_write()
3477{
3478 for (size_t i = 0; i < outputTracks.size(); i++) {
3479 outputTracks[i]->write(mMixBuffer, writeFrames);
3480 }
3481 mBytesWritten += mixBufferSize;
3482}
3483
3484void AudioFlinger::DuplicatingThread::threadLoop_standby()
3485{
3486 // DuplicatingThread implements standby by stopping all tracks
3487 for (size_t i = 0; i < outputTracks.size(); i++) {
3488 outputTracks[i]->stop();
3489 }
3490}
3491
3492void AudioFlinger::DuplicatingThread::saveOutputTracks()
3493{
3494 outputTracks = mOutputTracks;
3495}
3496
3497void AudioFlinger::DuplicatingThread::clearOutputTracks()
3498{
3499 outputTracks.clear();
3500}
3501
3502void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3503{
3504 Mutex::Autolock _l(mLock);
3505 // FIXME explain this formula
3506 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
3507 OutputTrack *outputTrack = new OutputTrack(thread,
3508 this,
3509 mSampleRate,
3510 mFormat,
3511 mChannelMask,
3512 frameCount);
3513 if (outputTrack->cblk() != NULL) {
3514 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3515 mOutputTracks.add(outputTrack);
3516 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3517 updateWaitTime_l();
3518 }
3519}
3520
3521void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3522{
3523 Mutex::Autolock _l(mLock);
3524 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3525 if (mOutputTracks[i]->thread() == thread) {
3526 mOutputTracks[i]->destroy();
3527 mOutputTracks.removeAt(i);
3528 updateWaitTime_l();
3529 return;
3530 }
3531 }
3532 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3533}
3534
3535// caller must hold mLock
3536void AudioFlinger::DuplicatingThread::updateWaitTime_l()
3537{
3538 mWaitTimeMs = UINT_MAX;
3539 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3540 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3541 if (strong != 0) {
3542 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3543 if (waitTimeMs < mWaitTimeMs) {
3544 mWaitTimeMs = waitTimeMs;
3545 }
3546 }
3547 }
3548}
3549
3550
3551bool AudioFlinger::DuplicatingThread::outputsReady(
3552 const SortedVector< sp<OutputTrack> > &outputTracks)
3553{
3554 for (size_t i = 0; i < outputTracks.size(); i++) {
3555 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
3556 if (thread == 0) {
3557 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
3558 outputTracks[i].get());
3559 return false;
3560 }
3561 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3562 // see note at standby() declaration
3563 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3564 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
3565 thread.get());
3566 return false;
3567 }
3568 }
3569 return true;
3570}
3571
3572uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
3573{
3574 return (mWaitTimeMs * 1000) / 2;
3575}
3576
3577void AudioFlinger::DuplicatingThread::cacheParameters_l()
3578{
3579 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3580 updateWaitTime_l();
3581
3582 MixerThread::cacheParameters_l();
3583}
3584
3585// ----------------------------------------------------------------------------
3586// Record
3587// ----------------------------------------------------------------------------
3588
3589AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
3590 AudioStreamIn *input,
3591 uint32_t sampleRate,
3592 audio_channel_mask_t channelMask,
3593 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08003594 audio_devices_t outDevice,
3595 audio_devices_t inDevice,
Eric Laurent81784c32012-11-19 14:55:58 -08003596 const sp<NBAIO_Sink>& teeSink) :
Eric Laurentd3922f72013-02-01 17:57:04 -08003597 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08003598 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
3599 // mRsmpInIndex and mInputBytes set by readInputParameters()
3600 mReqChannelCount(popcount(channelMask)),
3601 mReqSampleRate(sampleRate),
3602 // mBytesRead is only meaningful while active, and so is cleared in start()
3603 // (but might be better to also clear here for dump?)
3604 mTeeSink(teeSink)
3605{
3606 snprintf(mName, kNameLength, "AudioIn_%X", id);
3607
3608 readInputParameters();
3609
3610}
3611
3612
3613AudioFlinger::RecordThread::~RecordThread()
3614{
3615 delete[] mRsmpInBuffer;
3616 delete mResampler;
3617 delete[] mRsmpOutBuffer;
3618}
3619
3620void AudioFlinger::RecordThread::onFirstRef()
3621{
3622 run(mName, PRIORITY_URGENT_AUDIO);
3623}
3624
3625status_t AudioFlinger::RecordThread::readyToRun()
3626{
3627 status_t status = initCheck();
3628 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
3629 return status;
3630}
3631
3632bool AudioFlinger::RecordThread::threadLoop()
3633{
3634 AudioBufferProvider::Buffer buffer;
3635 sp<RecordTrack> activeTrack;
3636 Vector< sp<EffectChain> > effectChains;
3637
3638 nsecs_t lastWarning = 0;
3639
3640 inputStandBy();
3641 acquireWakeLock();
3642
3643 // used to verify we've read at least once before evaluating how many bytes were read
3644 bool readOnce = false;
3645
3646 // start recording
3647 while (!exitPending()) {
3648
3649 processConfigEvents();
3650
3651 { // scope for mLock
3652 Mutex::Autolock _l(mLock);
3653 checkForNewParameters_l();
3654 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3655 standby();
3656
3657 if (exitPending()) {
3658 break;
3659 }
3660
3661 releaseWakeLock_l();
3662 ALOGV("RecordThread: loop stopping");
3663 // go to sleep
3664 mWaitWorkCV.wait(mLock);
3665 ALOGV("RecordThread: loop starting");
3666 acquireWakeLock_l();
3667 continue;
3668 }
3669 if (mActiveTrack != 0) {
3670 if (mActiveTrack->mState == TrackBase::PAUSING) {
3671 standby();
3672 mActiveTrack.clear();
3673 mStartStopCond.broadcast();
3674 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3675 if (mReqChannelCount != mActiveTrack->channelCount()) {
3676 mActiveTrack.clear();
3677 mStartStopCond.broadcast();
3678 } else if (readOnce) {
3679 // record start succeeds only if first read from audio input
3680 // succeeds
3681 if (mBytesRead >= 0) {
3682 mActiveTrack->mState = TrackBase::ACTIVE;
3683 } else {
3684 mActiveTrack.clear();
3685 }
3686 mStartStopCond.broadcast();
3687 }
3688 mStandby = false;
3689 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
3690 removeTrack_l(mActiveTrack);
3691 mActiveTrack.clear();
3692 }
3693 }
3694 lockEffectChains_l(effectChains);
3695 }
3696
3697 if (mActiveTrack != 0) {
3698 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3699 mActiveTrack->mState != TrackBase::RESUMING) {
3700 unlockEffectChains(effectChains);
3701 usleep(kRecordThreadSleepUs);
3702 continue;
3703 }
3704 for (size_t i = 0; i < effectChains.size(); i ++) {
3705 effectChains[i]->process_l();
3706 }
3707
3708 buffer.frameCount = mFrameCount;
3709 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3710 readOnce = true;
3711 size_t framesOut = buffer.frameCount;
3712 if (mResampler == NULL) {
3713 // no resampling
3714 while (framesOut) {
3715 size_t framesIn = mFrameCount - mRsmpInIndex;
3716 if (framesIn) {
3717 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3718 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
3719 mActiveTrack->mFrameSize;
3720 if (framesIn > framesOut)
3721 framesIn = framesOut;
3722 mRsmpInIndex += framesIn;
3723 framesOut -= framesIn;
3724 if (mChannelCount == mReqChannelCount ||
3725 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
3726 memcpy(dst, src, framesIn * mFrameSize);
3727 } else {
3728 if (mChannelCount == 1) {
3729 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
3730 (int16_t *)src, framesIn);
3731 } else {
3732 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
3733 (int16_t *)src, framesIn);
3734 }
3735 }
3736 }
3737 if (framesOut && mFrameCount == mRsmpInIndex) {
3738 void *readInto;
3739 if (framesOut == mFrameCount &&
3740 (mChannelCount == mReqChannelCount ||
3741 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
3742 readInto = buffer.raw;
3743 framesOut = 0;
3744 } else {
3745 readInto = mRsmpInBuffer;
3746 mRsmpInIndex = 0;
3747 }
3748 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
3749 if (mBytesRead <= 0) {
3750 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
3751 {
3752 ALOGE("Error reading audio input");
3753 // Force input into standby so that it tries to
3754 // recover at next read attempt
3755 inputStandBy();
3756 usleep(kRecordThreadSleepUs);
3757 }
3758 mRsmpInIndex = mFrameCount;
3759 framesOut = 0;
3760 buffer.frameCount = 0;
3761 } else if (mTeeSink != 0) {
3762 (void) mTeeSink->write(readInto,
3763 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
3764 }
3765 }
3766 }
3767 } else {
3768 // resampling
3769
3770 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3771 // alter output frame count as if we were expecting stereo samples
3772 if (mChannelCount == 1 && mReqChannelCount == 1) {
3773 framesOut >>= 1;
3774 }
3775 mResampler->resample(mRsmpOutBuffer, framesOut,
3776 this /* AudioBufferProvider* */);
3777 // ditherAndClamp() works as long as all buffers returned by
3778 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
3779 if (mChannelCount == 2 && mReqChannelCount == 1) {
3780 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3781 // the resampler always outputs stereo samples:
3782 // do post stereo to mono conversion
3783 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
3784 framesOut);
3785 } else {
3786 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3787 }
3788
3789 }
3790 if (mFramestoDrop == 0) {
3791 mActiveTrack->releaseBuffer(&buffer);
3792 } else {
3793 if (mFramestoDrop > 0) {
3794 mFramestoDrop -= buffer.frameCount;
3795 if (mFramestoDrop <= 0) {
3796 clearSyncStartEvent();
3797 }
3798 } else {
3799 mFramestoDrop += buffer.frameCount;
3800 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
3801 mSyncStartEvent->isCancelled()) {
3802 ALOGW("Synced record %s, session %d, trigger session %d",
3803 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
3804 mActiveTrack->sessionId(),
3805 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
3806 clearSyncStartEvent();
3807 }
3808 }
3809 }
3810 mActiveTrack->clearOverflow();
3811 }
3812 // client isn't retrieving buffers fast enough
3813 else {
3814 if (!mActiveTrack->setOverflow()) {
3815 nsecs_t now = systemTime();
3816 if ((now - lastWarning) > kWarningThrottleNs) {
3817 ALOGW("RecordThread: buffer overflow");
3818 lastWarning = now;
3819 }
3820 }
3821 // Release the processor for a while before asking for a new buffer.
3822 // This will give the application more chance to read from the buffer and
3823 // clear the overflow.
3824 usleep(kRecordThreadSleepUs);
3825 }
3826 }
3827 // enable changes in effect chain
3828 unlockEffectChains(effectChains);
3829 effectChains.clear();
3830 }
3831
3832 standby();
3833
3834 {
3835 Mutex::Autolock _l(mLock);
3836 mActiveTrack.clear();
3837 mStartStopCond.broadcast();
3838 }
3839
3840 releaseWakeLock();
3841
3842 ALOGV("RecordThread %p exiting", this);
3843 return false;
3844}
3845
3846void AudioFlinger::RecordThread::standby()
3847{
3848 if (!mStandby) {
3849 inputStandBy();
3850 mStandby = true;
3851 }
3852}
3853
3854void AudioFlinger::RecordThread::inputStandBy()
3855{
3856 mInput->stream->common.standby(&mInput->stream->common);
3857}
3858
3859sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
3860 const sp<AudioFlinger::Client>& client,
3861 uint32_t sampleRate,
3862 audio_format_t format,
3863 audio_channel_mask_t channelMask,
3864 size_t frameCount,
3865 int sessionId,
3866 IAudioFlinger::track_flags_t flags,
3867 pid_t tid,
3868 status_t *status)
3869{
3870 sp<RecordTrack> track;
3871 status_t lStatus;
3872
3873 lStatus = initCheck();
3874 if (lStatus != NO_ERROR) {
3875 ALOGE("Audio driver not initialized.");
3876 goto Exit;
3877 }
3878
3879 // FIXME use flags and tid similar to createTrack_l()
3880
3881 { // scope for mLock
3882 Mutex::Autolock _l(mLock);
3883
3884 track = new RecordTrack(this, client, sampleRate,
3885 format, channelMask, frameCount, sessionId);
3886
3887 if (track->getCblk() == 0) {
3888 lStatus = NO_MEMORY;
3889 goto Exit;
3890 }
3891 mTracks.add(track);
3892
3893 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
3894 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
3895 mAudioFlinger->btNrecIsOff();
3896 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
3897 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
3898 }
3899 lStatus = NO_ERROR;
3900
3901Exit:
3902 if (status) {
3903 *status = lStatus;
3904 }
3905 return track;
3906}
3907
3908status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
3909 AudioSystem::sync_event_t event,
3910 int triggerSession)
3911{
3912 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
3913 sp<ThreadBase> strongMe = this;
3914 status_t status = NO_ERROR;
3915
3916 if (event == AudioSystem::SYNC_EVENT_NONE) {
3917 clearSyncStartEvent();
3918 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
3919 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
3920 triggerSession,
3921 recordTrack->sessionId(),
3922 syncStartEventCallback,
3923 this);
3924 // Sync event can be cancelled by the trigger session if the track is not in a
3925 // compatible state in which case we start record immediately
3926 if (mSyncStartEvent->isCancelled()) {
3927 clearSyncStartEvent();
3928 } else {
3929 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
3930 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
3931 }
3932 }
3933
3934 {
3935 AutoMutex lock(mLock);
3936 if (mActiveTrack != 0) {
3937 if (recordTrack != mActiveTrack.get()) {
3938 status = -EBUSY;
3939 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
3940 mActiveTrack->mState = TrackBase::ACTIVE;
3941 }
3942 return status;
3943 }
3944
3945 recordTrack->mState = TrackBase::IDLE;
3946 mActiveTrack = recordTrack;
3947 mLock.unlock();
3948 status_t status = AudioSystem::startInput(mId);
3949 mLock.lock();
3950 if (status != NO_ERROR) {
3951 mActiveTrack.clear();
3952 clearSyncStartEvent();
3953 return status;
3954 }
3955 mRsmpInIndex = mFrameCount;
3956 mBytesRead = 0;
3957 if (mResampler != NULL) {
3958 mResampler->reset();
3959 }
3960 mActiveTrack->mState = TrackBase::RESUMING;
3961 // signal thread to start
3962 ALOGV("Signal record thread");
3963 mWaitWorkCV.broadcast();
3964 // do not wait for mStartStopCond if exiting
3965 if (exitPending()) {
3966 mActiveTrack.clear();
3967 status = INVALID_OPERATION;
3968 goto startError;
3969 }
3970 mStartStopCond.wait(mLock);
3971 if (mActiveTrack == 0) {
3972 ALOGV("Record failed to start");
3973 status = BAD_VALUE;
3974 goto startError;
3975 }
3976 ALOGV("Record started OK");
3977 return status;
3978 }
3979startError:
3980 AudioSystem::stopInput(mId);
3981 clearSyncStartEvent();
3982 return status;
3983}
3984
3985void AudioFlinger::RecordThread::clearSyncStartEvent()
3986{
3987 if (mSyncStartEvent != 0) {
3988 mSyncStartEvent->cancel();
3989 }
3990 mSyncStartEvent.clear();
3991 mFramestoDrop = 0;
3992}
3993
3994void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
3995{
3996 sp<SyncEvent> strongEvent = event.promote();
3997
3998 if (strongEvent != 0) {
3999 RecordThread *me = (RecordThread *)strongEvent->cookie();
4000 me->handleSyncStartEvent(strongEvent);
4001 }
4002}
4003
4004void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4005{
4006 if (event == mSyncStartEvent) {
4007 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4008 // from audio HAL
4009 mFramestoDrop = mFrameCount * 2;
4010 }
4011}
4012
4013bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
4014 ALOGV("RecordThread::stop");
4015 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4016 return false;
4017 }
4018 recordTrack->mState = TrackBase::PAUSING;
4019 // do not wait for mStartStopCond if exiting
4020 if (exitPending()) {
4021 return true;
4022 }
4023 mStartStopCond.wait(mLock);
4024 // if we have been restarted, recordTrack == mActiveTrack.get() here
4025 if (exitPending() || recordTrack != mActiveTrack.get()) {
4026 ALOGV("Record stopped OK");
4027 return true;
4028 }
4029 return false;
4030}
4031
4032bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4033{
4034 return false;
4035}
4036
4037status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4038{
4039#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4040 if (!isValidSyncEvent(event)) {
4041 return BAD_VALUE;
4042 }
4043
4044 int eventSession = event->triggerSession();
4045 status_t ret = NAME_NOT_FOUND;
4046
4047 Mutex::Autolock _l(mLock);
4048
4049 for (size_t i = 0; i < mTracks.size(); i++) {
4050 sp<RecordTrack> track = mTracks[i];
4051 if (eventSession == track->sessionId()) {
4052 (void) track->setSyncEvent(event);
4053 ret = NO_ERROR;
4054 }
4055 }
4056 return ret;
4057#else
4058 return BAD_VALUE;
4059#endif
4060}
4061
4062// destroyTrack_l() must be called with ThreadBase::mLock held
4063void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4064{
4065 track->mState = TrackBase::TERMINATED;
4066 // active tracks are removed by threadLoop()
4067 if (mActiveTrack != track) {
4068 removeTrack_l(track);
4069 }
4070}
4071
4072void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4073{
4074 mTracks.remove(track);
4075 // need anything related to effects here?
4076}
4077
4078void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4079{
4080 dumpInternals(fd, args);
4081 dumpTracks(fd, args);
4082 dumpEffectChains(fd, args);
4083}
4084
4085void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4086{
4087 const size_t SIZE = 256;
4088 char buffer[SIZE];
4089 String8 result;
4090
4091 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4092 result.append(buffer);
4093
4094 if (mActiveTrack != 0) {
4095 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4096 result.append(buffer);
4097 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4098 result.append(buffer);
4099 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4100 result.append(buffer);
4101 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4102 result.append(buffer);
4103 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4104 result.append(buffer);
4105 } else {
4106 result.append("No active record client\n");
4107 }
4108
4109 write(fd, result.string(), result.size());
4110
4111 dumpBase(fd, args);
4112}
4113
4114void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4115{
4116 const size_t SIZE = 256;
4117 char buffer[SIZE];
4118 String8 result;
4119
4120 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4121 result.append(buffer);
4122 RecordTrack::appendDumpHeader(result);
4123 for (size_t i = 0; i < mTracks.size(); ++i) {
4124 sp<RecordTrack> track = mTracks[i];
4125 if (track != 0) {
4126 track->dump(buffer, SIZE);
4127 result.append(buffer);
4128 }
4129 }
4130
4131 if (mActiveTrack != 0) {
4132 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4133 result.append(buffer);
4134 RecordTrack::appendDumpHeader(result);
4135 mActiveTrack->dump(buffer, SIZE);
4136 result.append(buffer);
4137
4138 }
4139 write(fd, result.string(), result.size());
4140}
4141
4142// AudioBufferProvider interface
4143status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4144{
4145 size_t framesReq = buffer->frameCount;
4146 size_t framesReady = mFrameCount - mRsmpInIndex;
4147 int channelCount;
4148
4149 if (framesReady == 0) {
4150 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4151 if (mBytesRead <= 0) {
4152 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4153 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4154 // Force input into standby so that it tries to
4155 // recover at next read attempt
4156 inputStandBy();
4157 usleep(kRecordThreadSleepUs);
4158 }
4159 buffer->raw = NULL;
4160 buffer->frameCount = 0;
4161 return NOT_ENOUGH_DATA;
4162 }
4163 mRsmpInIndex = 0;
4164 framesReady = mFrameCount;
4165 }
4166
4167 if (framesReq > framesReady) {
4168 framesReq = framesReady;
4169 }
4170
4171 if (mChannelCount == 1 && mReqChannelCount == 2) {
4172 channelCount = 1;
4173 } else {
4174 channelCount = 2;
4175 }
4176 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4177 buffer->frameCount = framesReq;
4178 return NO_ERROR;
4179}
4180
4181// AudioBufferProvider interface
4182void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4183{
4184 mRsmpInIndex += buffer->frameCount;
4185 buffer->frameCount = 0;
4186}
4187
4188bool AudioFlinger::RecordThread::checkForNewParameters_l()
4189{
4190 bool reconfig = false;
4191
4192 while (!mNewParameters.isEmpty()) {
4193 status_t status = NO_ERROR;
4194 String8 keyValuePair = mNewParameters[0];
4195 AudioParameter param = AudioParameter(keyValuePair);
4196 int value;
4197 audio_format_t reqFormat = mFormat;
4198 uint32_t reqSamplingRate = mReqSampleRate;
4199 uint32_t reqChannelCount = mReqChannelCount;
4200
4201 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4202 reqSamplingRate = value;
4203 reconfig = true;
4204 }
4205 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4206 reqFormat = (audio_format_t) value;
4207 reconfig = true;
4208 }
4209 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4210 reqChannelCount = popcount(value);
4211 reconfig = true;
4212 }
4213 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4214 // do not accept frame count changes if tracks are open as the track buffer
4215 // size depends on frame count and correct behavior would not be guaranteed
4216 // if frame count is changed after track creation
4217 if (mActiveTrack != 0) {
4218 status = INVALID_OPERATION;
4219 } else {
4220 reconfig = true;
4221 }
4222 }
4223 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4224 // forward device change to effects that have requested to be
4225 // aware of attached audio device.
4226 for (size_t i = 0; i < mEffectChains.size(); i++) {
4227 mEffectChains[i]->setDevice_l(value);
4228 }
4229
4230 // store input device and output device but do not forward output device to audio HAL.
4231 // Note that status is ignored by the caller for output device
4232 // (see AudioFlinger::setParameters()
4233 if (audio_is_output_devices(value)) {
4234 mOutDevice = value;
4235 status = BAD_VALUE;
4236 } else {
4237 mInDevice = value;
4238 // disable AEC and NS if the device is a BT SCO headset supporting those
4239 // pre processings
4240 if (mTracks.size() > 0) {
4241 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4242 mAudioFlinger->btNrecIsOff();
4243 for (size_t i = 0; i < mTracks.size(); i++) {
4244 sp<RecordTrack> track = mTracks[i];
4245 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4246 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4247 }
4248 }
4249 }
4250 }
4251 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4252 mAudioSource != (audio_source_t)value) {
4253 // forward device change to effects that have requested to be
4254 // aware of attached audio device.
4255 for (size_t i = 0; i < mEffectChains.size(); i++) {
4256 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4257 }
4258 mAudioSource = (audio_source_t)value;
4259 }
4260 if (status == NO_ERROR) {
4261 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4262 keyValuePair.string());
4263 if (status == INVALID_OPERATION) {
4264 inputStandBy();
4265 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4266 keyValuePair.string());
4267 }
4268 if (reconfig) {
4269 if (status == BAD_VALUE &&
4270 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4271 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004272 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004273 <= (2 * reqSamplingRate)) &&
4274 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4275 <= FCC_2 &&
4276 (reqChannelCount <= FCC_2)) {
4277 status = NO_ERROR;
4278 }
4279 if (status == NO_ERROR) {
4280 readInputParameters();
4281 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4282 }
4283 }
4284 }
4285
4286 mNewParameters.removeAt(0);
4287
4288 mParamStatus = status;
4289 mParamCond.signal();
4290 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4291 // already timed out waiting for the status and will never signal the condition.
4292 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4293 }
4294 return reconfig;
4295}
4296
4297String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4298{
4299 char *s;
4300 String8 out_s8 = String8();
4301
4302 Mutex::Autolock _l(mLock);
4303 if (initCheck() != NO_ERROR) {
4304 return out_s8;
4305 }
4306
4307 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4308 out_s8 = String8(s);
4309 free(s);
4310 return out_s8;
4311}
4312
4313void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4314 AudioSystem::OutputDescriptor desc;
4315 void *param2 = NULL;
4316
4317 switch (event) {
4318 case AudioSystem::INPUT_OPENED:
4319 case AudioSystem::INPUT_CONFIG_CHANGED:
4320 desc.channels = mChannelMask;
4321 desc.samplingRate = mSampleRate;
4322 desc.format = mFormat;
4323 desc.frameCount = mFrameCount;
4324 desc.latency = 0;
4325 param2 = &desc;
4326 break;
4327
4328 case AudioSystem::INPUT_CLOSED:
4329 default:
4330 break;
4331 }
4332 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4333}
4334
4335void AudioFlinger::RecordThread::readInputParameters()
4336{
4337 delete mRsmpInBuffer;
4338 // mRsmpInBuffer is always assigned a new[] below
4339 delete mRsmpOutBuffer;
4340 mRsmpOutBuffer = NULL;
4341 delete mResampler;
4342 mResampler = NULL;
4343
4344 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4345 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4346 mChannelCount = (uint16_t)popcount(mChannelMask);
4347 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4348 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4349 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4350 mFrameCount = mInputBytes / mFrameSize;
4351 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
4352 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4353
4354 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
4355 {
4356 int channelCount;
4357 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4358 // stereo to mono post process as the resampler always outputs stereo.
4359 if (mChannelCount == 1 && mReqChannelCount == 2) {
4360 channelCount = 1;
4361 } else {
4362 channelCount = 2;
4363 }
4364 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4365 mResampler->setSampleRate(mSampleRate);
4366 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4367 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4368
4369 // optmization: if mono to mono, alter input frame count as if we were inputing
4370 // stereo samples
4371 if (mChannelCount == 1 && mReqChannelCount == 1) {
4372 mFrameCount >>= 1;
4373 }
4374
4375 }
4376 mRsmpInIndex = mFrameCount;
4377}
4378
4379unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4380{
4381 Mutex::Autolock _l(mLock);
4382 if (initCheck() != NO_ERROR) {
4383 return 0;
4384 }
4385
4386 return mInput->stream->get_input_frames_lost(mInput->stream);
4387}
4388
4389uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
4390{
4391 Mutex::Autolock _l(mLock);
4392 uint32_t result = 0;
4393 if (getEffectChain_l(sessionId) != 0) {
4394 result = EFFECT_SESSION;
4395 }
4396
4397 for (size_t i = 0; i < mTracks.size(); ++i) {
4398 if (sessionId == mTracks[i]->sessionId()) {
4399 result |= TRACK_SESSION;
4400 break;
4401 }
4402 }
4403
4404 return result;
4405}
4406
4407KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
4408{
4409 KeyedVector<int, bool> ids;
4410 Mutex::Autolock _l(mLock);
4411 for (size_t j = 0; j < mTracks.size(); ++j) {
4412 sp<RecordThread::RecordTrack> track = mTracks[j];
4413 int sessionId = track->sessionId();
4414 if (ids.indexOfKey(sessionId) < 0) {
4415 ids.add(sessionId, true);
4416 }
4417 }
4418 return ids;
4419}
4420
4421AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4422{
4423 Mutex::Autolock _l(mLock);
4424 AudioStreamIn *input = mInput;
4425 mInput = NULL;
4426 return input;
4427}
4428
4429// this method must always be called either with ThreadBase mLock held or inside the thread loop
4430audio_stream_t* AudioFlinger::RecordThread::stream() const
4431{
4432 if (mInput == NULL) {
4433 return NULL;
4434 }
4435 return &mInput->stream->common;
4436}
4437
4438status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
4439{
4440 // only one chain per input thread
4441 if (mEffectChains.size() != 0) {
4442 return INVALID_OPERATION;
4443 }
4444 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
4445
4446 chain->setInBuffer(NULL);
4447 chain->setOutBuffer(NULL);
4448
4449 checkSuspendOnAddEffectChain_l(chain);
4450
4451 mEffectChains.add(chain);
4452
4453 return NO_ERROR;
4454}
4455
4456size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
4457{
4458 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
4459 ALOGW_IF(mEffectChains.size() != 1,
4460 "removeEffectChain_l() %p invalid chain size %d on thread %p",
4461 chain.get(), mEffectChains.size(), this);
4462 if (mEffectChains.size() == 1) {
4463 mEffectChains.removeAt(0);
4464 }
4465 return 0;
4466}
4467
4468}; // namespace android