blob: aca6c182a2e4232bbdf455c500de21c2c4a74498 [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
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
138// Currently the client uses double-buffering by default, but doesn't tell us about that.
139// So for now we just assume that client is double-buffered.
140// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
141// N-buffering, so AudioFlinger could allocate the right amount of memory.
142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
188void CpuStats::sample(const String8 &title) {
189#ifdef DEBUG_CPU_USAGE
190 // get current thread's delta CPU time in wall clock ns
191 double wcNs;
192 bool valid = mCpuUsage.sampleAndEnable(wcNs);
193
194 // record sample for wall clock statistics
195 if (valid) {
196 mWcStats.sample(wcNs);
197 }
198
199 // get the current CPU number
200 int cpuNum = sched_getcpu();
201
202 // get the current CPU frequency in kHz
203 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
204
205 // check if either CPU number or frequency changed
206 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
207 mCpuNum = cpuNum;
208 mCpukHz = cpukHz;
209 // ignore sample for purposes of cycles
210 valid = false;
211 }
212
213 // if no change in CPU number or frequency, then record sample for cycle statistics
214 if (valid && mCpukHz > 0) {
215 double cycles = wcNs * cpukHz * 0.000001;
216 mHzStats.sample(cycles);
217 }
218
219 unsigned n = mWcStats.n();
220 // mCpuUsage.elapsed() is expensive, so don't call it every loop
221 if ((n & 127) == 1) {
222 long long elapsed = mCpuUsage.elapsed();
223 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
224 double perLoop = elapsed / (double) n;
225 double perLoop100 = perLoop * 0.01;
226 double perLoop1k = perLoop * 0.001;
227 double mean = mWcStats.mean();
228 double stddev = mWcStats.stddev();
229 double minimum = mWcStats.minimum();
230 double maximum = mWcStats.maximum();
231 double meanCycles = mHzStats.mean();
232 double stddevCycles = mHzStats.stddev();
233 double minCycles = mHzStats.minimum();
234 double maxCycles = mHzStats.maximum();
235 mCpuUsage.resetElapsed();
236 mWcStats.reset();
237 mHzStats.reset();
238 ALOGD("CPU usage for %s over past %.1f secs\n"
239 " (%u mixer loops at %.1f mean ms per loop):\n"
240 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
241 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
242 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
243 title.string(),
244 elapsed * .000000001, n, perLoop * .000001,
245 mean * .001,
246 stddev * .001,
247 minimum * .001,
248 maximum * .001,
249 mean / perLoop100,
250 stddev / perLoop100,
251 minimum / perLoop100,
252 maximum / perLoop100,
253 meanCycles / perLoop1k,
254 stddevCycles / perLoop1k,
255 minCycles / perLoop1k,
256 maxCycles / perLoop1k);
257
258 }
259 }
260#endif
261};
262
263// ----------------------------------------------------------------------------
264// ThreadBase
265// ----------------------------------------------------------------------------
266
267AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
268 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
269 : Thread(false /*canCallJava*/),
270 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700271 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700272 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
273 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800274 mParamStatus(NO_ERROR),
275 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
276 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
277 // mName will be set by concrete (non-virtual) subclass
278 mDeathRecipient(new PMDeathRecipient(this))
279{
280}
281
282AudioFlinger::ThreadBase::~ThreadBase()
283{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700284 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
285 for (size_t i = 0; i < mConfigEvents.size(); i++) {
286 delete mConfigEvents[i];
287 }
288 mConfigEvents.clear();
289
Eric Laurent81784c32012-11-19 14:55:58 -0800290 mParamCond.broadcast();
291 // do not lock the mutex in destructor
292 releaseWakeLock_l();
293 if (mPowerManager != 0) {
294 sp<IBinder> binder = mPowerManager->asBinder();
295 binder->unlinkToDeath(mDeathRecipient);
296 }
297}
298
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700299status_t AudioFlinger::ThreadBase::readyToRun()
300{
301 status_t status = initCheck();
302 if (status == NO_ERROR) {
303 ALOGI("AudioFlinger's thread %p ready to run", this);
304 } else {
305 ALOGE("No working audio driver found.");
306 }
307 return status;
308}
309
Eric Laurent81784c32012-11-19 14:55:58 -0800310void AudioFlinger::ThreadBase::exit()
311{
312 ALOGV("ThreadBase::exit");
313 // do any cleanup required for exit to succeed
314 preExit();
315 {
316 // This lock prevents the following race in thread (uniprocessor for illustration):
317 // if (!exitPending()) {
318 // // context switch from here to exit()
319 // // exit() calls requestExit(), what exitPending() observes
320 // // exit() calls signal(), which is dropped since no waiters
321 // // context switch back from exit() to here
322 // mWaitWorkCV.wait(...);
323 // // now thread is hung
324 // }
325 AutoMutex lock(mLock);
326 requestExit();
327 mWaitWorkCV.broadcast();
328 }
329 // When Thread::requestExitAndWait is made virtual and this method is renamed to
330 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
331 requestExitAndWait();
332}
333
334status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
335{
336 status_t status;
337
338 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
339 Mutex::Autolock _l(mLock);
340
341 mNewParameters.add(keyValuePairs);
342 mWaitWorkCV.signal();
343 // wait condition with timeout in case the thread loop has exited
344 // before the request could be processed
345 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
346 status = mParamStatus;
347 mWaitWorkCV.signal();
348 } else {
349 status = TIMED_OUT;
350 }
351 return status;
352}
353
354void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
355{
356 Mutex::Autolock _l(mLock);
357 sendIoConfigEvent_l(event, param);
358}
359
360// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
361void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
362{
363 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
364 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
365 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
366 param);
367 mWaitWorkCV.signal();
368}
369
370// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
371void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
372{
373 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
374 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
375 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
376 mConfigEvents.size(), pid, tid, prio);
377 mWaitWorkCV.signal();
378}
379
380void AudioFlinger::ThreadBase::processConfigEvents()
381{
Glenn Kastenf7773312013-08-13 16:00:42 -0700382 Mutex::Autolock _l(mLock);
383 processConfigEvents_l();
384}
385
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700386// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700387void AudioFlinger::ThreadBase::processConfigEvents_l()
388{
Eric Laurent81784c32012-11-19 14:55:58 -0800389 while (!mConfigEvents.isEmpty()) {
390 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
391 ConfigEvent *event = mConfigEvents[0];
392 mConfigEvents.removeAt(0);
393 // release mLock before locking AudioFlinger mLock: lock order is always
394 // AudioFlinger then ThreadBase to avoid cross deadlock
395 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700396 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700397 case CFG_EVENT_PRIO: {
398 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
399 // FIXME Need to understand why this has be done asynchronously
400 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
401 true /*asynchronous*/);
402 if (err != 0) {
403 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
404 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
405 }
406 } break;
407 case CFG_EVENT_IO: {
408 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700409 {
410 Mutex::Autolock _l(mAudioFlinger->mLock);
411 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
412 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700413 } break;
414 default:
415 ALOGE("processConfigEvents() unknown event type %d", event->type());
416 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800417 }
418 delete event;
419 mLock.lock();
420 }
Eric Laurent81784c32012-11-19 14:55:58 -0800421}
422
423void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
428
429 bool locked = AudioFlinger::dumpTryLock(mLock);
430 if (!locked) {
431 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
432 write(fd, buffer, strlen(buffer));
433 }
434
435 snprintf(buffer, SIZE, "io handle: %d\n", mId);
436 result.append(buffer);
437 snprintf(buffer, SIZE, "TID: %d\n", getTid());
438 result.append(buffer);
439 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
440 result.append(buffer);
441 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
442 result.append(buffer);
443 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
444 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700445 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
446 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700447 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800448 result.append(buffer);
449 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
450 result.append(buffer);
451 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
452 result.append(buffer);
453 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
454 result.append(buffer);
455
456 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
457 result.append(buffer);
458 result.append(" Index Command");
459 for (size_t i = 0; i < mNewParameters.size(); ++i) {
460 snprintf(buffer, SIZE, "\n %02d ", i);
461 result.append(buffer);
462 result.append(mNewParameters[i]);
463 }
464
465 snprintf(buffer, SIZE, "\n\nPending config events: \n");
466 result.append(buffer);
467 for (size_t i = 0; i < mConfigEvents.size(); i++) {
468 mConfigEvents[i]->dump(buffer, SIZE);
469 result.append(buffer);
470 }
471 result.append("\n");
472
473 write(fd, result.string(), result.size());
474
475 if (locked) {
476 mLock.unlock();
477 }
478}
479
480void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
481{
482 const size_t SIZE = 256;
483 char buffer[SIZE];
484 String8 result;
485
486 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
487 write(fd, buffer, strlen(buffer));
488
489 for (size_t i = 0; i < mEffectChains.size(); ++i) {
490 sp<EffectChain> chain = mEffectChains[i];
491 if (chain != 0) {
492 chain->dump(fd, args);
493 }
494 }
495}
496
497void AudioFlinger::ThreadBase::acquireWakeLock()
498{
499 Mutex::Autolock _l(mLock);
500 acquireWakeLock_l();
501}
502
503void AudioFlinger::ThreadBase::acquireWakeLock_l()
504{
505 if (mPowerManager == 0) {
506 // use checkService() to avoid blocking if power service is not up yet
507 sp<IBinder> binder =
508 defaultServiceManager()->checkService(String16("power"));
509 if (binder == 0) {
510 ALOGW("Thread %s cannot connect to the power manager service", mName);
511 } else {
512 mPowerManager = interface_cast<IPowerManager>(binder);
513 binder->linkToDeath(mDeathRecipient);
514 }
515 }
516 if (mPowerManager != 0) {
517 sp<IBinder> binder = new BBinder();
518 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
519 binder,
Dianne Hackborn61d404e2013-05-20 11:22:20 -0700520 String16(mName),
521 String16("media"));
Eric Laurent81784c32012-11-19 14:55:58 -0800522 if (status == NO_ERROR) {
523 mWakeLockToken = binder;
524 }
525 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
526 }
527}
528
529void AudioFlinger::ThreadBase::releaseWakeLock()
530{
531 Mutex::Autolock _l(mLock);
532 releaseWakeLock_l();
533}
534
535void AudioFlinger::ThreadBase::releaseWakeLock_l()
536{
537 if (mWakeLockToken != 0) {
538 ALOGV("releaseWakeLock_l() %s", mName);
539 if (mPowerManager != 0) {
540 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
541 }
542 mWakeLockToken.clear();
543 }
544}
545
546void AudioFlinger::ThreadBase::clearPowerManager()
547{
548 Mutex::Autolock _l(mLock);
549 releaseWakeLock_l();
550 mPowerManager.clear();
551}
552
553void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
554{
555 sp<ThreadBase> thread = mThread.promote();
556 if (thread != 0) {
557 thread->clearPowerManager();
558 }
559 ALOGW("power manager service died !!!");
560}
561
562void AudioFlinger::ThreadBase::setEffectSuspended(
563 const effect_uuid_t *type, bool suspend, int sessionId)
564{
565 Mutex::Autolock _l(mLock);
566 setEffectSuspended_l(type, suspend, sessionId);
567}
568
569void AudioFlinger::ThreadBase::setEffectSuspended_l(
570 const effect_uuid_t *type, bool suspend, int sessionId)
571{
572 sp<EffectChain> chain = getEffectChain_l(sessionId);
573 if (chain != 0) {
574 if (type != NULL) {
575 chain->setEffectSuspended_l(type, suspend);
576 } else {
577 chain->setEffectSuspendedAll_l(suspend);
578 }
579 }
580
581 updateSuspendedSessions_l(type, suspend, sessionId);
582}
583
584void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
585{
586 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
587 if (index < 0) {
588 return;
589 }
590
591 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
592 mSuspendedSessions.valueAt(index);
593
594 for (size_t i = 0; i < sessionEffects.size(); i++) {
595 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
596 for (int j = 0; j < desc->mRefCount; j++) {
597 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
598 chain->setEffectSuspendedAll_l(true);
599 } else {
600 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
601 desc->mType.timeLow);
602 chain->setEffectSuspended_l(&desc->mType, true);
603 }
604 }
605 }
606}
607
608void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
609 bool suspend,
610 int sessionId)
611{
612 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
613
614 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
615
616 if (suspend) {
617 if (index >= 0) {
618 sessionEffects = mSuspendedSessions.valueAt(index);
619 } else {
620 mSuspendedSessions.add(sessionId, sessionEffects);
621 }
622 } else {
623 if (index < 0) {
624 return;
625 }
626 sessionEffects = mSuspendedSessions.valueAt(index);
627 }
628
629
630 int key = EffectChain::kKeyForSuspendAll;
631 if (type != NULL) {
632 key = type->timeLow;
633 }
634 index = sessionEffects.indexOfKey(key);
635
636 sp<SuspendedSessionDesc> desc;
637 if (suspend) {
638 if (index >= 0) {
639 desc = sessionEffects.valueAt(index);
640 } else {
641 desc = new SuspendedSessionDesc();
642 if (type != NULL) {
643 desc->mType = *type;
644 }
645 sessionEffects.add(key, desc);
646 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
647 }
648 desc->mRefCount++;
649 } else {
650 if (index < 0) {
651 return;
652 }
653 desc = sessionEffects.valueAt(index);
654 if (--desc->mRefCount == 0) {
655 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
656 sessionEffects.removeItemsAt(index);
657 if (sessionEffects.isEmpty()) {
658 ALOGV("updateSuspendedSessions_l() restore removing session %d",
659 sessionId);
660 mSuspendedSessions.removeItem(sessionId);
661 }
662 }
663 }
664 if (!sessionEffects.isEmpty()) {
665 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
666 }
667}
668
669void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
670 bool enabled,
671 int sessionId)
672{
673 Mutex::Autolock _l(mLock);
674 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
675}
676
677void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
678 bool enabled,
679 int sessionId)
680{
681 if (mType != RECORD) {
682 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
683 // another session. This gives the priority to well behaved effect control panels
684 // and applications not using global effects.
685 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
686 // global effects
687 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
688 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
689 }
690 }
691
692 sp<EffectChain> chain = getEffectChain_l(sessionId);
693 if (chain != 0) {
694 chain->checkSuspendOnEffectEnabled(effect, enabled);
695 }
696}
697
698// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
699sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
700 const sp<AudioFlinger::Client>& client,
701 const sp<IEffectClient>& effectClient,
702 int32_t priority,
703 int sessionId,
704 effect_descriptor_t *desc,
705 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700706 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800707{
708 sp<EffectModule> effect;
709 sp<EffectHandle> handle;
710 status_t lStatus;
711 sp<EffectChain> chain;
712 bool chainCreated = false;
713 bool effectCreated = false;
714 bool effectRegistered = false;
715
716 lStatus = initCheck();
717 if (lStatus != NO_ERROR) {
718 ALOGW("createEffect_l() Audio driver not initialized.");
719 goto Exit;
720 }
721
Eric Laurent5baf2af2013-09-12 17:37:00 -0700722 // Allow global effects only on offloaded and mixer threads
723 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
724 switch (mType) {
725 case MIXER:
726 case OFFLOAD:
727 break;
728 case DIRECT:
729 case DUPLICATING:
730 case RECORD:
731 default:
732 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
733 lStatus = BAD_VALUE;
734 goto Exit;
735 }
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700737
Eric Laurent81784c32012-11-19 14:55:58 -0800738 // Only Pre processor effects are allowed on input threads and only on input threads
739 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
740 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
741 desc->name, desc->flags, mType);
742 lStatus = BAD_VALUE;
743 goto Exit;
744 }
745
746 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
747
748 { // scope for mLock
749 Mutex::Autolock _l(mLock);
750
751 // check for existing effect chain with the requested audio session
752 chain = getEffectChain_l(sessionId);
753 if (chain == 0) {
754 // create a new chain for this session
755 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
756 chain = new EffectChain(this, sessionId);
757 addEffectChain_l(chain);
758 chain->setStrategy(getStrategyForSession_l(sessionId));
759 chainCreated = true;
760 } else {
761 effect = chain->getEffectFromDesc_l(desc);
762 }
763
764 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
765
766 if (effect == 0) {
767 int id = mAudioFlinger->nextUniqueId();
768 // Check CPU and memory usage
769 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
770 if (lStatus != NO_ERROR) {
771 goto Exit;
772 }
773 effectRegistered = true;
774 // create a new effect module if none present in the chain
775 effect = new EffectModule(this, chain, desc, id, sessionId);
776 lStatus = effect->status();
777 if (lStatus != NO_ERROR) {
778 goto Exit;
779 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700780 effect->setOffloaded(mType == OFFLOAD, mId);
781
Eric Laurent81784c32012-11-19 14:55:58 -0800782 lStatus = chain->addEffect_l(effect);
783 if (lStatus != NO_ERROR) {
784 goto Exit;
785 }
786 effectCreated = true;
787
788 effect->setDevice(mOutDevice);
789 effect->setDevice(mInDevice);
790 effect->setMode(mAudioFlinger->getMode());
791 effect->setAudioSource(mAudioSource);
792 }
793 // create effect handle and connect it to effect module
794 handle = new EffectHandle(effect, client, effectClient, priority);
795 lStatus = effect->addHandle(handle.get());
796 if (enabled != NULL) {
797 *enabled = (int)effect->isEnabled();
798 }
799 }
800
801Exit:
802 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
803 Mutex::Autolock _l(mLock);
804 if (effectCreated) {
805 chain->removeEffect_l(effect);
806 }
807 if (effectRegistered) {
808 AudioSystem::unregisterEffect(effect->id());
809 }
810 if (chainCreated) {
811 removeEffectChain_l(chain);
812 }
813 handle.clear();
814 }
815
Glenn Kasten9156ef32013-08-06 15:39:08 -0700816 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800817 return handle;
818}
819
820sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
821{
822 Mutex::Autolock _l(mLock);
823 return getEffect_l(sessionId, effectId);
824}
825
826sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
827{
828 sp<EffectChain> chain = getEffectChain_l(sessionId);
829 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
830}
831
832// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
833// PlaybackThread::mLock held
834status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
835{
836 // check for existing effect chain with the requested audio session
837 int sessionId = effect->sessionId();
838 sp<EffectChain> chain = getEffectChain_l(sessionId);
839 bool chainCreated = false;
840
Eric Laurent5baf2af2013-09-12 17:37:00 -0700841 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
842 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
843 this, effect->desc().name, effect->desc().flags);
844
Eric Laurent81784c32012-11-19 14:55:58 -0800845 if (chain == 0) {
846 // create a new chain for this session
847 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
848 chain = new EffectChain(this, sessionId);
849 addEffectChain_l(chain);
850 chain->setStrategy(getStrategyForSession_l(sessionId));
851 chainCreated = true;
852 }
853 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
854
855 if (chain->getEffectFromId_l(effect->id()) != 0) {
856 ALOGW("addEffect_l() %p effect %s already present in chain %p",
857 this, effect->desc().name, chain.get());
858 return BAD_VALUE;
859 }
860
Eric Laurent5baf2af2013-09-12 17:37:00 -0700861 effect->setOffloaded(mType == OFFLOAD, mId);
862
Eric Laurent81784c32012-11-19 14:55:58 -0800863 status_t status = chain->addEffect_l(effect);
864 if (status != NO_ERROR) {
865 if (chainCreated) {
866 removeEffectChain_l(chain);
867 }
868 return status;
869 }
870
871 effect->setDevice(mOutDevice);
872 effect->setDevice(mInDevice);
873 effect->setMode(mAudioFlinger->getMode());
874 effect->setAudioSource(mAudioSource);
875 return NO_ERROR;
876}
877
878void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
879
880 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
881 effect_descriptor_t desc = effect->desc();
882 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
883 detachAuxEffect_l(effect->id());
884 }
885
886 sp<EffectChain> chain = effect->chain().promote();
887 if (chain != 0) {
888 // remove effect chain if removing last effect
889 if (chain->removeEffect_l(effect) == 0) {
890 removeEffectChain_l(chain);
891 }
892 } else {
893 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
894 }
895}
896
897void AudioFlinger::ThreadBase::lockEffectChains_l(
898 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
899{
900 effectChains = mEffectChains;
901 for (size_t i = 0; i < mEffectChains.size(); i++) {
902 mEffectChains[i]->lock();
903 }
904}
905
906void AudioFlinger::ThreadBase::unlockEffectChains(
907 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
908{
909 for (size_t i = 0; i < effectChains.size(); i++) {
910 effectChains[i]->unlock();
911 }
912}
913
914sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
915{
916 Mutex::Autolock _l(mLock);
917 return getEffectChain_l(sessionId);
918}
919
920sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
921{
922 size_t size = mEffectChains.size();
923 for (size_t i = 0; i < size; i++) {
924 if (mEffectChains[i]->sessionId() == sessionId) {
925 return mEffectChains[i];
926 }
927 }
928 return 0;
929}
930
931void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
932{
933 Mutex::Autolock _l(mLock);
934 size_t size = mEffectChains.size();
935 for (size_t i = 0; i < size; i++) {
936 mEffectChains[i]->setMode_l(mode);
937 }
938}
939
940void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
941 EffectHandle *handle,
942 bool unpinIfLast) {
943
944 Mutex::Autolock _l(mLock);
945 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
946 // delete the effect module if removing last handle on it
947 if (effect->removeHandle(handle) == 0) {
948 if (!effect->isPinned() || unpinIfLast) {
949 removeEffect_l(effect);
950 AudioSystem::unregisterEffect(effect->id());
951 }
952 }
953}
954
955// ----------------------------------------------------------------------------
956// Playback
957// ----------------------------------------------------------------------------
958
959AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
960 AudioStreamOut* output,
961 audio_io_handle_t id,
962 audio_devices_t device,
963 type_t type)
964 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700965 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700966 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800967 // mStreamTypes[] initialized in constructor body
968 mOutput(output),
969 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
970 mMixerStatus(MIXER_IDLE),
971 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
972 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800973 mBytesRemaining(0),
974 mCurrentWriteLength(0),
975 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -0700976 mWriteAckSequence(0),
977 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -0700978 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800979 mScreenState(AudioFlinger::mScreenState),
980 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700981 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
982 // mLatchD, mLatchQ,
983 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
985 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800986 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800987
988 // Assumes constructor is called by AudioFlinger with it's mLock held, but
989 // it would be safer to explicitly pass initial masterVolume/masterMute as
990 // parameter.
991 //
992 // If the HAL we are using has support for master volume or master mute,
993 // then do not attenuate or mute during mixing (just leave the volume at 1.0
994 // and the mute set to false).
995 mMasterVolume = audioFlinger->masterVolume_l();
996 mMasterMute = audioFlinger->masterMute_l();
997 if (mOutput && mOutput->audioHwDev) {
998 if (mOutput->audioHwDev->canSetMasterVolume()) {
999 mMasterVolume = 1.0;
1000 }
1001
1002 if (mOutput->audioHwDev->canSetMasterMute()) {
1003 mMasterMute = false;
1004 }
1005 }
1006
1007 readOutputParameters();
1008
1009 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1010 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1011 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1012 stream = (audio_stream_type_t) (stream + 1)) {
1013 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1014 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1015 }
1016 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1017 // because mAudioFlinger doesn't have one to copy from
1018}
1019
1020AudioFlinger::PlaybackThread::~PlaybackThread()
1021{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001022 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001023 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001024}
1025
1026void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1027{
1028 dumpInternals(fd, args);
1029 dumpTracks(fd, args);
1030 dumpEffectChains(fd, args);
1031}
1032
1033void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1034{
1035 const size_t SIZE = 256;
1036 char buffer[SIZE];
1037 String8 result;
1038
1039 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1040 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1041 const stream_type_t *st = &mStreamTypes[i];
1042 if (i > 0) {
1043 result.appendFormat(", ");
1044 }
1045 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1046 if (st->mute) {
1047 result.append("M");
1048 }
1049 }
1050 result.append("\n");
1051 write(fd, result.string(), result.length());
1052 result.clear();
1053
1054 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1055 result.append(buffer);
1056 Track::appendDumpHeader(result);
1057 for (size_t i = 0; i < mTracks.size(); ++i) {
1058 sp<Track> track = mTracks[i];
1059 if (track != 0) {
1060 track->dump(buffer, SIZE);
1061 result.append(buffer);
1062 }
1063 }
1064
1065 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1066 result.append(buffer);
1067 Track::appendDumpHeader(result);
1068 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1069 sp<Track> track = mActiveTracks[i].promote();
1070 if (track != 0) {
1071 track->dump(buffer, SIZE);
1072 result.append(buffer);
1073 }
1074 }
1075 write(fd, result.string(), result.size());
1076
1077 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1078 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1079 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1080 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1081}
1082
1083void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1084{
1085 const size_t SIZE = 256;
1086 char buffer[SIZE];
1087 String8 result;
1088
1089 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1090 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001091 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1092 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001093 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1094 ns2ms(systemTime() - mLastWriteTime));
1095 result.append(buffer);
1096 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1105 result.append(buffer);
1106 write(fd, result.string(), result.size());
1107 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1108
1109 dumpBase(fd, args);
1110}
1111
1112// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001113
1114void AudioFlinger::PlaybackThread::onFirstRef()
1115{
1116 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1117}
1118
1119// ThreadBase virtuals
1120void AudioFlinger::PlaybackThread::preExit()
1121{
1122 ALOGV(" preExit()");
1123 // FIXME this is using hard-coded strings but in the future, this functionality will be
1124 // converted to use audio HAL extensions required to support tunneling
1125 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1126}
1127
1128// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1129sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1130 const sp<AudioFlinger::Client>& client,
1131 audio_stream_type_t streamType,
1132 uint32_t sampleRate,
1133 audio_format_t format,
1134 audio_channel_mask_t channelMask,
1135 size_t frameCount,
1136 const sp<IMemory>& sharedBuffer,
1137 int sessionId,
1138 IAudioFlinger::track_flags_t *flags,
1139 pid_t tid,
1140 status_t *status)
1141{
1142 sp<Track> track;
1143 status_t lStatus;
1144
1145 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1146
1147 // client expresses a preference for FAST, but we get the final say
1148 if (*flags & IAudioFlinger::TRACK_FAST) {
1149 if (
1150 // not timed
1151 (!isTimed) &&
1152 // either of these use cases:
1153 (
1154 // use case 1: shared buffer with any frame count
1155 (
1156 (sharedBuffer != 0)
1157 ) ||
1158 // use case 2: callback handler and frame count is default or at least as large as HAL
1159 (
1160 (tid != -1) &&
1161 ((frameCount == 0) ||
1162 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1163 )
1164 ) &&
1165 // PCM data
1166 audio_is_linear_pcm(format) &&
1167 // mono or stereo
1168 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1169 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1170#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1171 // hardware sample rate
1172 (sampleRate == mSampleRate) &&
1173#endif
1174 // normal mixer has an associated fast mixer
1175 hasFastMixer() &&
1176 // there are sufficient fast track slots available
1177 (mFastTrackAvailMask != 0)
1178 // FIXME test that MixerThread for this fast track has a capable output HAL
1179 // FIXME add a permission test also?
1180 ) {
1181 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1182 if (frameCount == 0) {
1183 frameCount = mFrameCount * kFastTrackMultiplier;
1184 }
1185 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1186 frameCount, mFrameCount);
1187 } else {
1188 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1189 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1190 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1191 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1192 audio_is_linear_pcm(format),
1193 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1194 *flags &= ~IAudioFlinger::TRACK_FAST;
1195 // For compatibility with AudioTrack calculation, buffer depth is forced
1196 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1197 // This is probably too conservative, but legacy application code may depend on it.
1198 // If you change this calculation, also review the start threshold which is related.
1199 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1200 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1201 if (minBufCount < 2) {
1202 minBufCount = 2;
1203 }
1204 size_t minFrameCount = mNormalFrameCount * minBufCount;
1205 if (frameCount < minFrameCount) {
1206 frameCount = minFrameCount;
1207 }
1208 }
1209 }
1210
1211 if (mType == DIRECT) {
1212 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1213 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1214 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1215 "for output %p with format %d",
1216 sampleRate, format, channelMask, mOutput, mFormat);
1217 lStatus = BAD_VALUE;
1218 goto Exit;
1219 }
1220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001221 } else if (mType == OFFLOAD) {
1222 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1223 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1224 "for output %p with format %d",
1225 sampleRate, format, channelMask, mOutput, mFormat);
1226 lStatus = BAD_VALUE;
1227 goto Exit;
1228 }
Eric Laurent81784c32012-11-19 14:55:58 -08001229 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001230 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1231 ALOGE("createTrack_l() Bad parameter: format %d \""
1232 "for output %p with format %d",
1233 format, mOutput, mFormat);
1234 lStatus = BAD_VALUE;
1235 goto Exit;
1236 }
Eric Laurent81784c32012-11-19 14:55:58 -08001237 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1238 if (sampleRate > mSampleRate*2) {
1239 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1240 lStatus = BAD_VALUE;
1241 goto Exit;
1242 }
1243 }
1244
1245 lStatus = initCheck();
1246 if (lStatus != NO_ERROR) {
1247 ALOGE("Audio driver not initialized.");
1248 goto Exit;
1249 }
1250
1251 { // scope for mLock
1252 Mutex::Autolock _l(mLock);
1253
1254 // all tracks in same audio session must share the same routing strategy otherwise
1255 // conflicts will happen when tracks are moved from one output to another by audio policy
1256 // manager
1257 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1258 for (size_t i = 0; i < mTracks.size(); ++i) {
1259 sp<Track> t = mTracks[i];
1260 if (t != 0 && !t->isOutputTrack()) {
1261 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1262 if (sessionId == t->sessionId() && strategy != actual) {
1263 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1264 strategy, actual);
1265 lStatus = BAD_VALUE;
1266 goto Exit;
1267 }
1268 }
1269 }
1270
1271 if (!isTimed) {
1272 track = new Track(this, client, streamType, sampleRate, format,
1273 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1274 } else {
1275 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1276 channelMask, frameCount, sharedBuffer, sessionId);
1277 }
Glenn Kasten03003332013-08-06 15:40:54 -07001278
1279 // new Track always returns non-NULL,
1280 // but TimedTrack::create() is a factory that could fail by returning NULL
1281 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1282 if (lStatus != NO_ERROR) {
1283 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001284 goto Exit;
1285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001286
Eric Laurent81784c32012-11-19 14:55:58 -08001287 mTracks.add(track);
1288
1289 sp<EffectChain> chain = getEffectChain_l(sessionId);
1290 if (chain != 0) {
1291 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1292 track->setMainBuffer(chain->inBuffer());
1293 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1294 chain->incTrackCnt();
1295 }
1296
1297 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1298 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1299 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1300 // so ask activity manager to do this on our behalf
1301 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1302 }
1303 }
1304
1305 lStatus = NO_ERROR;
1306
1307Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001308 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001309 return track;
1310}
1311
1312uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1313{
1314 return latency;
1315}
1316
1317uint32_t AudioFlinger::PlaybackThread::latency() const
1318{
1319 Mutex::Autolock _l(mLock);
1320 return latency_l();
1321}
1322uint32_t AudioFlinger::PlaybackThread::latency_l() const
1323{
1324 if (initCheck() == NO_ERROR) {
1325 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1326 } else {
1327 return 0;
1328 }
1329}
1330
1331void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1332{
1333 Mutex::Autolock _l(mLock);
1334 // Don't apply master volume in SW if our HAL can do it for us.
1335 if (mOutput && mOutput->audioHwDev &&
1336 mOutput->audioHwDev->canSetMasterVolume()) {
1337 mMasterVolume = 1.0;
1338 } else {
1339 mMasterVolume = value;
1340 }
1341}
1342
1343void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1344{
1345 Mutex::Autolock _l(mLock);
1346 // Don't apply master mute in SW if our HAL can do it for us.
1347 if (mOutput && mOutput->audioHwDev &&
1348 mOutput->audioHwDev->canSetMasterMute()) {
1349 mMasterMute = false;
1350 } else {
1351 mMasterMute = muted;
1352 }
1353}
1354
1355void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1356{
1357 Mutex::Autolock _l(mLock);
1358 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001359 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001360}
1361
1362void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1363{
1364 Mutex::Autolock _l(mLock);
1365 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001366 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001367}
1368
1369float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1370{
1371 Mutex::Autolock _l(mLock);
1372 return mStreamTypes[stream].volume;
1373}
1374
1375// addTrack_l() must be called with ThreadBase::mLock held
1376status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1377{
1378 status_t status = ALREADY_EXISTS;
1379
1380 // set retry count for buffer fill
1381 track->mRetryCount = kMaxTrackStartupRetries;
1382 if (mActiveTracks.indexOf(track) < 0) {
1383 // the track is newly added, make sure it fills up all its
1384 // buffers before playing. This is to ensure the client will
1385 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001386 if (!track->isOutputTrack()) {
1387 TrackBase::track_state state = track->mState;
1388 mLock.unlock();
1389 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1390 mLock.lock();
1391 // abort track was stopped/paused while we released the lock
1392 if (state != track->mState) {
1393 if (status == NO_ERROR) {
1394 mLock.unlock();
1395 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1396 mLock.lock();
1397 }
1398 return INVALID_OPERATION;
1399 }
1400 // abort if start is rejected by audio policy manager
1401 if (status != NO_ERROR) {
1402 return PERMISSION_DENIED;
1403 }
1404#ifdef ADD_BATTERY_DATA
1405 // to track the speaker usage
1406 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1407#endif
1408 }
1409
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001411 track->mResetDone = false;
1412 track->mPresentationCompleteFrames = 0;
1413 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001414 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1415 if (chain != 0) {
1416 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1417 track->sessionId());
1418 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001419 }
1420
1421 status = NO_ERROR;
1422 }
1423
Eric Laurentede6c3b2013-09-19 14:37:46 -07001424 ALOGV("signal playback thread");
1425 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001426
1427 return status;
1428}
1429
Eric Laurentbfb1b832013-01-07 09:53:42 -08001430bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001431{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001432 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001433 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001434 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1435 track->mState = TrackBase::STOPPED;
1436 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001437 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001438 } else if (track->isFastTrack() || track->isOffloaded()) {
1439 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001440 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001441
1442 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001443}
1444
1445void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1446{
1447 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1448 mTracks.remove(track);
1449 deleteTrackName_l(track->name());
1450 // redundant as track is about to be destroyed, for dumpsys only
1451 track->mName = -1;
1452 if (track->isFastTrack()) {
1453 int index = track->mFastIndex;
1454 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1455 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1456 mFastTrackAvailMask |= 1 << index;
1457 // redundant as track is about to be destroyed, for dumpsys only
1458 track->mFastIndex = -1;
1459 }
1460 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1461 if (chain != 0) {
1462 chain->decTrackCnt();
1463 }
1464}
1465
Eric Laurentede6c3b2013-09-19 14:37:46 -07001466void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001467{
1468 // Thread could be blocked waiting for async
1469 // so signal it to handle state changes immediately
1470 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1471 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1472 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001473 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001474}
1475
Eric Laurent81784c32012-11-19 14:55:58 -08001476String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1477{
Eric Laurent81784c32012-11-19 14:55:58 -08001478 Mutex::Autolock _l(mLock);
1479 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001480 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001481 }
1482
Glenn Kastend8ea6992013-07-16 14:17:15 -07001483 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1484 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001485 free(s);
1486 return out_s8;
1487}
1488
1489// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1490void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1491 AudioSystem::OutputDescriptor desc;
1492 void *param2 = NULL;
1493
1494 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1495 param);
1496
1497 switch (event) {
1498 case AudioSystem::OUTPUT_OPENED:
1499 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001500 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001501 desc.samplingRate = mSampleRate;
1502 desc.format = mFormat;
1503 desc.frameCount = mNormalFrameCount; // FIXME see
1504 // AudioFlinger::frameCount(audio_io_handle_t)
1505 desc.latency = latency();
1506 param2 = &desc;
1507 break;
1508
1509 case AudioSystem::STREAM_CONFIG_CHANGED:
1510 param2 = &param;
1511 case AudioSystem::OUTPUT_CLOSED:
1512 default:
1513 break;
1514 }
1515 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1516}
1517
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518void AudioFlinger::PlaybackThread::writeCallback()
1519{
1520 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001521 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001522}
1523
1524void AudioFlinger::PlaybackThread::drainCallback()
1525{
1526 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001527 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001528}
1529
Eric Laurent3b4529e2013-09-05 18:09:19 -07001530void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001531{
1532 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001533 // reject out of sequence requests
1534 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1535 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001536 mWaitWorkCV.signal();
1537 }
1538}
1539
Eric Laurent3b4529e2013-09-05 18:09:19 -07001540void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001541{
1542 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001543 // reject out of sequence requests
1544 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1545 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001546 mWaitWorkCV.signal();
1547 }
1548}
1549
1550// static
1551int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1552 void *param,
1553 void *cookie)
1554{
1555 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1556 ALOGV("asyncCallback() event %d", event);
1557 switch (event) {
1558 case STREAM_CBK_EVENT_WRITE_READY:
1559 me->writeCallback();
1560 break;
1561 case STREAM_CBK_EVENT_DRAIN_READY:
1562 me->drainCallback();
1563 break;
1564 default:
1565 ALOGW("asyncCallback() unknown event %d", event);
1566 break;
1567 }
1568 return 0;
1569}
1570
Eric Laurent81784c32012-11-19 14:55:58 -08001571void AudioFlinger::PlaybackThread::readOutputParameters()
1572{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001573 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001574 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1575 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001576 if (!audio_is_output_channel(mChannelMask)) {
1577 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1578 }
1579 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1580 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1581 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1582 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001583 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001585 if (!audio_is_valid_format(mFormat)) {
1586 LOG_FATAL("HAL format %d not valid for output", mFormat);
1587 }
1588 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1589 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1590 mFormat);
1591 }
Eric Laurent81784c32012-11-19 14:55:58 -08001592 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001593 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1594 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001595 if (mFrameCount & 15) {
1596 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1597 mFrameCount);
1598 }
1599
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1601 (mOutput->stream->set_callback != NULL)) {
1602 if (mOutput->stream->set_callback(mOutput->stream,
1603 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1604 mUseAsyncWrite = true;
1605 }
1606 }
1607
Eric Laurent81784c32012-11-19 14:55:58 -08001608 // Calculate size of normal mix buffer relative to the HAL output buffer size
1609 double multiplier = 1.0;
1610 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1611 kUseFastMixer == FastMixer_Dynamic)) {
1612 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1613 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1614 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1615 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1616 maxNormalFrameCount = maxNormalFrameCount & ~15;
1617 if (maxNormalFrameCount < minNormalFrameCount) {
1618 maxNormalFrameCount = minNormalFrameCount;
1619 }
1620 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1621 if (multiplier <= 1.0) {
1622 multiplier = 1.0;
1623 } else if (multiplier <= 2.0) {
1624 if (2 * mFrameCount <= maxNormalFrameCount) {
1625 multiplier = 2.0;
1626 } else {
1627 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1628 }
1629 } else {
1630 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1631 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1632 // track, but we sometimes have to do this to satisfy the maximum frame count
1633 // constraint)
1634 // FIXME this rounding up should not be done if no HAL SRC
1635 uint32_t truncMult = (uint32_t) multiplier;
1636 if ((truncMult & 1)) {
1637 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1638 ++truncMult;
1639 }
1640 }
1641 multiplier = (double) truncMult;
1642 }
1643 }
1644 mNormalFrameCount = multiplier * mFrameCount;
1645 // round up to nearest 16 frames to satisfy AudioMixer
1646 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1647 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1648 mNormalFrameCount);
1649
Glenn Kastenc1fac192013-08-06 07:41:36 -07001650 delete[] mMixBuffer;
1651 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1652 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1653 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1654 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001655
1656 // force reconfiguration of effect chains and engines to take new buffer size and audio
1657 // parameters into account
1658 // Note that mLock is not held when readOutputParameters() is called from the constructor
1659 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1660 // matter.
1661 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1662 Vector< sp<EffectChain> > effectChains = mEffectChains;
1663 for (size_t i = 0; i < effectChains.size(); i ++) {
1664 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1665 }
1666}
1667
1668
1669status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1670{
1671 if (halFrames == NULL || dspFrames == NULL) {
1672 return BAD_VALUE;
1673 }
1674 Mutex::Autolock _l(mLock);
1675 if (initCheck() != NO_ERROR) {
1676 return INVALID_OPERATION;
1677 }
1678 size_t framesWritten = mBytesWritten / mFrameSize;
1679 *halFrames = framesWritten;
1680
1681 if (isSuspended()) {
1682 // return an estimation of rendered frames when the output is suspended
1683 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1684 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1685 return NO_ERROR;
1686 } else {
1687 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1688 }
1689}
1690
1691uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1692{
1693 Mutex::Autolock _l(mLock);
1694 uint32_t result = 0;
1695 if (getEffectChain_l(sessionId) != 0) {
1696 result = EFFECT_SESSION;
1697 }
1698
1699 for (size_t i = 0; i < mTracks.size(); ++i) {
1700 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001701 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001702 result |= TRACK_SESSION;
1703 break;
1704 }
1705 }
1706
1707 return result;
1708}
1709
1710uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1711{
1712 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1713 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1714 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1715 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1716 }
1717 for (size_t i = 0; i < mTracks.size(); i++) {
1718 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001719 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001720 return AudioSystem::getStrategyForStream(track->streamType());
1721 }
1722 }
1723 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1724}
1725
1726
1727AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1728{
1729 Mutex::Autolock _l(mLock);
1730 return mOutput;
1731}
1732
1733AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1734{
1735 Mutex::Autolock _l(mLock);
1736 AudioStreamOut *output = mOutput;
1737 mOutput = NULL;
1738 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1739 // must push a NULL and wait for ack
1740 mOutputSink.clear();
1741 mPipeSink.clear();
1742 mNormalSink.clear();
1743 return output;
1744}
1745
1746// this method must always be called either with ThreadBase mLock held or inside the thread loop
1747audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1748{
1749 if (mOutput == NULL) {
1750 return NULL;
1751 }
1752 return &mOutput->stream->common;
1753}
1754
1755uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1756{
1757 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1758}
1759
1760status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1761{
1762 if (!isValidSyncEvent(event)) {
1763 return BAD_VALUE;
1764 }
1765
1766 Mutex::Autolock _l(mLock);
1767
1768 for (size_t i = 0; i < mTracks.size(); ++i) {
1769 sp<Track> track = mTracks[i];
1770 if (event->triggerSession() == track->sessionId()) {
1771 (void) track->setSyncEvent(event);
1772 return NO_ERROR;
1773 }
1774 }
1775
1776 return NAME_NOT_FOUND;
1777}
1778
1779bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1780{
1781 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1782}
1783
1784void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1785 const Vector< sp<Track> >& tracksToRemove)
1786{
1787 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001788 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001789 for (size_t i = 0 ; i < count ; i++) {
1790 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001792 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001793#ifdef ADD_BATTERY_DATA
1794 // to track the speaker usage
1795 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1796#endif
1797 if (track->isTerminated()) {
1798 AudioSystem::releaseOutput(mId);
1799 }
Eric Laurent81784c32012-11-19 14:55:58 -08001800 }
1801 }
1802 }
Eric Laurent81784c32012-11-19 14:55:58 -08001803}
1804
1805void AudioFlinger::PlaybackThread::checkSilentMode_l()
1806{
1807 if (!mMasterMute) {
1808 char value[PROPERTY_VALUE_MAX];
1809 if (property_get("ro.audio.silent", value, "0") > 0) {
1810 char *endptr;
1811 unsigned long ul = strtoul(value, &endptr, 0);
1812 if (*endptr == '\0' && ul != 0) {
1813 ALOGD("Silence is golden");
1814 // The setprop command will not allow a property to be changed after
1815 // the first time it is set, so we don't have to worry about un-muting.
1816 setMasterMute_l(true);
1817 }
1818 }
1819 }
1820}
1821
1822// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001823ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001824{
1825 // FIXME rewrite to reduce number of system calls
1826 mLastWriteTime = systemTime();
1827 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001828 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001829
1830 // If an NBAIO sink is present, use it to write the normal mixer's submix
1831 if (mNormalSink != 0) {
1832#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833 size_t count = mBytesRemaining >> mBitShift;
1834 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001835 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001836 // update the setpoint when AudioFlinger::mScreenState changes
1837 uint32_t screenState = AudioFlinger::mScreenState;
1838 if (screenState != mScreenState) {
1839 mScreenState = screenState;
1840 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1841 if (pipe != NULL) {
1842 pipe->setAvgFrames((mScreenState & 1) ?
1843 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1844 }
1845 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001846 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001847 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001848 if (framesWritten > 0) {
1849 bytesWritten = framesWritten << mBitShift;
1850 } else {
1851 bytesWritten = framesWritten;
1852 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001853 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001854 if (status == NO_ERROR) {
1855 size_t totalFramesWritten = mNormalSink->framesWritten();
1856 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1857 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1858 mLatchDValid = true;
1859 }
1860 }
Eric Laurent81784c32012-11-19 14:55:58 -08001861 // otherwise use the HAL / AudioStreamOut directly
1862 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001863 // Direct output and offload threads
1864 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1865 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001866 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1867 mWriteAckSequence += 2;
1868 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001870 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001871 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001872 // FIXME We should have an implementation of timestamps for direct output threads.
1873 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001874 bytesWritten = mOutput->stream->write(mOutput->stream,
1875 mMixBuffer + offset, mBytesRemaining);
1876 if (mUseAsyncWrite &&
1877 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1878 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001879 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001881 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 }
Eric Laurent81784c32012-11-19 14:55:58 -08001883 }
1884
Eric Laurent81784c32012-11-19 14:55:58 -08001885 mNumWrites++;
1886 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001887
1888 return bytesWritten;
1889}
1890
1891void AudioFlinger::PlaybackThread::threadLoop_drain()
1892{
1893 if (mOutput->stream->drain) {
1894 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1895 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001896 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1897 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001899 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001900 }
1901 mOutput->stream->drain(mOutput->stream,
1902 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1903 : AUDIO_DRAIN_ALL);
1904 }
1905}
1906
1907void AudioFlinger::PlaybackThread::threadLoop_exit()
1908{
1909 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001910}
1911
1912/*
1913The derived values that are cached:
1914 - mixBufferSize from frame count * frame size
1915 - activeSleepTime from activeSleepTimeUs()
1916 - idleSleepTime from idleSleepTimeUs()
1917 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1918 - maxPeriod from frame count and sample rate (MIXER only)
1919
1920The parameters that affect these derived values are:
1921 - frame count
1922 - frame size
1923 - sample rate
1924 - device type: A2DP or not
1925 - device latency
1926 - format: PCM or not
1927 - active sleep time
1928 - idle sleep time
1929*/
1930
1931void AudioFlinger::PlaybackThread::cacheParameters_l()
1932{
1933 mixBufferSize = mNormalFrameCount * mFrameSize;
1934 activeSleepTime = activeSleepTimeUs();
1935 idleSleepTime = idleSleepTimeUs();
1936}
1937
1938void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1939{
Glenn Kasten7c027242012-12-26 14:43:16 -08001940 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001941 this, streamType, mTracks.size());
1942 Mutex::Autolock _l(mLock);
1943
1944 size_t size = mTracks.size();
1945 for (size_t i = 0; i < size; i++) {
1946 sp<Track> t = mTracks[i];
1947 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001948 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001949 }
1950 }
1951}
1952
1953status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1954{
1955 int session = chain->sessionId();
1956 int16_t *buffer = mMixBuffer;
1957 bool ownsBuffer = false;
1958
1959 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1960 if (session > 0) {
1961 // Only one effect chain can be present in direct output thread and it uses
1962 // the mix buffer as input
1963 if (mType != DIRECT) {
1964 size_t numSamples = mNormalFrameCount * mChannelCount;
1965 buffer = new int16_t[numSamples];
1966 memset(buffer, 0, numSamples * sizeof(int16_t));
1967 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1968 ownsBuffer = true;
1969 }
1970
1971 // Attach all tracks with same session ID to this chain.
1972 for (size_t i = 0; i < mTracks.size(); ++i) {
1973 sp<Track> track = mTracks[i];
1974 if (session == track->sessionId()) {
1975 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1976 buffer);
1977 track->setMainBuffer(buffer);
1978 chain->incTrackCnt();
1979 }
1980 }
1981
1982 // indicate all active tracks in the chain
1983 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1984 sp<Track> track = mActiveTracks[i].promote();
1985 if (track == 0) {
1986 continue;
1987 }
1988 if (session == track->sessionId()) {
1989 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1990 chain->incActiveTrackCnt();
1991 }
1992 }
1993 }
1994
1995 chain->setInBuffer(buffer, ownsBuffer);
1996 chain->setOutBuffer(mMixBuffer);
1997 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1998 // chains list in order to be processed last as it contains output stage effects
1999 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2000 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2001 // after track specific effects and before output stage
2002 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2003 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2004 // Effect chain for other sessions are inserted at beginning of effect
2005 // chains list to be processed before output mix effects. Relative order between other
2006 // sessions is not important
2007 size_t size = mEffectChains.size();
2008 size_t i = 0;
2009 for (i = 0; i < size; i++) {
2010 if (mEffectChains[i]->sessionId() < session) {
2011 break;
2012 }
2013 }
2014 mEffectChains.insertAt(chain, i);
2015 checkSuspendOnAddEffectChain_l(chain);
2016
2017 return NO_ERROR;
2018}
2019
2020size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2021{
2022 int session = chain->sessionId();
2023
2024 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2025
2026 for (size_t i = 0; i < mEffectChains.size(); i++) {
2027 if (chain == mEffectChains[i]) {
2028 mEffectChains.removeAt(i);
2029 // detach all active tracks from the chain
2030 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2031 sp<Track> track = mActiveTracks[i].promote();
2032 if (track == 0) {
2033 continue;
2034 }
2035 if (session == track->sessionId()) {
2036 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2037 chain.get(), session);
2038 chain->decActiveTrackCnt();
2039 }
2040 }
2041
2042 // detach all tracks with same session ID from this chain
2043 for (size_t i = 0; i < mTracks.size(); ++i) {
2044 sp<Track> track = mTracks[i];
2045 if (session == track->sessionId()) {
2046 track->setMainBuffer(mMixBuffer);
2047 chain->decTrackCnt();
2048 }
2049 }
2050 break;
2051 }
2052 }
2053 return mEffectChains.size();
2054}
2055
2056status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2057 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2058{
2059 Mutex::Autolock _l(mLock);
2060 return attachAuxEffect_l(track, EffectId);
2061}
2062
2063status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2064 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2065{
2066 status_t status = NO_ERROR;
2067
2068 if (EffectId == 0) {
2069 track->setAuxBuffer(0, NULL);
2070 } else {
2071 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2072 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2073 if (effect != 0) {
2074 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2075 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2076 } else {
2077 status = INVALID_OPERATION;
2078 }
2079 } else {
2080 status = BAD_VALUE;
2081 }
2082 }
2083 return status;
2084}
2085
2086void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2087{
2088 for (size_t i = 0; i < mTracks.size(); ++i) {
2089 sp<Track> track = mTracks[i];
2090 if (track->auxEffectId() == effectId) {
2091 attachAuxEffect_l(track, 0);
2092 }
2093 }
2094}
2095
2096bool AudioFlinger::PlaybackThread::threadLoop()
2097{
2098 Vector< sp<Track> > tracksToRemove;
2099
2100 standbyTime = systemTime();
2101
2102 // MIXER
2103 nsecs_t lastWarning = 0;
2104
2105 // DUPLICATING
2106 // FIXME could this be made local to while loop?
2107 writeFrames = 0;
2108
2109 cacheParameters_l();
2110 sleepTime = idleSleepTime;
2111
2112 if (mType == MIXER) {
2113 sleepTimeShift = 0;
2114 }
2115
2116 CpuStats cpuStats;
2117 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2118
2119 acquireWakeLock();
2120
Glenn Kasten9e58b552013-01-18 15:09:48 -08002121 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2122 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2123 // and then that string will be logged at the next convenient opportunity.
2124 const char *logString = NULL;
2125
Eric Laurent664539d2013-09-23 18:24:31 -07002126 checkSilentMode_l();
2127
Eric Laurent81784c32012-11-19 14:55:58 -08002128 while (!exitPending())
2129 {
2130 cpuStats.sample(myName);
2131
2132 Vector< sp<EffectChain> > effectChains;
2133
2134 processConfigEvents();
2135
2136 { // scope for mLock
2137
2138 Mutex::Autolock _l(mLock);
2139
Glenn Kasten9e58b552013-01-18 15:09:48 -08002140 if (logString != NULL) {
2141 mNBLogWriter->logTimestamp();
2142 mNBLogWriter->log(logString);
2143 logString = NULL;
2144 }
2145
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002146 if (mLatchDValid) {
2147 mLatchQ = mLatchD;
2148 mLatchDValid = false;
2149 mLatchQValid = true;
2150 }
2151
Eric Laurent81784c32012-11-19 14:55:58 -08002152 if (checkForNewParameters_l()) {
2153 cacheParameters_l();
2154 }
2155
2156 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 if (mSignalPending) {
2158 // A signal was raised while we were unlocked
2159 mSignalPending = false;
2160 } else if (waitingAsyncCallback_l()) {
2161 if (exitPending()) {
2162 break;
2163 }
2164 releaseWakeLock_l();
2165 ALOGV("wait async completion");
2166 mWaitWorkCV.wait(mLock);
2167 ALOGV("async completion/wake");
2168 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002169 standbyTime = systemTime() + standbyDelay;
2170 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002171
2172 continue;
2173 }
2174 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175 isSuspended()) {
2176 // put audio hardware into standby after short delay
2177 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002178
2179 threadLoop_standby();
2180
2181 mStandby = true;
2182 }
2183
2184 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2185 // we're about to wait, flush the binder command buffer
2186 IPCThreadState::self()->flushCommands();
2187
2188 clearOutputTracks();
2189
2190 if (exitPending()) {
2191 break;
2192 }
2193
2194 releaseWakeLock_l();
2195 // wait until we have something to do...
2196 ALOGV("%s going to sleep", myName.string());
2197 mWaitWorkCV.wait(mLock);
2198 ALOGV("%s waking up", myName.string());
2199 acquireWakeLock_l();
2200
2201 mMixerStatus = MIXER_IDLE;
2202 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2203 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002205 checkSilentMode_l();
2206
2207 standbyTime = systemTime() + standbyDelay;
2208 sleepTime = idleSleepTime;
2209 if (mType == MIXER) {
2210 sleepTimeShift = 0;
2211 }
2212
2213 continue;
2214 }
2215 }
Eric Laurent81784c32012-11-19 14:55:58 -08002216 // mMixerStatusIgnoringFastTracks is also updated internally
2217 mMixerStatus = prepareTracks_l(&tracksToRemove);
2218
2219 // prevent any changes in effect chain list and in each effect chain
2220 // during mixing and effect process as the audio buffers could be deleted
2221 // or modified if an effect is created or deleted
2222 lockEffectChains_l(effectChains);
2223 }
2224
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225 if (mBytesRemaining == 0) {
2226 mCurrentWriteLength = 0;
2227 if (mMixerStatus == MIXER_TRACKS_READY) {
2228 // threadLoop_mix() sets mCurrentWriteLength
2229 threadLoop_mix();
2230 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2231 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2232 // threadLoop_sleepTime sets sleepTime to 0 if data
2233 // must be written to HAL
2234 threadLoop_sleepTime();
2235 if (sleepTime == 0) {
2236 mCurrentWriteLength = mixBufferSize;
2237 }
2238 }
2239 mBytesRemaining = mCurrentWriteLength;
2240 if (isSuspended()) {
2241 sleepTime = suspendSleepTimeUs();
2242 // simulate write to HAL when suspended
2243 mBytesWritten += mixBufferSize;
2244 mBytesRemaining = 0;
2245 }
Eric Laurent81784c32012-11-19 14:55:58 -08002246
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 // only process effects if we're going to write
2248 if (sleepTime == 0) {
2249 for (size_t i = 0; i < effectChains.size(); i ++) {
2250 effectChains[i]->process_l();
2251 }
Eric Laurent81784c32012-11-19 14:55:58 -08002252 }
2253 }
2254
2255 // enable changes in effect chain
2256 unlockEffectChains(effectChains);
2257
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258 if (!waitingAsyncCallback()) {
2259 // sleepTime == 0 means we must write to audio hardware
2260 if (sleepTime == 0) {
2261 if (mBytesRemaining) {
2262 ssize_t ret = threadLoop_write();
2263 if (ret < 0) {
2264 mBytesRemaining = 0;
2265 } else {
2266 mBytesWritten += ret;
2267 mBytesRemaining -= ret;
2268 }
2269 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2270 (mMixerStatus == MIXER_DRAIN_ALL)) {
2271 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002272 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273if (mType == MIXER) {
2274 // write blocked detection
2275 nsecs_t now = systemTime();
2276 nsecs_t delta = now - mLastWriteTime;
2277 if (!mStandby && delta > maxPeriod) {
2278 mNumDelayedWrites++;
2279 if ((now - lastWarning) > kWarningThrottleNs) {
2280 ATRACE_NAME("underrun");
2281 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2282 ns2ms(delta), mNumDelayedWrites, this);
2283 lastWarning = now;
2284 }
2285 }
Eric Laurent81784c32012-11-19 14:55:58 -08002286}
2287
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 mStandby = false;
2289 } else {
2290 usleep(sleepTime);
2291 }
Eric Laurent81784c32012-11-19 14:55:58 -08002292 }
2293
2294 // Finally let go of removed track(s), without the lock held
2295 // since we can't guarantee the destructors won't acquire that
2296 // same lock. This will also mutate and push a new fast mixer state.
2297 threadLoop_removeTracks(tracksToRemove);
2298 tracksToRemove.clear();
2299
2300 // FIXME I don't understand the need for this here;
2301 // it was in the original code but maybe the
2302 // assignment in saveOutputTracks() makes this unnecessary?
2303 clearOutputTracks();
2304
2305 // Effect chains will be actually deleted here if they were removed from
2306 // mEffectChains list during mixing or effects processing
2307 effectChains.clear();
2308
2309 // FIXME Note that the above .clear() is no longer necessary since effectChains
2310 // is now local to this block, but will keep it for now (at least until merge done).
2311 }
2312
Eric Laurentbfb1b832013-01-07 09:53:42 -08002313 threadLoop_exit();
2314
Eric Laurent81784c32012-11-19 14:55:58 -08002315 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002317 // put output stream into standby mode
2318 if (!mStandby) {
2319 mOutput->stream->common.standby(&mOutput->stream->common);
2320 }
2321 }
2322
2323 releaseWakeLock();
2324
2325 ALOGV("Thread %p type %d exiting", this, mType);
2326 return false;
2327}
2328
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329// removeTracks_l() must be called with ThreadBase::mLock held
2330void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2331{
2332 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002333 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334 for (size_t i=0 ; i<count ; i++) {
2335 const sp<Track>& track = tracksToRemove.itemAt(i);
2336 mActiveTracks.remove(track);
2337 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2338 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2339 if (chain != 0) {
2340 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2341 track->sessionId());
2342 chain->decActiveTrackCnt();
2343 }
2344 if (track->isTerminated()) {
2345 removeTrack_l(track);
2346 }
2347 }
2348 }
2349
2350}
Eric Laurent81784c32012-11-19 14:55:58 -08002351
Eric Laurentaccc1472013-09-20 09:36:34 -07002352status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2353{
2354 if (mNormalSink != 0) {
2355 return mNormalSink->getTimestamp(timestamp);
2356 }
2357 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2358 uint64_t position64;
2359 int ret = mOutput->stream->get_presentation_position(
2360 mOutput->stream, &position64, &timestamp.mTime);
2361 if (ret == 0) {
2362 timestamp.mPosition = (uint32_t)position64;
2363 return NO_ERROR;
2364 }
2365 }
2366 return INVALID_OPERATION;
2367}
Eric Laurent81784c32012-11-19 14:55:58 -08002368// ----------------------------------------------------------------------------
2369
2370AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2371 audio_io_handle_t id, audio_devices_t device, type_t type)
2372 : PlaybackThread(audioFlinger, output, id, device, type),
2373 // mAudioMixer below
2374 // mFastMixer below
2375 mFastMixerFutex(0)
2376 // mOutputSink below
2377 // mPipeSink below
2378 // mNormalSink below
2379{
2380 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002381 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002382 "mFrameCount=%d, mNormalFrameCount=%d",
2383 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2384 mNormalFrameCount);
2385 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2386
2387 // FIXME - Current mixer implementation only supports stereo output
2388 if (mChannelCount != FCC_2) {
2389 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2390 }
2391
2392 // create an NBAIO sink for the HAL output stream, and negotiate
2393 mOutputSink = new AudioStreamOutSink(output->stream);
2394 size_t numCounterOffers = 0;
2395 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2396 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2397 ALOG_ASSERT(index == 0);
2398
2399 // initialize fast mixer depending on configuration
2400 bool initFastMixer;
2401 switch (kUseFastMixer) {
2402 case FastMixer_Never:
2403 initFastMixer = false;
2404 break;
2405 case FastMixer_Always:
2406 initFastMixer = true;
2407 break;
2408 case FastMixer_Static:
2409 case FastMixer_Dynamic:
2410 initFastMixer = mFrameCount < mNormalFrameCount;
2411 break;
2412 }
2413 if (initFastMixer) {
2414
2415 // create a MonoPipe to connect our submix to FastMixer
2416 NBAIO_Format format = mOutputSink->format();
2417 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2418 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2419 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2420 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2421 const NBAIO_Format offers[1] = {format};
2422 size_t numCounterOffers = 0;
2423 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2424 ALOG_ASSERT(index == 0);
2425 monoPipe->setAvgFrames((mScreenState & 1) ?
2426 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2427 mPipeSink = monoPipe;
2428
Glenn Kasten46909e72013-02-26 09:20:22 -08002429#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002430 if (mTeeSinkOutputEnabled) {
2431 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2432 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2433 numCounterOffers = 0;
2434 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2435 ALOG_ASSERT(index == 0);
2436 mTeeSink = teeSink;
2437 PipeReader *teeSource = new PipeReader(*teeSink);
2438 numCounterOffers = 0;
2439 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2440 ALOG_ASSERT(index == 0);
2441 mTeeSource = teeSource;
2442 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002443#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002444
2445 // create fast mixer and configure it initially with just one fast track for our submix
2446 mFastMixer = new FastMixer();
2447 FastMixerStateQueue *sq = mFastMixer->sq();
2448#ifdef STATE_QUEUE_DUMP
2449 sq->setObserverDump(&mStateQueueObserverDump);
2450 sq->setMutatorDump(&mStateQueueMutatorDump);
2451#endif
2452 FastMixerState *state = sq->begin();
2453 FastTrack *fastTrack = &state->mFastTracks[0];
2454 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2455 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2456 fastTrack->mVolumeProvider = NULL;
2457 fastTrack->mGeneration++;
2458 state->mFastTracksGen++;
2459 state->mTrackMask = 1;
2460 // fast mixer will use the HAL output sink
2461 state->mOutputSink = mOutputSink.get();
2462 state->mOutputSinkGen++;
2463 state->mFrameCount = mFrameCount;
2464 state->mCommand = FastMixerState::COLD_IDLE;
2465 // already done in constructor initialization list
2466 //mFastMixerFutex = 0;
2467 state->mColdFutexAddr = &mFastMixerFutex;
2468 state->mColdGen++;
2469 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002470#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002471 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002472#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002473 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2474 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002475 sq->end();
2476 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2477
2478 // start the fast mixer
2479 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2480 pid_t tid = mFastMixer->getTid();
2481 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2482 if (err != 0) {
2483 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2484 kPriorityFastMixer, getpid_cached, tid, err);
2485 }
2486
2487#ifdef AUDIO_WATCHDOG
2488 // create and start the watchdog
2489 mAudioWatchdog = new AudioWatchdog();
2490 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2491 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2492 tid = mAudioWatchdog->getTid();
2493 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2494 if (err != 0) {
2495 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2496 kPriorityFastMixer, getpid_cached, tid, err);
2497 }
2498#endif
2499
2500 } else {
2501 mFastMixer = NULL;
2502 }
2503
2504 switch (kUseFastMixer) {
2505 case FastMixer_Never:
2506 case FastMixer_Dynamic:
2507 mNormalSink = mOutputSink;
2508 break;
2509 case FastMixer_Always:
2510 mNormalSink = mPipeSink;
2511 break;
2512 case FastMixer_Static:
2513 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2514 break;
2515 }
2516}
2517
2518AudioFlinger::MixerThread::~MixerThread()
2519{
2520 if (mFastMixer != NULL) {
2521 FastMixerStateQueue *sq = mFastMixer->sq();
2522 FastMixerState *state = sq->begin();
2523 if (state->mCommand == FastMixerState::COLD_IDLE) {
2524 int32_t old = android_atomic_inc(&mFastMixerFutex);
2525 if (old == -1) {
2526 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2527 }
2528 }
2529 state->mCommand = FastMixerState::EXIT;
2530 sq->end();
2531 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2532 mFastMixer->join();
2533 // Though the fast mixer thread has exited, it's state queue is still valid.
2534 // We'll use that extract the final state which contains one remaining fast track
2535 // corresponding to our sub-mix.
2536 state = sq->begin();
2537 ALOG_ASSERT(state->mTrackMask == 1);
2538 FastTrack *fastTrack = &state->mFastTracks[0];
2539 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2540 delete fastTrack->mBufferProvider;
2541 sq->end(false /*didModify*/);
2542 delete mFastMixer;
2543#ifdef AUDIO_WATCHDOG
2544 if (mAudioWatchdog != 0) {
2545 mAudioWatchdog->requestExit();
2546 mAudioWatchdog->requestExitAndWait();
2547 mAudioWatchdog.clear();
2548 }
2549#endif
2550 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002551 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002552 delete mAudioMixer;
2553}
2554
2555
2556uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2557{
2558 if (mFastMixer != NULL) {
2559 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2560 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2561 }
2562 return latency;
2563}
2564
2565
2566void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2567{
2568 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2569}
2570
Eric Laurentbfb1b832013-01-07 09:53:42 -08002571ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002572{
2573 // FIXME we should only do one push per cycle; confirm this is true
2574 // Start the fast mixer if it's not already running
2575 if (mFastMixer != NULL) {
2576 FastMixerStateQueue *sq = mFastMixer->sq();
2577 FastMixerState *state = sq->begin();
2578 if (state->mCommand != FastMixerState::MIX_WRITE &&
2579 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2580 if (state->mCommand == FastMixerState::COLD_IDLE) {
2581 int32_t old = android_atomic_inc(&mFastMixerFutex);
2582 if (old == -1) {
2583 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2584 }
2585#ifdef AUDIO_WATCHDOG
2586 if (mAudioWatchdog != 0) {
2587 mAudioWatchdog->resume();
2588 }
2589#endif
2590 }
2591 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002592 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2593 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002594 sq->end();
2595 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2596 if (kUseFastMixer == FastMixer_Dynamic) {
2597 mNormalSink = mPipeSink;
2598 }
2599 } else {
2600 sq->end(false /*didModify*/);
2601 }
2602 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002604}
2605
2606void AudioFlinger::MixerThread::threadLoop_standby()
2607{
2608 // Idle the fast mixer if it's currently running
2609 if (mFastMixer != NULL) {
2610 FastMixerStateQueue *sq = mFastMixer->sq();
2611 FastMixerState *state = sq->begin();
2612 if (!(state->mCommand & FastMixerState::IDLE)) {
2613 state->mCommand = FastMixerState::COLD_IDLE;
2614 state->mColdFutexAddr = &mFastMixerFutex;
2615 state->mColdGen++;
2616 mFastMixerFutex = 0;
2617 sq->end();
2618 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2619 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2620 if (kUseFastMixer == FastMixer_Dynamic) {
2621 mNormalSink = mOutputSink;
2622 }
2623#ifdef AUDIO_WATCHDOG
2624 if (mAudioWatchdog != 0) {
2625 mAudioWatchdog->pause();
2626 }
2627#endif
2628 } else {
2629 sq->end(false /*didModify*/);
2630 }
2631 }
2632 PlaybackThread::threadLoop_standby();
2633}
2634
Eric Laurentbfb1b832013-01-07 09:53:42 -08002635// Empty implementation for standard mixer
2636// Overridden for offloaded playback
2637void AudioFlinger::PlaybackThread::flushOutput_l()
2638{
2639}
2640
2641bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2642{
2643 return false;
2644}
2645
2646bool AudioFlinger::PlaybackThread::shouldStandby_l()
2647{
2648 return !mStandby;
2649}
2650
2651bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2652{
2653 Mutex::Autolock _l(mLock);
2654 return waitingAsyncCallback_l();
2655}
2656
Eric Laurent81784c32012-11-19 14:55:58 -08002657// shared by MIXER and DIRECT, overridden by DUPLICATING
2658void AudioFlinger::PlaybackThread::threadLoop_standby()
2659{
2660 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2661 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002663 // discard any pending drain or write ack by incrementing sequence
2664 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2665 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002667 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2668 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 }
Eric Laurent81784c32012-11-19 14:55:58 -08002670}
2671
2672void AudioFlinger::MixerThread::threadLoop_mix()
2673{
2674 // obtain the presentation timestamp of the next output buffer
2675 int64_t pts;
2676 status_t status = INVALID_OPERATION;
2677
2678 if (mNormalSink != 0) {
2679 status = mNormalSink->getNextWriteTimestamp(&pts);
2680 } else {
2681 status = mOutputSink->getNextWriteTimestamp(&pts);
2682 }
2683
2684 if (status != NO_ERROR) {
2685 pts = AudioBufferProvider::kInvalidPTS;
2686 }
2687
2688 // mix buffers...
2689 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002690 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002691 // increase sleep time progressively when application underrun condition clears.
2692 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2693 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2694 // such that we would underrun the audio HAL.
2695 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2696 sleepTimeShift--;
2697 }
2698 sleepTime = 0;
2699 standbyTime = systemTime() + standbyDelay;
2700 //TODO: delay standby when effects have a tail
2701}
2702
2703void AudioFlinger::MixerThread::threadLoop_sleepTime()
2704{
2705 // If no tracks are ready, sleep once for the duration of an output
2706 // buffer size, then write 0s to the output
2707 if (sleepTime == 0) {
2708 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2709 sleepTime = activeSleepTime >> sleepTimeShift;
2710 if (sleepTime < kMinThreadSleepTimeUs) {
2711 sleepTime = kMinThreadSleepTimeUs;
2712 }
2713 // reduce sleep time in case of consecutive application underruns to avoid
2714 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2715 // duration we would end up writing less data than needed by the audio HAL if
2716 // the condition persists.
2717 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2718 sleepTimeShift++;
2719 }
2720 } else {
2721 sleepTime = idleSleepTime;
2722 }
2723 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002724 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002725 sleepTime = 0;
2726 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2727 "anticipated start");
2728 }
2729 // TODO add standby time extension fct of effect tail
2730}
2731
2732// prepareTracks_l() must be called with ThreadBase::mLock held
2733AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2734 Vector< sp<Track> > *tracksToRemove)
2735{
2736
2737 mixer_state mixerStatus = MIXER_IDLE;
2738 // find out which tracks need to be processed
2739 size_t count = mActiveTracks.size();
2740 size_t mixedTracks = 0;
2741 size_t tracksWithEffect = 0;
2742 // counts only _active_ fast tracks
2743 size_t fastTracks = 0;
2744 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2745
2746 float masterVolume = mMasterVolume;
2747 bool masterMute = mMasterMute;
2748
2749 if (masterMute) {
2750 masterVolume = 0;
2751 }
2752 // Delegate master volume control to effect in output mix effect chain if needed
2753 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2754 if (chain != 0) {
2755 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2756 chain->setVolume_l(&v, &v);
2757 masterVolume = (float)((v + (1 << 23)) >> 24);
2758 chain.clear();
2759 }
2760
2761 // prepare a new state to push
2762 FastMixerStateQueue *sq = NULL;
2763 FastMixerState *state = NULL;
2764 bool didModify = false;
2765 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2766 if (mFastMixer != NULL) {
2767 sq = mFastMixer->sq();
2768 state = sq->begin();
2769 }
2770
2771 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002772 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002773 if (t == 0) {
2774 continue;
2775 }
2776
2777 // this const just means the local variable doesn't change
2778 Track* const track = t.get();
2779
2780 // process fast tracks
2781 if (track->isFastTrack()) {
2782
2783 // It's theoretically possible (though unlikely) for a fast track to be created
2784 // and then removed within the same normal mix cycle. This is not a problem, as
2785 // the track never becomes active so it's fast mixer slot is never touched.
2786 // The converse, of removing an (active) track and then creating a new track
2787 // at the identical fast mixer slot within the same normal mix cycle,
2788 // is impossible because the slot isn't marked available until the end of each cycle.
2789 int j = track->mFastIndex;
2790 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2791 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2792 FastTrack *fastTrack = &state->mFastTracks[j];
2793
2794 // Determine whether the track is currently in underrun condition,
2795 // and whether it had a recent underrun.
2796 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2797 FastTrackUnderruns underruns = ftDump->mUnderruns;
2798 uint32_t recentFull = (underruns.mBitFields.mFull -
2799 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2800 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2801 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2802 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2803 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2804 uint32_t recentUnderruns = recentPartial + recentEmpty;
2805 track->mObservedUnderruns = underruns;
2806 // don't count underruns that occur while stopping or pausing
2807 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002808 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2809 recentUnderruns > 0) {
2810 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2811 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813
2814 // This is similar to the state machine for normal tracks,
2815 // with a few modifications for fast tracks.
2816 bool isActive = true;
2817 switch (track->mState) {
2818 case TrackBase::STOPPING_1:
2819 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002821 track->mState = TrackBase::STOPPING_2;
2822 }
2823 break;
2824 case TrackBase::PAUSING:
2825 // ramp down is not yet implemented
2826 track->setPaused();
2827 break;
2828 case TrackBase::RESUMING:
2829 // ramp up is not yet implemented
2830 track->mState = TrackBase::ACTIVE;
2831 break;
2832 case TrackBase::ACTIVE:
2833 if (recentFull > 0 || recentPartial > 0) {
2834 // track has provided at least some frames recently: reset retry count
2835 track->mRetryCount = kMaxTrackRetries;
2836 }
2837 if (recentUnderruns == 0) {
2838 // no recent underruns: stay active
2839 break;
2840 }
2841 // there has recently been an underrun of some kind
2842 if (track->sharedBuffer() == 0) {
2843 // were any of the recent underruns "empty" (no frames available)?
2844 if (recentEmpty == 0) {
2845 // no, then ignore the partial underruns as they are allowed indefinitely
2846 break;
2847 }
2848 // there has recently been an "empty" underrun: decrement the retry counter
2849 if (--(track->mRetryCount) > 0) {
2850 break;
2851 }
2852 // indicate to client process that the track was disabled because of underrun;
2853 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002854 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002855 // remove from active list, but state remains ACTIVE [confusing but true]
2856 isActive = false;
2857 break;
2858 }
2859 // fall through
2860 case TrackBase::STOPPING_2:
2861 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002862 case TrackBase::STOPPED:
2863 case TrackBase::FLUSHED: // flush() while active
2864 // Check for presentation complete if track is inactive
2865 // We have consumed all the buffers of this track.
2866 // This would be incomplete if we auto-paused on underrun
2867 {
2868 size_t audioHALFrames =
2869 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2870 size_t framesWritten = mBytesWritten / mFrameSize;
2871 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2872 // track stays in active list until presentation is complete
2873 break;
2874 }
2875 }
2876 if (track->isStopping_2()) {
2877 track->mState = TrackBase::STOPPED;
2878 }
2879 if (track->isStopped()) {
2880 // Can't reset directly, as fast mixer is still polling this track
2881 // track->reset();
2882 // So instead mark this track as needing to be reset after push with ack
2883 resetMask |= 1 << i;
2884 }
2885 isActive = false;
2886 break;
2887 case TrackBase::IDLE:
2888 default:
2889 LOG_FATAL("unexpected track state %d", track->mState);
2890 }
2891
2892 if (isActive) {
2893 // was it previously inactive?
2894 if (!(state->mTrackMask & (1 << j))) {
2895 ExtendedAudioBufferProvider *eabp = track;
2896 VolumeProvider *vp = track;
2897 fastTrack->mBufferProvider = eabp;
2898 fastTrack->mVolumeProvider = vp;
2899 fastTrack->mSampleRate = track->mSampleRate;
2900 fastTrack->mChannelMask = track->mChannelMask;
2901 fastTrack->mGeneration++;
2902 state->mTrackMask |= 1 << j;
2903 didModify = true;
2904 // no acknowledgement required for newly active tracks
2905 }
2906 // cache the combined master volume and stream type volume for fast mixer; this
2907 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002908 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002909 ++fastTracks;
2910 } else {
2911 // was it previously active?
2912 if (state->mTrackMask & (1 << j)) {
2913 fastTrack->mBufferProvider = NULL;
2914 fastTrack->mGeneration++;
2915 state->mTrackMask &= ~(1 << j);
2916 didModify = true;
2917 // If any fast tracks were removed, we must wait for acknowledgement
2918 // because we're about to decrement the last sp<> on those tracks.
2919 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2920 } else {
2921 LOG_FATAL("fast track %d should have been active", j);
2922 }
2923 tracksToRemove->add(track);
2924 // Avoids a misleading display in dumpsys
2925 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2926 }
2927 continue;
2928 }
2929
2930 { // local variable scope to avoid goto warning
2931
2932 audio_track_cblk_t* cblk = track->cblk();
2933
2934 // The first time a track is added we wait
2935 // for all its buffers to be filled before processing it
2936 int name = track->name();
2937 // make sure that we have enough frames to mix one full buffer.
2938 // enforce this condition only once to enable draining the buffer in case the client
2939 // app does not call stop() and relies on underrun to stop:
2940 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2941 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002942 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002943 uint32_t sr = track->sampleRate();
2944 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002945 desiredFrames = mNormalFrameCount;
2946 } else {
2947 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002948 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002949 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002950 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002951 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2952 // the minimum track buffer size is normally twice the number of frames necessary
2953 // to fill one buffer and the resampler should not leave more than one buffer worth
2954 // of unreleased frames after each pass, but just in case...
2955 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2956 }
Eric Laurent81784c32012-11-19 14:55:58 -08002957 uint32_t minFrames = 1;
2958 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2959 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002960 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002961 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002962 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2963 size_t framesReady;
2964 if (track->sharedBuffer() == 0) {
2965 framesReady = track->framesReady();
2966 } else if (track->isStopped()) {
2967 framesReady = 0;
2968 } else {
2969 framesReady = 1;
2970 }
2971 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002972 !track->isPaused() && !track->isTerminated())
2973 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002974 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002975
2976 mixedTracks++;
2977
2978 // track->mainBuffer() != mMixBuffer means there is an effect chain
2979 // connected to the track
2980 chain.clear();
2981 if (track->mainBuffer() != mMixBuffer) {
2982 chain = getEffectChain_l(track->sessionId());
2983 // Delegate volume control to effect in track effect chain if needed
2984 if (chain != 0) {
2985 tracksWithEffect++;
2986 } else {
2987 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2988 "session %d",
2989 name, track->sessionId());
2990 }
2991 }
2992
2993
2994 int param = AudioMixer::VOLUME;
2995 if (track->mFillingUpStatus == Track::FS_FILLED) {
2996 // no ramp for the first volume setting
2997 track->mFillingUpStatus = Track::FS_ACTIVE;
2998 if (track->mState == TrackBase::RESUMING) {
2999 track->mState = TrackBase::ACTIVE;
3000 param = AudioMixer::RAMP_VOLUME;
3001 }
3002 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003003 // FIXME should not make a decision based on mServer
3004 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003005 // If the track is stopped before the first frame was mixed,
3006 // do not apply ramp
3007 param = AudioMixer::RAMP_VOLUME;
3008 }
3009
3010 // compute volume for this track
3011 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003012 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003013 vl = vr = va = 0;
3014 if (track->isPausing()) {
3015 track->setPaused();
3016 }
3017 } else {
3018
3019 // read original volumes with volume control
3020 float typeVolume = mStreamTypes[track->streamType()].volume;
3021 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003022 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003023 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003024 vl = vlr & 0xFFFF;
3025 vr = vlr >> 16;
3026 // track volumes come from shared memory, so can't be trusted and must be clamped
3027 if (vl > MAX_GAIN_INT) {
3028 ALOGV("Track left volume out of range: %04X", vl);
3029 vl = MAX_GAIN_INT;
3030 }
3031 if (vr > MAX_GAIN_INT) {
3032 ALOGV("Track right volume out of range: %04X", vr);
3033 vr = MAX_GAIN_INT;
3034 }
3035 // now apply the master volume and stream type volume
3036 vl = (uint32_t)(v * vl) << 12;
3037 vr = (uint32_t)(v * vr) << 12;
3038 // assuming master volume and stream type volume each go up to 1.0,
3039 // vl and vr are now in 8.24 format
3040
Glenn Kastene3aa6592012-12-04 12:22:46 -08003041 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003042 // send level comes from shared memory and so may be corrupt
3043 if (sendLevel > MAX_GAIN_INT) {
3044 ALOGV("Track send level out of range: %04X", sendLevel);
3045 sendLevel = MAX_GAIN_INT;
3046 }
3047 va = (uint32_t)(v * sendLevel);
3048 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049
Eric Laurent81784c32012-11-19 14:55:58 -08003050 // Delegate volume control to effect in track effect chain if needed
3051 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3052 // Do not ramp volume if volume is controlled by effect
3053 param = AudioMixer::VOLUME;
3054 track->mHasVolumeController = true;
3055 } else {
3056 // force no volume ramp when volume controller was just disabled or removed
3057 // from effect chain to avoid volume spike
3058 if (track->mHasVolumeController) {
3059 param = AudioMixer::VOLUME;
3060 }
3061 track->mHasVolumeController = false;
3062 }
3063
3064 // Convert volumes from 8.24 to 4.12 format
3065 // This additional clamping is needed in case chain->setVolume_l() overshot
3066 vl = (vl + (1 << 11)) >> 12;
3067 if (vl > MAX_GAIN_INT) {
3068 vl = MAX_GAIN_INT;
3069 }
3070 vr = (vr + (1 << 11)) >> 12;
3071 if (vr > MAX_GAIN_INT) {
3072 vr = MAX_GAIN_INT;
3073 }
3074
3075 if (va > MAX_GAIN_INT) {
3076 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3077 }
3078
3079 // XXX: these things DON'T need to be done each time
3080 mAudioMixer->setBufferProvider(name, track);
3081 mAudioMixer->enable(name);
3082
3083 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3084 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3085 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3086 mAudioMixer->setParameter(
3087 name,
3088 AudioMixer::TRACK,
3089 AudioMixer::FORMAT, (void *)track->format());
3090 mAudioMixer->setParameter(
3091 name,
3092 AudioMixer::TRACK,
3093 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003094 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3095 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003096 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003097 if (reqSampleRate == 0) {
3098 reqSampleRate = mSampleRate;
3099 } else if (reqSampleRate > maxSampleRate) {
3100 reqSampleRate = maxSampleRate;
3101 }
Eric Laurent81784c32012-11-19 14:55:58 -08003102 mAudioMixer->setParameter(
3103 name,
3104 AudioMixer::RESAMPLE,
3105 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003106 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003107 mAudioMixer->setParameter(
3108 name,
3109 AudioMixer::TRACK,
3110 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3111 mAudioMixer->setParameter(
3112 name,
3113 AudioMixer::TRACK,
3114 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3115
3116 // reset retry count
3117 track->mRetryCount = kMaxTrackRetries;
3118
3119 // If one track is ready, set the mixer ready if:
3120 // - the mixer was not ready during previous round OR
3121 // - no other track is not ready
3122 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3123 mixerStatus != MIXER_TRACKS_ENABLED) {
3124 mixerStatus = MIXER_TRACKS_READY;
3125 }
3126 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003127 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003128 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003129 }
Eric Laurent81784c32012-11-19 14:55:58 -08003130 // clear effect chain input buffer if an active track underruns to avoid sending
3131 // previous audio buffer again to effects
3132 chain = getEffectChain_l(track->sessionId());
3133 if (chain != 0) {
3134 chain->clearInputBuffer();
3135 }
3136
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003137 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003138 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3139 track->isStopped() || track->isPaused()) {
3140 // We have consumed all the buffers of this track.
3141 // Remove it from the list of active tracks.
3142 // TODO: use actual buffer filling status instead of latency when available from
3143 // audio HAL
3144 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3145 size_t framesWritten = mBytesWritten / mFrameSize;
3146 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3147 if (track->isStopped()) {
3148 track->reset();
3149 }
3150 tracksToRemove->add(track);
3151 }
3152 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003153 // No buffers for this track. Give it a few chances to
3154 // fill a buffer, then remove it from active list.
3155 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003156 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003157 tracksToRemove->add(track);
3158 // indicate to client process that the track was disabled because of underrun;
3159 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003160 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003161 // If one track is not ready, mark the mixer also not ready if:
3162 // - the mixer was ready during previous round OR
3163 // - no other track is ready
3164 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3165 mixerStatus != MIXER_TRACKS_READY) {
3166 mixerStatus = MIXER_TRACKS_ENABLED;
3167 }
3168 }
3169 mAudioMixer->disable(name);
3170 }
3171
3172 } // local variable scope to avoid goto warning
3173track_is_ready: ;
3174
3175 }
3176
3177 // Push the new FastMixer state if necessary
3178 bool pauseAudioWatchdog = false;
3179 if (didModify) {
3180 state->mFastTracksGen++;
3181 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3182 if (kUseFastMixer == FastMixer_Dynamic &&
3183 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3184 state->mCommand = FastMixerState::COLD_IDLE;
3185 state->mColdFutexAddr = &mFastMixerFutex;
3186 state->mColdGen++;
3187 mFastMixerFutex = 0;
3188 if (kUseFastMixer == FastMixer_Dynamic) {
3189 mNormalSink = mOutputSink;
3190 }
3191 // If we go into cold idle, need to wait for acknowledgement
3192 // so that fast mixer stops doing I/O.
3193 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3194 pauseAudioWatchdog = true;
3195 }
Eric Laurent81784c32012-11-19 14:55:58 -08003196 }
3197 if (sq != NULL) {
3198 sq->end(didModify);
3199 sq->push(block);
3200 }
3201#ifdef AUDIO_WATCHDOG
3202 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3203 mAudioWatchdog->pause();
3204 }
3205#endif
3206
3207 // Now perform the deferred reset on fast tracks that have stopped
3208 while (resetMask != 0) {
3209 size_t i = __builtin_ctz(resetMask);
3210 ALOG_ASSERT(i < count);
3211 resetMask &= ~(1 << i);
3212 sp<Track> t = mActiveTracks[i].promote();
3213 if (t == 0) {
3214 continue;
3215 }
3216 Track* track = t.get();
3217 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3218 track->reset();
3219 }
3220
3221 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003223
3224 // mix buffer must be cleared if all tracks are connected to an
3225 // effect chain as in this case the mixer will not write to
3226 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3228 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003229 // FIXME as a performance optimization, should remember previous zero status
3230 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3231 }
3232
3233 // if any fast tracks, then status is ready
3234 mMixerStatusIgnoringFastTracks = mixerStatus;
3235 if (fastTracks > 0) {
3236 mixerStatus = MIXER_TRACKS_READY;
3237 }
3238 return mixerStatus;
3239}
3240
3241// getTrackName_l() must be called with ThreadBase::mLock held
3242int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3243{
3244 return mAudioMixer->getTrackName(channelMask, sessionId);
3245}
3246
3247// deleteTrackName_l() must be called with ThreadBase::mLock held
3248void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3249{
3250 ALOGV("remove track (%d) and delete from mixer", name);
3251 mAudioMixer->deleteTrackName(name);
3252}
3253
3254// checkForNewParameters_l() must be called with ThreadBase::mLock held
3255bool AudioFlinger::MixerThread::checkForNewParameters_l()
3256{
3257 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3258 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3259 bool reconfig = false;
3260
3261 while (!mNewParameters.isEmpty()) {
3262
3263 if (mFastMixer != NULL) {
3264 FastMixerStateQueue *sq = mFastMixer->sq();
3265 FastMixerState *state = sq->begin();
3266 if (!(state->mCommand & FastMixerState::IDLE)) {
3267 previousCommand = state->mCommand;
3268 state->mCommand = FastMixerState::HOT_IDLE;
3269 sq->end();
3270 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3271 } else {
3272 sq->end(false /*didModify*/);
3273 }
3274 }
3275
3276 status_t status = NO_ERROR;
3277 String8 keyValuePair = mNewParameters[0];
3278 AudioParameter param = AudioParameter(keyValuePair);
3279 int value;
3280
3281 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3282 reconfig = true;
3283 }
3284 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3285 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3286 status = BAD_VALUE;
3287 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003288 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003289 reconfig = true;
3290 }
3291 }
3292 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003293 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003294 status = BAD_VALUE;
3295 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003296 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003297 reconfig = true;
3298 }
3299 }
3300 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3301 // do not accept frame count changes if tracks are open as the track buffer
3302 // size depends on frame count and correct behavior would not be guaranteed
3303 // if frame count is changed after track creation
3304 if (!mTracks.isEmpty()) {
3305 status = INVALID_OPERATION;
3306 } else {
3307 reconfig = true;
3308 }
3309 }
3310 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3311#ifdef ADD_BATTERY_DATA
3312 // when changing the audio output device, call addBatteryData to notify
3313 // the change
3314 if (mOutDevice != value) {
3315 uint32_t params = 0;
3316 // check whether speaker is on
3317 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3318 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3319 }
3320
3321 audio_devices_t deviceWithoutSpeaker
3322 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3323 // check if any other device (except speaker) is on
3324 if (value & deviceWithoutSpeaker ) {
3325 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3326 }
3327
3328 if (params != 0) {
3329 addBatteryData(params);
3330 }
3331 }
3332#endif
3333
3334 // forward device change to effects that have requested to be
3335 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003336 if (value != AUDIO_DEVICE_NONE) {
3337 mOutDevice = value;
3338 for (size_t i = 0; i < mEffectChains.size(); i++) {
3339 mEffectChains[i]->setDevice_l(mOutDevice);
3340 }
Eric Laurent81784c32012-11-19 14:55:58 -08003341 }
3342 }
3343
3344 if (status == NO_ERROR) {
3345 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3346 keyValuePair.string());
3347 if (!mStandby && status == INVALID_OPERATION) {
3348 mOutput->stream->common.standby(&mOutput->stream->common);
3349 mStandby = true;
3350 mBytesWritten = 0;
3351 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3352 keyValuePair.string());
3353 }
3354 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003355 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003356 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003357 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3358 for (size_t i = 0; i < mTracks.size() ; i++) {
3359 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3360 if (name < 0) {
3361 break;
3362 }
3363 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3366 }
3367 }
3368
3369 mNewParameters.removeAt(0);
3370
3371 mParamStatus = status;
3372 mParamCond.signal();
3373 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3374 // already timed out waiting for the status and will never signal the condition.
3375 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3376 }
3377
3378 if (!(previousCommand & FastMixerState::IDLE)) {
3379 ALOG_ASSERT(mFastMixer != NULL);
3380 FastMixerStateQueue *sq = mFastMixer->sq();
3381 FastMixerState *state = sq->begin();
3382 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3383 state->mCommand = previousCommand;
3384 sq->end();
3385 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3386 }
3387
3388 return reconfig;
3389}
3390
3391
3392void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3393{
3394 const size_t SIZE = 256;
3395 char buffer[SIZE];
3396 String8 result;
3397
3398 PlaybackThread::dumpInternals(fd, args);
3399
3400 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3401 result.append(buffer);
3402 write(fd, result.string(), result.size());
3403
3404 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003405 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003406 copy.dump(fd);
3407
3408#ifdef STATE_QUEUE_DUMP
3409 // Similar for state queue
3410 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3411 observerCopy.dump(fd);
3412 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3413 mutatorCopy.dump(fd);
3414#endif
3415
Glenn Kasten46909e72013-02-26 09:20:22 -08003416#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003417 // Write the tee output to a .wav file
3418 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003419#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003420
3421#ifdef AUDIO_WATCHDOG
3422 if (mAudioWatchdog != 0) {
3423 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3424 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3425 wdCopy.dump(fd);
3426 }
3427#endif
3428}
3429
3430uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3431{
3432 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3433}
3434
3435uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3436{
3437 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3438}
3439
3440void AudioFlinger::MixerThread::cacheParameters_l()
3441{
3442 PlaybackThread::cacheParameters_l();
3443
3444 // FIXME: Relaxed timing because of a certain device that can't meet latency
3445 // Should be reduced to 2x after the vendor fixes the driver issue
3446 // increase threshold again due to low power audio mode. The way this warning
3447 // threshold is calculated and its usefulness should be reconsidered anyway.
3448 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3449}
3450
3451// ----------------------------------------------------------------------------
3452
3453AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3454 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3455 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3456 // mLeftVolFloat, mRightVolFloat
3457{
3458}
3459
Eric Laurentbfb1b832013-01-07 09:53:42 -08003460AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3461 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3462 ThreadBase::type_t type)
3463 : PlaybackThread(audioFlinger, output, id, device, type)
3464 // mLeftVolFloat, mRightVolFloat
3465{
3466}
3467
Eric Laurent81784c32012-11-19 14:55:58 -08003468AudioFlinger::DirectOutputThread::~DirectOutputThread()
3469{
3470}
3471
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3473{
3474 audio_track_cblk_t* cblk = track->cblk();
3475 float left, right;
3476
3477 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3478 left = right = 0;
3479 } else {
3480 float typeVolume = mStreamTypes[track->streamType()].volume;
3481 float v = mMasterVolume * typeVolume;
3482 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3483 uint32_t vlr = proxy->getVolumeLR();
3484 float v_clamped = v * (vlr & 0xFFFF);
3485 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3486 left = v_clamped/MAX_GAIN;
3487 v_clamped = v * (vlr >> 16);
3488 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3489 right = v_clamped/MAX_GAIN;
3490 }
3491
3492 if (lastTrack) {
3493 if (left != mLeftVolFloat || right != mRightVolFloat) {
3494 mLeftVolFloat = left;
3495 mRightVolFloat = right;
3496
3497 // Convert volumes from float to 8.24
3498 uint32_t vl = (uint32_t)(left * (1 << 24));
3499 uint32_t vr = (uint32_t)(right * (1 << 24));
3500
3501 // Delegate volume control to effect in track effect chain if needed
3502 // only one effect chain can be present on DirectOutputThread, so if
3503 // there is one, the track is connected to it
3504 if (!mEffectChains.isEmpty()) {
3505 mEffectChains[0]->setVolume_l(&vl, &vr);
3506 left = (float)vl / (1 << 24);
3507 right = (float)vr / (1 << 24);
3508 }
3509 if (mOutput->stream->set_volume) {
3510 mOutput->stream->set_volume(mOutput->stream, left, right);
3511 }
3512 }
3513 }
3514}
3515
3516
Eric Laurent81784c32012-11-19 14:55:58 -08003517AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3518 Vector< sp<Track> > *tracksToRemove
3519)
3520{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003521 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003522 mixer_state mixerStatus = MIXER_IDLE;
3523
3524 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003525 for (size_t i = 0; i < count; i++) {
3526 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003527 // The track died recently
3528 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003529 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003530 }
3531
3532 Track* const track = t.get();
3533 audio_track_cblk_t* cblk = track->cblk();
3534
3535 // The first time a track is added we wait
3536 // for all its buffers to be filled before processing it
3537 uint32_t minFrames;
3538 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3539 minFrames = mNormalFrameCount;
3540 } else {
3541 minFrames = 1;
3542 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003543 // Only consider last track started for volume and mixer state control.
3544 // This is the last entry in mActiveTracks unless a track underruns.
3545 // As we only care about the transition phase between two tracks on a
3546 // direct output, it is not a problem to ignore the underrun case.
3547 bool last = (i == (count - 1));
3548
Eric Laurent81784c32012-11-19 14:55:58 -08003549 if ((track->framesReady() >= minFrames) && track->isReady() &&
3550 !track->isPaused() && !track->isTerminated())
3551 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003552 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003553
3554 if (track->mFillingUpStatus == Track::FS_FILLED) {
3555 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003556 // make sure processVolume_l() will apply new volume even if 0
3557 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003558 if (track->mState == TrackBase::RESUMING) {
3559 track->mState = TrackBase::ACTIVE;
3560 }
3561 }
3562
3563 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564 processVolume_l(track, last);
3565 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003566 // reset retry count
3567 track->mRetryCount = kMaxTrackRetriesDirect;
3568 mActiveTrack = t;
3569 mixerStatus = MIXER_TRACKS_READY;
3570 }
Eric Laurent81784c32012-11-19 14:55:58 -08003571 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003572 // clear effect chain input buffer if the last active track started underruns
3573 // to avoid sending previous audio buffer again to effects
3574 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003575 mEffectChains[0]->clearInputBuffer();
3576 }
3577
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003578 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003579 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3580 track->isStopped() || track->isPaused()) {
3581 // We have consumed all the buffers of this track.
3582 // Remove it from the list of active tracks.
3583 // TODO: implement behavior for compressed audio
3584 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3585 size_t framesWritten = mBytesWritten / mFrameSize;
3586 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3587 if (track->isStopped()) {
3588 track->reset();
3589 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003590 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003591 }
3592 } else {
3593 // No buffers for this track. Give it a few chances to
3594 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003595 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003596 if (--(track->mRetryCount) <= 0) {
3597 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003598 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003600 mixerStatus = MIXER_TRACKS_ENABLED;
3601 }
3602 }
3603 }
3604 }
3605
Eric Laurent81784c32012-11-19 14:55:58 -08003606 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003608
3609 return mixerStatus;
3610}
3611
3612void AudioFlinger::DirectOutputThread::threadLoop_mix()
3613{
Eric Laurent81784c32012-11-19 14:55:58 -08003614 size_t frameCount = mFrameCount;
3615 int8_t *curBuf = (int8_t *)mMixBuffer;
3616 // output audio to hardware
3617 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003618 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003619 buffer.frameCount = frameCount;
3620 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003621 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003622 memset(curBuf, 0, frameCount * mFrameSize);
3623 break;
3624 }
3625 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3626 frameCount -= buffer.frameCount;
3627 curBuf += buffer.frameCount * mFrameSize;
3628 mActiveTrack->releaseBuffer(&buffer);
3629 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003630 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003631 sleepTime = 0;
3632 standbyTime = systemTime() + standbyDelay;
3633 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003634}
3635
3636void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3637{
3638 if (sleepTime == 0) {
3639 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3640 sleepTime = activeSleepTime;
3641 } else {
3642 sleepTime = idleSleepTime;
3643 }
3644 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3645 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3646 sleepTime = 0;
3647 }
3648}
3649
3650// getTrackName_l() must be called with ThreadBase::mLock held
3651int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3652 int sessionId)
3653{
3654 return 0;
3655}
3656
3657// deleteTrackName_l() must be called with ThreadBase::mLock held
3658void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3659{
3660}
3661
3662// checkForNewParameters_l() must be called with ThreadBase::mLock held
3663bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3664{
3665 bool reconfig = false;
3666
3667 while (!mNewParameters.isEmpty()) {
3668 status_t status = NO_ERROR;
3669 String8 keyValuePair = mNewParameters[0];
3670 AudioParameter param = AudioParameter(keyValuePair);
3671 int value;
3672
3673 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3674 // do not accept frame count changes if tracks are open as the track buffer
3675 // size depends on frame count and correct behavior would not be garantied
3676 // if frame count is changed after track creation
3677 if (!mTracks.isEmpty()) {
3678 status = INVALID_OPERATION;
3679 } else {
3680 reconfig = true;
3681 }
3682 }
3683 if (status == NO_ERROR) {
3684 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3685 keyValuePair.string());
3686 if (!mStandby && status == INVALID_OPERATION) {
3687 mOutput->stream->common.standby(&mOutput->stream->common);
3688 mStandby = true;
3689 mBytesWritten = 0;
3690 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3691 keyValuePair.string());
3692 }
3693 if (status == NO_ERROR && reconfig) {
3694 readOutputParameters();
3695 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3696 }
3697 }
3698
3699 mNewParameters.removeAt(0);
3700
3701 mParamStatus = status;
3702 mParamCond.signal();
3703 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3704 // already timed out waiting for the status and will never signal the condition.
3705 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3706 }
3707 return reconfig;
3708}
3709
3710uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3711{
3712 uint32_t time;
3713 if (audio_is_linear_pcm(mFormat)) {
3714 time = PlaybackThread::activeSleepTimeUs();
3715 } else {
3716 time = 10000;
3717 }
3718 return time;
3719}
3720
3721uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3722{
3723 uint32_t time;
3724 if (audio_is_linear_pcm(mFormat)) {
3725 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3726 } else {
3727 time = 10000;
3728 }
3729 return time;
3730}
3731
3732uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3733{
3734 uint32_t time;
3735 if (audio_is_linear_pcm(mFormat)) {
3736 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3737 } else {
3738 time = 10000;
3739 }
3740 return time;
3741}
3742
3743void AudioFlinger::DirectOutputThread::cacheParameters_l()
3744{
3745 PlaybackThread::cacheParameters_l();
3746
3747 // use shorter standby delay as on normal output to release
3748 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003749 if (audio_is_linear_pcm(mFormat)) {
3750 standbyDelay = microseconds(activeSleepTime*2);
3751 } else {
3752 standbyDelay = kOffloadStandbyDelayNs;
3753 }
Eric Laurent81784c32012-11-19 14:55:58 -08003754}
3755
3756// ----------------------------------------------------------------------------
3757
Eric Laurentbfb1b832013-01-07 09:53:42 -08003758AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3759 const sp<AudioFlinger::OffloadThread>& offloadThread)
3760 : Thread(false /*canCallJava*/),
3761 mOffloadThread(offloadThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003762 mWriteAckSequence(0),
3763 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003764{
3765}
3766
3767AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3768{
3769}
3770
3771void AudioFlinger::AsyncCallbackThread::onFirstRef()
3772{
3773 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3774}
3775
3776bool AudioFlinger::AsyncCallbackThread::threadLoop()
3777{
3778 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003779 uint32_t writeAckSequence;
3780 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003781
3782 {
3783 Mutex::Autolock _l(mLock);
3784 mWaitWorkCV.wait(mLock);
3785 if (exitPending()) {
3786 break;
3787 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003788 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3789 mWriteAckSequence, mDrainSequence);
3790 writeAckSequence = mWriteAckSequence;
3791 mWriteAckSequence &= ~1;
3792 drainSequence = mDrainSequence;
3793 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003794 }
3795 {
3796 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3797 if (offloadThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003798 if (writeAckSequence & 1) {
3799 offloadThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003801 if (drainSequence & 1) {
3802 offloadThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003803 }
3804 }
3805 }
3806 }
3807 return false;
3808}
3809
3810void AudioFlinger::AsyncCallbackThread::exit()
3811{
3812 ALOGV("AsyncCallbackThread::exit");
3813 Mutex::Autolock _l(mLock);
3814 requestExit();
3815 mWaitWorkCV.broadcast();
3816}
3817
Eric Laurent3b4529e2013-09-05 18:09:19 -07003818void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819{
3820 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003821 // bit 0 is cleared
3822 mWriteAckSequence = sequence << 1;
3823}
3824
3825void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3826{
3827 Mutex::Autolock _l(mLock);
3828 // ignore unexpected callbacks
3829 if (mWriteAckSequence & 2) {
3830 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831 mWaitWorkCV.signal();
3832 }
3833}
3834
Eric Laurent3b4529e2013-09-05 18:09:19 -07003835void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003836{
3837 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003838 // bit 0 is cleared
3839 mDrainSequence = sequence << 1;
3840}
3841
3842void AudioFlinger::AsyncCallbackThread::resetDraining()
3843{
3844 Mutex::Autolock _l(mLock);
3845 // ignore unexpected callbacks
3846 if (mDrainSequence & 2) {
3847 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003848 mWaitWorkCV.signal();
3849 }
3850}
3851
3852
3853// ----------------------------------------------------------------------------
3854AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3855 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3856 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3857 mHwPaused(false),
3858 mPausedBytesRemaining(0)
3859{
3860 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3861}
3862
3863AudioFlinger::OffloadThread::~OffloadThread()
3864{
3865 mPreviousTrack.clear();
3866}
3867
3868void AudioFlinger::OffloadThread::threadLoop_exit()
3869{
3870 if (mFlushPending || mHwPaused) {
3871 // If a flush is pending or track was paused, just discard buffered data
3872 flushHw_l();
3873 } else {
3874 mMixerStatus = MIXER_DRAIN_ALL;
3875 threadLoop_drain();
3876 }
3877 mCallbackThread->exit();
3878 PlaybackThread::threadLoop_exit();
3879}
3880
3881AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3882 Vector< sp<Track> > *tracksToRemove
3883)
3884{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 size_t count = mActiveTracks.size();
3886
3887 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003888 bool doHwPause = false;
3889 bool doHwResume = false;
3890
Eric Laurentede6c3b2013-09-19 14:37:46 -07003891 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3892
Eric Laurentbfb1b832013-01-07 09:53:42 -08003893 // find out which tracks need to be processed
3894 for (size_t i = 0; i < count; i++) {
3895 sp<Track> t = mActiveTracks[i].promote();
3896 // The track died recently
3897 if (t == 0) {
3898 continue;
3899 }
3900 Track* const track = t.get();
3901 audio_track_cblk_t* cblk = track->cblk();
3902 if (mPreviousTrack != NULL) {
3903 if (t != mPreviousTrack) {
3904 // Flush any data still being written from last track
3905 mBytesRemaining = 0;
3906 if (mPausedBytesRemaining) {
3907 // Last track was paused so we also need to flush saved
3908 // mixbuffer state and invalidate track so that it will
3909 // re-submit that unwritten data when it is next resumed
3910 mPausedBytesRemaining = 0;
3911 // Invalidate is a bit drastic - would be more efficient
3912 // to have a flag to tell client that some of the
3913 // previously written data was lost
3914 mPreviousTrack->invalidate();
3915 }
3916 }
3917 }
3918 mPreviousTrack = t;
3919 bool last = (i == (count - 1));
3920 if (track->isPausing()) {
3921 track->setPaused();
3922 if (last) {
3923 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003924 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925 mHwPaused = true;
3926 }
3927 // If we were part way through writing the mixbuffer to
3928 // the HAL we must save this until we resume
3929 // BUG - this will be wrong if a different track is made active,
3930 // in that case we want to discard the pending data in the
3931 // mixbuffer and tell the client to present it again when the
3932 // track is resumed
3933 mPausedWriteLength = mCurrentWriteLength;
3934 mPausedBytesRemaining = mBytesRemaining;
3935 mBytesRemaining = 0; // stop writing
3936 }
3937 tracksToRemove->add(track);
3938 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003939 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003940 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 if (track->mFillingUpStatus == Track::FS_FILLED) {
3942 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003943 // make sure processVolume_l() will apply new volume even if 0
3944 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003946 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003947 if (last) {
3948 if (mPausedBytesRemaining) {
3949 // Need to continue write that was interrupted
3950 mCurrentWriteLength = mPausedWriteLength;
3951 mBytesRemaining = mPausedBytesRemaining;
3952 mPausedBytesRemaining = 0;
3953 }
3954 if (mHwPaused) {
3955 doHwResume = true;
3956 mHwPaused = false;
3957 // threadLoop_mix() will handle the case that we need to
3958 // resume an interrupted write
3959 }
3960 // enable write to audio HAL
3961 sleepTime = 0;
3962 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003963 }
3964 }
3965
3966 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003967 // reset retry count
3968 track->mRetryCount = kMaxTrackRetriesOffload;
3969 mActiveTrack = t;
3970 mixerStatus = MIXER_TRACKS_READY;
3971 }
3972 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003973 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003974 if (track->isStopping_1()) {
3975 // Hardware buffer can hold a large amount of audio so we must
3976 // wait for all current track's data to drain before we say
3977 // that the track is stopped.
3978 if (mBytesRemaining == 0) {
3979 // Only start draining when all data in mixbuffer
3980 // has been written
3981 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3982 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurentbfb1b832013-01-07 09:53:42 -08003983 if (last) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07003984 sleepTime = 0;
3985 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003986 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07003987 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003988 if (mHwPaused) {
3989 // It is possible to move from PAUSED to STOPPING_1 without
3990 // a resume so we must ensure hardware is running
3991 mOutput->stream->resume(mOutput->stream);
3992 mHwPaused = false;
3993 }
3994 }
3995 }
3996 } else if (track->isStopping_2()) {
3997 // Drain has completed, signal presentation complete
Eric Laurent3b4529e2013-09-05 18:09:19 -07003998 if (!(mDrainSequence & 1) || !last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003999 track->mState = TrackBase::STOPPED;
4000 size_t audioHALFrames =
4001 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4002 size_t framesWritten =
4003 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4004 track->presentationComplete(framesWritten, audioHALFrames);
4005 track->reset();
4006 tracksToRemove->add(track);
4007 }
4008 } else {
4009 // No buffers for this track. Give it a few chances to
4010 // fill a buffer, then remove it from active list.
4011 if (--(track->mRetryCount) <= 0) {
4012 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4013 track->name());
4014 tracksToRemove->add(track);
4015 } else if (last){
4016 mixerStatus = MIXER_TRACKS_ENABLED;
4017 }
4018 }
4019 }
4020 // compute volume for this track
4021 processVolume_l(track, last);
4022 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004023
Eric Laurent972a1732013-09-04 09:42:59 -07004024 // make sure the pause/flush/resume sequence is executed in the right order
4025 if (doHwPause) {
4026 mOutput->stream->pause(mOutput->stream);
4027 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004028 if (mFlushPending) {
4029 flushHw_l();
4030 mFlushPending = false;
4031 }
Eric Laurent972a1732013-09-04 09:42:59 -07004032 if (doHwResume) {
4033 mOutput->stream->resume(mOutput->stream);
4034 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004035
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036 // remove all the tracks that need to be...
4037 removeTracks_l(*tracksToRemove);
4038
4039 return mixerStatus;
4040}
4041
4042void AudioFlinger::OffloadThread::flushOutput_l()
4043{
4044 mFlushPending = true;
4045}
4046
4047// must be called with thread mutex locked
4048bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4049{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004050 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4051 mWriteAckSequence, mDrainSequence);
4052 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004053 return true;
4054 }
4055 return false;
4056}
4057
4058// must be called with thread mutex locked
4059bool AudioFlinger::OffloadThread::shouldStandby_l()
4060{
4061 bool TrackPaused = false;
4062
4063 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4064 // after a timeout and we will enter standby then.
4065 if (mTracks.size() > 0) {
4066 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4067 }
4068
4069 return !mStandby && !TrackPaused;
4070}
4071
4072
4073bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4074{
4075 Mutex::Autolock _l(mLock);
4076 return waitingAsyncCallback_l();
4077}
4078
4079void AudioFlinger::OffloadThread::flushHw_l()
4080{
4081 mOutput->stream->flush(mOutput->stream);
4082 // Flush anything still waiting in the mixbuffer
4083 mCurrentWriteLength = 0;
4084 mBytesRemaining = 0;
4085 mPausedWriteLength = 0;
4086 mPausedBytesRemaining = 0;
4087 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004088 // discard any pending drain or write ack by incrementing sequence
4089 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4090 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004091 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004092 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4093 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004094 }
4095}
4096
4097// ----------------------------------------------------------------------------
4098
Eric Laurent81784c32012-11-19 14:55:58 -08004099AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4100 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4101 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4102 DUPLICATING),
4103 mWaitTimeMs(UINT_MAX)
4104{
4105 addOutputTrack(mainThread);
4106}
4107
4108AudioFlinger::DuplicatingThread::~DuplicatingThread()
4109{
4110 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4111 mOutputTracks[i]->destroy();
4112 }
4113}
4114
4115void AudioFlinger::DuplicatingThread::threadLoop_mix()
4116{
4117 // mix buffers...
4118 if (outputsReady(outputTracks)) {
4119 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4120 } else {
4121 memset(mMixBuffer, 0, mixBufferSize);
4122 }
4123 sleepTime = 0;
4124 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004126 standbyTime = systemTime() + standbyDelay;
4127}
4128
4129void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4130{
4131 if (sleepTime == 0) {
4132 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4133 sleepTime = activeSleepTime;
4134 } else {
4135 sleepTime = idleSleepTime;
4136 }
4137 } else if (mBytesWritten != 0) {
4138 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4139 writeFrames = mNormalFrameCount;
4140 memset(mMixBuffer, 0, mixBufferSize);
4141 } else {
4142 // flush remaining overflow buffers in output tracks
4143 writeFrames = 0;
4144 }
4145 sleepTime = 0;
4146 }
4147}
4148
Eric Laurentbfb1b832013-01-07 09:53:42 -08004149ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004150{
4151 for (size_t i = 0; i < outputTracks.size(); i++) {
4152 outputTracks[i]->write(mMixBuffer, writeFrames);
4153 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004155}
4156
4157void AudioFlinger::DuplicatingThread::threadLoop_standby()
4158{
4159 // DuplicatingThread implements standby by stopping all tracks
4160 for (size_t i = 0; i < outputTracks.size(); i++) {
4161 outputTracks[i]->stop();
4162 }
4163}
4164
4165void AudioFlinger::DuplicatingThread::saveOutputTracks()
4166{
4167 outputTracks = mOutputTracks;
4168}
4169
4170void AudioFlinger::DuplicatingThread::clearOutputTracks()
4171{
4172 outputTracks.clear();
4173}
4174
4175void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4176{
4177 Mutex::Autolock _l(mLock);
4178 // FIXME explain this formula
4179 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4180 OutputTrack *outputTrack = new OutputTrack(thread,
4181 this,
4182 mSampleRate,
4183 mFormat,
4184 mChannelMask,
4185 frameCount);
4186 if (outputTrack->cblk() != NULL) {
4187 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4188 mOutputTracks.add(outputTrack);
4189 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4190 updateWaitTime_l();
4191 }
4192}
4193
4194void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4195{
4196 Mutex::Autolock _l(mLock);
4197 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4198 if (mOutputTracks[i]->thread() == thread) {
4199 mOutputTracks[i]->destroy();
4200 mOutputTracks.removeAt(i);
4201 updateWaitTime_l();
4202 return;
4203 }
4204 }
4205 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4206}
4207
4208// caller must hold mLock
4209void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4210{
4211 mWaitTimeMs = UINT_MAX;
4212 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4213 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4214 if (strong != 0) {
4215 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4216 if (waitTimeMs < mWaitTimeMs) {
4217 mWaitTimeMs = waitTimeMs;
4218 }
4219 }
4220 }
4221}
4222
4223
4224bool AudioFlinger::DuplicatingThread::outputsReady(
4225 const SortedVector< sp<OutputTrack> > &outputTracks)
4226{
4227 for (size_t i = 0; i < outputTracks.size(); i++) {
4228 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4229 if (thread == 0) {
4230 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4231 outputTracks[i].get());
4232 return false;
4233 }
4234 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4235 // see note at standby() declaration
4236 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4237 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4238 thread.get());
4239 return false;
4240 }
4241 }
4242 return true;
4243}
4244
4245uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4246{
4247 return (mWaitTimeMs * 1000) / 2;
4248}
4249
4250void AudioFlinger::DuplicatingThread::cacheParameters_l()
4251{
4252 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4253 updateWaitTime_l();
4254
4255 MixerThread::cacheParameters_l();
4256}
4257
4258// ----------------------------------------------------------------------------
4259// Record
4260// ----------------------------------------------------------------------------
4261
4262AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4263 AudioStreamIn *input,
4264 uint32_t sampleRate,
4265 audio_channel_mask_t channelMask,
4266 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004267 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004268 audio_devices_t inDevice
4269#ifdef TEE_SINK
4270 , const sp<NBAIO_Sink>& teeSink
4271#endif
4272 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004273 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004274 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004275 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004276 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004277 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004278 // mBytesRead is only meaningful while active, and so is cleared in start()
4279 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004280#ifdef TEE_SINK
4281 , mTeeSink(teeSink)
4282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004283{
4284 snprintf(mName, kNameLength, "AudioIn_%X", id);
4285
4286 readInputParameters();
4287
4288}
4289
4290
4291AudioFlinger::RecordThread::~RecordThread()
4292{
4293 delete[] mRsmpInBuffer;
4294 delete mResampler;
4295 delete[] mRsmpOutBuffer;
4296}
4297
4298void AudioFlinger::RecordThread::onFirstRef()
4299{
4300 run(mName, PRIORITY_URGENT_AUDIO);
4301}
4302
Eric Laurent81784c32012-11-19 14:55:58 -08004303bool AudioFlinger::RecordThread::threadLoop()
4304{
4305 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004306
4307 nsecs_t lastWarning = 0;
4308
4309 inputStandBy();
4310 acquireWakeLock();
4311
4312 // used to verify we've read at least once before evaluating how many bytes were read
4313 bool readOnce = false;
4314
Glenn Kasten5edadd42013-08-14 16:30:49 -07004315 // used to request a deferred sleep, to be executed later while mutex is unlocked
4316 bool doSleep = false;
4317
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004319 for (;;) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004320 sp<RecordTrack> activeTrack;
Glenn Kastenb86432b2013-08-14 15:08:12 -07004321 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004322 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004323
Glenn Kasten5edadd42013-08-14 16:30:49 -07004324 // sleep with mutex unlocked
4325 if (doSleep) {
4326 doSleep = false;
4327 usleep(kRecordThreadSleepUs);
4328 }
4329
Eric Laurent81784c32012-11-19 14:55:58 -08004330 { // scope for mLock
4331 Mutex::Autolock _l(mLock);
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004332 if (exitPending()) {
4333 break;
4334 }
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004335 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004336 // return value 'reconfig' is currently unused
4337 bool reconfig = checkForNewParameters_l();
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004338 // make a stable copy of mActiveTrack
4339 activeTrack = mActiveTrack;
4340 if (activeTrack == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004341 standby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004342 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004343 releaseWakeLock_l();
4344 ALOGV("RecordThread: loop stopping");
4345 // go to sleep
4346 mWaitWorkCV.wait(mLock);
4347 ALOGV("RecordThread: loop starting");
4348 acquireWakeLock_l();
4349 continue;
4350 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004351
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004352 if (activeTrack->isTerminated()) {
4353 removeTrack_l(activeTrack);
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004354 mActiveTrack.clear();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004355 continue;
4356 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004357
Glenn Kastenb86432b2013-08-14 15:08:12 -07004358 activeTrackState = activeTrack->mState;
4359 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004360 case TrackBase::PAUSING:
4361 standby();
4362 mActiveTrack.clear();
4363 mStartStopCond.broadcast();
4364 doSleep = true;
4365 continue;
4366
4367 case TrackBase::RESUMING:
4368 mStandby = false;
4369 if (mReqChannelCount != activeTrack->channelCount()) {
4370 mActiveTrack.clear();
4371 mStartStopCond.broadcast();
4372 continue;
4373 }
4374 if (readOnce) {
4375 mStartStopCond.broadcast();
4376 // record start succeeds only if first read from audio input succeeds
4377 if (mBytesRead < 0) {
4378 mActiveTrack.clear();
4379 continue;
4380 }
4381 activeTrack->mState = TrackBase::ACTIVE;
4382 }
4383 break;
4384
4385 case TrackBase::ACTIVE:
4386 break;
4387
4388 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004389 doSleep = true;
4390 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004391
4392 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004393 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004394 }
4395
Eric Laurent81784c32012-11-19 14:55:58 -08004396 lockEffectChains_l(effectChains);
4397 }
4398
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004399 // thread mutex is now unlocked, mActiveTrack unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004400 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4401
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004402 for (size_t i = 0; i < effectChains.size(); i ++) {
4403 // thread mutex is not locked, but effect chain is locked
4404 effectChains[i]->process_l();
4405 }
4406
4407 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004408 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004409 if (status == NO_ERROR) {
4410 readOnce = true;
4411 size_t framesOut = buffer.frameCount;
4412 if (mResampler == NULL) {
4413 // no resampling
4414 while (framesOut) {
4415 size_t framesIn = mFrameCount - mRsmpInIndex;
4416 if (framesIn > 0) {
4417 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4418 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004419 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004420 if (framesIn > framesOut) {
4421 framesIn = framesOut;
4422 }
4423 mRsmpInIndex += framesIn;
4424 framesOut -= framesIn;
4425 if (mChannelCount == mReqChannelCount) {
4426 memcpy(dst, src, framesIn * mFrameSize);
4427 } else {
4428 if (mChannelCount == 1) {
4429 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4430 (int16_t *)src, framesIn);
4431 } else {
4432 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4433 (int16_t *)src, framesIn);
4434 }
4435 }
4436 }
4437 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4438 void *readInto;
4439 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4440 readInto = buffer.raw;
4441 framesOut = 0;
4442 } else {
4443 readInto = mRsmpInBuffer;
4444 mRsmpInIndex = 0;
4445 }
4446 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4447 mBufferSize);
4448 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004449 // TODO: verify that it's benign to use a stale track state
4450 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004451 {
4452 ALOGE("Error reading audio input");
4453 // Force input into standby so that it tries to
4454 // recover at next read attempt
4455 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004456 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004457 }
4458 mRsmpInIndex = mFrameCount;
4459 framesOut = 0;
4460 buffer.frameCount = 0;
4461 }
4462#ifdef TEE_SINK
4463 else if (mTeeSink != 0) {
4464 (void) mTeeSink->write(readInto,
4465 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4466 }
4467#endif
4468 }
4469 }
4470 } else {
4471 // resampling
4472
4473 // resampler accumulates, but we only have one source track
4474 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4475 // alter output frame count as if we were expecting stereo samples
4476 if (mChannelCount == 1 && mReqChannelCount == 1) {
4477 framesOut >>= 1;
4478 }
4479 mResampler->resample(mRsmpOutBuffer, framesOut,
4480 this /* AudioBufferProvider* */);
4481 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004482 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004483 if (mChannelCount == 2 && mReqChannelCount == 1) {
4484 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4485 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4486 // the resampler always outputs stereo samples:
4487 // do post stereo to mono conversion
4488 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4489 framesOut);
4490 } else {
4491 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4492 }
4493 // now done with mRsmpOutBuffer
4494
4495 }
4496 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004497 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004498 } else {
4499 if (mFramestoDrop > 0) {
4500 mFramestoDrop -= buffer.frameCount;
4501 if (mFramestoDrop <= 0) {
4502 clearSyncStartEvent();
4503 }
4504 } else {
4505 mFramestoDrop += buffer.frameCount;
4506 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4507 mSyncStartEvent->isCancelled()) {
4508 ALOGW("Synced record %s, session %d, trigger session %d",
4509 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004510 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004511 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4512 clearSyncStartEvent();
4513 }
4514 }
4515 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004516 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004517 }
4518 // client isn't retrieving buffers fast enough
4519 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004520 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004521 nsecs_t now = systemTime();
4522 if ((now - lastWarning) > kWarningThrottleNs) {
4523 ALOGW("RecordThread: buffer overflow");
4524 lastWarning = now;
4525 }
4526 }
4527 // Release the processor for a while before asking for a new buffer.
4528 // This will give the application more chance to read from the buffer and
4529 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004530 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004531 }
4532
Eric Laurent81784c32012-11-19 14:55:58 -08004533 // enable changes in effect chain
4534 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004535 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004536 }
4537
4538 standby();
4539
4540 {
4541 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004542 for (size_t i = 0; i < mTracks.size(); i++) {
4543 sp<RecordTrack> track = mTracks[i];
4544 track->invalidate();
4545 }
Eric Laurent81784c32012-11-19 14:55:58 -08004546 mActiveTrack.clear();
4547 mStartStopCond.broadcast();
4548 }
4549
4550 releaseWakeLock();
4551
4552 ALOGV("RecordThread %p exiting", this);
4553 return false;
4554}
4555
4556void AudioFlinger::RecordThread::standby()
4557{
4558 if (!mStandby) {
4559 inputStandBy();
4560 mStandby = true;
4561 }
4562}
4563
4564void AudioFlinger::RecordThread::inputStandBy()
4565{
4566 mInput->stream->common.standby(&mInput->stream->common);
4567}
4568
Glenn Kastene198c362013-08-13 09:13:36 -07004569sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004570 const sp<AudioFlinger::Client>& client,
4571 uint32_t sampleRate,
4572 audio_format_t format,
4573 audio_channel_mask_t channelMask,
4574 size_t frameCount,
4575 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004576 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004577 pid_t tid,
4578 status_t *status)
4579{
4580 sp<RecordTrack> track;
4581 status_t lStatus;
4582
4583 lStatus = initCheck();
4584 if (lStatus != NO_ERROR) {
4585 ALOGE("Audio driver not initialized.");
4586 goto Exit;
4587 }
4588
Glenn Kasten90e58b12013-07-31 16:16:02 -07004589 // client expresses a preference for FAST, but we get the final say
4590 if (*flags & IAudioFlinger::TRACK_FAST) {
4591 if (
4592 // use case: callback handler and frame count is default or at least as large as HAL
4593 (
4594 (tid != -1) &&
4595 ((frameCount == 0) ||
4596 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4597 ) &&
4598 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4599 // mono or stereo
4600 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4601 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4602 // hardware sample rate
4603 (sampleRate == mSampleRate) &&
4604 // record thread has an associated fast recorder
4605 hasFastRecorder()
4606 // FIXME test that RecordThread for this fast track has a capable output HAL
4607 // FIXME add a permission test also?
4608 ) {
4609 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4610 if (frameCount == 0) {
4611 frameCount = mFrameCount * kFastTrackMultiplier;
4612 }
4613 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4614 frameCount, mFrameCount);
4615 } else {
4616 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4617 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4618 "hasFastRecorder=%d tid=%d",
4619 frameCount, mFrameCount, format,
4620 audio_is_linear_pcm(format),
4621 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4622 *flags &= ~IAudioFlinger::TRACK_FAST;
4623 // For compatibility with AudioRecord calculation, buffer depth is forced
4624 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4625 // This is probably too conservative, but legacy application code may depend on it.
4626 // If you change this calculation, also review the start threshold which is related.
4627 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4628 size_t mNormalFrameCount = 2048; // FIXME
4629 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4630 if (minBufCount < 2) {
4631 minBufCount = 2;
4632 }
4633 size_t minFrameCount = mNormalFrameCount * minBufCount;
4634 if (frameCount < minFrameCount) {
4635 frameCount = minFrameCount;
4636 }
4637 }
4638 }
4639
Eric Laurent81784c32012-11-19 14:55:58 -08004640 // FIXME use flags and tid similar to createTrack_l()
4641
4642 { // scope for mLock
4643 Mutex::Autolock _l(mLock);
4644
4645 track = new RecordTrack(this, client, sampleRate,
4646 format, channelMask, frameCount, sessionId);
4647
Glenn Kasten03003332013-08-06 15:40:54 -07004648 lStatus = track->initCheck();
4649 if (lStatus != NO_ERROR) {
4650 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004651 goto Exit;
4652 }
4653 mTracks.add(track);
4654
4655 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4656 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4657 mAudioFlinger->btNrecIsOff();
4658 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4659 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004660
4661 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4662 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4663 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4664 // so ask activity manager to do this on our behalf
4665 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4666 }
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668 lStatus = NO_ERROR;
4669
4670Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004671 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004672 return track;
4673}
4674
4675status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4676 AudioSystem::sync_event_t event,
4677 int triggerSession)
4678{
4679 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4680 sp<ThreadBase> strongMe = this;
4681 status_t status = NO_ERROR;
4682
4683 if (event == AudioSystem::SYNC_EVENT_NONE) {
4684 clearSyncStartEvent();
4685 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4686 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4687 triggerSession,
4688 recordTrack->sessionId(),
4689 syncStartEventCallback,
4690 this);
4691 // Sync event can be cancelled by the trigger session if the track is not in a
4692 // compatible state in which case we start record immediately
4693 if (mSyncStartEvent->isCancelled()) {
4694 clearSyncStartEvent();
4695 } else {
4696 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4697 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4698 }
4699 }
4700
4701 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004702 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004703 AutoMutex lock(mLock);
4704 if (mActiveTrack != 0) {
4705 if (recordTrack != mActiveTrack.get()) {
4706 status = -EBUSY;
4707 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4708 mActiveTrack->mState = TrackBase::ACTIVE;
4709 }
4710 return status;
4711 }
4712
Glenn Kasten47c20702013-08-13 15:37:35 -07004713 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004714 recordTrack->mState = TrackBase::IDLE;
4715 mActiveTrack = recordTrack;
4716 mLock.unlock();
4717 status_t status = AudioSystem::startInput(mId);
4718 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004719 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004720 if (status != NO_ERROR) {
4721 mActiveTrack.clear();
4722 clearSyncStartEvent();
4723 return status;
4724 }
4725 mRsmpInIndex = mFrameCount;
4726 mBytesRead = 0;
4727 if (mResampler != NULL) {
4728 mResampler->reset();
4729 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004730 // FIXME hijacking a playback track state name which was intended for start after pause;
4731 // here 'STARTING_2' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004732 mActiveTrack->mState = TrackBase::RESUMING;
4733 // signal thread to start
4734 ALOGV("Signal record thread");
4735 mWaitWorkCV.broadcast();
4736 // do not wait for mStartStopCond if exiting
4737 if (exitPending()) {
4738 mActiveTrack.clear();
4739 status = INVALID_OPERATION;
4740 goto startError;
4741 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004742 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004743 mStartStopCond.wait(mLock);
4744 if (mActiveTrack == 0) {
4745 ALOGV("Record failed to start");
4746 status = BAD_VALUE;
4747 goto startError;
4748 }
4749 ALOGV("Record started OK");
4750 return status;
4751 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004752
Eric Laurent81784c32012-11-19 14:55:58 -08004753startError:
4754 AudioSystem::stopInput(mId);
4755 clearSyncStartEvent();
4756 return status;
4757}
4758
4759void AudioFlinger::RecordThread::clearSyncStartEvent()
4760{
4761 if (mSyncStartEvent != 0) {
4762 mSyncStartEvent->cancel();
4763 }
4764 mSyncStartEvent.clear();
4765 mFramestoDrop = 0;
4766}
4767
4768void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4769{
4770 sp<SyncEvent> strongEvent = event.promote();
4771
4772 if (strongEvent != 0) {
4773 RecordThread *me = (RecordThread *)strongEvent->cookie();
4774 me->handleSyncStartEvent(strongEvent);
4775 }
4776}
4777
4778void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4779{
4780 if (event == mSyncStartEvent) {
4781 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4782 // from audio HAL
4783 mFramestoDrop = mFrameCount * 2;
4784 }
4785}
4786
Glenn Kastena8356f62013-07-25 14:37:52 -07004787bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004788 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004789 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004790 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4791 return false;
4792 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004793 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08004794 recordTrack->mState = TrackBase::PAUSING;
4795 // do not wait for mStartStopCond if exiting
4796 if (exitPending()) {
4797 return true;
4798 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004799 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004800 mStartStopCond.wait(mLock);
4801 // if we have been restarted, recordTrack == mActiveTrack.get() here
4802 if (exitPending() || recordTrack != mActiveTrack.get()) {
4803 ALOGV("Record stopped OK");
4804 return true;
4805 }
4806 return false;
4807}
4808
4809bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4810{
4811 return false;
4812}
4813
4814status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4815{
4816#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4817 if (!isValidSyncEvent(event)) {
4818 return BAD_VALUE;
4819 }
4820
4821 int eventSession = event->triggerSession();
4822 status_t ret = NAME_NOT_FOUND;
4823
4824 Mutex::Autolock _l(mLock);
4825
4826 for (size_t i = 0; i < mTracks.size(); i++) {
4827 sp<RecordTrack> track = mTracks[i];
4828 if (eventSession == track->sessionId()) {
4829 (void) track->setSyncEvent(event);
4830 ret = NO_ERROR;
4831 }
4832 }
4833 return ret;
4834#else
4835 return BAD_VALUE;
4836#endif
4837}
4838
4839// destroyTrack_l() must be called with ThreadBase::mLock held
4840void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4841{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004842 track->terminate();
4843 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004844 // active tracks are removed by threadLoop()
4845 if (mActiveTrack != track) {
4846 removeTrack_l(track);
4847 }
4848}
4849
4850void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4851{
4852 mTracks.remove(track);
4853 // need anything related to effects here?
4854}
4855
4856void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4857{
4858 dumpInternals(fd, args);
4859 dumpTracks(fd, args);
4860 dumpEffectChains(fd, args);
4861}
4862
4863void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4864{
4865 const size_t SIZE = 256;
4866 char buffer[SIZE];
4867 String8 result;
4868
4869 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4870 result.append(buffer);
4871
4872 if (mActiveTrack != 0) {
4873 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4874 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004875 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004876 result.append(buffer);
4877 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4878 result.append(buffer);
4879 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4880 result.append(buffer);
4881 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4882 result.append(buffer);
4883 } else {
4884 result.append("No active record client\n");
4885 }
4886
4887 write(fd, result.string(), result.size());
4888
4889 dumpBase(fd, args);
4890}
4891
4892void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4893{
4894 const size_t SIZE = 256;
4895 char buffer[SIZE];
4896 String8 result;
4897
4898 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4899 result.append(buffer);
4900 RecordTrack::appendDumpHeader(result);
4901 for (size_t i = 0; i < mTracks.size(); ++i) {
4902 sp<RecordTrack> track = mTracks[i];
4903 if (track != 0) {
4904 track->dump(buffer, SIZE);
4905 result.append(buffer);
4906 }
4907 }
4908
4909 if (mActiveTrack != 0) {
4910 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4911 result.append(buffer);
4912 RecordTrack::appendDumpHeader(result);
4913 mActiveTrack->dump(buffer, SIZE);
4914 result.append(buffer);
4915
4916 }
4917 write(fd, result.string(), result.size());
4918}
4919
4920// AudioBufferProvider interface
4921status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4922{
4923 size_t framesReq = buffer->frameCount;
4924 size_t framesReady = mFrameCount - mRsmpInIndex;
4925 int channelCount;
4926
4927 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004928 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004929 if (mBytesRead <= 0) {
4930 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4931 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4932 // Force input into standby so that it tries to
4933 // recover at next read attempt
4934 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004935 // FIXME an awkward place to sleep, consider using doSleep when this is pulled up
Eric Laurent81784c32012-11-19 14:55:58 -08004936 usleep(kRecordThreadSleepUs);
4937 }
4938 buffer->raw = NULL;
4939 buffer->frameCount = 0;
4940 return NOT_ENOUGH_DATA;
4941 }
4942 mRsmpInIndex = 0;
4943 framesReady = mFrameCount;
4944 }
4945
4946 if (framesReq > framesReady) {
4947 framesReq = framesReady;
4948 }
4949
4950 if (mChannelCount == 1 && mReqChannelCount == 2) {
4951 channelCount = 1;
4952 } else {
4953 channelCount = 2;
4954 }
4955 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4956 buffer->frameCount = framesReq;
4957 return NO_ERROR;
4958}
4959
4960// AudioBufferProvider interface
4961void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4962{
4963 mRsmpInIndex += buffer->frameCount;
4964 buffer->frameCount = 0;
4965}
4966
4967bool AudioFlinger::RecordThread::checkForNewParameters_l()
4968{
4969 bool reconfig = false;
4970
4971 while (!mNewParameters.isEmpty()) {
4972 status_t status = NO_ERROR;
4973 String8 keyValuePair = mNewParameters[0];
4974 AudioParameter param = AudioParameter(keyValuePair);
4975 int value;
4976 audio_format_t reqFormat = mFormat;
4977 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07004978 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004979
4980 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4981 reqSamplingRate = value;
4982 reconfig = true;
4983 }
4984 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004985 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4986 status = BAD_VALUE;
4987 } else {
4988 reqFormat = (audio_format_t) value;
4989 reconfig = true;
4990 }
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
4992 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07004993 audio_channel_mask_t mask = (audio_channel_mask_t) value;
4994 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
4995 status = BAD_VALUE;
4996 } else {
4997 reqChannelMask = mask;
4998 reconfig = true;
4999 }
Eric Laurent81784c32012-11-19 14:55:58 -08005000 }
5001 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5002 // do not accept frame count changes if tracks are open as the track buffer
5003 // size depends on frame count and correct behavior would not be guaranteed
5004 // if frame count is changed after track creation
5005 if (mActiveTrack != 0) {
5006 status = INVALID_OPERATION;
5007 } else {
5008 reconfig = true;
5009 }
5010 }
5011 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5012 // forward device change to effects that have requested to be
5013 // aware of attached audio device.
5014 for (size_t i = 0; i < mEffectChains.size(); i++) {
5015 mEffectChains[i]->setDevice_l(value);
5016 }
5017
5018 // store input device and output device but do not forward output device to audio HAL.
5019 // Note that status is ignored by the caller for output device
5020 // (see AudioFlinger::setParameters()
5021 if (audio_is_output_devices(value)) {
5022 mOutDevice = value;
5023 status = BAD_VALUE;
5024 } else {
5025 mInDevice = value;
5026 // disable AEC and NS if the device is a BT SCO headset supporting those
5027 // pre processings
5028 if (mTracks.size() > 0) {
5029 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5030 mAudioFlinger->btNrecIsOff();
5031 for (size_t i = 0; i < mTracks.size(); i++) {
5032 sp<RecordTrack> track = mTracks[i];
5033 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5034 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5035 }
5036 }
5037 }
5038 }
5039 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5040 mAudioSource != (audio_source_t)value) {
5041 // forward device change to effects that have requested to be
5042 // aware of attached audio device.
5043 for (size_t i = 0; i < mEffectChains.size(); i++) {
5044 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5045 }
5046 mAudioSource = (audio_source_t)value;
5047 }
Glenn Kastene198c362013-08-13 09:13:36 -07005048
Eric Laurent81784c32012-11-19 14:55:58 -08005049 if (status == NO_ERROR) {
5050 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5051 keyValuePair.string());
5052 if (status == INVALID_OPERATION) {
5053 inputStandBy();
5054 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5055 keyValuePair.string());
5056 }
5057 if (reconfig) {
5058 if (status == BAD_VALUE &&
5059 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5060 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005061 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005062 <= (2 * reqSamplingRate)) &&
5063 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5064 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005065 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5066 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005067 status = NO_ERROR;
5068 }
5069 if (status == NO_ERROR) {
5070 readInputParameters();
5071 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5072 }
5073 }
5074 }
5075
5076 mNewParameters.removeAt(0);
5077
5078 mParamStatus = status;
5079 mParamCond.signal();
5080 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5081 // already timed out waiting for the status and will never signal the condition.
5082 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5083 }
5084 return reconfig;
5085}
5086
5087String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5088{
Eric Laurent81784c32012-11-19 14:55:58 -08005089 Mutex::Autolock _l(mLock);
5090 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005091 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005092 }
5093
Glenn Kastend8ea6992013-07-16 14:17:15 -07005094 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5095 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005096 free(s);
5097 return out_s8;
5098}
5099
5100void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5101 AudioSystem::OutputDescriptor desc;
5102 void *param2 = NULL;
5103
5104 switch (event) {
5105 case AudioSystem::INPUT_OPENED:
5106 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005107 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 desc.samplingRate = mSampleRate;
5109 desc.format = mFormat;
5110 desc.frameCount = mFrameCount;
5111 desc.latency = 0;
5112 param2 = &desc;
5113 break;
5114
5115 case AudioSystem::INPUT_CLOSED:
5116 default:
5117 break;
5118 }
5119 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5120}
5121
5122void AudioFlinger::RecordThread::readInputParameters()
5123{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005124 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005125 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005126 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 mRsmpOutBuffer = NULL;
5128 delete mResampler;
5129 mResampler = NULL;
5130
5131 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5132 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005133 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005134 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005135 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5136 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5137 }
Eric Laurent81784c32012-11-19 14:55:58 -08005138 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005139 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5140 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005141 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5142
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005143 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005144 int channelCount;
5145 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5146 // stereo to mono post process as the resampler always outputs stereo.
5147 if (mChannelCount == 1 && mReqChannelCount == 2) {
5148 channelCount = 1;
5149 } else {
5150 channelCount = 2;
5151 }
5152 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5153 mResampler->setSampleRate(mSampleRate);
5154 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005155 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005156
5157 // optmization: if mono to mono, alter input frame count as if we were inputing
5158 // stereo samples
5159 if (mChannelCount == 1 && mReqChannelCount == 1) {
5160 mFrameCount >>= 1;
5161 }
5162
5163 }
5164 mRsmpInIndex = mFrameCount;
5165}
5166
5167unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5168{
5169 Mutex::Autolock _l(mLock);
5170 if (initCheck() != NO_ERROR) {
5171 return 0;
5172 }
5173
5174 return mInput->stream->get_input_frames_lost(mInput->stream);
5175}
5176
5177uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5178{
5179 Mutex::Autolock _l(mLock);
5180 uint32_t result = 0;
5181 if (getEffectChain_l(sessionId) != 0) {
5182 result = EFFECT_SESSION;
5183 }
5184
5185 for (size_t i = 0; i < mTracks.size(); ++i) {
5186 if (sessionId == mTracks[i]->sessionId()) {
5187 result |= TRACK_SESSION;
5188 break;
5189 }
5190 }
5191
5192 return result;
5193}
5194
5195KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5196{
5197 KeyedVector<int, bool> ids;
5198 Mutex::Autolock _l(mLock);
5199 for (size_t j = 0; j < mTracks.size(); ++j) {
5200 sp<RecordThread::RecordTrack> track = mTracks[j];
5201 int sessionId = track->sessionId();
5202 if (ids.indexOfKey(sessionId) < 0) {
5203 ids.add(sessionId, true);
5204 }
5205 }
5206 return ids;
5207}
5208
5209AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5210{
5211 Mutex::Autolock _l(mLock);
5212 AudioStreamIn *input = mInput;
5213 mInput = NULL;
5214 return input;
5215}
5216
5217// this method must always be called either with ThreadBase mLock held or inside the thread loop
5218audio_stream_t* AudioFlinger::RecordThread::stream() const
5219{
5220 if (mInput == NULL) {
5221 return NULL;
5222 }
5223 return &mInput->stream->common;
5224}
5225
5226status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5227{
5228 // only one chain per input thread
5229 if (mEffectChains.size() != 0) {
5230 return INVALID_OPERATION;
5231 }
5232 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5233
5234 chain->setInBuffer(NULL);
5235 chain->setOutBuffer(NULL);
5236
5237 checkSuspendOnAddEffectChain_l(chain);
5238
5239 mEffectChains.add(chain);
5240
5241 return NO_ERROR;
5242}
5243
5244size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5245{
5246 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5247 ALOGW_IF(mEffectChains.size() != 1,
5248 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5249 chain.get(), mEffectChains.size(), this);
5250 if (mEffectChains.size() == 1) {
5251 mEffectChains.removeAt(0);
5252 }
5253 return 0;
5254}
5255
5256}; // namespace android