blob: fd64395cd0f1adf105ab85919c83fd71c2b50367 [file] [log] [blame]
Eric Laurentca7cc822012-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 Rayaf348742012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurentca7cc822012-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 Rayaf348742012-11-30 11:11:54 -080029#include <utils/Trace.h>
Eric Laurentca7cc822012-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);
939
940 // Assumes constructor is called by AudioFlinger with it's mLock held, but
941 // it would be safer to explicitly pass initial masterVolume/masterMute as
942 // parameter.
943 //
944 // If the HAL we are using has support for master volume or master mute,
945 // then do not attenuate or mute during mixing (just leave the volume at 1.0
946 // and the mute set to false).
947 mMasterVolume = audioFlinger->masterVolume_l();
948 mMasterMute = audioFlinger->masterMute_l();
949 if (mOutput && mOutput->audioHwDev) {
950 if (mOutput->audioHwDev->canSetMasterVolume()) {
951 mMasterVolume = 1.0;
952 }
953
954 if (mOutput->audioHwDev->canSetMasterMute()) {
955 mMasterMute = false;
956 }
957 }
958
959 readOutputParameters();
960
961 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
962 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
963 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
964 stream = (audio_stream_type_t) (stream + 1)) {
965 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
966 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
967 }
968 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
969 // because mAudioFlinger doesn't have one to copy from
970}
971
972AudioFlinger::PlaybackThread::~PlaybackThread()
973{
974 delete [] mMixBuffer;
975}
976
977void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
978{
979 dumpInternals(fd, args);
980 dumpTracks(fd, args);
981 dumpEffectChains(fd, args);
982}
983
984void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
985{
986 const size_t SIZE = 256;
987 char buffer[SIZE];
988 String8 result;
989
990 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
991 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
992 const stream_type_t *st = &mStreamTypes[i];
993 if (i > 0) {
994 result.appendFormat(", ");
995 }
996 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
997 if (st->mute) {
998 result.append("M");
999 }
1000 }
1001 result.append("\n");
1002 write(fd, result.string(), result.length());
1003 result.clear();
1004
1005 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1006 result.append(buffer);
1007 Track::appendDumpHeader(result);
1008 for (size_t i = 0; i < mTracks.size(); ++i) {
1009 sp<Track> track = mTracks[i];
1010 if (track != 0) {
1011 track->dump(buffer, SIZE);
1012 result.append(buffer);
1013 }
1014 }
1015
1016 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1017 result.append(buffer);
1018 Track::appendDumpHeader(result);
1019 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1020 sp<Track> track = mActiveTracks[i].promote();
1021 if (track != 0) {
1022 track->dump(buffer, SIZE);
1023 result.append(buffer);
1024 }
1025 }
1026 write(fd, result.string(), result.size());
1027
1028 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1029 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1030 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1031 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1032}
1033
1034void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1035{
1036 const size_t SIZE = 256;
1037 char buffer[SIZE];
1038 String8 result;
1039
1040 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1041 result.append(buffer);
1042 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1043 ns2ms(systemTime() - mLastWriteTime));
1044 result.append(buffer);
1045 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1046 result.append(buffer);
1047 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1048 result.append(buffer);
1049 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1050 result.append(buffer);
1051 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1052 result.append(buffer);
1053 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1054 result.append(buffer);
1055 write(fd, result.string(), result.size());
1056 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1057
1058 dumpBase(fd, args);
1059}
1060
1061// Thread virtuals
1062status_t AudioFlinger::PlaybackThread::readyToRun()
1063{
1064 status_t status = initCheck();
1065 if (status == NO_ERROR) {
1066 ALOGI("AudioFlinger's thread %p ready to run", this);
1067 } else {
1068 ALOGE("No working audio driver found.");
1069 }
1070 return status;
1071}
1072
1073void AudioFlinger::PlaybackThread::onFirstRef()
1074{
1075 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1076}
1077
1078// ThreadBase virtuals
1079void AudioFlinger::PlaybackThread::preExit()
1080{
1081 ALOGV(" preExit()");
1082 // FIXME this is using hard-coded strings but in the future, this functionality will be
1083 // converted to use audio HAL extensions required to support tunneling
1084 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1085}
1086
1087// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1088sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1089 const sp<AudioFlinger::Client>& client,
1090 audio_stream_type_t streamType,
1091 uint32_t sampleRate,
1092 audio_format_t format,
1093 audio_channel_mask_t channelMask,
1094 size_t frameCount,
1095 const sp<IMemory>& sharedBuffer,
1096 int sessionId,
1097 IAudioFlinger::track_flags_t *flags,
1098 pid_t tid,
1099 status_t *status)
1100{
1101 sp<Track> track;
1102 status_t lStatus;
1103
1104 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1105
1106 // client expresses a preference for FAST, but we get the final say
1107 if (*flags & IAudioFlinger::TRACK_FAST) {
1108 if (
1109 // not timed
1110 (!isTimed) &&
1111 // either of these use cases:
1112 (
1113 // use case 1: shared buffer with any frame count
1114 (
1115 (sharedBuffer != 0)
1116 ) ||
1117 // use case 2: callback handler and frame count is default or at least as large as HAL
1118 (
1119 (tid != -1) &&
1120 ((frameCount == 0) ||
1121 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1122 )
1123 ) &&
1124 // PCM data
1125 audio_is_linear_pcm(format) &&
1126 // mono or stereo
1127 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1128 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1129#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1130 // hardware sample rate
1131 (sampleRate == mSampleRate) &&
1132#endif
1133 // normal mixer has an associated fast mixer
1134 hasFastMixer() &&
1135 // there are sufficient fast track slots available
1136 (mFastTrackAvailMask != 0)
1137 // FIXME test that MixerThread for this fast track has a capable output HAL
1138 // FIXME add a permission test also?
1139 ) {
1140 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1141 if (frameCount == 0) {
1142 frameCount = mFrameCount * kFastTrackMultiplier;
1143 }
1144 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1145 frameCount, mFrameCount);
1146 } else {
1147 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1148 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1149 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1150 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1151 audio_is_linear_pcm(format),
1152 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1153 *flags &= ~IAudioFlinger::TRACK_FAST;
1154 // For compatibility with AudioTrack calculation, buffer depth is forced
1155 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1156 // This is probably too conservative, but legacy application code may depend on it.
1157 // If you change this calculation, also review the start threshold which is related.
1158 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1159 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1160 if (minBufCount < 2) {
1161 minBufCount = 2;
1162 }
1163 size_t minFrameCount = mNormalFrameCount * minBufCount;
1164 if (frameCount < minFrameCount) {
1165 frameCount = minFrameCount;
1166 }
1167 }
1168 }
1169
1170 if (mType == DIRECT) {
1171 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1172 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1173 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1174 "for output %p with format %d",
1175 sampleRate, format, channelMask, mOutput, mFormat);
1176 lStatus = BAD_VALUE;
1177 goto Exit;
1178 }
1179 }
1180 } else {
1181 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1182 if (sampleRate > mSampleRate*2) {
1183 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1184 lStatus = BAD_VALUE;
1185 goto Exit;
1186 }
1187 }
1188
1189 lStatus = initCheck();
1190 if (lStatus != NO_ERROR) {
1191 ALOGE("Audio driver not initialized.");
1192 goto Exit;
1193 }
1194
1195 { // scope for mLock
1196 Mutex::Autolock _l(mLock);
1197
1198 // all tracks in same audio session must share the same routing strategy otherwise
1199 // conflicts will happen when tracks are moved from one output to another by audio policy
1200 // manager
1201 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1202 for (size_t i = 0; i < mTracks.size(); ++i) {
1203 sp<Track> t = mTracks[i];
1204 if (t != 0 && !t->isOutputTrack()) {
1205 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1206 if (sessionId == t->sessionId() && strategy != actual) {
1207 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1208 strategy, actual);
1209 lStatus = BAD_VALUE;
1210 goto Exit;
1211 }
1212 }
1213 }
1214
1215 if (!isTimed) {
1216 track = new Track(this, client, streamType, sampleRate, format,
1217 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1218 } else {
1219 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1220 channelMask, frameCount, sharedBuffer, sessionId);
1221 }
1222 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1223 lStatus = NO_MEMORY;
1224 goto Exit;
1225 }
1226 mTracks.add(track);
1227
1228 sp<EffectChain> chain = getEffectChain_l(sessionId);
1229 if (chain != 0) {
1230 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1231 track->setMainBuffer(chain->inBuffer());
1232 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1233 chain->incTrackCnt();
1234 }
1235
1236 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1237 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1238 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1239 // so ask activity manager to do this on our behalf
1240 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1241 }
1242 }
1243
1244 lStatus = NO_ERROR;
1245
1246Exit:
1247 if (status) {
1248 *status = lStatus;
1249 }
1250 return track;
1251}
1252
1253uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1254{
1255 return latency;
1256}
1257
1258uint32_t AudioFlinger::PlaybackThread::latency() const
1259{
1260 Mutex::Autolock _l(mLock);
1261 return latency_l();
1262}
1263uint32_t AudioFlinger::PlaybackThread::latency_l() const
1264{
1265 if (initCheck() == NO_ERROR) {
1266 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1267 } else {
1268 return 0;
1269 }
1270}
1271
1272void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1273{
1274 Mutex::Autolock _l(mLock);
1275 // Don't apply master volume in SW if our HAL can do it for us.
1276 if (mOutput && mOutput->audioHwDev &&
1277 mOutput->audioHwDev->canSetMasterVolume()) {
1278 mMasterVolume = 1.0;
1279 } else {
1280 mMasterVolume = value;
1281 }
1282}
1283
1284void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1285{
1286 Mutex::Autolock _l(mLock);
1287 // Don't apply master mute in SW if our HAL can do it for us.
1288 if (mOutput && mOutput->audioHwDev &&
1289 mOutput->audioHwDev->canSetMasterMute()) {
1290 mMasterMute = false;
1291 } else {
1292 mMasterMute = muted;
1293 }
1294}
1295
1296void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1297{
1298 Mutex::Autolock _l(mLock);
1299 mStreamTypes[stream].volume = value;
1300}
1301
1302void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1303{
1304 Mutex::Autolock _l(mLock);
1305 mStreamTypes[stream].mute = muted;
1306}
1307
1308float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1309{
1310 Mutex::Autolock _l(mLock);
1311 return mStreamTypes[stream].volume;
1312}
1313
1314// addTrack_l() must be called with ThreadBase::mLock held
1315status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1316{
1317 status_t status = ALREADY_EXISTS;
1318
1319 // set retry count for buffer fill
1320 track->mRetryCount = kMaxTrackStartupRetries;
1321 if (mActiveTracks.indexOf(track) < 0) {
1322 // the track is newly added, make sure it fills up all its
1323 // buffers before playing. This is to ensure the client will
1324 // effectively get the latency it requested.
1325 track->mFillingUpStatus = Track::FS_FILLING;
1326 track->mResetDone = false;
1327 track->mPresentationCompleteFrames = 0;
1328 mActiveTracks.add(track);
1329 if (track->mainBuffer() != mMixBuffer) {
1330 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1331 if (chain != 0) {
1332 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1333 track->sessionId());
1334 chain->incActiveTrackCnt();
1335 }
1336 }
1337
1338 status = NO_ERROR;
1339 }
1340
1341 ALOGV("mWaitWorkCV.broadcast");
1342 mWaitWorkCV.broadcast();
1343
1344 return status;
1345}
1346
1347// destroyTrack_l() must be called with ThreadBase::mLock held
1348void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1349{
1350 track->mState = TrackBase::TERMINATED;
1351 // active tracks are removed by threadLoop()
1352 if (mActiveTracks.indexOf(track) < 0) {
1353 removeTrack_l(track);
1354 }
1355}
1356
1357void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1358{
1359 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1360 mTracks.remove(track);
1361 deleteTrackName_l(track->name());
1362 // redundant as track is about to be destroyed, for dumpsys only
1363 track->mName = -1;
1364 if (track->isFastTrack()) {
1365 int index = track->mFastIndex;
1366 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1367 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1368 mFastTrackAvailMask |= 1 << index;
1369 // redundant as track is about to be destroyed, for dumpsys only
1370 track->mFastIndex = -1;
1371 }
1372 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1373 if (chain != 0) {
1374 chain->decTrackCnt();
1375 }
1376}
1377
1378String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1379{
1380 String8 out_s8 = String8("");
1381 char *s;
1382
1383 Mutex::Autolock _l(mLock);
1384 if (initCheck() != NO_ERROR) {
1385 return out_s8;
1386 }
1387
1388 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1389 out_s8 = String8(s);
1390 free(s);
1391 return out_s8;
1392}
1393
1394// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1395void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1396 AudioSystem::OutputDescriptor desc;
1397 void *param2 = NULL;
1398
1399 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1400 param);
1401
1402 switch (event) {
1403 case AudioSystem::OUTPUT_OPENED:
1404 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1405 desc.channels = mChannelMask;
1406 desc.samplingRate = mSampleRate;
1407 desc.format = mFormat;
1408 desc.frameCount = mNormalFrameCount; // FIXME see
1409 // AudioFlinger::frameCount(audio_io_handle_t)
1410 desc.latency = latency();
1411 param2 = &desc;
1412 break;
1413
1414 case AudioSystem::STREAM_CONFIG_CHANGED:
1415 param2 = &param;
1416 case AudioSystem::OUTPUT_CLOSED:
1417 default:
1418 break;
1419 }
1420 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1421}
1422
1423void AudioFlinger::PlaybackThread::readOutputParameters()
1424{
1425 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1426 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1427 mChannelCount = (uint16_t)popcount(mChannelMask);
1428 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1429 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1430 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1431 if (mFrameCount & 15) {
1432 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1433 mFrameCount);
1434 }
1435
1436 // Calculate size of normal mix buffer relative to the HAL output buffer size
1437 double multiplier = 1.0;
1438 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1439 kUseFastMixer == FastMixer_Dynamic)) {
1440 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1441 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1442 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1443 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1444 maxNormalFrameCount = maxNormalFrameCount & ~15;
1445 if (maxNormalFrameCount < minNormalFrameCount) {
1446 maxNormalFrameCount = minNormalFrameCount;
1447 }
1448 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1449 if (multiplier <= 1.0) {
1450 multiplier = 1.0;
1451 } else if (multiplier <= 2.0) {
1452 if (2 * mFrameCount <= maxNormalFrameCount) {
1453 multiplier = 2.0;
1454 } else {
1455 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1456 }
1457 } else {
1458 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1459 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1460 // track, but we sometimes have to do this to satisfy the maximum frame count
1461 // constraint)
1462 // FIXME this rounding up should not be done if no HAL SRC
1463 uint32_t truncMult = (uint32_t) multiplier;
1464 if ((truncMult & 1)) {
1465 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1466 ++truncMult;
1467 }
1468 }
1469 multiplier = (double) truncMult;
1470 }
1471 }
1472 mNormalFrameCount = multiplier * mFrameCount;
1473 // round up to nearest 16 frames to satisfy AudioMixer
1474 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1475 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1476 mNormalFrameCount);
1477
1478 delete[] mMixBuffer;
1479 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
1480 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
1481
1482 // force reconfiguration of effect chains and engines to take new buffer size and audio
1483 // parameters into account
1484 // Note that mLock is not held when readOutputParameters() is called from the constructor
1485 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1486 // matter.
1487 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1488 Vector< sp<EffectChain> > effectChains = mEffectChains;
1489 for (size_t i = 0; i < effectChains.size(); i ++) {
1490 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1491 }
1492}
1493
1494
1495status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1496{
1497 if (halFrames == NULL || dspFrames == NULL) {
1498 return BAD_VALUE;
1499 }
1500 Mutex::Autolock _l(mLock);
1501 if (initCheck() != NO_ERROR) {
1502 return INVALID_OPERATION;
1503 }
1504 size_t framesWritten = mBytesWritten / mFrameSize;
1505 *halFrames = framesWritten;
1506
1507 if (isSuspended()) {
1508 // return an estimation of rendered frames when the output is suspended
1509 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1510 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1511 return NO_ERROR;
1512 } else {
1513 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1514 }
1515}
1516
1517uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1518{
1519 Mutex::Autolock _l(mLock);
1520 uint32_t result = 0;
1521 if (getEffectChain_l(sessionId) != 0) {
1522 result = EFFECT_SESSION;
1523 }
1524
1525 for (size_t i = 0; i < mTracks.size(); ++i) {
1526 sp<Track> track = mTracks[i];
1527 if (sessionId == track->sessionId() &&
1528 !(track->mCblk->flags & CBLK_INVALID)) {
1529 result |= TRACK_SESSION;
1530 break;
1531 }
1532 }
1533
1534 return result;
1535}
1536
1537uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1538{
1539 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1540 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1541 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1542 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1543 }
1544 for (size_t i = 0; i < mTracks.size(); i++) {
1545 sp<Track> track = mTracks[i];
1546 if (sessionId == track->sessionId() &&
1547 !(track->mCblk->flags & CBLK_INVALID)) {
1548 return AudioSystem::getStrategyForStream(track->streamType());
1549 }
1550 }
1551 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1552}
1553
1554
1555AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1556{
1557 Mutex::Autolock _l(mLock);
1558 return mOutput;
1559}
1560
1561AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1562{
1563 Mutex::Autolock _l(mLock);
1564 AudioStreamOut *output = mOutput;
1565 mOutput = NULL;
1566 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1567 // must push a NULL and wait for ack
1568 mOutputSink.clear();
1569 mPipeSink.clear();
1570 mNormalSink.clear();
1571 return output;
1572}
1573
1574// this method must always be called either with ThreadBase mLock held or inside the thread loop
1575audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1576{
1577 if (mOutput == NULL) {
1578 return NULL;
1579 }
1580 return &mOutput->stream->common;
1581}
1582
1583uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1584{
1585 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1586}
1587
1588status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1589{
1590 if (!isValidSyncEvent(event)) {
1591 return BAD_VALUE;
1592 }
1593
1594 Mutex::Autolock _l(mLock);
1595
1596 for (size_t i = 0; i < mTracks.size(); ++i) {
1597 sp<Track> track = mTracks[i];
1598 if (event->triggerSession() == track->sessionId()) {
1599 (void) track->setSyncEvent(event);
1600 return NO_ERROR;
1601 }
1602 }
1603
1604 return NAME_NOT_FOUND;
1605}
1606
1607bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1608{
1609 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1610}
1611
1612void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1613 const Vector< sp<Track> >& tracksToRemove)
1614{
1615 size_t count = tracksToRemove.size();
1616 if (CC_UNLIKELY(count)) {
1617 for (size_t i = 0 ; i < count ; i++) {
1618 const sp<Track>& track = tracksToRemove.itemAt(i);
1619 if ((track->sharedBuffer() != 0) &&
1620 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
1621 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1622 }
1623 }
1624 }
1625
1626}
1627
1628void AudioFlinger::PlaybackThread::checkSilentMode_l()
1629{
1630 if (!mMasterMute) {
1631 char value[PROPERTY_VALUE_MAX];
1632 if (property_get("ro.audio.silent", value, "0") > 0) {
1633 char *endptr;
1634 unsigned long ul = strtoul(value, &endptr, 0);
1635 if (*endptr == '\0' && ul != 0) {
1636 ALOGD("Silence is golden");
1637 // The setprop command will not allow a property to be changed after
1638 // the first time it is set, so we don't have to worry about un-muting.
1639 setMasterMute_l(true);
1640 }
1641 }
1642 }
1643}
1644
1645// shared by MIXER and DIRECT, overridden by DUPLICATING
1646void AudioFlinger::PlaybackThread::threadLoop_write()
1647{
1648 // FIXME rewrite to reduce number of system calls
1649 mLastWriteTime = systemTime();
1650 mInWrite = true;
1651 int bytesWritten;
1652
1653 // If an NBAIO sink is present, use it to write the normal mixer's submix
1654 if (mNormalSink != 0) {
1655#define mBitShift 2 // FIXME
1656 size_t count = mixBufferSize >> mBitShift;
Simon Wilson7a90bc92012-11-29 15:18:50 -08001657 ATRACE_BEGIN("write");
Eric Laurentca7cc822012-11-19 14:55:58 -08001658 // update the setpoint when AudioFlinger::mScreenState changes
1659 uint32_t screenState = AudioFlinger::mScreenState;
1660 if (screenState != mScreenState) {
1661 mScreenState = screenState;
1662 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1663 if (pipe != NULL) {
1664 pipe->setAvgFrames((mScreenState & 1) ?
1665 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1666 }
1667 }
1668 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Simon Wilson7a90bc92012-11-29 15:18:50 -08001669 ATRACE_END();
Eric Laurentca7cc822012-11-19 14:55:58 -08001670 if (framesWritten > 0) {
1671 bytesWritten = framesWritten << mBitShift;
1672 } else {
1673 bytesWritten = framesWritten;
1674 }
1675 // otherwise use the HAL / AudioStreamOut directly
1676 } else {
1677 // Direct output thread.
1678 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
1679 }
1680
1681 if (bytesWritten > 0) {
1682 mBytesWritten += mixBufferSize;
1683 }
1684 mNumWrites++;
1685 mInWrite = false;
1686}
1687
1688/*
1689The derived values that are cached:
1690 - mixBufferSize from frame count * frame size
1691 - activeSleepTime from activeSleepTimeUs()
1692 - idleSleepTime from idleSleepTimeUs()
1693 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1694 - maxPeriod from frame count and sample rate (MIXER only)
1695
1696The parameters that affect these derived values are:
1697 - frame count
1698 - frame size
1699 - sample rate
1700 - device type: A2DP or not
1701 - device latency
1702 - format: PCM or not
1703 - active sleep time
1704 - idle sleep time
1705*/
1706
1707void AudioFlinger::PlaybackThread::cacheParameters_l()
1708{
1709 mixBufferSize = mNormalFrameCount * mFrameSize;
1710 activeSleepTime = activeSleepTimeUs();
1711 idleSleepTime = idleSleepTimeUs();
1712}
1713
1714void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1715{
1716 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1717 this, streamType, mTracks.size());
1718 Mutex::Autolock _l(mLock);
1719
1720 size_t size = mTracks.size();
1721 for (size_t i = 0; i < size; i++) {
1722 sp<Track> t = mTracks[i];
1723 if (t->streamType() == streamType) {
1724 android_atomic_or(CBLK_INVALID, &t->mCblk->flags);
1725 t->mCblk->cv.signal();
1726 }
1727 }
1728}
1729
1730status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1731{
1732 int session = chain->sessionId();
1733 int16_t *buffer = mMixBuffer;
1734 bool ownsBuffer = false;
1735
1736 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1737 if (session > 0) {
1738 // Only one effect chain can be present in direct output thread and it uses
1739 // the mix buffer as input
1740 if (mType != DIRECT) {
1741 size_t numSamples = mNormalFrameCount * mChannelCount;
1742 buffer = new int16_t[numSamples];
1743 memset(buffer, 0, numSamples * sizeof(int16_t));
1744 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1745 ownsBuffer = true;
1746 }
1747
1748 // Attach all tracks with same session ID to this chain.
1749 for (size_t i = 0; i < mTracks.size(); ++i) {
1750 sp<Track> track = mTracks[i];
1751 if (session == track->sessionId()) {
1752 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1753 buffer);
1754 track->setMainBuffer(buffer);
1755 chain->incTrackCnt();
1756 }
1757 }
1758
1759 // indicate all active tracks in the chain
1760 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1761 sp<Track> track = mActiveTracks[i].promote();
1762 if (track == 0) {
1763 continue;
1764 }
1765 if (session == track->sessionId()) {
1766 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1767 chain->incActiveTrackCnt();
1768 }
1769 }
1770 }
1771
1772 chain->setInBuffer(buffer, ownsBuffer);
1773 chain->setOutBuffer(mMixBuffer);
1774 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1775 // chains list in order to be processed last as it contains output stage effects
1776 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1777 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1778 // after track specific effects and before output stage
1779 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1780 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1781 // Effect chain for other sessions are inserted at beginning of effect
1782 // chains list to be processed before output mix effects. Relative order between other
1783 // sessions is not important
1784 size_t size = mEffectChains.size();
1785 size_t i = 0;
1786 for (i = 0; i < size; i++) {
1787 if (mEffectChains[i]->sessionId() < session) {
1788 break;
1789 }
1790 }
1791 mEffectChains.insertAt(chain, i);
1792 checkSuspendOnAddEffectChain_l(chain);
1793
1794 return NO_ERROR;
1795}
1796
1797size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1798{
1799 int session = chain->sessionId();
1800
1801 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1802
1803 for (size_t i = 0; i < mEffectChains.size(); i++) {
1804 if (chain == mEffectChains[i]) {
1805 mEffectChains.removeAt(i);
1806 // detach all active tracks from the chain
1807 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1808 sp<Track> track = mActiveTracks[i].promote();
1809 if (track == 0) {
1810 continue;
1811 }
1812 if (session == track->sessionId()) {
1813 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1814 chain.get(), session);
1815 chain->decActiveTrackCnt();
1816 }
1817 }
1818
1819 // detach all tracks with same session ID from this chain
1820 for (size_t i = 0; i < mTracks.size(); ++i) {
1821 sp<Track> track = mTracks[i];
1822 if (session == track->sessionId()) {
1823 track->setMainBuffer(mMixBuffer);
1824 chain->decTrackCnt();
1825 }
1826 }
1827 break;
1828 }
1829 }
1830 return mEffectChains.size();
1831}
1832
1833status_t AudioFlinger::PlaybackThread::attachAuxEffect(
1834 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
1835{
1836 Mutex::Autolock _l(mLock);
1837 return attachAuxEffect_l(track, EffectId);
1838}
1839
1840status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
1841 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
1842{
1843 status_t status = NO_ERROR;
1844
1845 if (EffectId == 0) {
1846 track->setAuxBuffer(0, NULL);
1847 } else {
1848 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
1849 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
1850 if (effect != 0) {
1851 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1852 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
1853 } else {
1854 status = INVALID_OPERATION;
1855 }
1856 } else {
1857 status = BAD_VALUE;
1858 }
1859 }
1860 return status;
1861}
1862
1863void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
1864{
1865 for (size_t i = 0; i < mTracks.size(); ++i) {
1866 sp<Track> track = mTracks[i];
1867 if (track->auxEffectId() == effectId) {
1868 attachAuxEffect_l(track, 0);
1869 }
1870 }
1871}
1872
1873bool AudioFlinger::PlaybackThread::threadLoop()
1874{
1875 Vector< sp<Track> > tracksToRemove;
1876
1877 standbyTime = systemTime();
1878
1879 // MIXER
1880 nsecs_t lastWarning = 0;
1881
1882 // DUPLICATING
1883 // FIXME could this be made local to while loop?
1884 writeFrames = 0;
1885
1886 cacheParameters_l();
1887 sleepTime = idleSleepTime;
1888
1889 if (mType == MIXER) {
1890 sleepTimeShift = 0;
1891 }
1892
1893 CpuStats cpuStats;
1894 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
1895
1896 acquireWakeLock();
1897
1898 while (!exitPending())
1899 {
1900 cpuStats.sample(myName);
1901
1902 Vector< sp<EffectChain> > effectChains;
1903
1904 processConfigEvents();
1905
1906 { // scope for mLock
1907
1908 Mutex::Autolock _l(mLock);
1909
1910 if (checkForNewParameters_l()) {
1911 cacheParameters_l();
1912 }
1913
1914 saveOutputTracks();
1915
1916 // put audio hardware into standby after short delay
1917 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1918 isSuspended())) {
1919 if (!mStandby) {
1920
1921 threadLoop_standby();
1922
1923 mStandby = true;
1924 }
1925
1926 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1927 // we're about to wait, flush the binder command buffer
1928 IPCThreadState::self()->flushCommands();
1929
1930 clearOutputTracks();
1931
1932 if (exitPending()) {
1933 break;
1934 }
1935
1936 releaseWakeLock_l();
1937 // wait until we have something to do...
1938 ALOGV("%s going to sleep", myName.string());
1939 mWaitWorkCV.wait(mLock);
1940 ALOGV("%s waking up", myName.string());
1941 acquireWakeLock_l();
1942
1943 mMixerStatus = MIXER_IDLE;
1944 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
1945 mBytesWritten = 0;
1946
1947 checkSilentMode_l();
1948
1949 standbyTime = systemTime() + standbyDelay;
1950 sleepTime = idleSleepTime;
1951 if (mType == MIXER) {
1952 sleepTimeShift = 0;
1953 }
1954
1955 continue;
1956 }
1957 }
1958
1959 // mMixerStatusIgnoringFastTracks is also updated internally
1960 mMixerStatus = prepareTracks_l(&tracksToRemove);
1961
1962 // prevent any changes in effect chain list and in each effect chain
1963 // during mixing and effect process as the audio buffers could be deleted
1964 // or modified if an effect is created or deleted
1965 lockEffectChains_l(effectChains);
1966 }
1967
1968 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
1969 threadLoop_mix();
1970 } else {
1971 threadLoop_sleepTime();
1972 }
1973
1974 if (isSuspended()) {
1975 sleepTime = suspendSleepTimeUs();
1976 mBytesWritten += mixBufferSize;
1977 }
1978
1979 // only process effects if we're going to write
1980 if (sleepTime == 0) {
1981 for (size_t i = 0; i < effectChains.size(); i ++) {
1982 effectChains[i]->process_l();
1983 }
1984 }
1985
1986 // enable changes in effect chain
1987 unlockEffectChains(effectChains);
1988
1989 // sleepTime == 0 means we must write to audio hardware
1990 if (sleepTime == 0) {
1991
1992 threadLoop_write();
1993
1994if (mType == MIXER) {
1995 // write blocked detection
1996 nsecs_t now = systemTime();
1997 nsecs_t delta = now - mLastWriteTime;
1998 if (!mStandby && delta > maxPeriod) {
1999 mNumDelayedWrites++;
2000 if ((now - lastWarning) > kWarningThrottleNs) {
Alex Rayaf348742012-11-30 11:11:54 -08002001 ATRACE_NAME("underrun");
Eric Laurentca7cc822012-11-19 14:55:58 -08002002 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2003 ns2ms(delta), mNumDelayedWrites, this);
2004 lastWarning = now;
2005 }
2006 }
2007}
2008
2009 mStandby = false;
2010 } else {
2011 usleep(sleepTime);
2012 }
2013
2014 // Finally let go of removed track(s), without the lock held
2015 // since we can't guarantee the destructors won't acquire that
2016 // same lock. This will also mutate and push a new fast mixer state.
2017 threadLoop_removeTracks(tracksToRemove);
2018 tracksToRemove.clear();
2019
2020 // FIXME I don't understand the need for this here;
2021 // it was in the original code but maybe the
2022 // assignment in saveOutputTracks() makes this unnecessary?
2023 clearOutputTracks();
2024
2025 // Effect chains will be actually deleted here if they were removed from
2026 // mEffectChains list during mixing or effects processing
2027 effectChains.clear();
2028
2029 // FIXME Note that the above .clear() is no longer necessary since effectChains
2030 // is now local to this block, but will keep it for now (at least until merge done).
2031 }
2032
2033 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2034 if (mType == MIXER || mType == DIRECT) {
2035 // put output stream into standby mode
2036 if (!mStandby) {
2037 mOutput->stream->common.standby(&mOutput->stream->common);
2038 }
2039 }
2040
2041 releaseWakeLock();
2042
2043 ALOGV("Thread %p type %d exiting", this, mType);
2044 return false;
2045}
2046
2047
2048// ----------------------------------------------------------------------------
2049
2050AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2051 audio_io_handle_t id, audio_devices_t device, type_t type)
2052 : PlaybackThread(audioFlinger, output, id, device, type),
2053 // mAudioMixer below
2054 // mFastMixer below
2055 mFastMixerFutex(0)
2056 // mOutputSink below
2057 // mPipeSink below
2058 // mNormalSink below
2059{
2060 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2061 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, "
2062 "mFrameCount=%d, mNormalFrameCount=%d",
2063 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2064 mNormalFrameCount);
2065 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2066
2067 // FIXME - Current mixer implementation only supports stereo output
2068 if (mChannelCount != FCC_2) {
2069 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2070 }
2071
2072 // create an NBAIO sink for the HAL output stream, and negotiate
2073 mOutputSink = new AudioStreamOutSink(output->stream);
2074 size_t numCounterOffers = 0;
2075 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2076 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2077 ALOG_ASSERT(index == 0);
2078
2079 // initialize fast mixer depending on configuration
2080 bool initFastMixer;
2081 switch (kUseFastMixer) {
2082 case FastMixer_Never:
2083 initFastMixer = false;
2084 break;
2085 case FastMixer_Always:
2086 initFastMixer = true;
2087 break;
2088 case FastMixer_Static:
2089 case FastMixer_Dynamic:
2090 initFastMixer = mFrameCount < mNormalFrameCount;
2091 break;
2092 }
2093 if (initFastMixer) {
2094
2095 // create a MonoPipe to connect our submix to FastMixer
2096 NBAIO_Format format = mOutputSink->format();
2097 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2098 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2099 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2100 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2101 const NBAIO_Format offers[1] = {format};
2102 size_t numCounterOffers = 0;
2103 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2104 ALOG_ASSERT(index == 0);
2105 monoPipe->setAvgFrames((mScreenState & 1) ?
2106 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2107 mPipeSink = monoPipe;
2108
2109#ifdef TEE_SINK_FRAMES
2110 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2111 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2112 numCounterOffers = 0;
2113 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2114 ALOG_ASSERT(index == 0);
2115 mTeeSink = teeSink;
2116 PipeReader *teeSource = new PipeReader(*teeSink);
2117 numCounterOffers = 0;
2118 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2119 ALOG_ASSERT(index == 0);
2120 mTeeSource = teeSource;
2121#endif
2122
2123 // create fast mixer and configure it initially with just one fast track for our submix
2124 mFastMixer = new FastMixer();
2125 FastMixerStateQueue *sq = mFastMixer->sq();
2126#ifdef STATE_QUEUE_DUMP
2127 sq->setObserverDump(&mStateQueueObserverDump);
2128 sq->setMutatorDump(&mStateQueueMutatorDump);
2129#endif
2130 FastMixerState *state = sq->begin();
2131 FastTrack *fastTrack = &state->mFastTracks[0];
2132 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2133 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2134 fastTrack->mVolumeProvider = NULL;
2135 fastTrack->mGeneration++;
2136 state->mFastTracksGen++;
2137 state->mTrackMask = 1;
2138 // fast mixer will use the HAL output sink
2139 state->mOutputSink = mOutputSink.get();
2140 state->mOutputSinkGen++;
2141 state->mFrameCount = mFrameCount;
2142 state->mCommand = FastMixerState::COLD_IDLE;
2143 // already done in constructor initialization list
2144 //mFastMixerFutex = 0;
2145 state->mColdFutexAddr = &mFastMixerFutex;
2146 state->mColdGen++;
2147 state->mDumpState = &mFastMixerDumpState;
2148 state->mTeeSink = mTeeSink.get();
2149 sq->end();
2150 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2151
2152 // start the fast mixer
2153 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2154 pid_t tid = mFastMixer->getTid();
2155 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2156 if (err != 0) {
2157 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2158 kPriorityFastMixer, getpid_cached, tid, err);
2159 }
2160
2161#ifdef AUDIO_WATCHDOG
2162 // create and start the watchdog
2163 mAudioWatchdog = new AudioWatchdog();
2164 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2165 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2166 tid = mAudioWatchdog->getTid();
2167 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2168 if (err != 0) {
2169 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2170 kPriorityFastMixer, getpid_cached, tid, err);
2171 }
2172#endif
2173
2174 } else {
2175 mFastMixer = NULL;
2176 }
2177
2178 switch (kUseFastMixer) {
2179 case FastMixer_Never:
2180 case FastMixer_Dynamic:
2181 mNormalSink = mOutputSink;
2182 break;
2183 case FastMixer_Always:
2184 mNormalSink = mPipeSink;
2185 break;
2186 case FastMixer_Static:
2187 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2188 break;
2189 }
2190}
2191
2192AudioFlinger::MixerThread::~MixerThread()
2193{
2194 if (mFastMixer != NULL) {
2195 FastMixerStateQueue *sq = mFastMixer->sq();
2196 FastMixerState *state = sq->begin();
2197 if (state->mCommand == FastMixerState::COLD_IDLE) {
2198 int32_t old = android_atomic_inc(&mFastMixerFutex);
2199 if (old == -1) {
2200 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2201 }
2202 }
2203 state->mCommand = FastMixerState::EXIT;
2204 sq->end();
2205 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2206 mFastMixer->join();
2207 // Though the fast mixer thread has exited, it's state queue is still valid.
2208 // We'll use that extract the final state which contains one remaining fast track
2209 // corresponding to our sub-mix.
2210 state = sq->begin();
2211 ALOG_ASSERT(state->mTrackMask == 1);
2212 FastTrack *fastTrack = &state->mFastTracks[0];
2213 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2214 delete fastTrack->mBufferProvider;
2215 sq->end(false /*didModify*/);
2216 delete mFastMixer;
2217#ifdef AUDIO_WATCHDOG
2218 if (mAudioWatchdog != 0) {
2219 mAudioWatchdog->requestExit();
2220 mAudioWatchdog->requestExitAndWait();
2221 mAudioWatchdog.clear();
2222 }
2223#endif
2224 }
2225 delete mAudioMixer;
2226}
2227
2228
2229uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2230{
2231 if (mFastMixer != NULL) {
2232 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2233 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2234 }
2235 return latency;
2236}
2237
2238
2239void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2240{
2241 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2242}
2243
2244void AudioFlinger::MixerThread::threadLoop_write()
2245{
2246 // FIXME we should only do one push per cycle; confirm this is true
2247 // Start the fast mixer if it's not already running
2248 if (mFastMixer != NULL) {
2249 FastMixerStateQueue *sq = mFastMixer->sq();
2250 FastMixerState *state = sq->begin();
2251 if (state->mCommand != FastMixerState::MIX_WRITE &&
2252 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2253 if (state->mCommand == FastMixerState::COLD_IDLE) {
2254 int32_t old = android_atomic_inc(&mFastMixerFutex);
2255 if (old == -1) {
2256 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2257 }
2258#ifdef AUDIO_WATCHDOG
2259 if (mAudioWatchdog != 0) {
2260 mAudioWatchdog->resume();
2261 }
2262#endif
2263 }
2264 state->mCommand = FastMixerState::MIX_WRITE;
2265 sq->end();
2266 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2267 if (kUseFastMixer == FastMixer_Dynamic) {
2268 mNormalSink = mPipeSink;
2269 }
2270 } else {
2271 sq->end(false /*didModify*/);
2272 }
2273 }
2274 PlaybackThread::threadLoop_write();
2275}
2276
2277void AudioFlinger::MixerThread::threadLoop_standby()
2278{
2279 // Idle the fast mixer if it's currently running
2280 if (mFastMixer != NULL) {
2281 FastMixerStateQueue *sq = mFastMixer->sq();
2282 FastMixerState *state = sq->begin();
2283 if (!(state->mCommand & FastMixerState::IDLE)) {
2284 state->mCommand = FastMixerState::COLD_IDLE;
2285 state->mColdFutexAddr = &mFastMixerFutex;
2286 state->mColdGen++;
2287 mFastMixerFutex = 0;
2288 sq->end();
2289 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2290 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2291 if (kUseFastMixer == FastMixer_Dynamic) {
2292 mNormalSink = mOutputSink;
2293 }
2294#ifdef AUDIO_WATCHDOG
2295 if (mAudioWatchdog != 0) {
2296 mAudioWatchdog->pause();
2297 }
2298#endif
2299 } else {
2300 sq->end(false /*didModify*/);
2301 }
2302 }
2303 PlaybackThread::threadLoop_standby();
2304}
2305
2306// shared by MIXER and DIRECT, overridden by DUPLICATING
2307void AudioFlinger::PlaybackThread::threadLoop_standby()
2308{
2309 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2310 mOutput->stream->common.standby(&mOutput->stream->common);
2311}
2312
2313void AudioFlinger::MixerThread::threadLoop_mix()
2314{
2315 // obtain the presentation timestamp of the next output buffer
2316 int64_t pts;
2317 status_t status = INVALID_OPERATION;
2318
2319 if (mNormalSink != 0) {
2320 status = mNormalSink->getNextWriteTimestamp(&pts);
2321 } else {
2322 status = mOutputSink->getNextWriteTimestamp(&pts);
2323 }
2324
2325 if (status != NO_ERROR) {
2326 pts = AudioBufferProvider::kInvalidPTS;
2327 }
2328
2329 // mix buffers...
2330 mAudioMixer->process(pts);
2331 // increase sleep time progressively when application underrun condition clears.
2332 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2333 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2334 // such that we would underrun the audio HAL.
2335 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2336 sleepTimeShift--;
2337 }
2338 sleepTime = 0;
2339 standbyTime = systemTime() + standbyDelay;
2340 //TODO: delay standby when effects have a tail
2341}
2342
2343void AudioFlinger::MixerThread::threadLoop_sleepTime()
2344{
2345 // If no tracks are ready, sleep once for the duration of an output
2346 // buffer size, then write 0s to the output
2347 if (sleepTime == 0) {
2348 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2349 sleepTime = activeSleepTime >> sleepTimeShift;
2350 if (sleepTime < kMinThreadSleepTimeUs) {
2351 sleepTime = kMinThreadSleepTimeUs;
2352 }
2353 // reduce sleep time in case of consecutive application underruns to avoid
2354 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2355 // duration we would end up writing less data than needed by the audio HAL if
2356 // the condition persists.
2357 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2358 sleepTimeShift++;
2359 }
2360 } else {
2361 sleepTime = idleSleepTime;
2362 }
2363 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2364 memset (mMixBuffer, 0, mixBufferSize);
2365 sleepTime = 0;
2366 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2367 "anticipated start");
2368 }
2369 // TODO add standby time extension fct of effect tail
2370}
2371
2372// prepareTracks_l() must be called with ThreadBase::mLock held
2373AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2374 Vector< sp<Track> > *tracksToRemove)
2375{
2376
2377 mixer_state mixerStatus = MIXER_IDLE;
2378 // find out which tracks need to be processed
2379 size_t count = mActiveTracks.size();
2380 size_t mixedTracks = 0;
2381 size_t tracksWithEffect = 0;
2382 // counts only _active_ fast tracks
2383 size_t fastTracks = 0;
2384 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2385
2386 float masterVolume = mMasterVolume;
2387 bool masterMute = mMasterMute;
2388
2389 if (masterMute) {
2390 masterVolume = 0;
2391 }
2392 // Delegate master volume control to effect in output mix effect chain if needed
2393 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2394 if (chain != 0) {
2395 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2396 chain->setVolume_l(&v, &v);
2397 masterVolume = (float)((v + (1 << 23)) >> 24);
2398 chain.clear();
2399 }
2400
2401 // prepare a new state to push
2402 FastMixerStateQueue *sq = NULL;
2403 FastMixerState *state = NULL;
2404 bool didModify = false;
2405 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2406 if (mFastMixer != NULL) {
2407 sq = mFastMixer->sq();
2408 state = sq->begin();
2409 }
2410
2411 for (size_t i=0 ; i<count ; i++) {
2412 sp<Track> t = mActiveTracks[i].promote();
2413 if (t == 0) {
2414 continue;
2415 }
2416
2417 // this const just means the local variable doesn't change
2418 Track* const track = t.get();
2419
2420 // process fast tracks
2421 if (track->isFastTrack()) {
2422
2423 // It's theoretically possible (though unlikely) for a fast track to be created
2424 // and then removed within the same normal mix cycle. This is not a problem, as
2425 // the track never becomes active so it's fast mixer slot is never touched.
2426 // The converse, of removing an (active) track and then creating a new track
2427 // at the identical fast mixer slot within the same normal mix cycle,
2428 // is impossible because the slot isn't marked available until the end of each cycle.
2429 int j = track->mFastIndex;
2430 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2431 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2432 FastTrack *fastTrack = &state->mFastTracks[j];
2433
2434 // Determine whether the track is currently in underrun condition,
2435 // and whether it had a recent underrun.
2436 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2437 FastTrackUnderruns underruns = ftDump->mUnderruns;
2438 uint32_t recentFull = (underruns.mBitFields.mFull -
2439 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2440 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2441 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2442 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2443 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2444 uint32_t recentUnderruns = recentPartial + recentEmpty;
2445 track->mObservedUnderruns = underruns;
2446 // don't count underruns that occur while stopping or pausing
2447 // or stopped which can occur when flush() is called while active
2448 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2449 track->mUnderrunCount += recentUnderruns;
2450 }
2451
2452 // This is similar to the state machine for normal tracks,
2453 // with a few modifications for fast tracks.
2454 bool isActive = true;
2455 switch (track->mState) {
2456 case TrackBase::STOPPING_1:
2457 // track stays active in STOPPING_1 state until first underrun
2458 if (recentUnderruns > 0) {
2459 track->mState = TrackBase::STOPPING_2;
2460 }
2461 break;
2462 case TrackBase::PAUSING:
2463 // ramp down is not yet implemented
2464 track->setPaused();
2465 break;
2466 case TrackBase::RESUMING:
2467 // ramp up is not yet implemented
2468 track->mState = TrackBase::ACTIVE;
2469 break;
2470 case TrackBase::ACTIVE:
2471 if (recentFull > 0 || recentPartial > 0) {
2472 // track has provided at least some frames recently: reset retry count
2473 track->mRetryCount = kMaxTrackRetries;
2474 }
2475 if (recentUnderruns == 0) {
2476 // no recent underruns: stay active
2477 break;
2478 }
2479 // there has recently been an underrun of some kind
2480 if (track->sharedBuffer() == 0) {
2481 // were any of the recent underruns "empty" (no frames available)?
2482 if (recentEmpty == 0) {
2483 // no, then ignore the partial underruns as they are allowed indefinitely
2484 break;
2485 }
2486 // there has recently been an "empty" underrun: decrement the retry counter
2487 if (--(track->mRetryCount) > 0) {
2488 break;
2489 }
2490 // indicate to client process that the track was disabled because of underrun;
2491 // it will then automatically call start() when data is available
2492 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
2493 // remove from active list, but state remains ACTIVE [confusing but true]
2494 isActive = false;
2495 break;
2496 }
2497 // fall through
2498 case TrackBase::STOPPING_2:
2499 case TrackBase::PAUSED:
2500 case TrackBase::TERMINATED:
2501 case TrackBase::STOPPED:
2502 case TrackBase::FLUSHED: // flush() while active
2503 // Check for presentation complete if track is inactive
2504 // We have consumed all the buffers of this track.
2505 // This would be incomplete if we auto-paused on underrun
2506 {
2507 size_t audioHALFrames =
2508 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2509 size_t framesWritten = mBytesWritten / mFrameSize;
2510 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2511 // track stays in active list until presentation is complete
2512 break;
2513 }
2514 }
2515 if (track->isStopping_2()) {
2516 track->mState = TrackBase::STOPPED;
2517 }
2518 if (track->isStopped()) {
2519 // Can't reset directly, as fast mixer is still polling this track
2520 // track->reset();
2521 // So instead mark this track as needing to be reset after push with ack
2522 resetMask |= 1 << i;
2523 }
2524 isActive = false;
2525 break;
2526 case TrackBase::IDLE:
2527 default:
2528 LOG_FATAL("unexpected track state %d", track->mState);
2529 }
2530
2531 if (isActive) {
2532 // was it previously inactive?
2533 if (!(state->mTrackMask & (1 << j))) {
2534 ExtendedAudioBufferProvider *eabp = track;
2535 VolumeProvider *vp = track;
2536 fastTrack->mBufferProvider = eabp;
2537 fastTrack->mVolumeProvider = vp;
2538 fastTrack->mSampleRate = track->mSampleRate;
2539 fastTrack->mChannelMask = track->mChannelMask;
2540 fastTrack->mGeneration++;
2541 state->mTrackMask |= 1 << j;
2542 didModify = true;
2543 // no acknowledgement required for newly active tracks
2544 }
2545 // cache the combined master volume and stream type volume for fast mixer; this
2546 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2547 track->mCachedVolume = track->isMuted() ?
2548 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2549 ++fastTracks;
2550 } else {
2551 // was it previously active?
2552 if (state->mTrackMask & (1 << j)) {
2553 fastTrack->mBufferProvider = NULL;
2554 fastTrack->mGeneration++;
2555 state->mTrackMask &= ~(1 << j);
2556 didModify = true;
2557 // If any fast tracks were removed, we must wait for acknowledgement
2558 // because we're about to decrement the last sp<> on those tracks.
2559 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2560 } else {
2561 LOG_FATAL("fast track %d should have been active", j);
2562 }
2563 tracksToRemove->add(track);
2564 // Avoids a misleading display in dumpsys
2565 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2566 }
2567 continue;
2568 }
2569
2570 { // local variable scope to avoid goto warning
2571
2572 audio_track_cblk_t* cblk = track->cblk();
2573
2574 // The first time a track is added we wait
2575 // for all its buffers to be filled before processing it
2576 int name = track->name();
2577 // make sure that we have enough frames to mix one full buffer.
2578 // enforce this condition only once to enable draining the buffer in case the client
2579 // app does not call stop() and relies on underrun to stop:
2580 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2581 // during last round
2582 uint32_t minFrames = 1;
2583 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2584 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
2585 if (t->sampleRate() == mSampleRate) {
2586 minFrames = mNormalFrameCount;
2587 } else {
2588 // +1 for rounding and +1 for additional sample needed for interpolation
2589 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2590 // add frames already consumed but not yet released by the resampler
2591 // because cblk->framesReady() will include these frames
2592 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2593 // the minimum track buffer size is normally twice the number of frames necessary
2594 // to fill one buffer and the resampler should not leave more than one buffer worth
2595 // of unreleased frames after each pass, but just in case...
2596 ALOG_ASSERT(minFrames <= cblk->frameCount);
2597 }
2598 }
2599 if ((track->framesReady() >= minFrames) && track->isReady() &&
2600 !track->isPaused() && !track->isTerminated())
2601 {
2602 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
2603 this);
2604
2605 mixedTracks++;
2606
2607 // track->mainBuffer() != mMixBuffer means there is an effect chain
2608 // connected to the track
2609 chain.clear();
2610 if (track->mainBuffer() != mMixBuffer) {
2611 chain = getEffectChain_l(track->sessionId());
2612 // Delegate volume control to effect in track effect chain if needed
2613 if (chain != 0) {
2614 tracksWithEffect++;
2615 } else {
2616 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2617 "session %d",
2618 name, track->sessionId());
2619 }
2620 }
2621
2622
2623 int param = AudioMixer::VOLUME;
2624 if (track->mFillingUpStatus == Track::FS_FILLED) {
2625 // no ramp for the first volume setting
2626 track->mFillingUpStatus = Track::FS_ACTIVE;
2627 if (track->mState == TrackBase::RESUMING) {
2628 track->mState = TrackBase::ACTIVE;
2629 param = AudioMixer::RAMP_VOLUME;
2630 }
2631 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2632 } else if (cblk->server != 0) {
2633 // If the track is stopped before the first frame was mixed,
2634 // do not apply ramp
2635 param = AudioMixer::RAMP_VOLUME;
2636 }
2637
2638 // compute volume for this track
2639 uint32_t vl, vr, va;
2640 if (track->isMuted() || track->isPausing() ||
2641 mStreamTypes[track->streamType()].mute) {
2642 vl = vr = va = 0;
2643 if (track->isPausing()) {
2644 track->setPaused();
2645 }
2646 } else {
2647
2648 // read original volumes with volume control
2649 float typeVolume = mStreamTypes[track->streamType()].volume;
2650 float v = masterVolume * typeVolume;
2651 uint32_t vlr = cblk->getVolumeLR();
2652 vl = vlr & 0xFFFF;
2653 vr = vlr >> 16;
2654 // track volumes come from shared memory, so can't be trusted and must be clamped
2655 if (vl > MAX_GAIN_INT) {
2656 ALOGV("Track left volume out of range: %04X", vl);
2657 vl = MAX_GAIN_INT;
2658 }
2659 if (vr > MAX_GAIN_INT) {
2660 ALOGV("Track right volume out of range: %04X", vr);
2661 vr = MAX_GAIN_INT;
2662 }
2663 // now apply the master volume and stream type volume
2664 vl = (uint32_t)(v * vl) << 12;
2665 vr = (uint32_t)(v * vr) << 12;
2666 // assuming master volume and stream type volume each go up to 1.0,
2667 // vl and vr are now in 8.24 format
2668
2669 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2670 // send level comes from shared memory and so may be corrupt
2671 if (sendLevel > MAX_GAIN_INT) {
2672 ALOGV("Track send level out of range: %04X", sendLevel);
2673 sendLevel = MAX_GAIN_INT;
2674 }
2675 va = (uint32_t)(v * sendLevel);
2676 }
2677 // Delegate volume control to effect in track effect chain if needed
2678 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2679 // Do not ramp volume if volume is controlled by effect
2680 param = AudioMixer::VOLUME;
2681 track->mHasVolumeController = true;
2682 } else {
2683 // force no volume ramp when volume controller was just disabled or removed
2684 // from effect chain to avoid volume spike
2685 if (track->mHasVolumeController) {
2686 param = AudioMixer::VOLUME;
2687 }
2688 track->mHasVolumeController = false;
2689 }
2690
2691 // Convert volumes from 8.24 to 4.12 format
2692 // This additional clamping is needed in case chain->setVolume_l() overshot
2693 vl = (vl + (1 << 11)) >> 12;
2694 if (vl > MAX_GAIN_INT) {
2695 vl = MAX_GAIN_INT;
2696 }
2697 vr = (vr + (1 << 11)) >> 12;
2698 if (vr > MAX_GAIN_INT) {
2699 vr = MAX_GAIN_INT;
2700 }
2701
2702 if (va > MAX_GAIN_INT) {
2703 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
2704 }
2705
2706 // XXX: these things DON'T need to be done each time
2707 mAudioMixer->setBufferProvider(name, track);
2708 mAudioMixer->enable(name);
2709
2710 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2711 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2712 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
2713 mAudioMixer->setParameter(
2714 name,
2715 AudioMixer::TRACK,
2716 AudioMixer::FORMAT, (void *)track->format());
2717 mAudioMixer->setParameter(
2718 name,
2719 AudioMixer::TRACK,
2720 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
2721 mAudioMixer->setParameter(
2722 name,
2723 AudioMixer::RESAMPLE,
2724 AudioMixer::SAMPLE_RATE,
2725 (void *)(cblk->sampleRate));
2726 mAudioMixer->setParameter(
2727 name,
2728 AudioMixer::TRACK,
2729 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2730 mAudioMixer->setParameter(
2731 name,
2732 AudioMixer::TRACK,
2733 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2734
2735 // reset retry count
2736 track->mRetryCount = kMaxTrackRetries;
2737
2738 // If one track is ready, set the mixer ready if:
2739 // - the mixer was not ready during previous round OR
2740 // - no other track is not ready
2741 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
2742 mixerStatus != MIXER_TRACKS_ENABLED) {
2743 mixerStatus = MIXER_TRACKS_READY;
2744 }
2745 } else {
2746 // clear effect chain input buffer if an active track underruns to avoid sending
2747 // previous audio buffer again to effects
2748 chain = getEffectChain_l(track->sessionId());
2749 if (chain != 0) {
2750 chain->clearInputBuffer();
2751 }
2752
2753 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
2754 cblk->server, this);
2755 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
2756 track->isStopped() || track->isPaused()) {
2757 // We have consumed all the buffers of this track.
2758 // Remove it from the list of active tracks.
2759 // TODO: use actual buffer filling status instead of latency when available from
2760 // audio HAL
2761 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
2762 size_t framesWritten = mBytesWritten / mFrameSize;
2763 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
2764 if (track->isStopped()) {
2765 track->reset();
2766 }
2767 tracksToRemove->add(track);
2768 }
2769 } else {
2770 track->mUnderrunCount++;
2771 // No buffers for this track. Give it a few chances to
2772 // fill a buffer, then remove it from active list.
2773 if (--(track->mRetryCount) <= 0) {
2774 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
2775 tracksToRemove->add(track);
2776 // indicate to client process that the track was disabled because of underrun;
2777 // it will then automatically call start() when data is available
2778 android_atomic_or(CBLK_DISABLED, &cblk->flags);
2779 // If one track is not ready, mark the mixer also not ready if:
2780 // - the mixer was ready during previous round OR
2781 // - no other track is ready
2782 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
2783 mixerStatus != MIXER_TRACKS_READY) {
2784 mixerStatus = MIXER_TRACKS_ENABLED;
2785 }
2786 }
2787 mAudioMixer->disable(name);
2788 }
2789
2790 } // local variable scope to avoid goto warning
2791track_is_ready: ;
2792
2793 }
2794
2795 // Push the new FastMixer state if necessary
2796 bool pauseAudioWatchdog = false;
2797 if (didModify) {
2798 state->mFastTracksGen++;
2799 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2800 if (kUseFastMixer == FastMixer_Dynamic &&
2801 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2802 state->mCommand = FastMixerState::COLD_IDLE;
2803 state->mColdFutexAddr = &mFastMixerFutex;
2804 state->mColdGen++;
2805 mFastMixerFutex = 0;
2806 if (kUseFastMixer == FastMixer_Dynamic) {
2807 mNormalSink = mOutputSink;
2808 }
2809 // If we go into cold idle, need to wait for acknowledgement
2810 // so that fast mixer stops doing I/O.
2811 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2812 pauseAudioWatchdog = true;
2813 }
2814 sq->end();
2815 }
2816 if (sq != NULL) {
2817 sq->end(didModify);
2818 sq->push(block);
2819 }
2820#ifdef AUDIO_WATCHDOG
2821 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
2822 mAudioWatchdog->pause();
2823 }
2824#endif
2825
2826 // Now perform the deferred reset on fast tracks that have stopped
2827 while (resetMask != 0) {
2828 size_t i = __builtin_ctz(resetMask);
2829 ALOG_ASSERT(i < count);
2830 resetMask &= ~(1 << i);
2831 sp<Track> t = mActiveTracks[i].promote();
2832 if (t == 0) {
2833 continue;
2834 }
2835 Track* track = t.get();
2836 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
2837 track->reset();
2838 }
2839
2840 // remove all the tracks that need to be...
2841 count = tracksToRemove->size();
2842 if (CC_UNLIKELY(count)) {
2843 for (size_t i=0 ; i<count ; i++) {
2844 const sp<Track>& track = tracksToRemove->itemAt(i);
2845 mActiveTracks.remove(track);
2846 if (track->mainBuffer() != mMixBuffer) {
2847 chain = getEffectChain_l(track->sessionId());
2848 if (chain != 0) {
2849 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2850 track->sessionId());
2851 chain->decActiveTrackCnt();
2852 }
2853 }
2854 if (track->isTerminated()) {
2855 removeTrack_l(track);
2856 }
2857 }
2858 }
2859
2860 // mix buffer must be cleared if all tracks are connected to an
2861 // effect chain as in this case the mixer will not write to
2862 // mix buffer and track effects will accumulate into it
2863 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
2864 (mixedTracks == 0 && fastTracks > 0)) {
2865 // FIXME as a performance optimization, should remember previous zero status
2866 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2867 }
2868
2869 // if any fast tracks, then status is ready
2870 mMixerStatusIgnoringFastTracks = mixerStatus;
2871 if (fastTracks > 0) {
2872 mixerStatus = MIXER_TRACKS_READY;
2873 }
2874 return mixerStatus;
2875}
2876
2877// getTrackName_l() must be called with ThreadBase::mLock held
2878int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
2879{
2880 return mAudioMixer->getTrackName(channelMask, sessionId);
2881}
2882
2883// deleteTrackName_l() must be called with ThreadBase::mLock held
2884void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2885{
2886 ALOGV("remove track (%d) and delete from mixer", name);
2887 mAudioMixer->deleteTrackName(name);
2888}
2889
2890// checkForNewParameters_l() must be called with ThreadBase::mLock held
2891bool AudioFlinger::MixerThread::checkForNewParameters_l()
2892{
2893 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2894 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2895 bool reconfig = false;
2896
2897 while (!mNewParameters.isEmpty()) {
2898
2899 if (mFastMixer != NULL) {
2900 FastMixerStateQueue *sq = mFastMixer->sq();
2901 FastMixerState *state = sq->begin();
2902 if (!(state->mCommand & FastMixerState::IDLE)) {
2903 previousCommand = state->mCommand;
2904 state->mCommand = FastMixerState::HOT_IDLE;
2905 sq->end();
2906 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2907 } else {
2908 sq->end(false /*didModify*/);
2909 }
2910 }
2911
2912 status_t status = NO_ERROR;
2913 String8 keyValuePair = mNewParameters[0];
2914 AudioParameter param = AudioParameter(keyValuePair);
2915 int value;
2916
2917 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2918 reconfig = true;
2919 }
2920 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
2921 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
2922 status = BAD_VALUE;
2923 } else {
2924 reconfig = true;
2925 }
2926 }
2927 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
2928 if (value != AUDIO_CHANNEL_OUT_STEREO) {
2929 status = BAD_VALUE;
2930 } else {
2931 reconfig = true;
2932 }
2933 }
2934 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2935 // do not accept frame count changes if tracks are open as the track buffer
2936 // size depends on frame count and correct behavior would not be guaranteed
2937 // if frame count is changed after track creation
2938 if (!mTracks.isEmpty()) {
2939 status = INVALID_OPERATION;
2940 } else {
2941 reconfig = true;
2942 }
2943 }
2944 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
2945#ifdef ADD_BATTERY_DATA
2946 // when changing the audio output device, call addBatteryData to notify
2947 // the change
2948 if (mOutDevice != value) {
2949 uint32_t params = 0;
2950 // check whether speaker is on
2951 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
2952 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2953 }
2954
2955 audio_devices_t deviceWithoutSpeaker
2956 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2957 // check if any other device (except speaker) is on
2958 if (value & deviceWithoutSpeaker ) {
2959 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2960 }
2961
2962 if (params != 0) {
2963 addBatteryData(params);
2964 }
2965 }
2966#endif
2967
2968 // forward device change to effects that have requested to be
2969 // aware of attached audio device.
2970 mOutDevice = value;
2971 for (size_t i = 0; i < mEffectChains.size(); i++) {
2972 mEffectChains[i]->setDevice_l(mOutDevice);
2973 }
2974 }
2975
2976 if (status == NO_ERROR) {
2977 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2978 keyValuePair.string());
2979 if (!mStandby && status == INVALID_OPERATION) {
2980 mOutput->stream->common.standby(&mOutput->stream->common);
2981 mStandby = true;
2982 mBytesWritten = 0;
2983 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2984 keyValuePair.string());
2985 }
2986 if (status == NO_ERROR && reconfig) {
2987 delete mAudioMixer;
2988 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2989 mAudioMixer = NULL;
2990 readOutputParameters();
2991 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2992 for (size_t i = 0; i < mTracks.size() ; i++) {
2993 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
2994 if (name < 0) {
2995 break;
2996 }
2997 mTracks[i]->mName = name;
2998 // limit track sample rate to 2 x new output sample rate
2999 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3000 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3001 }
3002 }
3003 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3004 }
3005 }
3006
3007 mNewParameters.removeAt(0);
3008
3009 mParamStatus = status;
3010 mParamCond.signal();
3011 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3012 // already timed out waiting for the status and will never signal the condition.
3013 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3014 }
3015
3016 if (!(previousCommand & FastMixerState::IDLE)) {
3017 ALOG_ASSERT(mFastMixer != NULL);
3018 FastMixerStateQueue *sq = mFastMixer->sq();
3019 FastMixerState *state = sq->begin();
3020 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3021 state->mCommand = previousCommand;
3022 sq->end();
3023 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3024 }
3025
3026 return reconfig;
3027}
3028
3029
3030void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3031{
3032 const size_t SIZE = 256;
3033 char buffer[SIZE];
3034 String8 result;
3035
3036 PlaybackThread::dumpInternals(fd, args);
3037
3038 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3039 result.append(buffer);
3040 write(fd, result.string(), result.size());
3041
3042 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3043 FastMixerDumpState copy = mFastMixerDumpState;
3044 copy.dump(fd);
3045
3046#ifdef STATE_QUEUE_DUMP
3047 // Similar for state queue
3048 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3049 observerCopy.dump(fd);
3050 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3051 mutatorCopy.dump(fd);
3052#endif
3053
3054 // Write the tee output to a .wav file
3055 dumpTee(fd, mTeeSource, mId);
3056
3057#ifdef AUDIO_WATCHDOG
3058 if (mAudioWatchdog != 0) {
3059 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3060 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3061 wdCopy.dump(fd);
3062 }
3063#endif
3064}
3065
3066uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3067{
3068 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3069}
3070
3071uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3072{
3073 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3074}
3075
3076void AudioFlinger::MixerThread::cacheParameters_l()
3077{
3078 PlaybackThread::cacheParameters_l();
3079
3080 // FIXME: Relaxed timing because of a certain device that can't meet latency
3081 // Should be reduced to 2x after the vendor fixes the driver issue
3082 // increase threshold again due to low power audio mode. The way this warning
3083 // threshold is calculated and its usefulness should be reconsidered anyway.
3084 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3085}
3086
3087// ----------------------------------------------------------------------------
3088
3089AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3090 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3091 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3092 // mLeftVolFloat, mRightVolFloat
3093{
3094}
3095
3096AudioFlinger::DirectOutputThread::~DirectOutputThread()
3097{
3098}
3099
3100AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3101 Vector< sp<Track> > *tracksToRemove
3102)
3103{
3104 sp<Track> trackToRemove;
3105
3106 mixer_state mixerStatus = MIXER_IDLE;
3107
3108 // find out which tracks need to be processed
3109 if (mActiveTracks.size() != 0) {
3110 sp<Track> t = mActiveTracks[0].promote();
3111 // The track died recently
3112 if (t == 0) {
3113 return MIXER_IDLE;
3114 }
3115
3116 Track* const track = t.get();
3117 audio_track_cblk_t* cblk = track->cblk();
3118
3119 // The first time a track is added we wait
3120 // for all its buffers to be filled before processing it
3121 uint32_t minFrames;
3122 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3123 minFrames = mNormalFrameCount;
3124 } else {
3125 minFrames = 1;
3126 }
3127 if ((track->framesReady() >= minFrames) && track->isReady() &&
3128 !track->isPaused() && !track->isTerminated())
3129 {
3130 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3131
3132 if (track->mFillingUpStatus == Track::FS_FILLED) {
3133 track->mFillingUpStatus = Track::FS_ACTIVE;
3134 mLeftVolFloat = mRightVolFloat = 0;
3135 if (track->mState == TrackBase::RESUMING) {
3136 track->mState = TrackBase::ACTIVE;
3137 }
3138 }
3139
3140 // compute volume for this track
3141 float left, right;
3142 if (track->isMuted() || mMasterMute || track->isPausing() ||
3143 mStreamTypes[track->streamType()].mute) {
3144 left = right = 0;
3145 if (track->isPausing()) {
3146 track->setPaused();
3147 }
3148 } else {
3149 float typeVolume = mStreamTypes[track->streamType()].volume;
3150 float v = mMasterVolume * typeVolume;
3151 uint32_t vlr = cblk->getVolumeLR();
3152 float v_clamped = v * (vlr & 0xFFFF);
3153 if (v_clamped > MAX_GAIN) {
3154 v_clamped = MAX_GAIN;
3155 }
3156 left = v_clamped/MAX_GAIN;
3157 v_clamped = v * (vlr >> 16);
3158 if (v_clamped > MAX_GAIN) {
3159 v_clamped = MAX_GAIN;
3160 }
3161 right = v_clamped/MAX_GAIN;
3162 }
3163
3164 if (left != mLeftVolFloat || right != mRightVolFloat) {
3165 mLeftVolFloat = left;
3166 mRightVolFloat = right;
3167
3168 // Convert volumes from float to 8.24
3169 uint32_t vl = (uint32_t)(left * (1 << 24));
3170 uint32_t vr = (uint32_t)(right * (1 << 24));
3171
3172 // Delegate volume control to effect in track effect chain if needed
3173 // only one effect chain can be present on DirectOutputThread, so if
3174 // there is one, the track is connected to it
3175 if (!mEffectChains.isEmpty()) {
3176 // Do not ramp volume if volume is controlled by effect
3177 mEffectChains[0]->setVolume_l(&vl, &vr);
3178 left = (float)vl / (1 << 24);
3179 right = (float)vr / (1 << 24);
3180 }
3181 mOutput->stream->set_volume(mOutput->stream, left, right);
3182 }
3183
3184 // reset retry count
3185 track->mRetryCount = kMaxTrackRetriesDirect;
3186 mActiveTrack = t;
3187 mixerStatus = MIXER_TRACKS_READY;
3188 } else {
3189 // clear effect chain input buffer if an active track underruns to avoid sending
3190 // previous audio buffer again to effects
3191 if (!mEffectChains.isEmpty()) {
3192 mEffectChains[0]->clearInputBuffer();
3193 }
3194
3195 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3196 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3197 track->isStopped() || track->isPaused()) {
3198 // We have consumed all the buffers of this track.
3199 // Remove it from the list of active tracks.
3200 // TODO: implement behavior for compressed audio
3201 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3202 size_t framesWritten = mBytesWritten / mFrameSize;
3203 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3204 if (track->isStopped()) {
3205 track->reset();
3206 }
3207 trackToRemove = track;
3208 }
3209 } else {
3210 // No buffers for this track. Give it a few chances to
3211 // fill a buffer, then remove it from active list.
3212 if (--(track->mRetryCount) <= 0) {
3213 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3214 trackToRemove = track;
3215 } else {
3216 mixerStatus = MIXER_TRACKS_ENABLED;
3217 }
3218 }
3219 }
3220 }
3221
3222 // FIXME merge this with similar code for removing multiple tracks
3223 // remove all the tracks that need to be...
3224 if (CC_UNLIKELY(trackToRemove != 0)) {
3225 tracksToRemove->add(trackToRemove);
3226 mActiveTracks.remove(trackToRemove);
3227 if (!mEffectChains.isEmpty()) {
3228 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3229 trackToRemove->sessionId());
3230 mEffectChains[0]->decActiveTrackCnt();
3231 }
3232 if (trackToRemove->isTerminated()) {
3233 removeTrack_l(trackToRemove);
3234 }
3235 }
3236
3237 return mixerStatus;
3238}
3239
3240void AudioFlinger::DirectOutputThread::threadLoop_mix()
3241{
3242 AudioBufferProvider::Buffer buffer;
3243 size_t frameCount = mFrameCount;
3244 int8_t *curBuf = (int8_t *)mMixBuffer;
3245 // output audio to hardware
3246 while (frameCount) {
3247 buffer.frameCount = frameCount;
3248 mActiveTrack->getNextBuffer(&buffer);
3249 if (CC_UNLIKELY(buffer.raw == NULL)) {
3250 memset(curBuf, 0, frameCount * mFrameSize);
3251 break;
3252 }
3253 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3254 frameCount -= buffer.frameCount;
3255 curBuf += buffer.frameCount * mFrameSize;
3256 mActiveTrack->releaseBuffer(&buffer);
3257 }
3258 sleepTime = 0;
3259 standbyTime = systemTime() + standbyDelay;
3260 mActiveTrack.clear();
3261
3262}
3263
3264void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3265{
3266 if (sleepTime == 0) {
3267 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3268 sleepTime = activeSleepTime;
3269 } else {
3270 sleepTime = idleSleepTime;
3271 }
3272 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3273 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3274 sleepTime = 0;
3275 }
3276}
3277
3278// getTrackName_l() must be called with ThreadBase::mLock held
3279int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3280 int sessionId)
3281{
3282 return 0;
3283}
3284
3285// deleteTrackName_l() must be called with ThreadBase::mLock held
3286void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3287{
3288}
3289
3290// checkForNewParameters_l() must be called with ThreadBase::mLock held
3291bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3292{
3293 bool reconfig = false;
3294
3295 while (!mNewParameters.isEmpty()) {
3296 status_t status = NO_ERROR;
3297 String8 keyValuePair = mNewParameters[0];
3298 AudioParameter param = AudioParameter(keyValuePair);
3299 int value;
3300
3301 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3302 // do not accept frame count changes if tracks are open as the track buffer
3303 // size depends on frame count and correct behavior would not be garantied
3304 // if frame count is changed after track creation
3305 if (!mTracks.isEmpty()) {
3306 status = INVALID_OPERATION;
3307 } else {
3308 reconfig = true;
3309 }
3310 }
3311 if (status == NO_ERROR) {
3312 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3313 keyValuePair.string());
3314 if (!mStandby && status == INVALID_OPERATION) {
3315 mOutput->stream->common.standby(&mOutput->stream->common);
3316 mStandby = true;
3317 mBytesWritten = 0;
3318 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3319 keyValuePair.string());
3320 }
3321 if (status == NO_ERROR && reconfig) {
3322 readOutputParameters();
3323 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3324 }
3325 }
3326
3327 mNewParameters.removeAt(0);
3328
3329 mParamStatus = status;
3330 mParamCond.signal();
3331 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3332 // already timed out waiting for the status and will never signal the condition.
3333 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3334 }
3335 return reconfig;
3336}
3337
3338uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3339{
3340 uint32_t time;
3341 if (audio_is_linear_pcm(mFormat)) {
3342 time = PlaybackThread::activeSleepTimeUs();
3343 } else {
3344 time = 10000;
3345 }
3346 return time;
3347}
3348
3349uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3350{
3351 uint32_t time;
3352 if (audio_is_linear_pcm(mFormat)) {
3353 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3354 } else {
3355 time = 10000;
3356 }
3357 return time;
3358}
3359
3360uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3361{
3362 uint32_t time;
3363 if (audio_is_linear_pcm(mFormat)) {
3364 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3365 } else {
3366 time = 10000;
3367 }
3368 return time;
3369}
3370
3371void AudioFlinger::DirectOutputThread::cacheParameters_l()
3372{
3373 PlaybackThread::cacheParameters_l();
3374
3375 // use shorter standby delay as on normal output to release
3376 // hardware resources as soon as possible
3377 standbyDelay = microseconds(activeSleepTime*2);
3378}
3379
3380// ----------------------------------------------------------------------------
3381
3382AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3383 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3384 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3385 DUPLICATING),
3386 mWaitTimeMs(UINT_MAX)
3387{
3388 addOutputTrack(mainThread);
3389}
3390
3391AudioFlinger::DuplicatingThread::~DuplicatingThread()
3392{
3393 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3394 mOutputTracks[i]->destroy();
3395 }
3396}
3397
3398void AudioFlinger::DuplicatingThread::threadLoop_mix()
3399{
3400 // mix buffers...
3401 if (outputsReady(outputTracks)) {
3402 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3403 } else {
3404 memset(mMixBuffer, 0, mixBufferSize);
3405 }
3406 sleepTime = 0;
3407 writeFrames = mNormalFrameCount;
3408 standbyTime = systemTime() + standbyDelay;
3409}
3410
3411void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3412{
3413 if (sleepTime == 0) {
3414 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3415 sleepTime = activeSleepTime;
3416 } else {
3417 sleepTime = idleSleepTime;
3418 }
3419 } else if (mBytesWritten != 0) {
3420 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3421 writeFrames = mNormalFrameCount;
3422 memset(mMixBuffer, 0, mixBufferSize);
3423 } else {
3424 // flush remaining overflow buffers in output tracks
3425 writeFrames = 0;
3426 }
3427 sleepTime = 0;
3428 }
3429}
3430
3431void AudioFlinger::DuplicatingThread::threadLoop_write()
3432{
3433 for (size_t i = 0; i < outputTracks.size(); i++) {
3434 outputTracks[i]->write(mMixBuffer, writeFrames);
3435 }
3436 mBytesWritten += mixBufferSize;
3437}
3438
3439void AudioFlinger::DuplicatingThread::threadLoop_standby()
3440{
3441 // DuplicatingThread implements standby by stopping all tracks
3442 for (size_t i = 0; i < outputTracks.size(); i++) {
3443 outputTracks[i]->stop();
3444 }
3445}
3446
3447void AudioFlinger::DuplicatingThread::saveOutputTracks()
3448{
3449 outputTracks = mOutputTracks;
3450}
3451
3452void AudioFlinger::DuplicatingThread::clearOutputTracks()
3453{
3454 outputTracks.clear();
3455}
3456
3457void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3458{
3459 Mutex::Autolock _l(mLock);
3460 // FIXME explain this formula
3461 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
3462 OutputTrack *outputTrack = new OutputTrack(thread,
3463 this,
3464 mSampleRate,
3465 mFormat,
3466 mChannelMask,
3467 frameCount);
3468 if (outputTrack->cblk() != NULL) {
3469 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3470 mOutputTracks.add(outputTrack);
3471 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3472 updateWaitTime_l();
3473 }
3474}
3475
3476void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3477{
3478 Mutex::Autolock _l(mLock);
3479 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3480 if (mOutputTracks[i]->thread() == thread) {
3481 mOutputTracks[i]->destroy();
3482 mOutputTracks.removeAt(i);
3483 updateWaitTime_l();
3484 return;
3485 }
3486 }
3487 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3488}
3489
3490// caller must hold mLock
3491void AudioFlinger::DuplicatingThread::updateWaitTime_l()
3492{
3493 mWaitTimeMs = UINT_MAX;
3494 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3495 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3496 if (strong != 0) {
3497 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3498 if (waitTimeMs < mWaitTimeMs) {
3499 mWaitTimeMs = waitTimeMs;
3500 }
3501 }
3502 }
3503}
3504
3505
3506bool AudioFlinger::DuplicatingThread::outputsReady(
3507 const SortedVector< sp<OutputTrack> > &outputTracks)
3508{
3509 for (size_t i = 0; i < outputTracks.size(); i++) {
3510 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
3511 if (thread == 0) {
3512 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
3513 outputTracks[i].get());
3514 return false;
3515 }
3516 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3517 // see note at standby() declaration
3518 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3519 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
3520 thread.get());
3521 return false;
3522 }
3523 }
3524 return true;
3525}
3526
3527uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
3528{
3529 return (mWaitTimeMs * 1000) / 2;
3530}
3531
3532void AudioFlinger::DuplicatingThread::cacheParameters_l()
3533{
3534 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3535 updateWaitTime_l();
3536
3537 MixerThread::cacheParameters_l();
3538}
3539
3540// ----------------------------------------------------------------------------
3541// Record
3542// ----------------------------------------------------------------------------
3543
3544AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
3545 AudioStreamIn *input,
3546 uint32_t sampleRate,
3547 audio_channel_mask_t channelMask,
3548 audio_io_handle_t id,
3549 audio_devices_t device,
3550 const sp<NBAIO_Sink>& teeSink) :
3551 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
3552 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
3553 // mRsmpInIndex and mInputBytes set by readInputParameters()
3554 mReqChannelCount(popcount(channelMask)),
3555 mReqSampleRate(sampleRate),
3556 // mBytesRead is only meaningful while active, and so is cleared in start()
3557 // (but might be better to also clear here for dump?)
3558 mTeeSink(teeSink)
3559{
3560 snprintf(mName, kNameLength, "AudioIn_%X", id);
3561
3562 readInputParameters();
3563
3564}
3565
3566
3567AudioFlinger::RecordThread::~RecordThread()
3568{
3569 delete[] mRsmpInBuffer;
3570 delete mResampler;
3571 delete[] mRsmpOutBuffer;
3572}
3573
3574void AudioFlinger::RecordThread::onFirstRef()
3575{
3576 run(mName, PRIORITY_URGENT_AUDIO);
3577}
3578
3579status_t AudioFlinger::RecordThread::readyToRun()
3580{
3581 status_t status = initCheck();
3582 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
3583 return status;
3584}
3585
3586bool AudioFlinger::RecordThread::threadLoop()
3587{
3588 AudioBufferProvider::Buffer buffer;
3589 sp<RecordTrack> activeTrack;
3590 Vector< sp<EffectChain> > effectChains;
3591
3592 nsecs_t lastWarning = 0;
3593
3594 inputStandBy();
3595 acquireWakeLock();
3596
3597 // used to verify we've read at least once before evaluating how many bytes were read
3598 bool readOnce = false;
3599
3600 // start recording
3601 while (!exitPending()) {
3602
3603 processConfigEvents();
3604
3605 { // scope for mLock
3606 Mutex::Autolock _l(mLock);
3607 checkForNewParameters_l();
3608 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3609 standby();
3610
3611 if (exitPending()) {
3612 break;
3613 }
3614
3615 releaseWakeLock_l();
3616 ALOGV("RecordThread: loop stopping");
3617 // go to sleep
3618 mWaitWorkCV.wait(mLock);
3619 ALOGV("RecordThread: loop starting");
3620 acquireWakeLock_l();
3621 continue;
3622 }
3623 if (mActiveTrack != 0) {
3624 if (mActiveTrack->mState == TrackBase::PAUSING) {
3625 standby();
3626 mActiveTrack.clear();
3627 mStartStopCond.broadcast();
3628 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3629 if (mReqChannelCount != mActiveTrack->channelCount()) {
3630 mActiveTrack.clear();
3631 mStartStopCond.broadcast();
3632 } else if (readOnce) {
3633 // record start succeeds only if first read from audio input
3634 // succeeds
3635 if (mBytesRead >= 0) {
3636 mActiveTrack->mState = TrackBase::ACTIVE;
3637 } else {
3638 mActiveTrack.clear();
3639 }
3640 mStartStopCond.broadcast();
3641 }
3642 mStandby = false;
3643 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
3644 removeTrack_l(mActiveTrack);
3645 mActiveTrack.clear();
3646 }
3647 }
3648 lockEffectChains_l(effectChains);
3649 }
3650
3651 if (mActiveTrack != 0) {
3652 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3653 mActiveTrack->mState != TrackBase::RESUMING) {
3654 unlockEffectChains(effectChains);
3655 usleep(kRecordThreadSleepUs);
3656 continue;
3657 }
3658 for (size_t i = 0; i < effectChains.size(); i ++) {
3659 effectChains[i]->process_l();
3660 }
3661
3662 buffer.frameCount = mFrameCount;
3663 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3664 readOnce = true;
3665 size_t framesOut = buffer.frameCount;
3666 if (mResampler == NULL) {
3667 // no resampling
3668 while (framesOut) {
3669 size_t framesIn = mFrameCount - mRsmpInIndex;
3670 if (framesIn) {
3671 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3672 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
3673 mActiveTrack->mFrameSize;
3674 if (framesIn > framesOut)
3675 framesIn = framesOut;
3676 mRsmpInIndex += framesIn;
3677 framesOut -= framesIn;
3678 if (mChannelCount == mReqChannelCount ||
3679 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
3680 memcpy(dst, src, framesIn * mFrameSize);
3681 } else {
3682 if (mChannelCount == 1) {
3683 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
3684 (int16_t *)src, framesIn);
3685 } else {
3686 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
3687 (int16_t *)src, framesIn);
3688 }
3689 }
3690 }
3691 if (framesOut && mFrameCount == mRsmpInIndex) {
3692 void *readInto;
3693 if (framesOut == mFrameCount &&
3694 (mChannelCount == mReqChannelCount ||
3695 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
3696 readInto = buffer.raw;
3697 framesOut = 0;
3698 } else {
3699 readInto = mRsmpInBuffer;
3700 mRsmpInIndex = 0;
3701 }
3702 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
3703 if (mBytesRead <= 0) {
3704 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
3705 {
3706 ALOGE("Error reading audio input");
3707 // Force input into standby so that it tries to
3708 // recover at next read attempt
3709 inputStandBy();
3710 usleep(kRecordThreadSleepUs);
3711 }
3712 mRsmpInIndex = mFrameCount;
3713 framesOut = 0;
3714 buffer.frameCount = 0;
3715 } else if (mTeeSink != 0) {
3716 (void) mTeeSink->write(readInto,
3717 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
3718 }
3719 }
3720 }
3721 } else {
3722 // resampling
3723
3724 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3725 // alter output frame count as if we were expecting stereo samples
3726 if (mChannelCount == 1 && mReqChannelCount == 1) {
3727 framesOut >>= 1;
3728 }
3729 mResampler->resample(mRsmpOutBuffer, framesOut,
3730 this /* AudioBufferProvider* */);
3731 // ditherAndClamp() works as long as all buffers returned by
3732 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
3733 if (mChannelCount == 2 && mReqChannelCount == 1) {
3734 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3735 // the resampler always outputs stereo samples:
3736 // do post stereo to mono conversion
3737 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
3738 framesOut);
3739 } else {
3740 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3741 }
3742
3743 }
3744 if (mFramestoDrop == 0) {
3745 mActiveTrack->releaseBuffer(&buffer);
3746 } else {
3747 if (mFramestoDrop > 0) {
3748 mFramestoDrop -= buffer.frameCount;
3749 if (mFramestoDrop <= 0) {
3750 clearSyncStartEvent();
3751 }
3752 } else {
3753 mFramestoDrop += buffer.frameCount;
3754 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
3755 mSyncStartEvent->isCancelled()) {
3756 ALOGW("Synced record %s, session %d, trigger session %d",
3757 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
3758 mActiveTrack->sessionId(),
3759 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
3760 clearSyncStartEvent();
3761 }
3762 }
3763 }
3764 mActiveTrack->clearOverflow();
3765 }
3766 // client isn't retrieving buffers fast enough
3767 else {
3768 if (!mActiveTrack->setOverflow()) {
3769 nsecs_t now = systemTime();
3770 if ((now - lastWarning) > kWarningThrottleNs) {
3771 ALOGW("RecordThread: buffer overflow");
3772 lastWarning = now;
3773 }
3774 }
3775 // Release the processor for a while before asking for a new buffer.
3776 // This will give the application more chance to read from the buffer and
3777 // clear the overflow.
3778 usleep(kRecordThreadSleepUs);
3779 }
3780 }
3781 // enable changes in effect chain
3782 unlockEffectChains(effectChains);
3783 effectChains.clear();
3784 }
3785
3786 standby();
3787
3788 {
3789 Mutex::Autolock _l(mLock);
3790 mActiveTrack.clear();
3791 mStartStopCond.broadcast();
3792 }
3793
3794 releaseWakeLock();
3795
3796 ALOGV("RecordThread %p exiting", this);
3797 return false;
3798}
3799
3800void AudioFlinger::RecordThread::standby()
3801{
3802 if (!mStandby) {
3803 inputStandBy();
3804 mStandby = true;
3805 }
3806}
3807
3808void AudioFlinger::RecordThread::inputStandBy()
3809{
3810 mInput->stream->common.standby(&mInput->stream->common);
3811}
3812
3813sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
3814 const sp<AudioFlinger::Client>& client,
3815 uint32_t sampleRate,
3816 audio_format_t format,
3817 audio_channel_mask_t channelMask,
3818 size_t frameCount,
3819 int sessionId,
3820 IAudioFlinger::track_flags_t flags,
3821 pid_t tid,
3822 status_t *status)
3823{
3824 sp<RecordTrack> track;
3825 status_t lStatus;
3826
3827 lStatus = initCheck();
3828 if (lStatus != NO_ERROR) {
3829 ALOGE("Audio driver not initialized.");
3830 goto Exit;
3831 }
3832
3833 // FIXME use flags and tid similar to createTrack_l()
3834
3835 { // scope for mLock
3836 Mutex::Autolock _l(mLock);
3837
3838 track = new RecordTrack(this, client, sampleRate,
3839 format, channelMask, frameCount, sessionId);
3840
3841 if (track->getCblk() == 0) {
3842 lStatus = NO_MEMORY;
3843 goto Exit;
3844 }
3845 mTracks.add(track);
3846
3847 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
3848 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
3849 mAudioFlinger->btNrecIsOff();
3850 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
3851 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
3852 }
3853 lStatus = NO_ERROR;
3854
3855Exit:
3856 if (status) {
3857 *status = lStatus;
3858 }
3859 return track;
3860}
3861
3862status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
3863 AudioSystem::sync_event_t event,
3864 int triggerSession)
3865{
3866 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
3867 sp<ThreadBase> strongMe = this;
3868 status_t status = NO_ERROR;
3869
3870 if (event == AudioSystem::SYNC_EVENT_NONE) {
3871 clearSyncStartEvent();
3872 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
3873 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
3874 triggerSession,
3875 recordTrack->sessionId(),
3876 syncStartEventCallback,
3877 this);
3878 // Sync event can be cancelled by the trigger session if the track is not in a
3879 // compatible state in which case we start record immediately
3880 if (mSyncStartEvent->isCancelled()) {
3881 clearSyncStartEvent();
3882 } else {
3883 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
3884 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
3885 }
3886 }
3887
3888 {
3889 AutoMutex lock(mLock);
3890 if (mActiveTrack != 0) {
3891 if (recordTrack != mActiveTrack.get()) {
3892 status = -EBUSY;
3893 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
3894 mActiveTrack->mState = TrackBase::ACTIVE;
3895 }
3896 return status;
3897 }
3898
3899 recordTrack->mState = TrackBase::IDLE;
3900 mActiveTrack = recordTrack;
3901 mLock.unlock();
3902 status_t status = AudioSystem::startInput(mId);
3903 mLock.lock();
3904 if (status != NO_ERROR) {
3905 mActiveTrack.clear();
3906 clearSyncStartEvent();
3907 return status;
3908 }
3909 mRsmpInIndex = mFrameCount;
3910 mBytesRead = 0;
3911 if (mResampler != NULL) {
3912 mResampler->reset();
3913 }
3914 mActiveTrack->mState = TrackBase::RESUMING;
3915 // signal thread to start
3916 ALOGV("Signal record thread");
3917 mWaitWorkCV.broadcast();
3918 // do not wait for mStartStopCond if exiting
3919 if (exitPending()) {
3920 mActiveTrack.clear();
3921 status = INVALID_OPERATION;
3922 goto startError;
3923 }
3924 mStartStopCond.wait(mLock);
3925 if (mActiveTrack == 0) {
3926 ALOGV("Record failed to start");
3927 status = BAD_VALUE;
3928 goto startError;
3929 }
3930 ALOGV("Record started OK");
3931 return status;
3932 }
3933startError:
3934 AudioSystem::stopInput(mId);
3935 clearSyncStartEvent();
3936 return status;
3937}
3938
3939void AudioFlinger::RecordThread::clearSyncStartEvent()
3940{
3941 if (mSyncStartEvent != 0) {
3942 mSyncStartEvent->cancel();
3943 }
3944 mSyncStartEvent.clear();
3945 mFramestoDrop = 0;
3946}
3947
3948void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
3949{
3950 sp<SyncEvent> strongEvent = event.promote();
3951
3952 if (strongEvent != 0) {
3953 RecordThread *me = (RecordThread *)strongEvent->cookie();
3954 me->handleSyncStartEvent(strongEvent);
3955 }
3956}
3957
3958void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
3959{
3960 if (event == mSyncStartEvent) {
3961 // TODO: use actual buffer filling status instead of 2 buffers when info is available
3962 // from audio HAL
3963 mFramestoDrop = mFrameCount * 2;
3964 }
3965}
3966
3967bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
3968 ALOGV("RecordThread::stop");
3969 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
3970 return false;
3971 }
3972 recordTrack->mState = TrackBase::PAUSING;
3973 // do not wait for mStartStopCond if exiting
3974 if (exitPending()) {
3975 return true;
3976 }
3977 mStartStopCond.wait(mLock);
3978 // if we have been restarted, recordTrack == mActiveTrack.get() here
3979 if (exitPending() || recordTrack != mActiveTrack.get()) {
3980 ALOGV("Record stopped OK");
3981 return true;
3982 }
3983 return false;
3984}
3985
3986bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3987{
3988 return false;
3989}
3990
3991status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
3992{
3993#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
3994 if (!isValidSyncEvent(event)) {
3995 return BAD_VALUE;
3996 }
3997
3998 int eventSession = event->triggerSession();
3999 status_t ret = NAME_NOT_FOUND;
4000
4001 Mutex::Autolock _l(mLock);
4002
4003 for (size_t i = 0; i < mTracks.size(); i++) {
4004 sp<RecordTrack> track = mTracks[i];
4005 if (eventSession == track->sessionId()) {
4006 (void) track->setSyncEvent(event);
4007 ret = NO_ERROR;
4008 }
4009 }
4010 return ret;
4011#else
4012 return BAD_VALUE;
4013#endif
4014}
4015
4016// destroyTrack_l() must be called with ThreadBase::mLock held
4017void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4018{
4019 track->mState = TrackBase::TERMINATED;
4020 // active tracks are removed by threadLoop()
4021 if (mActiveTrack != track) {
4022 removeTrack_l(track);
4023 }
4024}
4025
4026void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4027{
4028 mTracks.remove(track);
4029 // need anything related to effects here?
4030}
4031
4032void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4033{
4034 dumpInternals(fd, args);
4035 dumpTracks(fd, args);
4036 dumpEffectChains(fd, args);
4037}
4038
4039void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4040{
4041 const size_t SIZE = 256;
4042 char buffer[SIZE];
4043 String8 result;
4044
4045 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4046 result.append(buffer);
4047
4048 if (mActiveTrack != 0) {
4049 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4050 result.append(buffer);
4051 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4052 result.append(buffer);
4053 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4054 result.append(buffer);
4055 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4056 result.append(buffer);
4057 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4058 result.append(buffer);
4059 } else {
4060 result.append("No active record client\n");
4061 }
4062
4063 write(fd, result.string(), result.size());
4064
4065 dumpBase(fd, args);
4066}
4067
4068void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4069{
4070 const size_t SIZE = 256;
4071 char buffer[SIZE];
4072 String8 result;
4073
4074 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4075 result.append(buffer);
4076 RecordTrack::appendDumpHeader(result);
4077 for (size_t i = 0; i < mTracks.size(); ++i) {
4078 sp<RecordTrack> track = mTracks[i];
4079 if (track != 0) {
4080 track->dump(buffer, SIZE);
4081 result.append(buffer);
4082 }
4083 }
4084
4085 if (mActiveTrack != 0) {
4086 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4087 result.append(buffer);
4088 RecordTrack::appendDumpHeader(result);
4089 mActiveTrack->dump(buffer, SIZE);
4090 result.append(buffer);
4091
4092 }
4093 write(fd, result.string(), result.size());
4094}
4095
4096// AudioBufferProvider interface
4097status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4098{
4099 size_t framesReq = buffer->frameCount;
4100 size_t framesReady = mFrameCount - mRsmpInIndex;
4101 int channelCount;
4102
4103 if (framesReady == 0) {
4104 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4105 if (mBytesRead <= 0) {
4106 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4107 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4108 // Force input into standby so that it tries to
4109 // recover at next read attempt
4110 inputStandBy();
4111 usleep(kRecordThreadSleepUs);
4112 }
4113 buffer->raw = NULL;
4114 buffer->frameCount = 0;
4115 return NOT_ENOUGH_DATA;
4116 }
4117 mRsmpInIndex = 0;
4118 framesReady = mFrameCount;
4119 }
4120
4121 if (framesReq > framesReady) {
4122 framesReq = framesReady;
4123 }
4124
4125 if (mChannelCount == 1 && mReqChannelCount == 2) {
4126 channelCount = 1;
4127 } else {
4128 channelCount = 2;
4129 }
4130 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4131 buffer->frameCount = framesReq;
4132 return NO_ERROR;
4133}
4134
4135// AudioBufferProvider interface
4136void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4137{
4138 mRsmpInIndex += buffer->frameCount;
4139 buffer->frameCount = 0;
4140}
4141
4142bool AudioFlinger::RecordThread::checkForNewParameters_l()
4143{
4144 bool reconfig = false;
4145
4146 while (!mNewParameters.isEmpty()) {
4147 status_t status = NO_ERROR;
4148 String8 keyValuePair = mNewParameters[0];
4149 AudioParameter param = AudioParameter(keyValuePair);
4150 int value;
4151 audio_format_t reqFormat = mFormat;
4152 uint32_t reqSamplingRate = mReqSampleRate;
4153 uint32_t reqChannelCount = mReqChannelCount;
4154
4155 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4156 reqSamplingRate = value;
4157 reconfig = true;
4158 }
4159 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4160 reqFormat = (audio_format_t) value;
4161 reconfig = true;
4162 }
4163 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4164 reqChannelCount = popcount(value);
4165 reconfig = true;
4166 }
4167 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4168 // do not accept frame count changes if tracks are open as the track buffer
4169 // size depends on frame count and correct behavior would not be guaranteed
4170 // if frame count is changed after track creation
4171 if (mActiveTrack != 0) {
4172 status = INVALID_OPERATION;
4173 } else {
4174 reconfig = true;
4175 }
4176 }
4177 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4178 // forward device change to effects that have requested to be
4179 // aware of attached audio device.
4180 for (size_t i = 0; i < mEffectChains.size(); i++) {
4181 mEffectChains[i]->setDevice_l(value);
4182 }
4183
4184 // store input device and output device but do not forward output device to audio HAL.
4185 // Note that status is ignored by the caller for output device
4186 // (see AudioFlinger::setParameters()
4187 if (audio_is_output_devices(value)) {
4188 mOutDevice = value;
4189 status = BAD_VALUE;
4190 } else {
4191 mInDevice = value;
4192 // disable AEC and NS if the device is a BT SCO headset supporting those
4193 // pre processings
4194 if (mTracks.size() > 0) {
4195 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4196 mAudioFlinger->btNrecIsOff();
4197 for (size_t i = 0; i < mTracks.size(); i++) {
4198 sp<RecordTrack> track = mTracks[i];
4199 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4200 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4201 }
4202 }
4203 }
4204 }
4205 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4206 mAudioSource != (audio_source_t)value) {
4207 // forward device change to effects that have requested to be
4208 // aware of attached audio device.
4209 for (size_t i = 0; i < mEffectChains.size(); i++) {
4210 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4211 }
4212 mAudioSource = (audio_source_t)value;
4213 }
4214 if (status == NO_ERROR) {
4215 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4216 keyValuePair.string());
4217 if (status == INVALID_OPERATION) {
4218 inputStandBy();
4219 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4220 keyValuePair.string());
4221 }
4222 if (reconfig) {
4223 if (status == BAD_VALUE &&
4224 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4225 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
4226 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common)
4227 <= (2 * reqSamplingRate)) &&
4228 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4229 <= FCC_2 &&
4230 (reqChannelCount <= FCC_2)) {
4231 status = NO_ERROR;
4232 }
4233 if (status == NO_ERROR) {
4234 readInputParameters();
4235 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4236 }
4237 }
4238 }
4239
4240 mNewParameters.removeAt(0);
4241
4242 mParamStatus = status;
4243 mParamCond.signal();
4244 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4245 // already timed out waiting for the status and will never signal the condition.
4246 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4247 }
4248 return reconfig;
4249}
4250
4251String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4252{
4253 char *s;
4254 String8 out_s8 = String8();
4255
4256 Mutex::Autolock _l(mLock);
4257 if (initCheck() != NO_ERROR) {
4258 return out_s8;
4259 }
4260
4261 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4262 out_s8 = String8(s);
4263 free(s);
4264 return out_s8;
4265}
4266
4267void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4268 AudioSystem::OutputDescriptor desc;
4269 void *param2 = NULL;
4270
4271 switch (event) {
4272 case AudioSystem::INPUT_OPENED:
4273 case AudioSystem::INPUT_CONFIG_CHANGED:
4274 desc.channels = mChannelMask;
4275 desc.samplingRate = mSampleRate;
4276 desc.format = mFormat;
4277 desc.frameCount = mFrameCount;
4278 desc.latency = 0;
4279 param2 = &desc;
4280 break;
4281
4282 case AudioSystem::INPUT_CLOSED:
4283 default:
4284 break;
4285 }
4286 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4287}
4288
4289void AudioFlinger::RecordThread::readInputParameters()
4290{
4291 delete mRsmpInBuffer;
4292 // mRsmpInBuffer is always assigned a new[] below
4293 delete mRsmpOutBuffer;
4294 mRsmpOutBuffer = NULL;
4295 delete mResampler;
4296 mResampler = NULL;
4297
4298 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4299 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4300 mChannelCount = (uint16_t)popcount(mChannelMask);
4301 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4302 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4303 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4304 mFrameCount = mInputBytes / mFrameSize;
4305 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
4306 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4307
4308 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
4309 {
4310 int channelCount;
4311 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4312 // stereo to mono post process as the resampler always outputs stereo.
4313 if (mChannelCount == 1 && mReqChannelCount == 2) {
4314 channelCount = 1;
4315 } else {
4316 channelCount = 2;
4317 }
4318 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4319 mResampler->setSampleRate(mSampleRate);
4320 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4321 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4322
4323 // optmization: if mono to mono, alter input frame count as if we were inputing
4324 // stereo samples
4325 if (mChannelCount == 1 && mReqChannelCount == 1) {
4326 mFrameCount >>= 1;
4327 }
4328
4329 }
4330 mRsmpInIndex = mFrameCount;
4331}
4332
4333unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4334{
4335 Mutex::Autolock _l(mLock);
4336 if (initCheck() != NO_ERROR) {
4337 return 0;
4338 }
4339
4340 return mInput->stream->get_input_frames_lost(mInput->stream);
4341}
4342
4343uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
4344{
4345 Mutex::Autolock _l(mLock);
4346 uint32_t result = 0;
4347 if (getEffectChain_l(sessionId) != 0) {
4348 result = EFFECT_SESSION;
4349 }
4350
4351 for (size_t i = 0; i < mTracks.size(); ++i) {
4352 if (sessionId == mTracks[i]->sessionId()) {
4353 result |= TRACK_SESSION;
4354 break;
4355 }
4356 }
4357
4358 return result;
4359}
4360
4361KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
4362{
4363 KeyedVector<int, bool> ids;
4364 Mutex::Autolock _l(mLock);
4365 for (size_t j = 0; j < mTracks.size(); ++j) {
4366 sp<RecordThread::RecordTrack> track = mTracks[j];
4367 int sessionId = track->sessionId();
4368 if (ids.indexOfKey(sessionId) < 0) {
4369 ids.add(sessionId, true);
4370 }
4371 }
4372 return ids;
4373}
4374
4375AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4376{
4377 Mutex::Autolock _l(mLock);
4378 AudioStreamIn *input = mInput;
4379 mInput = NULL;
4380 return input;
4381}
4382
4383// this method must always be called either with ThreadBase mLock held or inside the thread loop
4384audio_stream_t* AudioFlinger::RecordThread::stream() const
4385{
4386 if (mInput == NULL) {
4387 return NULL;
4388 }
4389 return &mInput->stream->common;
4390}
4391
4392status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
4393{
4394 // only one chain per input thread
4395 if (mEffectChains.size() != 0) {
4396 return INVALID_OPERATION;
4397 }
4398 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
4399
4400 chain->setInBuffer(NULL);
4401 chain->setOutBuffer(NULL);
4402
4403 checkSuspendOnAddEffectChain_l(chain);
4404
4405 mEffectChains.add(chain);
4406
4407 return NO_ERROR;
4408}
4409
4410size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
4411{
4412 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
4413 ALOGW_IF(mEffectChains.size() != 1,
4414 "removeEffectChain_l() %p invalid chain size %d on thread %p",
4415 chain.get(), mEffectChains.size(), this);
4416 if (mEffectChains.size() == 1) {
4417 mEffectChains.removeAt(0);
4418 }
4419 return 0;
4420}
4421
4422}; // namespace android