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