blob: e71c66e9d747e44a6e3b9d1a8ecd5ff24c13f601 [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
296void AudioFlinger::ThreadBase::exit()
297{
298 ALOGV("ThreadBase::exit");
299 // do any cleanup required for exit to succeed
300 preExit();
301 {
302 // This lock prevents the following race in thread (uniprocessor for illustration):
303 // if (!exitPending()) {
304 // // context switch from here to exit()
305 // // exit() calls requestExit(), what exitPending() observes
306 // // exit() calls signal(), which is dropped since no waiters
307 // // context switch back from exit() to here
308 // mWaitWorkCV.wait(...);
309 // // now thread is hung
310 // }
311 AutoMutex lock(mLock);
312 requestExit();
313 mWaitWorkCV.broadcast();
314 }
315 // When Thread::requestExitAndWait is made virtual and this method is renamed to
316 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
317 requestExitAndWait();
318}
319
320status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
321{
322 status_t status;
323
324 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
325 Mutex::Autolock _l(mLock);
326
327 mNewParameters.add(keyValuePairs);
328 mWaitWorkCV.signal();
329 // wait condition with timeout in case the thread loop has exited
330 // before the request could be processed
331 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
332 status = mParamStatus;
333 mWaitWorkCV.signal();
334 } else {
335 status = TIMED_OUT;
336 }
337 return status;
338}
339
340void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
341{
342 Mutex::Autolock _l(mLock);
343 sendIoConfigEvent_l(event, param);
344}
345
346// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
347void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
348{
349 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
350 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
351 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
352 param);
353 mWaitWorkCV.signal();
354}
355
356// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
357void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
358{
359 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
360 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
361 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
362 mConfigEvents.size(), pid, tid, prio);
363 mWaitWorkCV.signal();
364}
365
366void AudioFlinger::ThreadBase::processConfigEvents()
367{
368 mLock.lock();
369 while (!mConfigEvents.isEmpty()) {
370 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
371 ConfigEvent *event = mConfigEvents[0];
372 mConfigEvents.removeAt(0);
373 // release mLock before locking AudioFlinger mLock: lock order is always
374 // AudioFlinger then ThreadBase to avoid cross deadlock
375 mLock.unlock();
376 switch(event->type()) {
377 case CFG_EVENT_PRIO: {
378 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700379 // FIXME Need to understand why this has be done asynchronously
380 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
381 true /*asynchronous*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800382 if (err != 0) {
383 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
384 "error %d",
385 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
386 }
387 } break;
388 case CFG_EVENT_IO: {
389 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
390 mAudioFlinger->mLock.lock();
391 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
392 mAudioFlinger->mLock.unlock();
393 } break;
394 default:
395 ALOGE("processConfigEvents() unknown event type %d", event->type());
396 break;
397 }
398 delete event;
399 mLock.lock();
400 }
401 mLock.unlock();
402}
403
404void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
405{
406 const size_t SIZE = 256;
407 char buffer[SIZE];
408 String8 result;
409
410 bool locked = AudioFlinger::dumpTryLock(mLock);
411 if (!locked) {
412 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
413 write(fd, buffer, strlen(buffer));
414 }
415
416 snprintf(buffer, SIZE, "io handle: %d\n", mId);
417 result.append(buffer);
418 snprintf(buffer, SIZE, "TID: %d\n", getTid());
419 result.append(buffer);
420 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
421 result.append(buffer);
422 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
423 result.append(buffer);
424 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
425 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700426 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800427 result.append(buffer);
428 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
429 result.append(buffer);
430 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
431 result.append(buffer);
432 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
433 result.append(buffer);
434
435 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
436 result.append(buffer);
437 result.append(" Index Command");
438 for (size_t i = 0; i < mNewParameters.size(); ++i) {
439 snprintf(buffer, SIZE, "\n %02d ", i);
440 result.append(buffer);
441 result.append(mNewParameters[i]);
442 }
443
444 snprintf(buffer, SIZE, "\n\nPending config events: \n");
445 result.append(buffer);
446 for (size_t i = 0; i < mConfigEvents.size(); i++) {
447 mConfigEvents[i]->dump(buffer, SIZE);
448 result.append(buffer);
449 }
450 result.append("\n");
451
452 write(fd, result.string(), result.size());
453
454 if (locked) {
455 mLock.unlock();
456 }
457}
458
459void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
460{
461 const size_t SIZE = 256;
462 char buffer[SIZE];
463 String8 result;
464
465 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
466 write(fd, buffer, strlen(buffer));
467
468 for (size_t i = 0; i < mEffectChains.size(); ++i) {
469 sp<EffectChain> chain = mEffectChains[i];
470 if (chain != 0) {
471 chain->dump(fd, args);
472 }
473 }
474}
475
476void AudioFlinger::ThreadBase::acquireWakeLock()
477{
478 Mutex::Autolock _l(mLock);
479 acquireWakeLock_l();
480}
481
482void AudioFlinger::ThreadBase::acquireWakeLock_l()
483{
484 if (mPowerManager == 0) {
485 // use checkService() to avoid blocking if power service is not up yet
486 sp<IBinder> binder =
487 defaultServiceManager()->checkService(String16("power"));
488 if (binder == 0) {
489 ALOGW("Thread %s cannot connect to the power manager service", mName);
490 } else {
491 mPowerManager = interface_cast<IPowerManager>(binder);
492 binder->linkToDeath(mDeathRecipient);
493 }
494 }
495 if (mPowerManager != 0) {
496 sp<IBinder> binder = new BBinder();
497 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
498 binder,
Dianne Hackborn61d404e2013-05-20 11:22:20 -0700499 String16(mName),
500 String16("media"));
Eric Laurent81784c32012-11-19 14:55:58 -0800501 if (status == NO_ERROR) {
502 mWakeLockToken = binder;
503 }
504 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
505 }
506}
507
508void AudioFlinger::ThreadBase::releaseWakeLock()
509{
510 Mutex::Autolock _l(mLock);
511 releaseWakeLock_l();
512}
513
514void AudioFlinger::ThreadBase::releaseWakeLock_l()
515{
516 if (mWakeLockToken != 0) {
517 ALOGV("releaseWakeLock_l() %s", mName);
518 if (mPowerManager != 0) {
519 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
520 }
521 mWakeLockToken.clear();
522 }
523}
524
525void AudioFlinger::ThreadBase::clearPowerManager()
526{
527 Mutex::Autolock _l(mLock);
528 releaseWakeLock_l();
529 mPowerManager.clear();
530}
531
532void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
533{
534 sp<ThreadBase> thread = mThread.promote();
535 if (thread != 0) {
536 thread->clearPowerManager();
537 }
538 ALOGW("power manager service died !!!");
539}
540
541void AudioFlinger::ThreadBase::setEffectSuspended(
542 const effect_uuid_t *type, bool suspend, int sessionId)
543{
544 Mutex::Autolock _l(mLock);
545 setEffectSuspended_l(type, suspend, sessionId);
546}
547
548void AudioFlinger::ThreadBase::setEffectSuspended_l(
549 const effect_uuid_t *type, bool suspend, int sessionId)
550{
551 sp<EffectChain> chain = getEffectChain_l(sessionId);
552 if (chain != 0) {
553 if (type != NULL) {
554 chain->setEffectSuspended_l(type, suspend);
555 } else {
556 chain->setEffectSuspendedAll_l(suspend);
557 }
558 }
559
560 updateSuspendedSessions_l(type, suspend, sessionId);
561}
562
563void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
564{
565 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
566 if (index < 0) {
567 return;
568 }
569
570 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
571 mSuspendedSessions.valueAt(index);
572
573 for (size_t i = 0; i < sessionEffects.size(); i++) {
574 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
575 for (int j = 0; j < desc->mRefCount; j++) {
576 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
577 chain->setEffectSuspendedAll_l(true);
578 } else {
579 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
580 desc->mType.timeLow);
581 chain->setEffectSuspended_l(&desc->mType, true);
582 }
583 }
584 }
585}
586
587void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
588 bool suspend,
589 int sessionId)
590{
591 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
592
593 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
594
595 if (suspend) {
596 if (index >= 0) {
597 sessionEffects = mSuspendedSessions.valueAt(index);
598 } else {
599 mSuspendedSessions.add(sessionId, sessionEffects);
600 }
601 } else {
602 if (index < 0) {
603 return;
604 }
605 sessionEffects = mSuspendedSessions.valueAt(index);
606 }
607
608
609 int key = EffectChain::kKeyForSuspendAll;
610 if (type != NULL) {
611 key = type->timeLow;
612 }
613 index = sessionEffects.indexOfKey(key);
614
615 sp<SuspendedSessionDesc> desc;
616 if (suspend) {
617 if (index >= 0) {
618 desc = sessionEffects.valueAt(index);
619 } else {
620 desc = new SuspendedSessionDesc();
621 if (type != NULL) {
622 desc->mType = *type;
623 }
624 sessionEffects.add(key, desc);
625 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
626 }
627 desc->mRefCount++;
628 } else {
629 if (index < 0) {
630 return;
631 }
632 desc = sessionEffects.valueAt(index);
633 if (--desc->mRefCount == 0) {
634 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
635 sessionEffects.removeItemsAt(index);
636 if (sessionEffects.isEmpty()) {
637 ALOGV("updateSuspendedSessions_l() restore removing session %d",
638 sessionId);
639 mSuspendedSessions.removeItem(sessionId);
640 }
641 }
642 }
643 if (!sessionEffects.isEmpty()) {
644 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
645 }
646}
647
648void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
649 bool enabled,
650 int sessionId)
651{
652 Mutex::Autolock _l(mLock);
653 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
654}
655
656void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
657 bool enabled,
658 int sessionId)
659{
660 if (mType != RECORD) {
661 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
662 // another session. This gives the priority to well behaved effect control panels
663 // and applications not using global effects.
664 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
665 // global effects
666 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
667 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
668 }
669 }
670
671 sp<EffectChain> chain = getEffectChain_l(sessionId);
672 if (chain != 0) {
673 chain->checkSuspendOnEffectEnabled(effect, enabled);
674 }
675}
676
677// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
678sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
679 const sp<AudioFlinger::Client>& client,
680 const sp<IEffectClient>& effectClient,
681 int32_t priority,
682 int sessionId,
683 effect_descriptor_t *desc,
684 int *enabled,
685 status_t *status
686 )
687{
688 sp<EffectModule> effect;
689 sp<EffectHandle> handle;
690 status_t lStatus;
691 sp<EffectChain> chain;
692 bool chainCreated = false;
693 bool effectCreated = false;
694 bool effectRegistered = false;
695
696 lStatus = initCheck();
697 if (lStatus != NO_ERROR) {
698 ALOGW("createEffect_l() Audio driver not initialized.");
699 goto Exit;
700 }
701
702 // Do not allow effects with session ID 0 on direct output or duplicating threads
703 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
704 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
705 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
706 desc->name, sessionId);
707 lStatus = BAD_VALUE;
708 goto Exit;
709 }
710 // Only Pre processor effects are allowed on input threads and only on input threads
711 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
712 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
713 desc->name, desc->flags, mType);
714 lStatus = BAD_VALUE;
715 goto Exit;
716 }
717
718 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
719
720 { // scope for mLock
721 Mutex::Autolock _l(mLock);
722
723 // check for existing effect chain with the requested audio session
724 chain = getEffectChain_l(sessionId);
725 if (chain == 0) {
726 // create a new chain for this session
727 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
728 chain = new EffectChain(this, sessionId);
729 addEffectChain_l(chain);
730 chain->setStrategy(getStrategyForSession_l(sessionId));
731 chainCreated = true;
732 } else {
733 effect = chain->getEffectFromDesc_l(desc);
734 }
735
736 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
737
738 if (effect == 0) {
739 int id = mAudioFlinger->nextUniqueId();
740 // Check CPU and memory usage
741 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
742 if (lStatus != NO_ERROR) {
743 goto Exit;
744 }
745 effectRegistered = true;
746 // create a new effect module if none present in the chain
747 effect = new EffectModule(this, chain, desc, id, sessionId);
748 lStatus = effect->status();
749 if (lStatus != NO_ERROR) {
750 goto Exit;
751 }
752 lStatus = chain->addEffect_l(effect);
753 if (lStatus != NO_ERROR) {
754 goto Exit;
755 }
756 effectCreated = true;
757
758 effect->setDevice(mOutDevice);
759 effect->setDevice(mInDevice);
760 effect->setMode(mAudioFlinger->getMode());
761 effect->setAudioSource(mAudioSource);
762 }
763 // create effect handle and connect it to effect module
764 handle = new EffectHandle(effect, client, effectClient, priority);
765 lStatus = effect->addHandle(handle.get());
766 if (enabled != NULL) {
767 *enabled = (int)effect->isEnabled();
768 }
769 }
770
771Exit:
772 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
773 Mutex::Autolock _l(mLock);
774 if (effectCreated) {
775 chain->removeEffect_l(effect);
776 }
777 if (effectRegistered) {
778 AudioSystem::unregisterEffect(effect->id());
779 }
780 if (chainCreated) {
781 removeEffectChain_l(chain);
782 }
783 handle.clear();
784 }
785
786 if (status != NULL) {
787 *status = lStatus;
788 }
789 return handle;
790}
791
792sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
793{
794 Mutex::Autolock _l(mLock);
795 return getEffect_l(sessionId, effectId);
796}
797
798sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
799{
800 sp<EffectChain> chain = getEffectChain_l(sessionId);
801 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
802}
803
804// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
805// PlaybackThread::mLock held
806status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
807{
808 // check for existing effect chain with the requested audio session
809 int sessionId = effect->sessionId();
810 sp<EffectChain> chain = getEffectChain_l(sessionId);
811 bool chainCreated = false;
812
813 if (chain == 0) {
814 // create a new chain for this session
815 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
816 chain = new EffectChain(this, sessionId);
817 addEffectChain_l(chain);
818 chain->setStrategy(getStrategyForSession_l(sessionId));
819 chainCreated = true;
820 }
821 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
822
823 if (chain->getEffectFromId_l(effect->id()) != 0) {
824 ALOGW("addEffect_l() %p effect %s already present in chain %p",
825 this, effect->desc().name, chain.get());
826 return BAD_VALUE;
827 }
828
829 status_t status = chain->addEffect_l(effect);
830 if (status != NO_ERROR) {
831 if (chainCreated) {
832 removeEffectChain_l(chain);
833 }
834 return status;
835 }
836
837 effect->setDevice(mOutDevice);
838 effect->setDevice(mInDevice);
839 effect->setMode(mAudioFlinger->getMode());
840 effect->setAudioSource(mAudioSource);
841 return NO_ERROR;
842}
843
844void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
845
846 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
847 effect_descriptor_t desc = effect->desc();
848 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
849 detachAuxEffect_l(effect->id());
850 }
851
852 sp<EffectChain> chain = effect->chain().promote();
853 if (chain != 0) {
854 // remove effect chain if removing last effect
855 if (chain->removeEffect_l(effect) == 0) {
856 removeEffectChain_l(chain);
857 }
858 } else {
859 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
860 }
861}
862
863void AudioFlinger::ThreadBase::lockEffectChains_l(
864 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
865{
866 effectChains = mEffectChains;
867 for (size_t i = 0; i < mEffectChains.size(); i++) {
868 mEffectChains[i]->lock();
869 }
870}
871
872void AudioFlinger::ThreadBase::unlockEffectChains(
873 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
874{
875 for (size_t i = 0; i < effectChains.size(); i++) {
876 effectChains[i]->unlock();
877 }
878}
879
880sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
881{
882 Mutex::Autolock _l(mLock);
883 return getEffectChain_l(sessionId);
884}
885
886sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
887{
888 size_t size = mEffectChains.size();
889 for (size_t i = 0; i < size; i++) {
890 if (mEffectChains[i]->sessionId() == sessionId) {
891 return mEffectChains[i];
892 }
893 }
894 return 0;
895}
896
897void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
898{
899 Mutex::Autolock _l(mLock);
900 size_t size = mEffectChains.size();
901 for (size_t i = 0; i < size; i++) {
902 mEffectChains[i]->setMode_l(mode);
903 }
904}
905
906void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
907 EffectHandle *handle,
908 bool unpinIfLast) {
909
910 Mutex::Autolock _l(mLock);
911 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
912 // delete the effect module if removing last handle on it
913 if (effect->removeHandle(handle) == 0) {
914 if (!effect->isPinned() || unpinIfLast) {
915 removeEffect_l(effect);
916 AudioSystem::unregisterEffect(effect->id());
917 }
918 }
919}
920
921// ----------------------------------------------------------------------------
922// Playback
923// ----------------------------------------------------------------------------
924
925AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
926 AudioStreamOut* output,
927 audio_io_handle_t id,
928 audio_devices_t device,
929 type_t type)
930 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700931 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800932 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800933 // mStreamTypes[] initialized in constructor body
934 mOutput(output),
935 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
936 mMixerStatus(MIXER_IDLE),
937 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
938 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800939 mBytesRemaining(0),
940 mCurrentWriteLength(0),
941 mUseAsyncWrite(false),
942 mWriteBlocked(false),
943 mDraining(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800944 mScreenState(AudioFlinger::mScreenState),
945 // index 0 is reserved for normal mixer's submix
946 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
947{
948 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800949 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800950
951 // Assumes constructor is called by AudioFlinger with it's mLock held, but
952 // it would be safer to explicitly pass initial masterVolume/masterMute as
953 // parameter.
954 //
955 // If the HAL we are using has support for master volume or master mute,
956 // then do not attenuate or mute during mixing (just leave the volume at 1.0
957 // and the mute set to false).
958 mMasterVolume = audioFlinger->masterVolume_l();
959 mMasterMute = audioFlinger->masterMute_l();
960 if (mOutput && mOutput->audioHwDev) {
961 if (mOutput->audioHwDev->canSetMasterVolume()) {
962 mMasterVolume = 1.0;
963 }
964
965 if (mOutput->audioHwDev->canSetMasterMute()) {
966 mMasterMute = false;
967 }
968 }
969
970 readOutputParameters();
971
972 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
973 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
974 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
975 stream = (audio_stream_type_t) (stream + 1)) {
976 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
977 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
978 }
979 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
980 // because mAudioFlinger doesn't have one to copy from
981}
982
983AudioFlinger::PlaybackThread::~PlaybackThread()
984{
Glenn Kasten9e58b552013-01-18 15:09:48 -0800985 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800986 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -0800987}
988
989void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
990{
991 dumpInternals(fd, args);
992 dumpTracks(fd, args);
993 dumpEffectChains(fd, args);
994}
995
996void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
997{
998 const size_t SIZE = 256;
999 char buffer[SIZE];
1000 String8 result;
1001
1002 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1003 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1004 const stream_type_t *st = &mStreamTypes[i];
1005 if (i > 0) {
1006 result.appendFormat(", ");
1007 }
1008 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1009 if (st->mute) {
1010 result.append("M");
1011 }
1012 }
1013 result.append("\n");
1014 write(fd, result.string(), result.length());
1015 result.clear();
1016
1017 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1018 result.append(buffer);
1019 Track::appendDumpHeader(result);
1020 for (size_t i = 0; i < mTracks.size(); ++i) {
1021 sp<Track> track = mTracks[i];
1022 if (track != 0) {
1023 track->dump(buffer, SIZE);
1024 result.append(buffer);
1025 }
1026 }
1027
1028 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1029 result.append(buffer);
1030 Track::appendDumpHeader(result);
1031 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1032 sp<Track> track = mActiveTracks[i].promote();
1033 if (track != 0) {
1034 track->dump(buffer, SIZE);
1035 result.append(buffer);
1036 }
1037 }
1038 write(fd, result.string(), result.size());
1039
1040 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1041 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1042 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1043 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1044}
1045
1046void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1047{
1048 const size_t SIZE = 256;
1049 char buffer[SIZE];
1050 String8 result;
1051
1052 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1053 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001054 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1055 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001056 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1057 ns2ms(systemTime() - mLastWriteTime));
1058 result.append(buffer);
1059 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1060 result.append(buffer);
1061 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1062 result.append(buffer);
1063 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1064 result.append(buffer);
1065 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1066 result.append(buffer);
1067 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1068 result.append(buffer);
1069 write(fd, result.string(), result.size());
1070 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1071
1072 dumpBase(fd, args);
1073}
1074
1075// Thread virtuals
1076status_t AudioFlinger::PlaybackThread::readyToRun()
1077{
1078 status_t status = initCheck();
1079 if (status == NO_ERROR) {
1080 ALOGI("AudioFlinger's thread %p ready to run", this);
1081 } else {
1082 ALOGE("No working audio driver found.");
1083 }
1084 return status;
1085}
1086
1087void AudioFlinger::PlaybackThread::onFirstRef()
1088{
1089 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1090}
1091
1092// ThreadBase virtuals
1093void AudioFlinger::PlaybackThread::preExit()
1094{
1095 ALOGV(" preExit()");
1096 // FIXME this is using hard-coded strings but in the future, this functionality will be
1097 // converted to use audio HAL extensions required to support tunneling
1098 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1099}
1100
1101// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1102sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1103 const sp<AudioFlinger::Client>& client,
1104 audio_stream_type_t streamType,
1105 uint32_t sampleRate,
1106 audio_format_t format,
1107 audio_channel_mask_t channelMask,
1108 size_t frameCount,
1109 const sp<IMemory>& sharedBuffer,
1110 int sessionId,
1111 IAudioFlinger::track_flags_t *flags,
1112 pid_t tid,
1113 status_t *status)
1114{
1115 sp<Track> track;
1116 status_t lStatus;
1117
1118 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1119
1120 // client expresses a preference for FAST, but we get the final say
1121 if (*flags & IAudioFlinger::TRACK_FAST) {
1122 if (
1123 // not timed
1124 (!isTimed) &&
1125 // either of these use cases:
1126 (
1127 // use case 1: shared buffer with any frame count
1128 (
1129 (sharedBuffer != 0)
1130 ) ||
1131 // use case 2: callback handler and frame count is default or at least as large as HAL
1132 (
1133 (tid != -1) &&
1134 ((frameCount == 0) ||
1135 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1136 )
1137 ) &&
1138 // PCM data
1139 audio_is_linear_pcm(format) &&
1140 // mono or stereo
1141 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1142 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1143#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1144 // hardware sample rate
1145 (sampleRate == mSampleRate) &&
1146#endif
1147 // normal mixer has an associated fast mixer
1148 hasFastMixer() &&
1149 // there are sufficient fast track slots available
1150 (mFastTrackAvailMask != 0)
1151 // FIXME test that MixerThread for this fast track has a capable output HAL
1152 // FIXME add a permission test also?
1153 ) {
1154 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1155 if (frameCount == 0) {
1156 frameCount = mFrameCount * kFastTrackMultiplier;
1157 }
1158 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1159 frameCount, mFrameCount);
1160 } else {
1161 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1162 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1163 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1164 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1165 audio_is_linear_pcm(format),
1166 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1167 *flags &= ~IAudioFlinger::TRACK_FAST;
1168 // For compatibility with AudioTrack calculation, buffer depth is forced
1169 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1170 // This is probably too conservative, but legacy application code may depend on it.
1171 // If you change this calculation, also review the start threshold which is related.
1172 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1173 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1174 if (minBufCount < 2) {
1175 minBufCount = 2;
1176 }
1177 size_t minFrameCount = mNormalFrameCount * minBufCount;
1178 if (frameCount < minFrameCount) {
1179 frameCount = minFrameCount;
1180 }
1181 }
1182 }
1183
1184 if (mType == DIRECT) {
1185 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1186 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1187 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1188 "for output %p with format %d",
1189 sampleRate, format, channelMask, mOutput, mFormat);
1190 lStatus = BAD_VALUE;
1191 goto Exit;
1192 }
1193 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001194 } else if (mType == OFFLOAD) {
1195 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1196 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1197 "for output %p with format %d",
1198 sampleRate, format, channelMask, mOutput, mFormat);
1199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
Eric Laurent81784c32012-11-19 14:55:58 -08001202 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001203 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1204 ALOGE("createTrack_l() Bad parameter: format %d \""
1205 "for output %p with format %d",
1206 format, mOutput, mFormat);
1207 lStatus = BAD_VALUE;
1208 goto Exit;
1209 }
Eric Laurent81784c32012-11-19 14:55:58 -08001210 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1211 if (sampleRate > mSampleRate*2) {
1212 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1213 lStatus = BAD_VALUE;
1214 goto Exit;
1215 }
1216 }
1217
1218 lStatus = initCheck();
1219 if (lStatus != NO_ERROR) {
1220 ALOGE("Audio driver not initialized.");
1221 goto Exit;
1222 }
1223
1224 { // scope for mLock
1225 Mutex::Autolock _l(mLock);
1226
1227 // all tracks in same audio session must share the same routing strategy otherwise
1228 // conflicts will happen when tracks are moved from one output to another by audio policy
1229 // manager
1230 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1231 for (size_t i = 0; i < mTracks.size(); ++i) {
1232 sp<Track> t = mTracks[i];
1233 if (t != 0 && !t->isOutputTrack()) {
1234 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1235 if (sessionId == t->sessionId() && strategy != actual) {
1236 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1237 strategy, actual);
1238 lStatus = BAD_VALUE;
1239 goto Exit;
1240 }
1241 }
1242 }
1243
1244 if (!isTimed) {
1245 track = new Track(this, client, streamType, sampleRate, format,
1246 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1247 } else {
1248 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1249 channelMask, frameCount, sharedBuffer, sessionId);
1250 }
1251 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1252 lStatus = NO_MEMORY;
1253 goto Exit;
1254 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001255
Eric Laurent81784c32012-11-19 14:55:58 -08001256 mTracks.add(track);
1257
1258 sp<EffectChain> chain = getEffectChain_l(sessionId);
1259 if (chain != 0) {
1260 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1261 track->setMainBuffer(chain->inBuffer());
1262 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1263 chain->incTrackCnt();
1264 }
1265
1266 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1267 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1268 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1269 // so ask activity manager to do this on our behalf
1270 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1271 }
1272 }
1273
1274 lStatus = NO_ERROR;
1275
1276Exit:
1277 if (status) {
1278 *status = lStatus;
1279 }
1280 return track;
1281}
1282
1283uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1284{
1285 return latency;
1286}
1287
1288uint32_t AudioFlinger::PlaybackThread::latency() const
1289{
1290 Mutex::Autolock _l(mLock);
1291 return latency_l();
1292}
1293uint32_t AudioFlinger::PlaybackThread::latency_l() const
1294{
1295 if (initCheck() == NO_ERROR) {
1296 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1297 } else {
1298 return 0;
1299 }
1300}
1301
1302void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1303{
1304 Mutex::Autolock _l(mLock);
1305 // Don't apply master volume in SW if our HAL can do it for us.
1306 if (mOutput && mOutput->audioHwDev &&
1307 mOutput->audioHwDev->canSetMasterVolume()) {
1308 mMasterVolume = 1.0;
1309 } else {
1310 mMasterVolume = value;
1311 }
1312}
1313
1314void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1315{
1316 Mutex::Autolock _l(mLock);
1317 // Don't apply master mute in SW if our HAL can do it for us.
1318 if (mOutput && mOutput->audioHwDev &&
1319 mOutput->audioHwDev->canSetMasterMute()) {
1320 mMasterMute = false;
1321 } else {
1322 mMasterMute = muted;
1323 }
1324}
1325
1326void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1327{
1328 Mutex::Autolock _l(mLock);
1329 mStreamTypes[stream].volume = value;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001330 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001331}
1332
1333void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1334{
1335 Mutex::Autolock _l(mLock);
1336 mStreamTypes[stream].mute = muted;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001337 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001338}
1339
1340float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1341{
1342 Mutex::Autolock _l(mLock);
1343 return mStreamTypes[stream].volume;
1344}
1345
1346// addTrack_l() must be called with ThreadBase::mLock held
1347status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1348{
1349 status_t status = ALREADY_EXISTS;
1350
1351 // set retry count for buffer fill
1352 track->mRetryCount = kMaxTrackStartupRetries;
1353 if (mActiveTracks.indexOf(track) < 0) {
1354 // the track is newly added, make sure it fills up all its
1355 // buffers before playing. This is to ensure the client will
1356 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001357 if (!track->isOutputTrack()) {
1358 TrackBase::track_state state = track->mState;
1359 mLock.unlock();
1360 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1361 mLock.lock();
1362 // abort track was stopped/paused while we released the lock
1363 if (state != track->mState) {
1364 if (status == NO_ERROR) {
1365 mLock.unlock();
1366 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1367 mLock.lock();
1368 }
1369 return INVALID_OPERATION;
1370 }
1371 // abort if start is rejected by audio policy manager
1372 if (status != NO_ERROR) {
1373 return PERMISSION_DENIED;
1374 }
1375#ifdef ADD_BATTERY_DATA
1376 // to track the speaker usage
1377 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1378#endif
1379 }
1380
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001381 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001382 track->mResetDone = false;
1383 track->mPresentationCompleteFrames = 0;
1384 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001385 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1386 if (chain != 0) {
1387 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1388 track->sessionId());
1389 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001390 }
1391
1392 status = NO_ERROR;
1393 }
1394
1395 ALOGV("mWaitWorkCV.broadcast");
1396 mWaitWorkCV.broadcast();
1397
1398 return status;
1399}
1400
Eric Laurentbfb1b832013-01-07 09:53:42 -08001401bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001402{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001403 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001404 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001405 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1406 track->mState = TrackBase::STOPPED;
1407 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001408 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001409 } else if (track->isFastTrack() || track->isOffloaded()) {
1410 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001411 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001412
1413 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001414}
1415
1416void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1417{
1418 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1419 mTracks.remove(track);
1420 deleteTrackName_l(track->name());
1421 // redundant as track is about to be destroyed, for dumpsys only
1422 track->mName = -1;
1423 if (track->isFastTrack()) {
1424 int index = track->mFastIndex;
1425 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1426 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1427 mFastTrackAvailMask |= 1 << index;
1428 // redundant as track is about to be destroyed, for dumpsys only
1429 track->mFastIndex = -1;
1430 }
1431 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1432 if (chain != 0) {
1433 chain->decTrackCnt();
1434 }
1435}
1436
Eric Laurentbfb1b832013-01-07 09:53:42 -08001437void AudioFlinger::PlaybackThread::signal_l()
1438{
1439 // Thread could be blocked waiting for async
1440 // so signal it to handle state changes immediately
1441 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1442 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1443 mSignalPending = true;
1444 mWaitWorkCV.signal();
1445}
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1448{
Eric Laurent81784c32012-11-19 14:55:58 -08001449 Mutex::Autolock _l(mLock);
1450 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001451 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001452 }
1453
Glenn Kastend8ea6992013-07-16 14:17:15 -07001454 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1455 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001456 free(s);
1457 return out_s8;
1458}
1459
1460// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1461void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1462 AudioSystem::OutputDescriptor desc;
1463 void *param2 = NULL;
1464
1465 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1466 param);
1467
1468 switch (event) {
1469 case AudioSystem::OUTPUT_OPENED:
1470 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001471 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001472 desc.samplingRate = mSampleRate;
1473 desc.format = mFormat;
1474 desc.frameCount = mNormalFrameCount; // FIXME see
1475 // AudioFlinger::frameCount(audio_io_handle_t)
1476 desc.latency = latency();
1477 param2 = &desc;
1478 break;
1479
1480 case AudioSystem::STREAM_CONFIG_CHANGED:
1481 param2 = &param;
1482 case AudioSystem::OUTPUT_CLOSED:
1483 default:
1484 break;
1485 }
1486 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1487}
1488
Eric Laurentbfb1b832013-01-07 09:53:42 -08001489void AudioFlinger::PlaybackThread::writeCallback()
1490{
1491 ALOG_ASSERT(mCallbackThread != 0);
1492 mCallbackThread->setWriteBlocked(false);
1493}
1494
1495void AudioFlinger::PlaybackThread::drainCallback()
1496{
1497 ALOG_ASSERT(mCallbackThread != 0);
1498 mCallbackThread->setDraining(false);
1499}
1500
1501void AudioFlinger::PlaybackThread::setWriteBlocked(bool value)
1502{
1503 Mutex::Autolock _l(mLock);
1504 mWriteBlocked = value;
1505 if (!value) {
1506 mWaitWorkCV.signal();
1507 }
1508}
1509
1510void AudioFlinger::PlaybackThread::setDraining(bool value)
1511{
1512 Mutex::Autolock _l(mLock);
1513 mDraining = value;
1514 if (!value) {
1515 mWaitWorkCV.signal();
1516 }
1517}
1518
1519// static
1520int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1521 void *param,
1522 void *cookie)
1523{
1524 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1525 ALOGV("asyncCallback() event %d", event);
1526 switch (event) {
1527 case STREAM_CBK_EVENT_WRITE_READY:
1528 me->writeCallback();
1529 break;
1530 case STREAM_CBK_EVENT_DRAIN_READY:
1531 me->drainCallback();
1532 break;
1533 default:
1534 ALOGW("asyncCallback() unknown event %d", event);
1535 break;
1536 }
1537 return 0;
1538}
1539
Eric Laurent81784c32012-11-19 14:55:58 -08001540void AudioFlinger::PlaybackThread::readOutputParameters()
1541{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001542 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001543 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1544 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001545 if (!audio_is_output_channel(mChannelMask)) {
1546 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1547 }
1548 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1549 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1550 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1551 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001552 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001553 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001554 if (!audio_is_valid_format(mFormat)) {
1555 LOG_FATAL("HAL format %d not valid for output", mFormat);
1556 }
1557 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1558 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1559 mFormat);
1560 }
Eric Laurent81784c32012-11-19 14:55:58 -08001561 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1562 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1563 if (mFrameCount & 15) {
1564 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1565 mFrameCount);
1566 }
1567
Eric Laurentbfb1b832013-01-07 09:53:42 -08001568 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1569 (mOutput->stream->set_callback != NULL)) {
1570 if (mOutput->stream->set_callback(mOutput->stream,
1571 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1572 mUseAsyncWrite = true;
1573 }
1574 }
1575
Eric Laurent81784c32012-11-19 14:55:58 -08001576 // Calculate size of normal mix buffer relative to the HAL output buffer size
1577 double multiplier = 1.0;
1578 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1579 kUseFastMixer == FastMixer_Dynamic)) {
1580 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1581 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1582 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1583 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1584 maxNormalFrameCount = maxNormalFrameCount & ~15;
1585 if (maxNormalFrameCount < minNormalFrameCount) {
1586 maxNormalFrameCount = minNormalFrameCount;
1587 }
1588 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1589 if (multiplier <= 1.0) {
1590 multiplier = 1.0;
1591 } else if (multiplier <= 2.0) {
1592 if (2 * mFrameCount <= maxNormalFrameCount) {
1593 multiplier = 2.0;
1594 } else {
1595 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1596 }
1597 } else {
1598 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1599 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1600 // track, but we sometimes have to do this to satisfy the maximum frame count
1601 // constraint)
1602 // FIXME this rounding up should not be done if no HAL SRC
1603 uint32_t truncMult = (uint32_t) multiplier;
1604 if ((truncMult & 1)) {
1605 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1606 ++truncMult;
1607 }
1608 }
1609 multiplier = (double) truncMult;
1610 }
1611 }
1612 mNormalFrameCount = multiplier * mFrameCount;
1613 // round up to nearest 16 frames to satisfy AudioMixer
1614 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1615 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1616 mNormalFrameCount);
1617
Eric Laurentbfb1b832013-01-07 09:53:42 -08001618 delete[] mAllocMixBuffer;
1619 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1620 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1621 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1622 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001623
1624 // force reconfiguration of effect chains and engines to take new buffer size and audio
1625 // parameters into account
1626 // Note that mLock is not held when readOutputParameters() is called from the constructor
1627 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1628 // matter.
1629 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1630 Vector< sp<EffectChain> > effectChains = mEffectChains;
1631 for (size_t i = 0; i < effectChains.size(); i ++) {
1632 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1633 }
1634}
1635
1636
1637status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1638{
1639 if (halFrames == NULL || dspFrames == NULL) {
1640 return BAD_VALUE;
1641 }
1642 Mutex::Autolock _l(mLock);
1643 if (initCheck() != NO_ERROR) {
1644 return INVALID_OPERATION;
1645 }
1646 size_t framesWritten = mBytesWritten / mFrameSize;
1647 *halFrames = framesWritten;
1648
1649 if (isSuspended()) {
1650 // return an estimation of rendered frames when the output is suspended
1651 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1652 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1653 return NO_ERROR;
1654 } else {
1655 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1656 }
1657}
1658
1659uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1660{
1661 Mutex::Autolock _l(mLock);
1662 uint32_t result = 0;
1663 if (getEffectChain_l(sessionId) != 0) {
1664 result = EFFECT_SESSION;
1665 }
1666
1667 for (size_t i = 0; i < mTracks.size(); ++i) {
1668 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001669 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001670 result |= TRACK_SESSION;
1671 break;
1672 }
1673 }
1674
1675 return result;
1676}
1677
1678uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1679{
1680 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1681 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1682 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1683 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1684 }
1685 for (size_t i = 0; i < mTracks.size(); i++) {
1686 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001687 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001688 return AudioSystem::getStrategyForStream(track->streamType());
1689 }
1690 }
1691 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1692}
1693
1694
1695AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1696{
1697 Mutex::Autolock _l(mLock);
1698 return mOutput;
1699}
1700
1701AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1702{
1703 Mutex::Autolock _l(mLock);
1704 AudioStreamOut *output = mOutput;
1705 mOutput = NULL;
1706 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1707 // must push a NULL and wait for ack
1708 mOutputSink.clear();
1709 mPipeSink.clear();
1710 mNormalSink.clear();
1711 return output;
1712}
1713
1714// this method must always be called either with ThreadBase mLock held or inside the thread loop
1715audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1716{
1717 if (mOutput == NULL) {
1718 return NULL;
1719 }
1720 return &mOutput->stream->common;
1721}
1722
1723uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1724{
1725 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1726}
1727
1728status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1729{
1730 if (!isValidSyncEvent(event)) {
1731 return BAD_VALUE;
1732 }
1733
1734 Mutex::Autolock _l(mLock);
1735
1736 for (size_t i = 0; i < mTracks.size(); ++i) {
1737 sp<Track> track = mTracks[i];
1738 if (event->triggerSession() == track->sessionId()) {
1739 (void) track->setSyncEvent(event);
1740 return NO_ERROR;
1741 }
1742 }
1743
1744 return NAME_NOT_FOUND;
1745}
1746
1747bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1748{
1749 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1750}
1751
1752void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1753 const Vector< sp<Track> >& tracksToRemove)
1754{
1755 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001756 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001757 for (size_t i = 0 ; i < count ; i++) {
1758 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001759 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001760 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001761#ifdef ADD_BATTERY_DATA
1762 // to track the speaker usage
1763 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1764#endif
1765 if (track->isTerminated()) {
1766 AudioSystem::releaseOutput(mId);
1767 }
Eric Laurent81784c32012-11-19 14:55:58 -08001768 }
1769 }
1770 }
Eric Laurent81784c32012-11-19 14:55:58 -08001771}
1772
1773void AudioFlinger::PlaybackThread::checkSilentMode_l()
1774{
1775 if (!mMasterMute) {
1776 char value[PROPERTY_VALUE_MAX];
1777 if (property_get("ro.audio.silent", value, "0") > 0) {
1778 char *endptr;
1779 unsigned long ul = strtoul(value, &endptr, 0);
1780 if (*endptr == '\0' && ul != 0) {
1781 ALOGD("Silence is golden");
1782 // The setprop command will not allow a property to be changed after
1783 // the first time it is set, so we don't have to worry about un-muting.
1784 setMasterMute_l(true);
1785 }
1786 }
1787 }
1788}
1789
1790// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001792{
1793 // FIXME rewrite to reduce number of system calls
1794 mLastWriteTime = systemTime();
1795 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001796 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001797
1798 // If an NBAIO sink is present, use it to write the normal mixer's submix
1799 if (mNormalSink != 0) {
1800#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001801 size_t count = mBytesRemaining >> mBitShift;
1802 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001803 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001804 // update the setpoint when AudioFlinger::mScreenState changes
1805 uint32_t screenState = AudioFlinger::mScreenState;
1806 if (screenState != mScreenState) {
1807 mScreenState = screenState;
1808 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1809 if (pipe != NULL) {
1810 pipe->setAvgFrames((mScreenState & 1) ?
1811 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1812 }
1813 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001814 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001815 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001816 if (framesWritten > 0) {
1817 bytesWritten = framesWritten << mBitShift;
1818 } else {
1819 bytesWritten = framesWritten;
1820 }
1821 // otherwise use the HAL / AudioStreamOut directly
1822 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001823 // Direct output and offload threads
1824 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1825 if (mUseAsyncWrite) {
1826 mWriteBlocked = true;
1827 ALOG_ASSERT(mCallbackThread != 0);
1828 mCallbackThread->setWriteBlocked(true);
1829 }
1830 bytesWritten = mOutput->stream->write(mOutput->stream,
1831 mMixBuffer + offset, mBytesRemaining);
1832 if (mUseAsyncWrite &&
1833 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1834 // do not wait for async callback in case of error of full write
1835 mWriteBlocked = false;
1836 ALOG_ASSERT(mCallbackThread != 0);
1837 mCallbackThread->setWriteBlocked(false);
1838 }
Eric Laurent81784c32012-11-19 14:55:58 -08001839 }
1840
Eric Laurent81784c32012-11-19 14:55:58 -08001841 mNumWrites++;
1842 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843
1844 return bytesWritten;
1845}
1846
1847void AudioFlinger::PlaybackThread::threadLoop_drain()
1848{
1849 if (mOutput->stream->drain) {
1850 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1851 if (mUseAsyncWrite) {
1852 mDraining = true;
1853 ALOG_ASSERT(mCallbackThread != 0);
1854 mCallbackThread->setDraining(true);
1855 }
1856 mOutput->stream->drain(mOutput->stream,
1857 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1858 : AUDIO_DRAIN_ALL);
1859 }
1860}
1861
1862void AudioFlinger::PlaybackThread::threadLoop_exit()
1863{
1864 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001865}
1866
1867/*
1868The derived values that are cached:
1869 - mixBufferSize from frame count * frame size
1870 - activeSleepTime from activeSleepTimeUs()
1871 - idleSleepTime from idleSleepTimeUs()
1872 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1873 - maxPeriod from frame count and sample rate (MIXER only)
1874
1875The parameters that affect these derived values are:
1876 - frame count
1877 - frame size
1878 - sample rate
1879 - device type: A2DP or not
1880 - device latency
1881 - format: PCM or not
1882 - active sleep time
1883 - idle sleep time
1884*/
1885
1886void AudioFlinger::PlaybackThread::cacheParameters_l()
1887{
1888 mixBufferSize = mNormalFrameCount * mFrameSize;
1889 activeSleepTime = activeSleepTimeUs();
1890 idleSleepTime = idleSleepTimeUs();
1891}
1892
1893void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1894{
Glenn Kasten7c027242012-12-26 14:43:16 -08001895 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001896 this, streamType, mTracks.size());
1897 Mutex::Autolock _l(mLock);
1898
1899 size_t size = mTracks.size();
1900 for (size_t i = 0; i < size; i++) {
1901 sp<Track> t = mTracks[i];
1902 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001903 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001904 }
1905 }
1906}
1907
1908status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1909{
1910 int session = chain->sessionId();
1911 int16_t *buffer = mMixBuffer;
1912 bool ownsBuffer = false;
1913
1914 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1915 if (session > 0) {
1916 // Only one effect chain can be present in direct output thread and it uses
1917 // the mix buffer as input
1918 if (mType != DIRECT) {
1919 size_t numSamples = mNormalFrameCount * mChannelCount;
1920 buffer = new int16_t[numSamples];
1921 memset(buffer, 0, numSamples * sizeof(int16_t));
1922 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1923 ownsBuffer = true;
1924 }
1925
1926 // Attach all tracks with same session ID to this chain.
1927 for (size_t i = 0; i < mTracks.size(); ++i) {
1928 sp<Track> track = mTracks[i];
1929 if (session == track->sessionId()) {
1930 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1931 buffer);
1932 track->setMainBuffer(buffer);
1933 chain->incTrackCnt();
1934 }
1935 }
1936
1937 // indicate all active tracks in the chain
1938 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1939 sp<Track> track = mActiveTracks[i].promote();
1940 if (track == 0) {
1941 continue;
1942 }
1943 if (session == track->sessionId()) {
1944 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1945 chain->incActiveTrackCnt();
1946 }
1947 }
1948 }
1949
1950 chain->setInBuffer(buffer, ownsBuffer);
1951 chain->setOutBuffer(mMixBuffer);
1952 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1953 // chains list in order to be processed last as it contains output stage effects
1954 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1955 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1956 // after track specific effects and before output stage
1957 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1958 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1959 // Effect chain for other sessions are inserted at beginning of effect
1960 // chains list to be processed before output mix effects. Relative order between other
1961 // sessions is not important
1962 size_t size = mEffectChains.size();
1963 size_t i = 0;
1964 for (i = 0; i < size; i++) {
1965 if (mEffectChains[i]->sessionId() < session) {
1966 break;
1967 }
1968 }
1969 mEffectChains.insertAt(chain, i);
1970 checkSuspendOnAddEffectChain_l(chain);
1971
1972 return NO_ERROR;
1973}
1974
1975size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1976{
1977 int session = chain->sessionId();
1978
1979 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1980
1981 for (size_t i = 0; i < mEffectChains.size(); i++) {
1982 if (chain == mEffectChains[i]) {
1983 mEffectChains.removeAt(i);
1984 // detach all active tracks from the chain
1985 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1986 sp<Track> track = mActiveTracks[i].promote();
1987 if (track == 0) {
1988 continue;
1989 }
1990 if (session == track->sessionId()) {
1991 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1992 chain.get(), session);
1993 chain->decActiveTrackCnt();
1994 }
1995 }
1996
1997 // detach all tracks with same session ID from this chain
1998 for (size_t i = 0; i < mTracks.size(); ++i) {
1999 sp<Track> track = mTracks[i];
2000 if (session == track->sessionId()) {
2001 track->setMainBuffer(mMixBuffer);
2002 chain->decTrackCnt();
2003 }
2004 }
2005 break;
2006 }
2007 }
2008 return mEffectChains.size();
2009}
2010
2011status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2012 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2013{
2014 Mutex::Autolock _l(mLock);
2015 return attachAuxEffect_l(track, EffectId);
2016}
2017
2018status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2019 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2020{
2021 status_t status = NO_ERROR;
2022
2023 if (EffectId == 0) {
2024 track->setAuxBuffer(0, NULL);
2025 } else {
2026 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2027 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2028 if (effect != 0) {
2029 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2030 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2031 } else {
2032 status = INVALID_OPERATION;
2033 }
2034 } else {
2035 status = BAD_VALUE;
2036 }
2037 }
2038 return status;
2039}
2040
2041void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2042{
2043 for (size_t i = 0; i < mTracks.size(); ++i) {
2044 sp<Track> track = mTracks[i];
2045 if (track->auxEffectId() == effectId) {
2046 attachAuxEffect_l(track, 0);
2047 }
2048 }
2049}
2050
2051bool AudioFlinger::PlaybackThread::threadLoop()
2052{
2053 Vector< sp<Track> > tracksToRemove;
2054
2055 standbyTime = systemTime();
2056
2057 // MIXER
2058 nsecs_t lastWarning = 0;
2059
2060 // DUPLICATING
2061 // FIXME could this be made local to while loop?
2062 writeFrames = 0;
2063
2064 cacheParameters_l();
2065 sleepTime = idleSleepTime;
2066
2067 if (mType == MIXER) {
2068 sleepTimeShift = 0;
2069 }
2070
2071 CpuStats cpuStats;
2072 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2073
2074 acquireWakeLock();
2075
Glenn Kasten9e58b552013-01-18 15:09:48 -08002076 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2077 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2078 // and then that string will be logged at the next convenient opportunity.
2079 const char *logString = NULL;
2080
Eric Laurent81784c32012-11-19 14:55:58 -08002081 while (!exitPending())
2082 {
2083 cpuStats.sample(myName);
2084
2085 Vector< sp<EffectChain> > effectChains;
2086
2087 processConfigEvents();
2088
2089 { // scope for mLock
2090
2091 Mutex::Autolock _l(mLock);
2092
Glenn Kasten9e58b552013-01-18 15:09:48 -08002093 if (logString != NULL) {
2094 mNBLogWriter->logTimestamp();
2095 mNBLogWriter->log(logString);
2096 logString = NULL;
2097 }
2098
Eric Laurent81784c32012-11-19 14:55:58 -08002099 if (checkForNewParameters_l()) {
2100 cacheParameters_l();
2101 }
2102
2103 saveOutputTracks();
2104
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 if (mSignalPending) {
2106 // A signal was raised while we were unlocked
2107 mSignalPending = false;
2108 } else if (waitingAsyncCallback_l()) {
2109 if (exitPending()) {
2110 break;
2111 }
2112 releaseWakeLock_l();
2113 ALOGV("wait async completion");
2114 mWaitWorkCV.wait(mLock);
2115 ALOGV("async completion/wake");
2116 acquireWakeLock_l();
2117 if (exitPending()) {
2118 break;
2119 }
2120 if (!mActiveTracks.size() && (systemTime() > standbyTime)) {
2121 continue;
2122 }
2123 sleepTime = 0;
2124 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2125 isSuspended()) {
2126 // put audio hardware into standby after short delay
2127 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002128
2129 threadLoop_standby();
2130
2131 mStandby = true;
2132 }
2133
2134 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2135 // we're about to wait, flush the binder command buffer
2136 IPCThreadState::self()->flushCommands();
2137
2138 clearOutputTracks();
2139
2140 if (exitPending()) {
2141 break;
2142 }
2143
2144 releaseWakeLock_l();
2145 // wait until we have something to do...
2146 ALOGV("%s going to sleep", myName.string());
2147 mWaitWorkCV.wait(mLock);
2148 ALOGV("%s waking up", myName.string());
2149 acquireWakeLock_l();
2150
2151 mMixerStatus = MIXER_IDLE;
2152 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2153 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002154 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002155 checkSilentMode_l();
2156
2157 standbyTime = systemTime() + standbyDelay;
2158 sleepTime = idleSleepTime;
2159 if (mType == MIXER) {
2160 sleepTimeShift = 0;
2161 }
2162
2163 continue;
2164 }
2165 }
2166
2167 // mMixerStatusIgnoringFastTracks is also updated internally
2168 mMixerStatus = prepareTracks_l(&tracksToRemove);
2169
2170 // prevent any changes in effect chain list and in each effect chain
2171 // during mixing and effect process as the audio buffers could be deleted
2172 // or modified if an effect is created or deleted
2173 lockEffectChains_l(effectChains);
2174 }
2175
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176 if (mBytesRemaining == 0) {
2177 mCurrentWriteLength = 0;
2178 if (mMixerStatus == MIXER_TRACKS_READY) {
2179 // threadLoop_mix() sets mCurrentWriteLength
2180 threadLoop_mix();
2181 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2182 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2183 // threadLoop_sleepTime sets sleepTime to 0 if data
2184 // must be written to HAL
2185 threadLoop_sleepTime();
2186 if (sleepTime == 0) {
2187 mCurrentWriteLength = mixBufferSize;
2188 }
2189 }
2190 mBytesRemaining = mCurrentWriteLength;
2191 if (isSuspended()) {
2192 sleepTime = suspendSleepTimeUs();
2193 // simulate write to HAL when suspended
2194 mBytesWritten += mixBufferSize;
2195 mBytesRemaining = 0;
2196 }
Eric Laurent81784c32012-11-19 14:55:58 -08002197
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 // only process effects if we're going to write
2199 if (sleepTime == 0) {
2200 for (size_t i = 0; i < effectChains.size(); i ++) {
2201 effectChains[i]->process_l();
2202 }
Eric Laurent81784c32012-11-19 14:55:58 -08002203 }
2204 }
2205
2206 // enable changes in effect chain
2207 unlockEffectChains(effectChains);
2208
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209 if (!waitingAsyncCallback()) {
2210 // sleepTime == 0 means we must write to audio hardware
2211 if (sleepTime == 0) {
2212 if (mBytesRemaining) {
2213 ssize_t ret = threadLoop_write();
2214 if (ret < 0) {
2215 mBytesRemaining = 0;
2216 } else {
2217 mBytesWritten += ret;
2218 mBytesRemaining -= ret;
2219 }
2220 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2221 (mMixerStatus == MIXER_DRAIN_ALL)) {
2222 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002223 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002224if (mType == MIXER) {
2225 // write blocked detection
2226 nsecs_t now = systemTime();
2227 nsecs_t delta = now - mLastWriteTime;
2228 if (!mStandby && delta > maxPeriod) {
2229 mNumDelayedWrites++;
2230 if ((now - lastWarning) > kWarningThrottleNs) {
2231 ATRACE_NAME("underrun");
2232 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2233 ns2ms(delta), mNumDelayedWrites, this);
2234 lastWarning = now;
2235 }
2236 }
Eric Laurent81784c32012-11-19 14:55:58 -08002237}
2238
Eric Laurentbfb1b832013-01-07 09:53:42 -08002239 mStandby = false;
2240 } else {
2241 usleep(sleepTime);
2242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243 }
2244
2245 // Finally let go of removed track(s), without the lock held
2246 // since we can't guarantee the destructors won't acquire that
2247 // same lock. This will also mutate and push a new fast mixer state.
2248 threadLoop_removeTracks(tracksToRemove);
2249 tracksToRemove.clear();
2250
2251 // FIXME I don't understand the need for this here;
2252 // it was in the original code but maybe the
2253 // assignment in saveOutputTracks() makes this unnecessary?
2254 clearOutputTracks();
2255
2256 // Effect chains will be actually deleted here if they were removed from
2257 // mEffectChains list during mixing or effects processing
2258 effectChains.clear();
2259
2260 // FIXME Note that the above .clear() is no longer necessary since effectChains
2261 // is now local to this block, but will keep it for now (at least until merge done).
2262 }
2263
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264 threadLoop_exit();
2265
Eric Laurent81784c32012-11-19 14:55:58 -08002266 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002268 // put output stream into standby mode
2269 if (!mStandby) {
2270 mOutput->stream->common.standby(&mOutput->stream->common);
2271 }
2272 }
2273
2274 releaseWakeLock();
2275
2276 ALOGV("Thread %p type %d exiting", this, mType);
2277 return false;
2278}
2279
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280// removeTracks_l() must be called with ThreadBase::mLock held
2281void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2282{
2283 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002284 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002285 for (size_t i=0 ; i<count ; i++) {
2286 const sp<Track>& track = tracksToRemove.itemAt(i);
2287 mActiveTracks.remove(track);
2288 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2289 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2290 if (chain != 0) {
2291 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2292 track->sessionId());
2293 chain->decActiveTrackCnt();
2294 }
2295 if (track->isTerminated()) {
2296 removeTrack_l(track);
2297 }
2298 }
2299 }
2300
2301}
Eric Laurent81784c32012-11-19 14:55:58 -08002302
2303// ----------------------------------------------------------------------------
2304
2305AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2306 audio_io_handle_t id, audio_devices_t device, type_t type)
2307 : PlaybackThread(audioFlinger, output, id, device, type),
2308 // mAudioMixer below
2309 // mFastMixer below
2310 mFastMixerFutex(0)
2311 // mOutputSink below
2312 // mPipeSink below
2313 // mNormalSink below
2314{
2315 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002316 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002317 "mFrameCount=%d, mNormalFrameCount=%d",
2318 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2319 mNormalFrameCount);
2320 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2321
2322 // FIXME - Current mixer implementation only supports stereo output
2323 if (mChannelCount != FCC_2) {
2324 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2325 }
2326
2327 // create an NBAIO sink for the HAL output stream, and negotiate
2328 mOutputSink = new AudioStreamOutSink(output->stream);
2329 size_t numCounterOffers = 0;
2330 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2331 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2332 ALOG_ASSERT(index == 0);
2333
2334 // initialize fast mixer depending on configuration
2335 bool initFastMixer;
2336 switch (kUseFastMixer) {
2337 case FastMixer_Never:
2338 initFastMixer = false;
2339 break;
2340 case FastMixer_Always:
2341 initFastMixer = true;
2342 break;
2343 case FastMixer_Static:
2344 case FastMixer_Dynamic:
2345 initFastMixer = mFrameCount < mNormalFrameCount;
2346 break;
2347 }
2348 if (initFastMixer) {
2349
2350 // create a MonoPipe to connect our submix to FastMixer
2351 NBAIO_Format format = mOutputSink->format();
2352 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2353 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2354 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2355 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2356 const NBAIO_Format offers[1] = {format};
2357 size_t numCounterOffers = 0;
2358 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2359 ALOG_ASSERT(index == 0);
2360 monoPipe->setAvgFrames((mScreenState & 1) ?
2361 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2362 mPipeSink = monoPipe;
2363
Glenn Kasten46909e72013-02-26 09:20:22 -08002364#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002365 if (mTeeSinkOutputEnabled) {
2366 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2367 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2368 numCounterOffers = 0;
2369 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2370 ALOG_ASSERT(index == 0);
2371 mTeeSink = teeSink;
2372 PipeReader *teeSource = new PipeReader(*teeSink);
2373 numCounterOffers = 0;
2374 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2375 ALOG_ASSERT(index == 0);
2376 mTeeSource = teeSource;
2377 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002378#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002379
2380 // create fast mixer and configure it initially with just one fast track for our submix
2381 mFastMixer = new FastMixer();
2382 FastMixerStateQueue *sq = mFastMixer->sq();
2383#ifdef STATE_QUEUE_DUMP
2384 sq->setObserverDump(&mStateQueueObserverDump);
2385 sq->setMutatorDump(&mStateQueueMutatorDump);
2386#endif
2387 FastMixerState *state = sq->begin();
2388 FastTrack *fastTrack = &state->mFastTracks[0];
2389 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2390 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2391 fastTrack->mVolumeProvider = NULL;
2392 fastTrack->mGeneration++;
2393 state->mFastTracksGen++;
2394 state->mTrackMask = 1;
2395 // fast mixer will use the HAL output sink
2396 state->mOutputSink = mOutputSink.get();
2397 state->mOutputSinkGen++;
2398 state->mFrameCount = mFrameCount;
2399 state->mCommand = FastMixerState::COLD_IDLE;
2400 // already done in constructor initialization list
2401 //mFastMixerFutex = 0;
2402 state->mColdFutexAddr = &mFastMixerFutex;
2403 state->mColdGen++;
2404 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002405#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002406 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002407#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002408 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2409 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002410 sq->end();
2411 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2412
2413 // start the fast mixer
2414 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2415 pid_t tid = mFastMixer->getTid();
2416 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2417 if (err != 0) {
2418 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2419 kPriorityFastMixer, getpid_cached, tid, err);
2420 }
2421
2422#ifdef AUDIO_WATCHDOG
2423 // create and start the watchdog
2424 mAudioWatchdog = new AudioWatchdog();
2425 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2426 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2427 tid = mAudioWatchdog->getTid();
2428 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2429 if (err != 0) {
2430 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2431 kPriorityFastMixer, getpid_cached, tid, err);
2432 }
2433#endif
2434
2435 } else {
2436 mFastMixer = NULL;
2437 }
2438
2439 switch (kUseFastMixer) {
2440 case FastMixer_Never:
2441 case FastMixer_Dynamic:
2442 mNormalSink = mOutputSink;
2443 break;
2444 case FastMixer_Always:
2445 mNormalSink = mPipeSink;
2446 break;
2447 case FastMixer_Static:
2448 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2449 break;
2450 }
2451}
2452
2453AudioFlinger::MixerThread::~MixerThread()
2454{
2455 if (mFastMixer != NULL) {
2456 FastMixerStateQueue *sq = mFastMixer->sq();
2457 FastMixerState *state = sq->begin();
2458 if (state->mCommand == FastMixerState::COLD_IDLE) {
2459 int32_t old = android_atomic_inc(&mFastMixerFutex);
2460 if (old == -1) {
2461 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2462 }
2463 }
2464 state->mCommand = FastMixerState::EXIT;
2465 sq->end();
2466 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2467 mFastMixer->join();
2468 // Though the fast mixer thread has exited, it's state queue is still valid.
2469 // We'll use that extract the final state which contains one remaining fast track
2470 // corresponding to our sub-mix.
2471 state = sq->begin();
2472 ALOG_ASSERT(state->mTrackMask == 1);
2473 FastTrack *fastTrack = &state->mFastTracks[0];
2474 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2475 delete fastTrack->mBufferProvider;
2476 sq->end(false /*didModify*/);
2477 delete mFastMixer;
2478#ifdef AUDIO_WATCHDOG
2479 if (mAudioWatchdog != 0) {
2480 mAudioWatchdog->requestExit();
2481 mAudioWatchdog->requestExitAndWait();
2482 mAudioWatchdog.clear();
2483 }
2484#endif
2485 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002486 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002487 delete mAudioMixer;
2488}
2489
2490
2491uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2492{
2493 if (mFastMixer != NULL) {
2494 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2495 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2496 }
2497 return latency;
2498}
2499
2500
2501void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2502{
2503 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2504}
2505
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002507{
2508 // FIXME we should only do one push per cycle; confirm this is true
2509 // Start the fast mixer if it's not already running
2510 if (mFastMixer != NULL) {
2511 FastMixerStateQueue *sq = mFastMixer->sq();
2512 FastMixerState *state = sq->begin();
2513 if (state->mCommand != FastMixerState::MIX_WRITE &&
2514 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2515 if (state->mCommand == FastMixerState::COLD_IDLE) {
2516 int32_t old = android_atomic_inc(&mFastMixerFutex);
2517 if (old == -1) {
2518 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2519 }
2520#ifdef AUDIO_WATCHDOG
2521 if (mAudioWatchdog != 0) {
2522 mAudioWatchdog->resume();
2523 }
2524#endif
2525 }
2526 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002527 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2528 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002529 sq->end();
2530 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2531 if (kUseFastMixer == FastMixer_Dynamic) {
2532 mNormalSink = mPipeSink;
2533 }
2534 } else {
2535 sq->end(false /*didModify*/);
2536 }
2537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002538 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002539}
2540
2541void AudioFlinger::MixerThread::threadLoop_standby()
2542{
2543 // Idle the fast mixer if it's currently running
2544 if (mFastMixer != NULL) {
2545 FastMixerStateQueue *sq = mFastMixer->sq();
2546 FastMixerState *state = sq->begin();
2547 if (!(state->mCommand & FastMixerState::IDLE)) {
2548 state->mCommand = FastMixerState::COLD_IDLE;
2549 state->mColdFutexAddr = &mFastMixerFutex;
2550 state->mColdGen++;
2551 mFastMixerFutex = 0;
2552 sq->end();
2553 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2554 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2555 if (kUseFastMixer == FastMixer_Dynamic) {
2556 mNormalSink = mOutputSink;
2557 }
2558#ifdef AUDIO_WATCHDOG
2559 if (mAudioWatchdog != 0) {
2560 mAudioWatchdog->pause();
2561 }
2562#endif
2563 } else {
2564 sq->end(false /*didModify*/);
2565 }
2566 }
2567 PlaybackThread::threadLoop_standby();
2568}
2569
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570// Empty implementation for standard mixer
2571// Overridden for offloaded playback
2572void AudioFlinger::PlaybackThread::flushOutput_l()
2573{
2574}
2575
2576bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2577{
2578 return false;
2579}
2580
2581bool AudioFlinger::PlaybackThread::shouldStandby_l()
2582{
2583 return !mStandby;
2584}
2585
2586bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2587{
2588 Mutex::Autolock _l(mLock);
2589 return waitingAsyncCallback_l();
2590}
2591
Eric Laurent81784c32012-11-19 14:55:58 -08002592// shared by MIXER and DIRECT, overridden by DUPLICATING
2593void AudioFlinger::PlaybackThread::threadLoop_standby()
2594{
2595 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2596 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 if (mUseAsyncWrite != 0) {
2598 mWriteBlocked = false;
2599 mDraining = false;
2600 ALOG_ASSERT(mCallbackThread != 0);
2601 mCallbackThread->setWriteBlocked(false);
2602 mCallbackThread->setDraining(false);
2603 }
Eric Laurent81784c32012-11-19 14:55:58 -08002604}
2605
2606void AudioFlinger::MixerThread::threadLoop_mix()
2607{
2608 // obtain the presentation timestamp of the next output buffer
2609 int64_t pts;
2610 status_t status = INVALID_OPERATION;
2611
2612 if (mNormalSink != 0) {
2613 status = mNormalSink->getNextWriteTimestamp(&pts);
2614 } else {
2615 status = mOutputSink->getNextWriteTimestamp(&pts);
2616 }
2617
2618 if (status != NO_ERROR) {
2619 pts = AudioBufferProvider::kInvalidPTS;
2620 }
2621
2622 // mix buffers...
2623 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002624 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002625 // increase sleep time progressively when application underrun condition clears.
2626 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2627 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2628 // such that we would underrun the audio HAL.
2629 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2630 sleepTimeShift--;
2631 }
2632 sleepTime = 0;
2633 standbyTime = systemTime() + standbyDelay;
2634 //TODO: delay standby when effects have a tail
2635}
2636
2637void AudioFlinger::MixerThread::threadLoop_sleepTime()
2638{
2639 // If no tracks are ready, sleep once for the duration of an output
2640 // buffer size, then write 0s to the output
2641 if (sleepTime == 0) {
2642 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2643 sleepTime = activeSleepTime >> sleepTimeShift;
2644 if (sleepTime < kMinThreadSleepTimeUs) {
2645 sleepTime = kMinThreadSleepTimeUs;
2646 }
2647 // reduce sleep time in case of consecutive application underruns to avoid
2648 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2649 // duration we would end up writing less data than needed by the audio HAL if
2650 // the condition persists.
2651 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2652 sleepTimeShift++;
2653 }
2654 } else {
2655 sleepTime = idleSleepTime;
2656 }
2657 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2658 memset (mMixBuffer, 0, mixBufferSize);
2659 sleepTime = 0;
2660 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2661 "anticipated start");
2662 }
2663 // TODO add standby time extension fct of effect tail
2664}
2665
2666// prepareTracks_l() must be called with ThreadBase::mLock held
2667AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2668 Vector< sp<Track> > *tracksToRemove)
2669{
2670
2671 mixer_state mixerStatus = MIXER_IDLE;
2672 // find out which tracks need to be processed
2673 size_t count = mActiveTracks.size();
2674 size_t mixedTracks = 0;
2675 size_t tracksWithEffect = 0;
2676 // counts only _active_ fast tracks
2677 size_t fastTracks = 0;
2678 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2679
2680 float masterVolume = mMasterVolume;
2681 bool masterMute = mMasterMute;
2682
2683 if (masterMute) {
2684 masterVolume = 0;
2685 }
2686 // Delegate master volume control to effect in output mix effect chain if needed
2687 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2688 if (chain != 0) {
2689 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2690 chain->setVolume_l(&v, &v);
2691 masterVolume = (float)((v + (1 << 23)) >> 24);
2692 chain.clear();
2693 }
2694
2695 // prepare a new state to push
2696 FastMixerStateQueue *sq = NULL;
2697 FastMixerState *state = NULL;
2698 bool didModify = false;
2699 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2700 if (mFastMixer != NULL) {
2701 sq = mFastMixer->sq();
2702 state = sq->begin();
2703 }
2704
2705 for (size_t i=0 ; i<count ; i++) {
2706 sp<Track> t = mActiveTracks[i].promote();
2707 if (t == 0) {
2708 continue;
2709 }
2710
2711 // this const just means the local variable doesn't change
2712 Track* const track = t.get();
2713
2714 // process fast tracks
2715 if (track->isFastTrack()) {
2716
2717 // It's theoretically possible (though unlikely) for a fast track to be created
2718 // and then removed within the same normal mix cycle. This is not a problem, as
2719 // the track never becomes active so it's fast mixer slot is never touched.
2720 // The converse, of removing an (active) track and then creating a new track
2721 // at the identical fast mixer slot within the same normal mix cycle,
2722 // is impossible because the slot isn't marked available until the end of each cycle.
2723 int j = track->mFastIndex;
2724 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2725 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2726 FastTrack *fastTrack = &state->mFastTracks[j];
2727
2728 // Determine whether the track is currently in underrun condition,
2729 // and whether it had a recent underrun.
2730 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2731 FastTrackUnderruns underruns = ftDump->mUnderruns;
2732 uint32_t recentFull = (underruns.mBitFields.mFull -
2733 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2734 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2735 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2736 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2737 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2738 uint32_t recentUnderruns = recentPartial + recentEmpty;
2739 track->mObservedUnderruns = underruns;
2740 // don't count underruns that occur while stopping or pausing
2741 // or stopped which can occur when flush() is called while active
2742 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2743 track->mUnderrunCount += recentUnderruns;
2744 }
2745
2746 // This is similar to the state machine for normal tracks,
2747 // with a few modifications for fast tracks.
2748 bool isActive = true;
2749 switch (track->mState) {
2750 case TrackBase::STOPPING_1:
2751 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002753 track->mState = TrackBase::STOPPING_2;
2754 }
2755 break;
2756 case TrackBase::PAUSING:
2757 // ramp down is not yet implemented
2758 track->setPaused();
2759 break;
2760 case TrackBase::RESUMING:
2761 // ramp up is not yet implemented
2762 track->mState = TrackBase::ACTIVE;
2763 break;
2764 case TrackBase::ACTIVE:
2765 if (recentFull > 0 || recentPartial > 0) {
2766 // track has provided at least some frames recently: reset retry count
2767 track->mRetryCount = kMaxTrackRetries;
2768 }
2769 if (recentUnderruns == 0) {
2770 // no recent underruns: stay active
2771 break;
2772 }
2773 // there has recently been an underrun of some kind
2774 if (track->sharedBuffer() == 0) {
2775 // were any of the recent underruns "empty" (no frames available)?
2776 if (recentEmpty == 0) {
2777 // no, then ignore the partial underruns as they are allowed indefinitely
2778 break;
2779 }
2780 // there has recently been an "empty" underrun: decrement the retry counter
2781 if (--(track->mRetryCount) > 0) {
2782 break;
2783 }
2784 // indicate to client process that the track was disabled because of underrun;
2785 // it will then automatically call start() when data is available
2786 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
2787 // remove from active list, but state remains ACTIVE [confusing but true]
2788 isActive = false;
2789 break;
2790 }
2791 // fall through
2792 case TrackBase::STOPPING_2:
2793 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002794 case TrackBase::STOPPED:
2795 case TrackBase::FLUSHED: // flush() while active
2796 // Check for presentation complete if track is inactive
2797 // We have consumed all the buffers of this track.
2798 // This would be incomplete if we auto-paused on underrun
2799 {
2800 size_t audioHALFrames =
2801 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2802 size_t framesWritten = mBytesWritten / mFrameSize;
2803 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2804 // track stays in active list until presentation is complete
2805 break;
2806 }
2807 }
2808 if (track->isStopping_2()) {
2809 track->mState = TrackBase::STOPPED;
2810 }
2811 if (track->isStopped()) {
2812 // Can't reset directly, as fast mixer is still polling this track
2813 // track->reset();
2814 // So instead mark this track as needing to be reset after push with ack
2815 resetMask |= 1 << i;
2816 }
2817 isActive = false;
2818 break;
2819 case TrackBase::IDLE:
2820 default:
2821 LOG_FATAL("unexpected track state %d", track->mState);
2822 }
2823
2824 if (isActive) {
2825 // was it previously inactive?
2826 if (!(state->mTrackMask & (1 << j))) {
2827 ExtendedAudioBufferProvider *eabp = track;
2828 VolumeProvider *vp = track;
2829 fastTrack->mBufferProvider = eabp;
2830 fastTrack->mVolumeProvider = vp;
2831 fastTrack->mSampleRate = track->mSampleRate;
2832 fastTrack->mChannelMask = track->mChannelMask;
2833 fastTrack->mGeneration++;
2834 state->mTrackMask |= 1 << j;
2835 didModify = true;
2836 // no acknowledgement required for newly active tracks
2837 }
2838 // cache the combined master volume and stream type volume for fast mixer; this
2839 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002840 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002841 ++fastTracks;
2842 } else {
2843 // was it previously active?
2844 if (state->mTrackMask & (1 << j)) {
2845 fastTrack->mBufferProvider = NULL;
2846 fastTrack->mGeneration++;
2847 state->mTrackMask &= ~(1 << j);
2848 didModify = true;
2849 // If any fast tracks were removed, we must wait for acknowledgement
2850 // because we're about to decrement the last sp<> on those tracks.
2851 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2852 } else {
2853 LOG_FATAL("fast track %d should have been active", j);
2854 }
2855 tracksToRemove->add(track);
2856 // Avoids a misleading display in dumpsys
2857 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2858 }
2859 continue;
2860 }
2861
2862 { // local variable scope to avoid goto warning
2863
2864 audio_track_cblk_t* cblk = track->cblk();
2865
2866 // The first time a track is added we wait
2867 // for all its buffers to be filled before processing it
2868 int name = track->name();
2869 // make sure that we have enough frames to mix one full buffer.
2870 // enforce this condition only once to enable draining the buffer in case the client
2871 // app does not call stop() and relies on underrun to stop:
2872 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2873 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002874 size_t desiredFrames;
2875 if (t->sampleRate() == mSampleRate) {
2876 desiredFrames = mNormalFrameCount;
2877 } else {
2878 // +1 for rounding and +1 for additional sample needed for interpolation
2879 desiredFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2880 // add frames already consumed but not yet released by the resampler
2881 // because cblk->framesReady() will include these frames
2882 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2883 // the minimum track buffer size is normally twice the number of frames necessary
2884 // to fill one buffer and the resampler should not leave more than one buffer worth
2885 // of unreleased frames after each pass, but just in case...
2886 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2887 }
Eric Laurent81784c32012-11-19 14:55:58 -08002888 uint32_t minFrames = 1;
2889 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2890 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002891 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002892 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002893 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2894 size_t framesReady;
2895 if (track->sharedBuffer() == 0) {
2896 framesReady = track->framesReady();
2897 } else if (track->isStopped()) {
2898 framesReady = 0;
2899 } else {
2900 framesReady = 1;
2901 }
2902 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002903 !track->isPaused() && !track->isTerminated())
2904 {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->server, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002906
2907 mixedTracks++;
2908
2909 // track->mainBuffer() != mMixBuffer means there is an effect chain
2910 // connected to the track
2911 chain.clear();
2912 if (track->mainBuffer() != mMixBuffer) {
2913 chain = getEffectChain_l(track->sessionId());
2914 // Delegate volume control to effect in track effect chain if needed
2915 if (chain != 0) {
2916 tracksWithEffect++;
2917 } else {
2918 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2919 "session %d",
2920 name, track->sessionId());
2921 }
2922 }
2923
2924
2925 int param = AudioMixer::VOLUME;
2926 if (track->mFillingUpStatus == Track::FS_FILLED) {
2927 // no ramp for the first volume setting
2928 track->mFillingUpStatus = Track::FS_ACTIVE;
2929 if (track->mState == TrackBase::RESUMING) {
2930 track->mState = TrackBase::ACTIVE;
2931 param = AudioMixer::RAMP_VOLUME;
2932 }
2933 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2934 } else if (cblk->server != 0) {
2935 // If the track is stopped before the first frame was mixed,
2936 // do not apply ramp
2937 param = AudioMixer::RAMP_VOLUME;
2938 }
2939
2940 // compute volume for this track
2941 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002942 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002943 vl = vr = va = 0;
2944 if (track->isPausing()) {
2945 track->setPaused();
2946 }
2947 } else {
2948
2949 // read original volumes with volume control
2950 float typeVolume = mStreamTypes[track->streamType()].volume;
2951 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002952 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002953 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002954 vl = vlr & 0xFFFF;
2955 vr = vlr >> 16;
2956 // track volumes come from shared memory, so can't be trusted and must be clamped
2957 if (vl > MAX_GAIN_INT) {
2958 ALOGV("Track left volume out of range: %04X", vl);
2959 vl = MAX_GAIN_INT;
2960 }
2961 if (vr > MAX_GAIN_INT) {
2962 ALOGV("Track right volume out of range: %04X", vr);
2963 vr = MAX_GAIN_INT;
2964 }
2965 // now apply the master volume and stream type volume
2966 vl = (uint32_t)(v * vl) << 12;
2967 vr = (uint32_t)(v * vr) << 12;
2968 // assuming master volume and stream type volume each go up to 1.0,
2969 // vl and vr are now in 8.24 format
2970
Glenn Kastene3aa6592012-12-04 12:22:46 -08002971 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08002972 // send level comes from shared memory and so may be corrupt
2973 if (sendLevel > MAX_GAIN_INT) {
2974 ALOGV("Track send level out of range: %04X", sendLevel);
2975 sendLevel = MAX_GAIN_INT;
2976 }
2977 va = (uint32_t)(v * sendLevel);
2978 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 // Delegate volume control to effect in track effect chain if needed
2981 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2982 // Do not ramp volume if volume is controlled by effect
2983 param = AudioMixer::VOLUME;
2984 track->mHasVolumeController = true;
2985 } else {
2986 // force no volume ramp when volume controller was just disabled or removed
2987 // from effect chain to avoid volume spike
2988 if (track->mHasVolumeController) {
2989 param = AudioMixer::VOLUME;
2990 }
2991 track->mHasVolumeController = false;
2992 }
2993
2994 // Convert volumes from 8.24 to 4.12 format
2995 // This additional clamping is needed in case chain->setVolume_l() overshot
2996 vl = (vl + (1 << 11)) >> 12;
2997 if (vl > MAX_GAIN_INT) {
2998 vl = MAX_GAIN_INT;
2999 }
3000 vr = (vr + (1 << 11)) >> 12;
3001 if (vr > MAX_GAIN_INT) {
3002 vr = MAX_GAIN_INT;
3003 }
3004
3005 if (va > MAX_GAIN_INT) {
3006 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3007 }
3008
3009 // XXX: these things DON'T need to be done each time
3010 mAudioMixer->setBufferProvider(name, track);
3011 mAudioMixer->enable(name);
3012
3013 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3014 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3015 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3016 mAudioMixer->setParameter(
3017 name,
3018 AudioMixer::TRACK,
3019 AudioMixer::FORMAT, (void *)track->format());
3020 mAudioMixer->setParameter(
3021 name,
3022 AudioMixer::TRACK,
3023 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003024 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3025 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003026 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003027 if (reqSampleRate == 0) {
3028 reqSampleRate = mSampleRate;
3029 } else if (reqSampleRate > maxSampleRate) {
3030 reqSampleRate = maxSampleRate;
3031 }
Eric Laurent81784c32012-11-19 14:55:58 -08003032 mAudioMixer->setParameter(
3033 name,
3034 AudioMixer::RESAMPLE,
3035 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003036 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 mAudioMixer->setParameter(
3038 name,
3039 AudioMixer::TRACK,
3040 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3041 mAudioMixer->setParameter(
3042 name,
3043 AudioMixer::TRACK,
3044 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3045
3046 // reset retry count
3047 track->mRetryCount = kMaxTrackRetries;
3048
3049 // If one track is ready, set the mixer ready if:
3050 // - the mixer was not ready during previous round OR
3051 // - no other track is not ready
3052 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3053 mixerStatus != MIXER_TRACKS_ENABLED) {
3054 mixerStatus = MIXER_TRACKS_READY;
3055 }
3056 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003057 // only implemented for normal tracks, not fast tracks
3058 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
3059 // we missed desiredFrames whatever the actual number of frames missing was
3060 cblk->u.mStreaming.mUnderrunFrames += desiredFrames;
3061 // FIXME also wake futex so that underrun is noticed more quickly
3062 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->flags);
3063 }
Eric Laurent81784c32012-11-19 14:55:58 -08003064 // clear effect chain input buffer if an active track underruns to avoid sending
3065 // previous audio buffer again to effects
3066 chain = getEffectChain_l(track->sessionId());
3067 if (chain != 0) {
3068 chain->clearInputBuffer();
3069 }
3070
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->server, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003072 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3073 track->isStopped() || track->isPaused()) {
3074 // We have consumed all the buffers of this track.
3075 // Remove it from the list of active tracks.
3076 // TODO: use actual buffer filling status instead of latency when available from
3077 // audio HAL
3078 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3079 size_t framesWritten = mBytesWritten / mFrameSize;
3080 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3081 if (track->isStopped()) {
3082 track->reset();
3083 }
3084 tracksToRemove->add(track);
3085 }
3086 } else {
3087 track->mUnderrunCount++;
3088 // 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
3095 android_atomic_or(CBLK_DISABLED, &cblk->flags);
3096 // 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 {
3485 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3486
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
3510 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3511 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()) {
3849 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->server);
3850 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 {
3877 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->server);
3878 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
4191status_t AudioFlinger::RecordThread::readyToRun()
4192{
4193 status_t status = initCheck();
4194 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4195 return status;
4196}
4197
4198bool AudioFlinger::RecordThread::threadLoop()
4199{
4200 AudioBufferProvider::Buffer buffer;
4201 sp<RecordTrack> activeTrack;
4202 Vector< sp<EffectChain> > effectChains;
4203
4204 nsecs_t lastWarning = 0;
4205
4206 inputStandBy();
4207 acquireWakeLock();
4208
4209 // used to verify we've read at least once before evaluating how many bytes were read
4210 bool readOnce = false;
4211
4212 // start recording
4213 while (!exitPending()) {
4214
4215 processConfigEvents();
4216
4217 { // scope for mLock
4218 Mutex::Autolock _l(mLock);
4219 checkForNewParameters_l();
4220 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4221 standby();
4222
4223 if (exitPending()) {
4224 break;
4225 }
4226
4227 releaseWakeLock_l();
4228 ALOGV("RecordThread: loop stopping");
4229 // go to sleep
4230 mWaitWorkCV.wait(mLock);
4231 ALOGV("RecordThread: loop starting");
4232 acquireWakeLock_l();
4233 continue;
4234 }
4235 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004236 if (mActiveTrack->isTerminated()) {
4237 removeTrack_l(mActiveTrack);
4238 mActiveTrack.clear();
4239 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004240 standby();
4241 mActiveTrack.clear();
4242 mStartStopCond.broadcast();
4243 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4244 if (mReqChannelCount != mActiveTrack->channelCount()) {
4245 mActiveTrack.clear();
4246 mStartStopCond.broadcast();
4247 } else if (readOnce) {
4248 // record start succeeds only if first read from audio input
4249 // succeeds
4250 if (mBytesRead >= 0) {
4251 mActiveTrack->mState = TrackBase::ACTIVE;
4252 } else {
4253 mActiveTrack.clear();
4254 }
4255 mStartStopCond.broadcast();
4256 }
4257 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004258 }
4259 }
4260 lockEffectChains_l(effectChains);
4261 }
4262
4263 if (mActiveTrack != 0) {
4264 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4265 mActiveTrack->mState != TrackBase::RESUMING) {
4266 unlockEffectChains(effectChains);
4267 usleep(kRecordThreadSleepUs);
4268 continue;
4269 }
4270 for (size_t i = 0; i < effectChains.size(); i ++) {
4271 effectChains[i]->process_l();
4272 }
4273
4274 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004275 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004276 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004277 readOnce = true;
4278 size_t framesOut = buffer.frameCount;
4279 if (mResampler == NULL) {
4280 // no resampling
4281 while (framesOut) {
4282 size_t framesIn = mFrameCount - mRsmpInIndex;
4283 if (framesIn) {
4284 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4285 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4286 mActiveTrack->mFrameSize;
4287 if (framesIn > framesOut)
4288 framesIn = framesOut;
4289 mRsmpInIndex += framesIn;
4290 framesOut -= framesIn;
4291 if (mChannelCount == mReqChannelCount ||
4292 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4293 memcpy(dst, src, framesIn * mFrameSize);
4294 } else {
4295 if (mChannelCount == 1) {
4296 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4297 (int16_t *)src, framesIn);
4298 } else {
4299 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4300 (int16_t *)src, framesIn);
4301 }
4302 }
4303 }
4304 if (framesOut && mFrameCount == mRsmpInIndex) {
4305 void *readInto;
4306 if (framesOut == mFrameCount &&
4307 (mChannelCount == mReqChannelCount ||
4308 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4309 readInto = buffer.raw;
4310 framesOut = 0;
4311 } else {
4312 readInto = mRsmpInBuffer;
4313 mRsmpInIndex = 0;
4314 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004315 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004316 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004317 if (mBytesRead <= 0) {
4318 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4319 {
4320 ALOGE("Error reading audio input");
4321 // Force input into standby so that it tries to
4322 // recover at next read attempt
4323 inputStandBy();
4324 usleep(kRecordThreadSleepUs);
4325 }
4326 mRsmpInIndex = mFrameCount;
4327 framesOut = 0;
4328 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004329 }
4330#ifdef TEE_SINK
4331 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004332 (void) mTeeSink->write(readInto,
4333 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4334 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004335#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004336 }
4337 }
4338 } else {
4339 // resampling
4340
4341 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4342 // alter output frame count as if we were expecting stereo samples
4343 if (mChannelCount == 1 && mReqChannelCount == 1) {
4344 framesOut >>= 1;
4345 }
4346 mResampler->resample(mRsmpOutBuffer, framesOut,
4347 this /* AudioBufferProvider* */);
4348 // ditherAndClamp() works as long as all buffers returned by
4349 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4350 if (mChannelCount == 2 && mReqChannelCount == 1) {
4351 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4352 // the resampler always outputs stereo samples:
4353 // do post stereo to mono conversion
4354 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4355 framesOut);
4356 } else {
4357 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4358 }
4359
4360 }
4361 if (mFramestoDrop == 0) {
4362 mActiveTrack->releaseBuffer(&buffer);
4363 } else {
4364 if (mFramestoDrop > 0) {
4365 mFramestoDrop -= buffer.frameCount;
4366 if (mFramestoDrop <= 0) {
4367 clearSyncStartEvent();
4368 }
4369 } else {
4370 mFramestoDrop += buffer.frameCount;
4371 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4372 mSyncStartEvent->isCancelled()) {
4373 ALOGW("Synced record %s, session %d, trigger session %d",
4374 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4375 mActiveTrack->sessionId(),
4376 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4377 clearSyncStartEvent();
4378 }
4379 }
4380 }
4381 mActiveTrack->clearOverflow();
4382 }
4383 // client isn't retrieving buffers fast enough
4384 else {
4385 if (!mActiveTrack->setOverflow()) {
4386 nsecs_t now = systemTime();
4387 if ((now - lastWarning) > kWarningThrottleNs) {
4388 ALOGW("RecordThread: buffer overflow");
4389 lastWarning = now;
4390 }
4391 }
4392 // Release the processor for a while before asking for a new buffer.
4393 // This will give the application more chance to read from the buffer and
4394 // clear the overflow.
4395 usleep(kRecordThreadSleepUs);
4396 }
4397 }
4398 // enable changes in effect chain
4399 unlockEffectChains(effectChains);
4400 effectChains.clear();
4401 }
4402
4403 standby();
4404
4405 {
4406 Mutex::Autolock _l(mLock);
4407 mActiveTrack.clear();
4408 mStartStopCond.broadcast();
4409 }
4410
4411 releaseWakeLock();
4412
4413 ALOGV("RecordThread %p exiting", this);
4414 return false;
4415}
4416
4417void AudioFlinger::RecordThread::standby()
4418{
4419 if (!mStandby) {
4420 inputStandBy();
4421 mStandby = true;
4422 }
4423}
4424
4425void AudioFlinger::RecordThread::inputStandBy()
4426{
4427 mInput->stream->common.standby(&mInput->stream->common);
4428}
4429
4430sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4431 const sp<AudioFlinger::Client>& client,
4432 uint32_t sampleRate,
4433 audio_format_t format,
4434 audio_channel_mask_t channelMask,
4435 size_t frameCount,
4436 int sessionId,
4437 IAudioFlinger::track_flags_t flags,
4438 pid_t tid,
4439 status_t *status)
4440{
4441 sp<RecordTrack> track;
4442 status_t lStatus;
4443
4444 lStatus = initCheck();
4445 if (lStatus != NO_ERROR) {
4446 ALOGE("Audio driver not initialized.");
4447 goto Exit;
4448 }
4449
4450 // FIXME use flags and tid similar to createTrack_l()
4451
4452 { // scope for mLock
4453 Mutex::Autolock _l(mLock);
4454
4455 track = new RecordTrack(this, client, sampleRate,
4456 format, channelMask, frameCount, sessionId);
4457
4458 if (track->getCblk() == 0) {
4459 lStatus = NO_MEMORY;
4460 goto Exit;
4461 }
4462 mTracks.add(track);
4463
4464 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4465 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4466 mAudioFlinger->btNrecIsOff();
4467 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4468 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4469 }
4470 lStatus = NO_ERROR;
4471
4472Exit:
4473 if (status) {
4474 *status = lStatus;
4475 }
4476 return track;
4477}
4478
4479status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4480 AudioSystem::sync_event_t event,
4481 int triggerSession)
4482{
4483 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4484 sp<ThreadBase> strongMe = this;
4485 status_t status = NO_ERROR;
4486
4487 if (event == AudioSystem::SYNC_EVENT_NONE) {
4488 clearSyncStartEvent();
4489 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4490 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4491 triggerSession,
4492 recordTrack->sessionId(),
4493 syncStartEventCallback,
4494 this);
4495 // Sync event can be cancelled by the trigger session if the track is not in a
4496 // compatible state in which case we start record immediately
4497 if (mSyncStartEvent->isCancelled()) {
4498 clearSyncStartEvent();
4499 } else {
4500 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4501 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4502 }
4503 }
4504
4505 {
4506 AutoMutex lock(mLock);
4507 if (mActiveTrack != 0) {
4508 if (recordTrack != mActiveTrack.get()) {
4509 status = -EBUSY;
4510 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4511 mActiveTrack->mState = TrackBase::ACTIVE;
4512 }
4513 return status;
4514 }
4515
4516 recordTrack->mState = TrackBase::IDLE;
4517 mActiveTrack = recordTrack;
4518 mLock.unlock();
4519 status_t status = AudioSystem::startInput(mId);
4520 mLock.lock();
4521 if (status != NO_ERROR) {
4522 mActiveTrack.clear();
4523 clearSyncStartEvent();
4524 return status;
4525 }
4526 mRsmpInIndex = mFrameCount;
4527 mBytesRead = 0;
4528 if (mResampler != NULL) {
4529 mResampler->reset();
4530 }
4531 mActiveTrack->mState = TrackBase::RESUMING;
4532 // signal thread to start
4533 ALOGV("Signal record thread");
4534 mWaitWorkCV.broadcast();
4535 // do not wait for mStartStopCond if exiting
4536 if (exitPending()) {
4537 mActiveTrack.clear();
4538 status = INVALID_OPERATION;
4539 goto startError;
4540 }
4541 mStartStopCond.wait(mLock);
4542 if (mActiveTrack == 0) {
4543 ALOGV("Record failed to start");
4544 status = BAD_VALUE;
4545 goto startError;
4546 }
4547 ALOGV("Record started OK");
4548 return status;
4549 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004550
Eric Laurent81784c32012-11-19 14:55:58 -08004551startError:
4552 AudioSystem::stopInput(mId);
4553 clearSyncStartEvent();
4554 return status;
4555}
4556
4557void AudioFlinger::RecordThread::clearSyncStartEvent()
4558{
4559 if (mSyncStartEvent != 0) {
4560 mSyncStartEvent->cancel();
4561 }
4562 mSyncStartEvent.clear();
4563 mFramestoDrop = 0;
4564}
4565
4566void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4567{
4568 sp<SyncEvent> strongEvent = event.promote();
4569
4570 if (strongEvent != 0) {
4571 RecordThread *me = (RecordThread *)strongEvent->cookie();
4572 me->handleSyncStartEvent(strongEvent);
4573 }
4574}
4575
4576void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4577{
4578 if (event == mSyncStartEvent) {
4579 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4580 // from audio HAL
4581 mFramestoDrop = mFrameCount * 2;
4582 }
4583}
4584
Glenn Kastena8356f62013-07-25 14:37:52 -07004585bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004586 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004587 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004588 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4589 return false;
4590 }
4591 recordTrack->mState = TrackBase::PAUSING;
4592 // do not wait for mStartStopCond if exiting
4593 if (exitPending()) {
4594 return true;
4595 }
4596 mStartStopCond.wait(mLock);
4597 // if we have been restarted, recordTrack == mActiveTrack.get() here
4598 if (exitPending() || recordTrack != mActiveTrack.get()) {
4599 ALOGV("Record stopped OK");
4600 return true;
4601 }
4602 return false;
4603}
4604
4605bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4606{
4607 return false;
4608}
4609
4610status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4611{
4612#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4613 if (!isValidSyncEvent(event)) {
4614 return BAD_VALUE;
4615 }
4616
4617 int eventSession = event->triggerSession();
4618 status_t ret = NAME_NOT_FOUND;
4619
4620 Mutex::Autolock _l(mLock);
4621
4622 for (size_t i = 0; i < mTracks.size(); i++) {
4623 sp<RecordTrack> track = mTracks[i];
4624 if (eventSession == track->sessionId()) {
4625 (void) track->setSyncEvent(event);
4626 ret = NO_ERROR;
4627 }
4628 }
4629 return ret;
4630#else
4631 return BAD_VALUE;
4632#endif
4633}
4634
4635// destroyTrack_l() must be called with ThreadBase::mLock held
4636void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4637{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004638 track->terminate();
4639 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004640 // active tracks are removed by threadLoop()
4641 if (mActiveTrack != track) {
4642 removeTrack_l(track);
4643 }
4644}
4645
4646void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4647{
4648 mTracks.remove(track);
4649 // need anything related to effects here?
4650}
4651
4652void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4653{
4654 dumpInternals(fd, args);
4655 dumpTracks(fd, args);
4656 dumpEffectChains(fd, args);
4657}
4658
4659void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4660{
4661 const size_t SIZE = 256;
4662 char buffer[SIZE];
4663 String8 result;
4664
4665 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4666 result.append(buffer);
4667
4668 if (mActiveTrack != 0) {
4669 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4670 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004671 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004672 result.append(buffer);
4673 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4674 result.append(buffer);
4675 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4676 result.append(buffer);
4677 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4678 result.append(buffer);
4679 } else {
4680 result.append("No active record client\n");
4681 }
4682
4683 write(fd, result.string(), result.size());
4684
4685 dumpBase(fd, args);
4686}
4687
4688void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4689{
4690 const size_t SIZE = 256;
4691 char buffer[SIZE];
4692 String8 result;
4693
4694 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4695 result.append(buffer);
4696 RecordTrack::appendDumpHeader(result);
4697 for (size_t i = 0; i < mTracks.size(); ++i) {
4698 sp<RecordTrack> track = mTracks[i];
4699 if (track != 0) {
4700 track->dump(buffer, SIZE);
4701 result.append(buffer);
4702 }
4703 }
4704
4705 if (mActiveTrack != 0) {
4706 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4707 result.append(buffer);
4708 RecordTrack::appendDumpHeader(result);
4709 mActiveTrack->dump(buffer, SIZE);
4710 result.append(buffer);
4711
4712 }
4713 write(fd, result.string(), result.size());
4714}
4715
4716// AudioBufferProvider interface
4717status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4718{
4719 size_t framesReq = buffer->frameCount;
4720 size_t framesReady = mFrameCount - mRsmpInIndex;
4721 int channelCount;
4722
4723 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004724 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004725 if (mBytesRead <= 0) {
4726 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4727 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4728 // Force input into standby so that it tries to
4729 // recover at next read attempt
4730 inputStandBy();
4731 usleep(kRecordThreadSleepUs);
4732 }
4733 buffer->raw = NULL;
4734 buffer->frameCount = 0;
4735 return NOT_ENOUGH_DATA;
4736 }
4737 mRsmpInIndex = 0;
4738 framesReady = mFrameCount;
4739 }
4740
4741 if (framesReq > framesReady) {
4742 framesReq = framesReady;
4743 }
4744
4745 if (mChannelCount == 1 && mReqChannelCount == 2) {
4746 channelCount = 1;
4747 } else {
4748 channelCount = 2;
4749 }
4750 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4751 buffer->frameCount = framesReq;
4752 return NO_ERROR;
4753}
4754
4755// AudioBufferProvider interface
4756void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4757{
4758 mRsmpInIndex += buffer->frameCount;
4759 buffer->frameCount = 0;
4760}
4761
4762bool AudioFlinger::RecordThread::checkForNewParameters_l()
4763{
4764 bool reconfig = false;
4765
4766 while (!mNewParameters.isEmpty()) {
4767 status_t status = NO_ERROR;
4768 String8 keyValuePair = mNewParameters[0];
4769 AudioParameter param = AudioParameter(keyValuePair);
4770 int value;
4771 audio_format_t reqFormat = mFormat;
4772 uint32_t reqSamplingRate = mReqSampleRate;
4773 uint32_t reqChannelCount = mReqChannelCount;
4774
4775 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4776 reqSamplingRate = value;
4777 reconfig = true;
4778 }
4779 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4780 reqFormat = (audio_format_t) value;
4781 reconfig = true;
4782 }
4783 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4784 reqChannelCount = popcount(value);
4785 reconfig = true;
4786 }
4787 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4788 // do not accept frame count changes if tracks are open as the track buffer
4789 // size depends on frame count and correct behavior would not be guaranteed
4790 // if frame count is changed after track creation
4791 if (mActiveTrack != 0) {
4792 status = INVALID_OPERATION;
4793 } else {
4794 reconfig = true;
4795 }
4796 }
4797 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4798 // forward device change to effects that have requested to be
4799 // aware of attached audio device.
4800 for (size_t i = 0; i < mEffectChains.size(); i++) {
4801 mEffectChains[i]->setDevice_l(value);
4802 }
4803
4804 // store input device and output device but do not forward output device to audio HAL.
4805 // Note that status is ignored by the caller for output device
4806 // (see AudioFlinger::setParameters()
4807 if (audio_is_output_devices(value)) {
4808 mOutDevice = value;
4809 status = BAD_VALUE;
4810 } else {
4811 mInDevice = value;
4812 // disable AEC and NS if the device is a BT SCO headset supporting those
4813 // pre processings
4814 if (mTracks.size() > 0) {
4815 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4816 mAudioFlinger->btNrecIsOff();
4817 for (size_t i = 0; i < mTracks.size(); i++) {
4818 sp<RecordTrack> track = mTracks[i];
4819 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4820 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4821 }
4822 }
4823 }
4824 }
4825 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4826 mAudioSource != (audio_source_t)value) {
4827 // forward device change to effects that have requested to be
4828 // aware of attached audio device.
4829 for (size_t i = 0; i < mEffectChains.size(); i++) {
4830 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4831 }
4832 mAudioSource = (audio_source_t)value;
4833 }
4834 if (status == NO_ERROR) {
4835 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4836 keyValuePair.string());
4837 if (status == INVALID_OPERATION) {
4838 inputStandBy();
4839 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4840 keyValuePair.string());
4841 }
4842 if (reconfig) {
4843 if (status == BAD_VALUE &&
4844 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4845 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004846 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004847 <= (2 * reqSamplingRate)) &&
4848 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4849 <= FCC_2 &&
4850 (reqChannelCount <= FCC_2)) {
4851 status = NO_ERROR;
4852 }
4853 if (status == NO_ERROR) {
4854 readInputParameters();
4855 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4856 }
4857 }
4858 }
4859
4860 mNewParameters.removeAt(0);
4861
4862 mParamStatus = status;
4863 mParamCond.signal();
4864 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4865 // already timed out waiting for the status and will never signal the condition.
4866 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4867 }
4868 return reconfig;
4869}
4870
4871String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4872{
Eric Laurent81784c32012-11-19 14:55:58 -08004873 Mutex::Autolock _l(mLock);
4874 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07004875 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08004876 }
4877
Glenn Kastend8ea6992013-07-16 14:17:15 -07004878 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4879 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08004880 free(s);
4881 return out_s8;
4882}
4883
4884void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4885 AudioSystem::OutputDescriptor desc;
4886 void *param2 = NULL;
4887
4888 switch (event) {
4889 case AudioSystem::INPUT_OPENED:
4890 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07004891 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004892 desc.samplingRate = mSampleRate;
4893 desc.format = mFormat;
4894 desc.frameCount = mFrameCount;
4895 desc.latency = 0;
4896 param2 = &desc;
4897 break;
4898
4899 case AudioSystem::INPUT_CLOSED:
4900 default:
4901 break;
4902 }
4903 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4904}
4905
4906void AudioFlinger::RecordThread::readInputParameters()
4907{
4908 delete mRsmpInBuffer;
4909 // mRsmpInBuffer is always assigned a new[] below
4910 delete mRsmpOutBuffer;
4911 mRsmpOutBuffer = NULL;
4912 delete mResampler;
4913 mResampler = NULL;
4914
4915 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4916 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07004917 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004918 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4919 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);
4937 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4938
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