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