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