blob: 4234965b281e2a5901ae5fe9ea439950f9559607 [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
705 // Do not allow effects with session ID 0 on direct output or duplicating threads
706 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
707 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
708 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
709 desc->name, sessionId);
710 lStatus = BAD_VALUE;
711 goto Exit;
712 }
713 // Only Pre processor effects are allowed on input threads and only on input threads
714 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
715 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
716 desc->name, desc->flags, mType);
717 lStatus = BAD_VALUE;
718 goto Exit;
719 }
720
721 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
722
723 { // scope for mLock
724 Mutex::Autolock _l(mLock);
725
726 // check for existing effect chain with the requested audio session
727 chain = getEffectChain_l(sessionId);
728 if (chain == 0) {
729 // create a new chain for this session
730 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
731 chain = new EffectChain(this, sessionId);
732 addEffectChain_l(chain);
733 chain->setStrategy(getStrategyForSession_l(sessionId));
734 chainCreated = true;
735 } else {
736 effect = chain->getEffectFromDesc_l(desc);
737 }
738
739 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
740
741 if (effect == 0) {
742 int id = mAudioFlinger->nextUniqueId();
743 // Check CPU and memory usage
744 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
745 if (lStatus != NO_ERROR) {
746 goto Exit;
747 }
748 effectRegistered = true;
749 // create a new effect module if none present in the chain
750 effect = new EffectModule(this, chain, desc, id, sessionId);
751 lStatus = effect->status();
752 if (lStatus != NO_ERROR) {
753 goto Exit;
754 }
755 lStatus = chain->addEffect_l(effect);
756 if (lStatus != NO_ERROR) {
757 goto Exit;
758 }
759 effectCreated = true;
760
761 effect->setDevice(mOutDevice);
762 effect->setDevice(mInDevice);
763 effect->setMode(mAudioFlinger->getMode());
764 effect->setAudioSource(mAudioSource);
765 }
766 // create effect handle and connect it to effect module
767 handle = new EffectHandle(effect, client, effectClient, priority);
768 lStatus = effect->addHandle(handle.get());
769 if (enabled != NULL) {
770 *enabled = (int)effect->isEnabled();
771 }
772 }
773
774Exit:
775 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
776 Mutex::Autolock _l(mLock);
777 if (effectCreated) {
778 chain->removeEffect_l(effect);
779 }
780 if (effectRegistered) {
781 AudioSystem::unregisterEffect(effect->id());
782 }
783 if (chainCreated) {
784 removeEffectChain_l(chain);
785 }
786 handle.clear();
787 }
788
789 if (status != NULL) {
790 *status = lStatus;
791 }
792 return handle;
793}
794
795sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
796{
797 Mutex::Autolock _l(mLock);
798 return getEffect_l(sessionId, effectId);
799}
800
801sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
802{
803 sp<EffectChain> chain = getEffectChain_l(sessionId);
804 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
805}
806
807// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
808// PlaybackThread::mLock held
809status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
810{
811 // check for existing effect chain with the requested audio session
812 int sessionId = effect->sessionId();
813 sp<EffectChain> chain = getEffectChain_l(sessionId);
814 bool chainCreated = false;
815
816 if (chain == 0) {
817 // create a new chain for this session
818 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
819 chain = new EffectChain(this, sessionId);
820 addEffectChain_l(chain);
821 chain->setStrategy(getStrategyForSession_l(sessionId));
822 chainCreated = true;
823 }
824 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
825
826 if (chain->getEffectFromId_l(effect->id()) != 0) {
827 ALOGW("addEffect_l() %p effect %s already present in chain %p",
828 this, effect->desc().name, chain.get());
829 return BAD_VALUE;
830 }
831
832 status_t status = chain->addEffect_l(effect);
833 if (status != NO_ERROR) {
834 if (chainCreated) {
835 removeEffectChain_l(chain);
836 }
837 return status;
838 }
839
840 effect->setDevice(mOutDevice);
841 effect->setDevice(mInDevice);
842 effect->setMode(mAudioFlinger->getMode());
843 effect->setAudioSource(mAudioSource);
844 return NO_ERROR;
845}
846
847void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
848
849 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
850 effect_descriptor_t desc = effect->desc();
851 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
852 detachAuxEffect_l(effect->id());
853 }
854
855 sp<EffectChain> chain = effect->chain().promote();
856 if (chain != 0) {
857 // remove effect chain if removing last effect
858 if (chain->removeEffect_l(effect) == 0) {
859 removeEffectChain_l(chain);
860 }
861 } else {
862 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
863 }
864}
865
866void AudioFlinger::ThreadBase::lockEffectChains_l(
867 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
868{
869 effectChains = mEffectChains;
870 for (size_t i = 0; i < mEffectChains.size(); i++) {
871 mEffectChains[i]->lock();
872 }
873}
874
875void AudioFlinger::ThreadBase::unlockEffectChains(
876 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
877{
878 for (size_t i = 0; i < effectChains.size(); i++) {
879 effectChains[i]->unlock();
880 }
881}
882
883sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
884{
885 Mutex::Autolock _l(mLock);
886 return getEffectChain_l(sessionId);
887}
888
889sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
890{
891 size_t size = mEffectChains.size();
892 for (size_t i = 0; i < size; i++) {
893 if (mEffectChains[i]->sessionId() == sessionId) {
894 return mEffectChains[i];
895 }
896 }
897 return 0;
898}
899
900void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
901{
902 Mutex::Autolock _l(mLock);
903 size_t size = mEffectChains.size();
904 for (size_t i = 0; i < size; i++) {
905 mEffectChains[i]->setMode_l(mode);
906 }
907}
908
909void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
910 EffectHandle *handle,
911 bool unpinIfLast) {
912
913 Mutex::Autolock _l(mLock);
914 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
915 // delete the effect module if removing last handle on it
916 if (effect->removeHandle(handle) == 0) {
917 if (!effect->isPinned() || unpinIfLast) {
918 removeEffect_l(effect);
919 AudioSystem::unregisterEffect(effect->id());
920 }
921 }
922}
923
924// ----------------------------------------------------------------------------
925// Playback
926// ----------------------------------------------------------------------------
927
928AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
929 AudioStreamOut* output,
930 audio_io_handle_t id,
931 audio_devices_t device,
932 type_t type)
933 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700934 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800935 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800936 // mStreamTypes[] initialized in constructor body
937 mOutput(output),
938 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
939 mMixerStatus(MIXER_IDLE),
940 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
941 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800942 mBytesRemaining(0),
943 mCurrentWriteLength(0),
944 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -0700945 mWriteAckSequence(0),
946 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800947 mScreenState(AudioFlinger::mScreenState),
948 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700949 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
950 // mLatchD, mLatchQ,
951 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800952{
953 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800954 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800955
956 // Assumes constructor is called by AudioFlinger with it's mLock held, but
957 // it would be safer to explicitly pass initial masterVolume/masterMute as
958 // parameter.
959 //
960 // If the HAL we are using has support for master volume or master mute,
961 // then do not attenuate or mute during mixing (just leave the volume at 1.0
962 // and the mute set to false).
963 mMasterVolume = audioFlinger->masterVolume_l();
964 mMasterMute = audioFlinger->masterMute_l();
965 if (mOutput && mOutput->audioHwDev) {
966 if (mOutput->audioHwDev->canSetMasterVolume()) {
967 mMasterVolume = 1.0;
968 }
969
970 if (mOutput->audioHwDev->canSetMasterMute()) {
971 mMasterMute = false;
972 }
973 }
974
975 readOutputParameters();
976
977 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
978 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
979 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
980 stream = (audio_stream_type_t) (stream + 1)) {
981 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
982 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
983 }
984 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
985 // because mAudioFlinger doesn't have one to copy from
986}
987
988AudioFlinger::PlaybackThread::~PlaybackThread()
989{
Glenn Kasten9e58b552013-01-18 15:09:48 -0800990 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800991 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -0800992}
993
994void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
995{
996 dumpInternals(fd, args);
997 dumpTracks(fd, args);
998 dumpEffectChains(fd, args);
999}
1000
1001void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1002{
1003 const size_t SIZE = 256;
1004 char buffer[SIZE];
1005 String8 result;
1006
1007 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1008 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1009 const stream_type_t *st = &mStreamTypes[i];
1010 if (i > 0) {
1011 result.appendFormat(", ");
1012 }
1013 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1014 if (st->mute) {
1015 result.append("M");
1016 }
1017 }
1018 result.append("\n");
1019 write(fd, result.string(), result.length());
1020 result.clear();
1021
1022 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1023 result.append(buffer);
1024 Track::appendDumpHeader(result);
1025 for (size_t i = 0; i < mTracks.size(); ++i) {
1026 sp<Track> track = mTracks[i];
1027 if (track != 0) {
1028 track->dump(buffer, SIZE);
1029 result.append(buffer);
1030 }
1031 }
1032
1033 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1034 result.append(buffer);
1035 Track::appendDumpHeader(result);
1036 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1037 sp<Track> track = mActiveTracks[i].promote();
1038 if (track != 0) {
1039 track->dump(buffer, SIZE);
1040 result.append(buffer);
1041 }
1042 }
1043 write(fd, result.string(), result.size());
1044
1045 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1046 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1047 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1048 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1049}
1050
1051void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1052{
1053 const size_t SIZE = 256;
1054 char buffer[SIZE];
1055 String8 result;
1056
1057 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1058 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001059 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1060 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001061 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1062 ns2ms(systemTime() - mLastWriteTime));
1063 result.append(buffer);
1064 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1065 result.append(buffer);
1066 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1067 result.append(buffer);
1068 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1069 result.append(buffer);
1070 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1071 result.append(buffer);
1072 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1073 result.append(buffer);
1074 write(fd, result.string(), result.size());
1075 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1076
1077 dumpBase(fd, args);
1078}
1079
1080// Thread virtuals
1081status_t AudioFlinger::PlaybackThread::readyToRun()
1082{
1083 status_t status = initCheck();
1084 if (status == NO_ERROR) {
1085 ALOGI("AudioFlinger's thread %p ready to run", this);
1086 } else {
1087 ALOGE("No working audio driver found.");
1088 }
1089 return status;
1090}
1091
1092void AudioFlinger::PlaybackThread::onFirstRef()
1093{
1094 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1095}
1096
1097// ThreadBase virtuals
1098void AudioFlinger::PlaybackThread::preExit()
1099{
1100 ALOGV(" preExit()");
1101 // FIXME this is using hard-coded strings but in the future, this functionality will be
1102 // converted to use audio HAL extensions required to support tunneling
1103 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1104}
1105
1106// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1107sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1108 const sp<AudioFlinger::Client>& client,
1109 audio_stream_type_t streamType,
1110 uint32_t sampleRate,
1111 audio_format_t format,
1112 audio_channel_mask_t channelMask,
1113 size_t frameCount,
1114 const sp<IMemory>& sharedBuffer,
1115 int sessionId,
1116 IAudioFlinger::track_flags_t *flags,
1117 pid_t tid,
1118 status_t *status)
1119{
1120 sp<Track> track;
1121 status_t lStatus;
1122
1123 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1124
1125 // client expresses a preference for FAST, but we get the final say
1126 if (*flags & IAudioFlinger::TRACK_FAST) {
1127 if (
1128 // not timed
1129 (!isTimed) &&
1130 // either of these use cases:
1131 (
1132 // use case 1: shared buffer with any frame count
1133 (
1134 (sharedBuffer != 0)
1135 ) ||
1136 // use case 2: callback handler and frame count is default or at least as large as HAL
1137 (
1138 (tid != -1) &&
1139 ((frameCount == 0) ||
1140 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1141 )
1142 ) &&
1143 // PCM data
1144 audio_is_linear_pcm(format) &&
1145 // mono or stereo
1146 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1147 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1148#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1149 // hardware sample rate
1150 (sampleRate == mSampleRate) &&
1151#endif
1152 // normal mixer has an associated fast mixer
1153 hasFastMixer() &&
1154 // there are sufficient fast track slots available
1155 (mFastTrackAvailMask != 0)
1156 // FIXME test that MixerThread for this fast track has a capable output HAL
1157 // FIXME add a permission test also?
1158 ) {
1159 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1160 if (frameCount == 0) {
1161 frameCount = mFrameCount * kFastTrackMultiplier;
1162 }
1163 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1164 frameCount, mFrameCount);
1165 } else {
1166 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1167 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1168 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1169 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1170 audio_is_linear_pcm(format),
1171 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1172 *flags &= ~IAudioFlinger::TRACK_FAST;
1173 // For compatibility with AudioTrack calculation, buffer depth is forced
1174 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1175 // This is probably too conservative, but legacy application code may depend on it.
1176 // If you change this calculation, also review the start threshold which is related.
1177 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1178 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1179 if (minBufCount < 2) {
1180 minBufCount = 2;
1181 }
1182 size_t minFrameCount = mNormalFrameCount * minBufCount;
1183 if (frameCount < minFrameCount) {
1184 frameCount = minFrameCount;
1185 }
1186 }
1187 }
1188
1189 if (mType == DIRECT) {
1190 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1191 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1192 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1193 "for output %p with format %d",
1194 sampleRate, format, channelMask, mOutput, mFormat);
1195 lStatus = BAD_VALUE;
1196 goto Exit;
1197 }
1198 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001199 } else if (mType == OFFLOAD) {
1200 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1201 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1202 "for output %p with format %d",
1203 sampleRate, format, channelMask, mOutput, mFormat);
1204 lStatus = BAD_VALUE;
1205 goto Exit;
1206 }
Eric Laurent81784c32012-11-19 14:55:58 -08001207 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001208 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1209 ALOGE("createTrack_l() Bad parameter: format %d \""
1210 "for output %p with format %d",
1211 format, mOutput, mFormat);
1212 lStatus = BAD_VALUE;
1213 goto Exit;
1214 }
Eric Laurent81784c32012-11-19 14:55:58 -08001215 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1216 if (sampleRate > mSampleRate*2) {
1217 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1218 lStatus = BAD_VALUE;
1219 goto Exit;
1220 }
1221 }
1222
1223 lStatus = initCheck();
1224 if (lStatus != NO_ERROR) {
1225 ALOGE("Audio driver not initialized.");
1226 goto Exit;
1227 }
1228
1229 { // scope for mLock
1230 Mutex::Autolock _l(mLock);
1231
1232 // all tracks in same audio session must share the same routing strategy otherwise
1233 // conflicts will happen when tracks are moved from one output to another by audio policy
1234 // manager
1235 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1236 for (size_t i = 0; i < mTracks.size(); ++i) {
1237 sp<Track> t = mTracks[i];
1238 if (t != 0 && !t->isOutputTrack()) {
1239 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1240 if (sessionId == t->sessionId() && strategy != actual) {
1241 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1242 strategy, actual);
1243 lStatus = BAD_VALUE;
1244 goto Exit;
1245 }
1246 }
1247 }
1248
1249 if (!isTimed) {
1250 track = new Track(this, client, streamType, sampleRate, format,
1251 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1252 } else {
1253 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1254 channelMask, frameCount, sharedBuffer, sessionId);
1255 }
1256 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1257 lStatus = NO_MEMORY;
1258 goto Exit;
1259 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001260
Eric Laurent81784c32012-11-19 14:55:58 -08001261 mTracks.add(track);
1262
1263 sp<EffectChain> chain = getEffectChain_l(sessionId);
1264 if (chain != 0) {
1265 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1266 track->setMainBuffer(chain->inBuffer());
1267 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1268 chain->incTrackCnt();
1269 }
1270
1271 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1272 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1273 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1274 // so ask activity manager to do this on our behalf
1275 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1276 }
1277 }
1278
1279 lStatus = NO_ERROR;
1280
1281Exit:
1282 if (status) {
1283 *status = lStatus;
1284 }
1285 return track;
1286}
1287
1288uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1289{
1290 return latency;
1291}
1292
1293uint32_t AudioFlinger::PlaybackThread::latency() const
1294{
1295 Mutex::Autolock _l(mLock);
1296 return latency_l();
1297}
1298uint32_t AudioFlinger::PlaybackThread::latency_l() const
1299{
1300 if (initCheck() == NO_ERROR) {
1301 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1302 } else {
1303 return 0;
1304 }
1305}
1306
1307void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1308{
1309 Mutex::Autolock _l(mLock);
1310 // Don't apply master volume in SW if our HAL can do it for us.
1311 if (mOutput && mOutput->audioHwDev &&
1312 mOutput->audioHwDev->canSetMasterVolume()) {
1313 mMasterVolume = 1.0;
1314 } else {
1315 mMasterVolume = value;
1316 }
1317}
1318
1319void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1320{
1321 Mutex::Autolock _l(mLock);
1322 // Don't apply master mute in SW if our HAL can do it for us.
1323 if (mOutput && mOutput->audioHwDev &&
1324 mOutput->audioHwDev->canSetMasterMute()) {
1325 mMasterMute = false;
1326 } else {
1327 mMasterMute = muted;
1328 }
1329}
1330
1331void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1332{
1333 Mutex::Autolock _l(mLock);
1334 mStreamTypes[stream].volume = value;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001335 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001336}
1337
1338void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1339{
1340 Mutex::Autolock _l(mLock);
1341 mStreamTypes[stream].mute = muted;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001342 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001343}
1344
1345float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1346{
1347 Mutex::Autolock _l(mLock);
1348 return mStreamTypes[stream].volume;
1349}
1350
1351// addTrack_l() must be called with ThreadBase::mLock held
1352status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1353{
1354 status_t status = ALREADY_EXISTS;
1355
1356 // set retry count for buffer fill
1357 track->mRetryCount = kMaxTrackStartupRetries;
1358 if (mActiveTracks.indexOf(track) < 0) {
1359 // the track is newly added, make sure it fills up all its
1360 // buffers before playing. This is to ensure the client will
1361 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001362 if (!track->isOutputTrack()) {
1363 TrackBase::track_state state = track->mState;
1364 mLock.unlock();
1365 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1366 mLock.lock();
1367 // abort track was stopped/paused while we released the lock
1368 if (state != track->mState) {
1369 if (status == NO_ERROR) {
1370 mLock.unlock();
1371 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1372 mLock.lock();
1373 }
1374 return INVALID_OPERATION;
1375 }
1376 // abort if start is rejected by audio policy manager
1377 if (status != NO_ERROR) {
1378 return PERMISSION_DENIED;
1379 }
1380#ifdef ADD_BATTERY_DATA
1381 // to track the speaker usage
1382 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1383#endif
1384 }
1385
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001386 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001387 track->mResetDone = false;
1388 track->mPresentationCompleteFrames = 0;
1389 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001390 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1391 if (chain != 0) {
1392 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1393 track->sessionId());
1394 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001395 }
1396
1397 status = NO_ERROR;
1398 }
1399
1400 ALOGV("mWaitWorkCV.broadcast");
1401 mWaitWorkCV.broadcast();
1402
1403 return status;
1404}
1405
Eric Laurentbfb1b832013-01-07 09:53:42 -08001406bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001408 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001409 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001410 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1411 track->mState = TrackBase::STOPPED;
1412 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001413 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001414 } else if (track->isFastTrack() || track->isOffloaded()) {
1415 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001416 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001417
1418 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001419}
1420
1421void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1422{
1423 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1424 mTracks.remove(track);
1425 deleteTrackName_l(track->name());
1426 // redundant as track is about to be destroyed, for dumpsys only
1427 track->mName = -1;
1428 if (track->isFastTrack()) {
1429 int index = track->mFastIndex;
1430 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1431 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1432 mFastTrackAvailMask |= 1 << index;
1433 // redundant as track is about to be destroyed, for dumpsys only
1434 track->mFastIndex = -1;
1435 }
1436 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1437 if (chain != 0) {
1438 chain->decTrackCnt();
1439 }
1440}
1441
Eric Laurentbfb1b832013-01-07 09:53:42 -08001442void AudioFlinger::PlaybackThread::signal_l()
1443{
1444 // Thread could be blocked waiting for async
1445 // so signal it to handle state changes immediately
1446 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1447 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1448 mSignalPending = true;
1449 mWaitWorkCV.signal();
1450}
1451
Eric Laurent81784c32012-11-19 14:55:58 -08001452String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1453{
Eric Laurent81784c32012-11-19 14:55:58 -08001454 Mutex::Autolock _l(mLock);
1455 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001456 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001457 }
1458
Glenn Kastend8ea6992013-07-16 14:17:15 -07001459 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1460 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001461 free(s);
1462 return out_s8;
1463}
1464
1465// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1466void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1467 AudioSystem::OutputDescriptor desc;
1468 void *param2 = NULL;
1469
1470 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1471 param);
1472
1473 switch (event) {
1474 case AudioSystem::OUTPUT_OPENED:
1475 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001476 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001477 desc.samplingRate = mSampleRate;
1478 desc.format = mFormat;
1479 desc.frameCount = mNormalFrameCount; // FIXME see
1480 // AudioFlinger::frameCount(audio_io_handle_t)
1481 desc.latency = latency();
1482 param2 = &desc;
1483 break;
1484
1485 case AudioSystem::STREAM_CONFIG_CHANGED:
1486 param2 = &param;
1487 case AudioSystem::OUTPUT_CLOSED:
1488 default:
1489 break;
1490 }
1491 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1492}
1493
Eric Laurentbfb1b832013-01-07 09:53:42 -08001494void AudioFlinger::PlaybackThread::writeCallback()
1495{
1496 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001497 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001498}
1499
1500void AudioFlinger::PlaybackThread::drainCallback()
1501{
1502 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001503 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001504}
1505
Eric Laurent3b4529e2013-09-05 18:09:19 -07001506void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001507{
1508 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001509 // reject out of sequence requests
1510 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1511 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001512 mWaitWorkCV.signal();
1513 }
1514}
1515
Eric Laurent3b4529e2013-09-05 18:09:19 -07001516void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001517{
1518 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001519 // reject out of sequence requests
1520 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1521 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001522 mWaitWorkCV.signal();
1523 }
1524}
1525
1526// static
1527int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1528 void *param,
1529 void *cookie)
1530{
1531 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1532 ALOGV("asyncCallback() event %d", event);
1533 switch (event) {
1534 case STREAM_CBK_EVENT_WRITE_READY:
1535 me->writeCallback();
1536 break;
1537 case STREAM_CBK_EVENT_DRAIN_READY:
1538 me->drainCallback();
1539 break;
1540 default:
1541 ALOGW("asyncCallback() unknown event %d", event);
1542 break;
1543 }
1544 return 0;
1545}
1546
Eric Laurent81784c32012-11-19 14:55:58 -08001547void AudioFlinger::PlaybackThread::readOutputParameters()
1548{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001549 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001550 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1551 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001552 if (!audio_is_output_channel(mChannelMask)) {
1553 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1554 }
1555 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1556 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1557 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1558 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001559 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001560 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001561 if (!audio_is_valid_format(mFormat)) {
1562 LOG_FATAL("HAL format %d not valid for output", mFormat);
1563 }
1564 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1565 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1566 mFormat);
1567 }
Eric Laurent81784c32012-11-19 14:55:58 -08001568 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1569 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1570 if (mFrameCount & 15) {
1571 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1572 mFrameCount);
1573 }
1574
Eric Laurentbfb1b832013-01-07 09:53:42 -08001575 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1576 (mOutput->stream->set_callback != NULL)) {
1577 if (mOutput->stream->set_callback(mOutput->stream,
1578 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1579 mUseAsyncWrite = true;
1580 }
1581 }
1582
Eric Laurent81784c32012-11-19 14:55:58 -08001583 // Calculate size of normal mix buffer relative to the HAL output buffer size
1584 double multiplier = 1.0;
1585 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1586 kUseFastMixer == FastMixer_Dynamic)) {
1587 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1588 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1589 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1590 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1591 maxNormalFrameCount = maxNormalFrameCount & ~15;
1592 if (maxNormalFrameCount < minNormalFrameCount) {
1593 maxNormalFrameCount = minNormalFrameCount;
1594 }
1595 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1596 if (multiplier <= 1.0) {
1597 multiplier = 1.0;
1598 } else if (multiplier <= 2.0) {
1599 if (2 * mFrameCount <= maxNormalFrameCount) {
1600 multiplier = 2.0;
1601 } else {
1602 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1603 }
1604 } else {
1605 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1606 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1607 // track, but we sometimes have to do this to satisfy the maximum frame count
1608 // constraint)
1609 // FIXME this rounding up should not be done if no HAL SRC
1610 uint32_t truncMult = (uint32_t) multiplier;
1611 if ((truncMult & 1)) {
1612 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1613 ++truncMult;
1614 }
1615 }
1616 multiplier = (double) truncMult;
1617 }
1618 }
1619 mNormalFrameCount = multiplier * mFrameCount;
1620 // round up to nearest 16 frames to satisfy AudioMixer
1621 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1622 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1623 mNormalFrameCount);
1624
Eric Laurentbfb1b832013-01-07 09:53:42 -08001625 delete[] mAllocMixBuffer;
1626 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1627 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1628 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1629 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001630
1631 // force reconfiguration of effect chains and engines to take new buffer size and audio
1632 // parameters into account
1633 // Note that mLock is not held when readOutputParameters() is called from the constructor
1634 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1635 // matter.
1636 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1637 Vector< sp<EffectChain> > effectChains = mEffectChains;
1638 for (size_t i = 0; i < effectChains.size(); i ++) {
1639 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1640 }
1641}
1642
1643
1644status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1645{
1646 if (halFrames == NULL || dspFrames == NULL) {
1647 return BAD_VALUE;
1648 }
1649 Mutex::Autolock _l(mLock);
1650 if (initCheck() != NO_ERROR) {
1651 return INVALID_OPERATION;
1652 }
1653 size_t framesWritten = mBytesWritten / mFrameSize;
1654 *halFrames = framesWritten;
1655
1656 if (isSuspended()) {
1657 // return an estimation of rendered frames when the output is suspended
1658 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1659 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1660 return NO_ERROR;
1661 } else {
1662 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1663 }
1664}
1665
1666uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1667{
1668 Mutex::Autolock _l(mLock);
1669 uint32_t result = 0;
1670 if (getEffectChain_l(sessionId) != 0) {
1671 result = EFFECT_SESSION;
1672 }
1673
1674 for (size_t i = 0; i < mTracks.size(); ++i) {
1675 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001676 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001677 result |= TRACK_SESSION;
1678 break;
1679 }
1680 }
1681
1682 return result;
1683}
1684
1685uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1686{
1687 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1688 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1689 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1690 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1691 }
1692 for (size_t i = 0; i < mTracks.size(); i++) {
1693 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001694 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001695 return AudioSystem::getStrategyForStream(track->streamType());
1696 }
1697 }
1698 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1699}
1700
1701
1702AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1703{
1704 Mutex::Autolock _l(mLock);
1705 return mOutput;
1706}
1707
1708AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1709{
1710 Mutex::Autolock _l(mLock);
1711 AudioStreamOut *output = mOutput;
1712 mOutput = NULL;
1713 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1714 // must push a NULL and wait for ack
1715 mOutputSink.clear();
1716 mPipeSink.clear();
1717 mNormalSink.clear();
1718 return output;
1719}
1720
1721// this method must always be called either with ThreadBase mLock held or inside the thread loop
1722audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1723{
1724 if (mOutput == NULL) {
1725 return NULL;
1726 }
1727 return &mOutput->stream->common;
1728}
1729
1730uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1731{
1732 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1733}
1734
1735status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1736{
1737 if (!isValidSyncEvent(event)) {
1738 return BAD_VALUE;
1739 }
1740
1741 Mutex::Autolock _l(mLock);
1742
1743 for (size_t i = 0; i < mTracks.size(); ++i) {
1744 sp<Track> track = mTracks[i];
1745 if (event->triggerSession() == track->sessionId()) {
1746 (void) track->setSyncEvent(event);
1747 return NO_ERROR;
1748 }
1749 }
1750
1751 return NAME_NOT_FOUND;
1752}
1753
1754bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1755{
1756 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1757}
1758
1759void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1760 const Vector< sp<Track> >& tracksToRemove)
1761{
1762 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001763 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001764 for (size_t i = 0 ; i < count ; i++) {
1765 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001767 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001768#ifdef ADD_BATTERY_DATA
1769 // to track the speaker usage
1770 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1771#endif
1772 if (track->isTerminated()) {
1773 AudioSystem::releaseOutput(mId);
1774 }
Eric Laurent81784c32012-11-19 14:55:58 -08001775 }
1776 }
1777 }
Eric Laurent81784c32012-11-19 14:55:58 -08001778}
1779
1780void AudioFlinger::PlaybackThread::checkSilentMode_l()
1781{
1782 if (!mMasterMute) {
1783 char value[PROPERTY_VALUE_MAX];
1784 if (property_get("ro.audio.silent", value, "0") > 0) {
1785 char *endptr;
1786 unsigned long ul = strtoul(value, &endptr, 0);
1787 if (*endptr == '\0' && ul != 0) {
1788 ALOGD("Silence is golden");
1789 // The setprop command will not allow a property to be changed after
1790 // the first time it is set, so we don't have to worry about un-muting.
1791 setMasterMute_l(true);
1792 }
1793 }
1794 }
1795}
1796
1797// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001798ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001799{
1800 // FIXME rewrite to reduce number of system calls
1801 mLastWriteTime = systemTime();
1802 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001803 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001804
1805 // If an NBAIO sink is present, use it to write the normal mixer's submix
1806 if (mNormalSink != 0) {
1807#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001808 size_t count = mBytesRemaining >> mBitShift;
1809 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001810 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001811 // update the setpoint when AudioFlinger::mScreenState changes
1812 uint32_t screenState = AudioFlinger::mScreenState;
1813 if (screenState != mScreenState) {
1814 mScreenState = screenState;
1815 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1816 if (pipe != NULL) {
1817 pipe->setAvgFrames((mScreenState & 1) ?
1818 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1819 }
1820 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001821 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001822 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001823 if (framesWritten > 0) {
1824 bytesWritten = framesWritten << mBitShift;
1825 } else {
1826 bytesWritten = framesWritten;
1827 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001828 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001829 if (status == NO_ERROR) {
1830 size_t totalFramesWritten = mNormalSink->framesWritten();
1831 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1832 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1833 mLatchDValid = true;
1834 }
1835 }
Eric Laurent81784c32012-11-19 14:55:58 -08001836 // otherwise use the HAL / AudioStreamOut directly
1837 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001838 // Direct output and offload threads
1839 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1840 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001841 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1842 mWriteAckSequence += 2;
1843 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001844 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001845 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001846 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001847 // FIXME We should have an implementation of timestamps for direct output threads.
1848 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001849 bytesWritten = mOutput->stream->write(mOutput->stream,
1850 mMixBuffer + offset, mBytesRemaining);
1851 if (mUseAsyncWrite &&
1852 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1853 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001854 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001856 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857 }
Eric Laurent81784c32012-11-19 14:55:58 -08001858 }
1859
Eric Laurent81784c32012-11-19 14:55:58 -08001860 mNumWrites++;
1861 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862
1863 return bytesWritten;
1864}
1865
1866void AudioFlinger::PlaybackThread::threadLoop_drain()
1867{
1868 if (mOutput->stream->drain) {
1869 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1870 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001871 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1872 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001874 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001875 }
1876 mOutput->stream->drain(mOutput->stream,
1877 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1878 : AUDIO_DRAIN_ALL);
1879 }
1880}
1881
1882void AudioFlinger::PlaybackThread::threadLoop_exit()
1883{
1884 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001885}
1886
1887/*
1888The derived values that are cached:
1889 - mixBufferSize from frame count * frame size
1890 - activeSleepTime from activeSleepTimeUs()
1891 - idleSleepTime from idleSleepTimeUs()
1892 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1893 - maxPeriod from frame count and sample rate (MIXER only)
1894
1895The parameters that affect these derived values are:
1896 - frame count
1897 - frame size
1898 - sample rate
1899 - device type: A2DP or not
1900 - device latency
1901 - format: PCM or not
1902 - active sleep time
1903 - idle sleep time
1904*/
1905
1906void AudioFlinger::PlaybackThread::cacheParameters_l()
1907{
1908 mixBufferSize = mNormalFrameCount * mFrameSize;
1909 activeSleepTime = activeSleepTimeUs();
1910 idleSleepTime = idleSleepTimeUs();
1911}
1912
1913void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1914{
Glenn Kasten7c027242012-12-26 14:43:16 -08001915 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001916 this, streamType, mTracks.size());
1917 Mutex::Autolock _l(mLock);
1918
1919 size_t size = mTracks.size();
1920 for (size_t i = 0; i < size; i++) {
1921 sp<Track> t = mTracks[i];
1922 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001923 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001924 }
1925 }
1926}
1927
1928status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1929{
1930 int session = chain->sessionId();
1931 int16_t *buffer = mMixBuffer;
1932 bool ownsBuffer = false;
1933
1934 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1935 if (session > 0) {
1936 // Only one effect chain can be present in direct output thread and it uses
1937 // the mix buffer as input
1938 if (mType != DIRECT) {
1939 size_t numSamples = mNormalFrameCount * mChannelCount;
1940 buffer = new int16_t[numSamples];
1941 memset(buffer, 0, numSamples * sizeof(int16_t));
1942 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1943 ownsBuffer = true;
1944 }
1945
1946 // Attach all tracks with same session ID to this chain.
1947 for (size_t i = 0; i < mTracks.size(); ++i) {
1948 sp<Track> track = mTracks[i];
1949 if (session == track->sessionId()) {
1950 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1951 buffer);
1952 track->setMainBuffer(buffer);
1953 chain->incTrackCnt();
1954 }
1955 }
1956
1957 // indicate all active tracks in the chain
1958 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1959 sp<Track> track = mActiveTracks[i].promote();
1960 if (track == 0) {
1961 continue;
1962 }
1963 if (session == track->sessionId()) {
1964 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1965 chain->incActiveTrackCnt();
1966 }
1967 }
1968 }
1969
1970 chain->setInBuffer(buffer, ownsBuffer);
1971 chain->setOutBuffer(mMixBuffer);
1972 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1973 // chains list in order to be processed last as it contains output stage effects
1974 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1975 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1976 // after track specific effects and before output stage
1977 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1978 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1979 // Effect chain for other sessions are inserted at beginning of effect
1980 // chains list to be processed before output mix effects. Relative order between other
1981 // sessions is not important
1982 size_t size = mEffectChains.size();
1983 size_t i = 0;
1984 for (i = 0; i < size; i++) {
1985 if (mEffectChains[i]->sessionId() < session) {
1986 break;
1987 }
1988 }
1989 mEffectChains.insertAt(chain, i);
1990 checkSuspendOnAddEffectChain_l(chain);
1991
1992 return NO_ERROR;
1993}
1994
1995size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1996{
1997 int session = chain->sessionId();
1998
1999 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2000
2001 for (size_t i = 0; i < mEffectChains.size(); i++) {
2002 if (chain == mEffectChains[i]) {
2003 mEffectChains.removeAt(i);
2004 // detach all active tracks from the chain
2005 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2006 sp<Track> track = mActiveTracks[i].promote();
2007 if (track == 0) {
2008 continue;
2009 }
2010 if (session == track->sessionId()) {
2011 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2012 chain.get(), session);
2013 chain->decActiveTrackCnt();
2014 }
2015 }
2016
2017 // detach all tracks with same session ID from this chain
2018 for (size_t i = 0; i < mTracks.size(); ++i) {
2019 sp<Track> track = mTracks[i];
2020 if (session == track->sessionId()) {
2021 track->setMainBuffer(mMixBuffer);
2022 chain->decTrackCnt();
2023 }
2024 }
2025 break;
2026 }
2027 }
2028 return mEffectChains.size();
2029}
2030
2031status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2032 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2033{
2034 Mutex::Autolock _l(mLock);
2035 return attachAuxEffect_l(track, EffectId);
2036}
2037
2038status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2039 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2040{
2041 status_t status = NO_ERROR;
2042
2043 if (EffectId == 0) {
2044 track->setAuxBuffer(0, NULL);
2045 } else {
2046 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2047 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2048 if (effect != 0) {
2049 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2050 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2051 } else {
2052 status = INVALID_OPERATION;
2053 }
2054 } else {
2055 status = BAD_VALUE;
2056 }
2057 }
2058 return status;
2059}
2060
2061void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2062{
2063 for (size_t i = 0; i < mTracks.size(); ++i) {
2064 sp<Track> track = mTracks[i];
2065 if (track->auxEffectId() == effectId) {
2066 attachAuxEffect_l(track, 0);
2067 }
2068 }
2069}
2070
2071bool AudioFlinger::PlaybackThread::threadLoop()
2072{
2073 Vector< sp<Track> > tracksToRemove;
2074
2075 standbyTime = systemTime();
2076
2077 // MIXER
2078 nsecs_t lastWarning = 0;
2079
2080 // DUPLICATING
2081 // FIXME could this be made local to while loop?
2082 writeFrames = 0;
2083
2084 cacheParameters_l();
2085 sleepTime = idleSleepTime;
2086
2087 if (mType == MIXER) {
2088 sleepTimeShift = 0;
2089 }
2090
2091 CpuStats cpuStats;
2092 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2093
2094 acquireWakeLock();
2095
Glenn Kasten9e58b552013-01-18 15:09:48 -08002096 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2097 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2098 // and then that string will be logged at the next convenient opportunity.
2099 const char *logString = NULL;
2100
Eric Laurent81784c32012-11-19 14:55:58 -08002101 while (!exitPending())
2102 {
2103 cpuStats.sample(myName);
2104
2105 Vector< sp<EffectChain> > effectChains;
2106
2107 processConfigEvents();
2108
2109 { // scope for mLock
2110
2111 Mutex::Autolock _l(mLock);
2112
Glenn Kasten9e58b552013-01-18 15:09:48 -08002113 if (logString != NULL) {
2114 mNBLogWriter->logTimestamp();
2115 mNBLogWriter->log(logString);
2116 logString = NULL;
2117 }
2118
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002119 if (mLatchDValid) {
2120 mLatchQ = mLatchD;
2121 mLatchDValid = false;
2122 mLatchQValid = true;
2123 }
2124
Eric Laurent81784c32012-11-19 14:55:58 -08002125 if (checkForNewParameters_l()) {
2126 cacheParameters_l();
2127 }
2128
2129 saveOutputTracks();
2130
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131 if (mSignalPending) {
2132 // A signal was raised while we were unlocked
2133 mSignalPending = false;
2134 } else if (waitingAsyncCallback_l()) {
2135 if (exitPending()) {
2136 break;
2137 }
2138 releaseWakeLock_l();
2139 ALOGV("wait async completion");
2140 mWaitWorkCV.wait(mLock);
2141 ALOGV("async completion/wake");
2142 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002143 standbyTime = systemTime() + standbyDelay;
2144 sleepTime = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 if (exitPending()) {
2146 break;
2147 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2149 isSuspended()) {
2150 // put audio hardware into standby after short delay
2151 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002152
2153 threadLoop_standby();
2154
2155 mStandby = true;
2156 }
2157
2158 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2159 // we're about to wait, flush the binder command buffer
2160 IPCThreadState::self()->flushCommands();
2161
2162 clearOutputTracks();
2163
2164 if (exitPending()) {
2165 break;
2166 }
2167
2168 releaseWakeLock_l();
2169 // wait until we have something to do...
2170 ALOGV("%s going to sleep", myName.string());
2171 mWaitWorkCV.wait(mLock);
2172 ALOGV("%s waking up", myName.string());
2173 acquireWakeLock_l();
2174
2175 mMixerStatus = MIXER_IDLE;
2176 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2177 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002179 checkSilentMode_l();
2180
2181 standbyTime = systemTime() + standbyDelay;
2182 sleepTime = idleSleepTime;
2183 if (mType == MIXER) {
2184 sleepTimeShift = 0;
2185 }
2186
2187 continue;
2188 }
2189 }
2190
2191 // mMixerStatusIgnoringFastTracks is also updated internally
2192 mMixerStatus = prepareTracks_l(&tracksToRemove);
2193
2194 // prevent any changes in effect chain list and in each effect chain
2195 // during mixing and effect process as the audio buffers could be deleted
2196 // or modified if an effect is created or deleted
2197 lockEffectChains_l(effectChains);
2198 }
2199
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 if (mBytesRemaining == 0) {
2201 mCurrentWriteLength = 0;
2202 if (mMixerStatus == MIXER_TRACKS_READY) {
2203 // threadLoop_mix() sets mCurrentWriteLength
2204 threadLoop_mix();
2205 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2206 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2207 // threadLoop_sleepTime sets sleepTime to 0 if data
2208 // must be written to HAL
2209 threadLoop_sleepTime();
2210 if (sleepTime == 0) {
2211 mCurrentWriteLength = mixBufferSize;
2212 }
2213 }
2214 mBytesRemaining = mCurrentWriteLength;
2215 if (isSuspended()) {
2216 sleepTime = suspendSleepTimeUs();
2217 // simulate write to HAL when suspended
2218 mBytesWritten += mixBufferSize;
2219 mBytesRemaining = 0;
2220 }
Eric Laurent81784c32012-11-19 14:55:58 -08002221
Eric Laurentbfb1b832013-01-07 09:53:42 -08002222 // only process effects if we're going to write
2223 if (sleepTime == 0) {
2224 for (size_t i = 0; i < effectChains.size(); i ++) {
2225 effectChains[i]->process_l();
2226 }
Eric Laurent81784c32012-11-19 14:55:58 -08002227 }
2228 }
2229
2230 // enable changes in effect chain
2231 unlockEffectChains(effectChains);
2232
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 if (!waitingAsyncCallback()) {
2234 // sleepTime == 0 means we must write to audio hardware
2235 if (sleepTime == 0) {
2236 if (mBytesRemaining) {
2237 ssize_t ret = threadLoop_write();
2238 if (ret < 0) {
2239 mBytesRemaining = 0;
2240 } else {
2241 mBytesWritten += ret;
2242 mBytesRemaining -= ret;
2243 }
2244 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2245 (mMixerStatus == MIXER_DRAIN_ALL)) {
2246 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002247 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002248if (mType == MIXER) {
2249 // write blocked detection
2250 nsecs_t now = systemTime();
2251 nsecs_t delta = now - mLastWriteTime;
2252 if (!mStandby && delta > maxPeriod) {
2253 mNumDelayedWrites++;
2254 if ((now - lastWarning) > kWarningThrottleNs) {
2255 ATRACE_NAME("underrun");
2256 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2257 ns2ms(delta), mNumDelayedWrites, this);
2258 lastWarning = now;
2259 }
2260 }
Eric Laurent81784c32012-11-19 14:55:58 -08002261}
2262
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263 mStandby = false;
2264 } else {
2265 usleep(sleepTime);
2266 }
Eric Laurent81784c32012-11-19 14:55:58 -08002267 }
2268
2269 // Finally let go of removed track(s), without the lock held
2270 // since we can't guarantee the destructors won't acquire that
2271 // same lock. This will also mutate and push a new fast mixer state.
2272 threadLoop_removeTracks(tracksToRemove);
2273 tracksToRemove.clear();
2274
2275 // FIXME I don't understand the need for this here;
2276 // it was in the original code but maybe the
2277 // assignment in saveOutputTracks() makes this unnecessary?
2278 clearOutputTracks();
2279
2280 // Effect chains will be actually deleted here if they were removed from
2281 // mEffectChains list during mixing or effects processing
2282 effectChains.clear();
2283
2284 // FIXME Note that the above .clear() is no longer necessary since effectChains
2285 // is now local to this block, but will keep it for now (at least until merge done).
2286 }
2287
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 threadLoop_exit();
2289
Eric Laurent81784c32012-11-19 14:55:58 -08002290 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002292 // put output stream into standby mode
2293 if (!mStandby) {
2294 mOutput->stream->common.standby(&mOutput->stream->common);
2295 }
2296 }
2297
2298 releaseWakeLock();
2299
2300 ALOGV("Thread %p type %d exiting", this, mType);
2301 return false;
2302}
2303
Eric Laurentbfb1b832013-01-07 09:53:42 -08002304// removeTracks_l() must be called with ThreadBase::mLock held
2305void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2306{
2307 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002308 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002309 for (size_t i=0 ; i<count ; i++) {
2310 const sp<Track>& track = tracksToRemove.itemAt(i);
2311 mActiveTracks.remove(track);
2312 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2313 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2314 if (chain != 0) {
2315 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2316 track->sessionId());
2317 chain->decActiveTrackCnt();
2318 }
2319 if (track->isTerminated()) {
2320 removeTrack_l(track);
2321 }
2322 }
2323 }
2324
2325}
Eric Laurent81784c32012-11-19 14:55:58 -08002326
2327// ----------------------------------------------------------------------------
2328
2329AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2330 audio_io_handle_t id, audio_devices_t device, type_t type)
2331 : PlaybackThread(audioFlinger, output, id, device, type),
2332 // mAudioMixer below
2333 // mFastMixer below
2334 mFastMixerFutex(0)
2335 // mOutputSink below
2336 // mPipeSink below
2337 // mNormalSink below
2338{
2339 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002340 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002341 "mFrameCount=%d, mNormalFrameCount=%d",
2342 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2343 mNormalFrameCount);
2344 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2345
2346 // FIXME - Current mixer implementation only supports stereo output
2347 if (mChannelCount != FCC_2) {
2348 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2349 }
2350
2351 // create an NBAIO sink for the HAL output stream, and negotiate
2352 mOutputSink = new AudioStreamOutSink(output->stream);
2353 size_t numCounterOffers = 0;
2354 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2355 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2356 ALOG_ASSERT(index == 0);
2357
2358 // initialize fast mixer depending on configuration
2359 bool initFastMixer;
2360 switch (kUseFastMixer) {
2361 case FastMixer_Never:
2362 initFastMixer = false;
2363 break;
2364 case FastMixer_Always:
2365 initFastMixer = true;
2366 break;
2367 case FastMixer_Static:
2368 case FastMixer_Dynamic:
2369 initFastMixer = mFrameCount < mNormalFrameCount;
2370 break;
2371 }
2372 if (initFastMixer) {
2373
2374 // create a MonoPipe to connect our submix to FastMixer
2375 NBAIO_Format format = mOutputSink->format();
2376 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2377 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2378 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2379 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2380 const NBAIO_Format offers[1] = {format};
2381 size_t numCounterOffers = 0;
2382 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2383 ALOG_ASSERT(index == 0);
2384 monoPipe->setAvgFrames((mScreenState & 1) ?
2385 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2386 mPipeSink = monoPipe;
2387
Glenn Kasten46909e72013-02-26 09:20:22 -08002388#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002389 if (mTeeSinkOutputEnabled) {
2390 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2391 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2392 numCounterOffers = 0;
2393 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2394 ALOG_ASSERT(index == 0);
2395 mTeeSink = teeSink;
2396 PipeReader *teeSource = new PipeReader(*teeSink);
2397 numCounterOffers = 0;
2398 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2399 ALOG_ASSERT(index == 0);
2400 mTeeSource = teeSource;
2401 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002402#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002403
2404 // create fast mixer and configure it initially with just one fast track for our submix
2405 mFastMixer = new FastMixer();
2406 FastMixerStateQueue *sq = mFastMixer->sq();
2407#ifdef STATE_QUEUE_DUMP
2408 sq->setObserverDump(&mStateQueueObserverDump);
2409 sq->setMutatorDump(&mStateQueueMutatorDump);
2410#endif
2411 FastMixerState *state = sq->begin();
2412 FastTrack *fastTrack = &state->mFastTracks[0];
2413 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2414 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2415 fastTrack->mVolumeProvider = NULL;
2416 fastTrack->mGeneration++;
2417 state->mFastTracksGen++;
2418 state->mTrackMask = 1;
2419 // fast mixer will use the HAL output sink
2420 state->mOutputSink = mOutputSink.get();
2421 state->mOutputSinkGen++;
2422 state->mFrameCount = mFrameCount;
2423 state->mCommand = FastMixerState::COLD_IDLE;
2424 // already done in constructor initialization list
2425 //mFastMixerFutex = 0;
2426 state->mColdFutexAddr = &mFastMixerFutex;
2427 state->mColdGen++;
2428 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002429#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002430 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002431#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002432 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2433 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002434 sq->end();
2435 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2436
2437 // start the fast mixer
2438 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2439 pid_t tid = mFastMixer->getTid();
2440 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2441 if (err != 0) {
2442 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2443 kPriorityFastMixer, getpid_cached, tid, err);
2444 }
2445
2446#ifdef AUDIO_WATCHDOG
2447 // create and start the watchdog
2448 mAudioWatchdog = new AudioWatchdog();
2449 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2450 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2451 tid = mAudioWatchdog->getTid();
2452 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2453 if (err != 0) {
2454 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2455 kPriorityFastMixer, getpid_cached, tid, err);
2456 }
2457#endif
2458
2459 } else {
2460 mFastMixer = NULL;
2461 }
2462
2463 switch (kUseFastMixer) {
2464 case FastMixer_Never:
2465 case FastMixer_Dynamic:
2466 mNormalSink = mOutputSink;
2467 break;
2468 case FastMixer_Always:
2469 mNormalSink = mPipeSink;
2470 break;
2471 case FastMixer_Static:
2472 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2473 break;
2474 }
2475}
2476
2477AudioFlinger::MixerThread::~MixerThread()
2478{
2479 if (mFastMixer != NULL) {
2480 FastMixerStateQueue *sq = mFastMixer->sq();
2481 FastMixerState *state = sq->begin();
2482 if (state->mCommand == FastMixerState::COLD_IDLE) {
2483 int32_t old = android_atomic_inc(&mFastMixerFutex);
2484 if (old == -1) {
2485 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2486 }
2487 }
2488 state->mCommand = FastMixerState::EXIT;
2489 sq->end();
2490 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2491 mFastMixer->join();
2492 // Though the fast mixer thread has exited, it's state queue is still valid.
2493 // We'll use that extract the final state which contains one remaining fast track
2494 // corresponding to our sub-mix.
2495 state = sq->begin();
2496 ALOG_ASSERT(state->mTrackMask == 1);
2497 FastTrack *fastTrack = &state->mFastTracks[0];
2498 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2499 delete fastTrack->mBufferProvider;
2500 sq->end(false /*didModify*/);
2501 delete mFastMixer;
2502#ifdef AUDIO_WATCHDOG
2503 if (mAudioWatchdog != 0) {
2504 mAudioWatchdog->requestExit();
2505 mAudioWatchdog->requestExitAndWait();
2506 mAudioWatchdog.clear();
2507 }
2508#endif
2509 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002510 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002511 delete mAudioMixer;
2512}
2513
2514
2515uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2516{
2517 if (mFastMixer != NULL) {
2518 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2519 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2520 }
2521 return latency;
2522}
2523
2524
2525void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2526{
2527 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2528}
2529
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002531{
2532 // FIXME we should only do one push per cycle; confirm this is true
2533 // Start the fast mixer if it's not already running
2534 if (mFastMixer != NULL) {
2535 FastMixerStateQueue *sq = mFastMixer->sq();
2536 FastMixerState *state = sq->begin();
2537 if (state->mCommand != FastMixerState::MIX_WRITE &&
2538 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2539 if (state->mCommand == FastMixerState::COLD_IDLE) {
2540 int32_t old = android_atomic_inc(&mFastMixerFutex);
2541 if (old == -1) {
2542 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2543 }
2544#ifdef AUDIO_WATCHDOG
2545 if (mAudioWatchdog != 0) {
2546 mAudioWatchdog->resume();
2547 }
2548#endif
2549 }
2550 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002551 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2552 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002553 sq->end();
2554 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2555 if (kUseFastMixer == FastMixer_Dynamic) {
2556 mNormalSink = mPipeSink;
2557 }
2558 } else {
2559 sq->end(false /*didModify*/);
2560 }
2561 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002563}
2564
2565void AudioFlinger::MixerThread::threadLoop_standby()
2566{
2567 // Idle the fast mixer if it's currently running
2568 if (mFastMixer != NULL) {
2569 FastMixerStateQueue *sq = mFastMixer->sq();
2570 FastMixerState *state = sq->begin();
2571 if (!(state->mCommand & FastMixerState::IDLE)) {
2572 state->mCommand = FastMixerState::COLD_IDLE;
2573 state->mColdFutexAddr = &mFastMixerFutex;
2574 state->mColdGen++;
2575 mFastMixerFutex = 0;
2576 sq->end();
2577 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2578 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2579 if (kUseFastMixer == FastMixer_Dynamic) {
2580 mNormalSink = mOutputSink;
2581 }
2582#ifdef AUDIO_WATCHDOG
2583 if (mAudioWatchdog != 0) {
2584 mAudioWatchdog->pause();
2585 }
2586#endif
2587 } else {
2588 sq->end(false /*didModify*/);
2589 }
2590 }
2591 PlaybackThread::threadLoop_standby();
2592}
2593
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594// Empty implementation for standard mixer
2595// Overridden for offloaded playback
2596void AudioFlinger::PlaybackThread::flushOutput_l()
2597{
2598}
2599
2600bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2601{
2602 return false;
2603}
2604
2605bool AudioFlinger::PlaybackThread::shouldStandby_l()
2606{
2607 return !mStandby;
2608}
2609
2610bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2611{
2612 Mutex::Autolock _l(mLock);
2613 return waitingAsyncCallback_l();
2614}
2615
Eric Laurent81784c32012-11-19 14:55:58 -08002616// shared by MIXER and DIRECT, overridden by DUPLICATING
2617void AudioFlinger::PlaybackThread::threadLoop_standby()
2618{
2619 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2620 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002621 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002622 // discard any pending drain or write ack by incrementing sequence
2623 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2624 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002625 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002626 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2627 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 }
Eric Laurent81784c32012-11-19 14:55:58 -08002629}
2630
2631void AudioFlinger::MixerThread::threadLoop_mix()
2632{
2633 // obtain the presentation timestamp of the next output buffer
2634 int64_t pts;
2635 status_t status = INVALID_OPERATION;
2636
2637 if (mNormalSink != 0) {
2638 status = mNormalSink->getNextWriteTimestamp(&pts);
2639 } else {
2640 status = mOutputSink->getNextWriteTimestamp(&pts);
2641 }
2642
2643 if (status != NO_ERROR) {
2644 pts = AudioBufferProvider::kInvalidPTS;
2645 }
2646
2647 // mix buffers...
2648 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002649 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002650 // increase sleep time progressively when application underrun condition clears.
2651 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2652 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2653 // such that we would underrun the audio HAL.
2654 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2655 sleepTimeShift--;
2656 }
2657 sleepTime = 0;
2658 standbyTime = systemTime() + standbyDelay;
2659 //TODO: delay standby when effects have a tail
2660}
2661
2662void AudioFlinger::MixerThread::threadLoop_sleepTime()
2663{
2664 // If no tracks are ready, sleep once for the duration of an output
2665 // buffer size, then write 0s to the output
2666 if (sleepTime == 0) {
2667 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2668 sleepTime = activeSleepTime >> sleepTimeShift;
2669 if (sleepTime < kMinThreadSleepTimeUs) {
2670 sleepTime = kMinThreadSleepTimeUs;
2671 }
2672 // reduce sleep time in case of consecutive application underruns to avoid
2673 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2674 // duration we would end up writing less data than needed by the audio HAL if
2675 // the condition persists.
2676 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2677 sleepTimeShift++;
2678 }
2679 } else {
2680 sleepTime = idleSleepTime;
2681 }
2682 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2683 memset (mMixBuffer, 0, mixBufferSize);
2684 sleepTime = 0;
2685 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2686 "anticipated start");
2687 }
2688 // TODO add standby time extension fct of effect tail
2689}
2690
2691// prepareTracks_l() must be called with ThreadBase::mLock held
2692AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2693 Vector< sp<Track> > *tracksToRemove)
2694{
2695
2696 mixer_state mixerStatus = MIXER_IDLE;
2697 // find out which tracks need to be processed
2698 size_t count = mActiveTracks.size();
2699 size_t mixedTracks = 0;
2700 size_t tracksWithEffect = 0;
2701 // counts only _active_ fast tracks
2702 size_t fastTracks = 0;
2703 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2704
2705 float masterVolume = mMasterVolume;
2706 bool masterMute = mMasterMute;
2707
2708 if (masterMute) {
2709 masterVolume = 0;
2710 }
2711 // Delegate master volume control to effect in output mix effect chain if needed
2712 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2713 if (chain != 0) {
2714 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2715 chain->setVolume_l(&v, &v);
2716 masterVolume = (float)((v + (1 << 23)) >> 24);
2717 chain.clear();
2718 }
2719
2720 // prepare a new state to push
2721 FastMixerStateQueue *sq = NULL;
2722 FastMixerState *state = NULL;
2723 bool didModify = false;
2724 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2725 if (mFastMixer != NULL) {
2726 sq = mFastMixer->sq();
2727 state = sq->begin();
2728 }
2729
2730 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002731 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002732 if (t == 0) {
2733 continue;
2734 }
2735
2736 // this const just means the local variable doesn't change
2737 Track* const track = t.get();
2738
2739 // process fast tracks
2740 if (track->isFastTrack()) {
2741
2742 // It's theoretically possible (though unlikely) for a fast track to be created
2743 // and then removed within the same normal mix cycle. This is not a problem, as
2744 // the track never becomes active so it's fast mixer slot is never touched.
2745 // The converse, of removing an (active) track and then creating a new track
2746 // at the identical fast mixer slot within the same normal mix cycle,
2747 // is impossible because the slot isn't marked available until the end of each cycle.
2748 int j = track->mFastIndex;
2749 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2750 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2751 FastTrack *fastTrack = &state->mFastTracks[j];
2752
2753 // Determine whether the track is currently in underrun condition,
2754 // and whether it had a recent underrun.
2755 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2756 FastTrackUnderruns underruns = ftDump->mUnderruns;
2757 uint32_t recentFull = (underruns.mBitFields.mFull -
2758 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2759 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2760 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2761 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2762 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2763 uint32_t recentUnderruns = recentPartial + recentEmpty;
2764 track->mObservedUnderruns = underruns;
2765 // don't count underruns that occur while stopping or pausing
2766 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002767 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2768 recentUnderruns > 0) {
2769 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2770 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002771 }
2772
2773 // This is similar to the state machine for normal tracks,
2774 // with a few modifications for fast tracks.
2775 bool isActive = true;
2776 switch (track->mState) {
2777 case TrackBase::STOPPING_1:
2778 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002780 track->mState = TrackBase::STOPPING_2;
2781 }
2782 break;
2783 case TrackBase::PAUSING:
2784 // ramp down is not yet implemented
2785 track->setPaused();
2786 break;
2787 case TrackBase::RESUMING:
2788 // ramp up is not yet implemented
2789 track->mState = TrackBase::ACTIVE;
2790 break;
2791 case TrackBase::ACTIVE:
2792 if (recentFull > 0 || recentPartial > 0) {
2793 // track has provided at least some frames recently: reset retry count
2794 track->mRetryCount = kMaxTrackRetries;
2795 }
2796 if (recentUnderruns == 0) {
2797 // no recent underruns: stay active
2798 break;
2799 }
2800 // there has recently been an underrun of some kind
2801 if (track->sharedBuffer() == 0) {
2802 // were any of the recent underruns "empty" (no frames available)?
2803 if (recentEmpty == 0) {
2804 // no, then ignore the partial underruns as they are allowed indefinitely
2805 break;
2806 }
2807 // there has recently been an "empty" underrun: decrement the retry counter
2808 if (--(track->mRetryCount) > 0) {
2809 break;
2810 }
2811 // indicate to client process that the track was disabled because of underrun;
2812 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002813 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // remove from active list, but state remains ACTIVE [confusing but true]
2815 isActive = false;
2816 break;
2817 }
2818 // fall through
2819 case TrackBase::STOPPING_2:
2820 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002821 case TrackBase::STOPPED:
2822 case TrackBase::FLUSHED: // flush() while active
2823 // Check for presentation complete if track is inactive
2824 // We have consumed all the buffers of this track.
2825 // This would be incomplete if we auto-paused on underrun
2826 {
2827 size_t audioHALFrames =
2828 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2829 size_t framesWritten = mBytesWritten / mFrameSize;
2830 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2831 // track stays in active list until presentation is complete
2832 break;
2833 }
2834 }
2835 if (track->isStopping_2()) {
2836 track->mState = TrackBase::STOPPED;
2837 }
2838 if (track->isStopped()) {
2839 // Can't reset directly, as fast mixer is still polling this track
2840 // track->reset();
2841 // So instead mark this track as needing to be reset after push with ack
2842 resetMask |= 1 << i;
2843 }
2844 isActive = false;
2845 break;
2846 case TrackBase::IDLE:
2847 default:
2848 LOG_FATAL("unexpected track state %d", track->mState);
2849 }
2850
2851 if (isActive) {
2852 // was it previously inactive?
2853 if (!(state->mTrackMask & (1 << j))) {
2854 ExtendedAudioBufferProvider *eabp = track;
2855 VolumeProvider *vp = track;
2856 fastTrack->mBufferProvider = eabp;
2857 fastTrack->mVolumeProvider = vp;
2858 fastTrack->mSampleRate = track->mSampleRate;
2859 fastTrack->mChannelMask = track->mChannelMask;
2860 fastTrack->mGeneration++;
2861 state->mTrackMask |= 1 << j;
2862 didModify = true;
2863 // no acknowledgement required for newly active tracks
2864 }
2865 // cache the combined master volume and stream type volume for fast mixer; this
2866 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002867 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002868 ++fastTracks;
2869 } else {
2870 // was it previously active?
2871 if (state->mTrackMask & (1 << j)) {
2872 fastTrack->mBufferProvider = NULL;
2873 fastTrack->mGeneration++;
2874 state->mTrackMask &= ~(1 << j);
2875 didModify = true;
2876 // If any fast tracks were removed, we must wait for acknowledgement
2877 // because we're about to decrement the last sp<> on those tracks.
2878 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2879 } else {
2880 LOG_FATAL("fast track %d should have been active", j);
2881 }
2882 tracksToRemove->add(track);
2883 // Avoids a misleading display in dumpsys
2884 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2885 }
2886 continue;
2887 }
2888
2889 { // local variable scope to avoid goto warning
2890
2891 audio_track_cblk_t* cblk = track->cblk();
2892
2893 // The first time a track is added we wait
2894 // for all its buffers to be filled before processing it
2895 int name = track->name();
2896 // make sure that we have enough frames to mix one full buffer.
2897 // enforce this condition only once to enable draining the buffer in case the client
2898 // app does not call stop() and relies on underrun to stop:
2899 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2900 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002901 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002902 uint32_t sr = track->sampleRate();
2903 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002904 desiredFrames = mNormalFrameCount;
2905 } else {
2906 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002907 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002908 // add frames already consumed but not yet released by the resampler
2909 // because cblk->framesReady() will include these frames
2910 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2911 // the minimum track buffer size is normally twice the number of frames necessary
2912 // to fill one buffer and the resampler should not leave more than one buffer worth
2913 // of unreleased frames after each pass, but just in case...
2914 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2915 }
Eric Laurent81784c32012-11-19 14:55:58 -08002916 uint32_t minFrames = 1;
2917 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2918 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002919 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002920 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002921 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2922 size_t framesReady;
2923 if (track->sharedBuffer() == 0) {
2924 framesReady = track->framesReady();
2925 } else if (track->isStopped()) {
2926 framesReady = 0;
2927 } else {
2928 framesReady = 1;
2929 }
2930 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002931 !track->isPaused() && !track->isTerminated())
2932 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002933 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002934
2935 mixedTracks++;
2936
2937 // track->mainBuffer() != mMixBuffer means there is an effect chain
2938 // connected to the track
2939 chain.clear();
2940 if (track->mainBuffer() != mMixBuffer) {
2941 chain = getEffectChain_l(track->sessionId());
2942 // Delegate volume control to effect in track effect chain if needed
2943 if (chain != 0) {
2944 tracksWithEffect++;
2945 } else {
2946 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2947 "session %d",
2948 name, track->sessionId());
2949 }
2950 }
2951
2952
2953 int param = AudioMixer::VOLUME;
2954 if (track->mFillingUpStatus == Track::FS_FILLED) {
2955 // no ramp for the first volume setting
2956 track->mFillingUpStatus = Track::FS_ACTIVE;
2957 if (track->mState == TrackBase::RESUMING) {
2958 track->mState = TrackBase::ACTIVE;
2959 param = AudioMixer::RAMP_VOLUME;
2960 }
2961 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002962 // FIXME should not make a decision based on mServer
2963 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002964 // If the track is stopped before the first frame was mixed,
2965 // do not apply ramp
2966 param = AudioMixer::RAMP_VOLUME;
2967 }
2968
2969 // compute volume for this track
2970 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002971 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002972 vl = vr = va = 0;
2973 if (track->isPausing()) {
2974 track->setPaused();
2975 }
2976 } else {
2977
2978 // read original volumes with volume control
2979 float typeVolume = mStreamTypes[track->streamType()].volume;
2980 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002981 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002982 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002983 vl = vlr & 0xFFFF;
2984 vr = vlr >> 16;
2985 // track volumes come from shared memory, so can't be trusted and must be clamped
2986 if (vl > MAX_GAIN_INT) {
2987 ALOGV("Track left volume out of range: %04X", vl);
2988 vl = MAX_GAIN_INT;
2989 }
2990 if (vr > MAX_GAIN_INT) {
2991 ALOGV("Track right volume out of range: %04X", vr);
2992 vr = MAX_GAIN_INT;
2993 }
2994 // now apply the master volume and stream type volume
2995 vl = (uint32_t)(v * vl) << 12;
2996 vr = (uint32_t)(v * vr) << 12;
2997 // assuming master volume and stream type volume each go up to 1.0,
2998 // vl and vr are now in 8.24 format
2999
Glenn Kastene3aa6592012-12-04 12:22:46 -08003000 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003001 // send level comes from shared memory and so may be corrupt
3002 if (sendLevel > MAX_GAIN_INT) {
3003 ALOGV("Track send level out of range: %04X", sendLevel);
3004 sendLevel = MAX_GAIN_INT;
3005 }
3006 va = (uint32_t)(v * sendLevel);
3007 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008
Eric Laurent81784c32012-11-19 14:55:58 -08003009 // Delegate volume control to effect in track effect chain if needed
3010 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3011 // Do not ramp volume if volume is controlled by effect
3012 param = AudioMixer::VOLUME;
3013 track->mHasVolumeController = true;
3014 } else {
3015 // force no volume ramp when volume controller was just disabled or removed
3016 // from effect chain to avoid volume spike
3017 if (track->mHasVolumeController) {
3018 param = AudioMixer::VOLUME;
3019 }
3020 track->mHasVolumeController = false;
3021 }
3022
3023 // Convert volumes from 8.24 to 4.12 format
3024 // This additional clamping is needed in case chain->setVolume_l() overshot
3025 vl = (vl + (1 << 11)) >> 12;
3026 if (vl > MAX_GAIN_INT) {
3027 vl = MAX_GAIN_INT;
3028 }
3029 vr = (vr + (1 << 11)) >> 12;
3030 if (vr > MAX_GAIN_INT) {
3031 vr = MAX_GAIN_INT;
3032 }
3033
3034 if (va > MAX_GAIN_INT) {
3035 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3036 }
3037
3038 // XXX: these things DON'T need to be done each time
3039 mAudioMixer->setBufferProvider(name, track);
3040 mAudioMixer->enable(name);
3041
3042 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3043 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3044 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3045 mAudioMixer->setParameter(
3046 name,
3047 AudioMixer::TRACK,
3048 AudioMixer::FORMAT, (void *)track->format());
3049 mAudioMixer->setParameter(
3050 name,
3051 AudioMixer::TRACK,
3052 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003053 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3054 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003055 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003056 if (reqSampleRate == 0) {
3057 reqSampleRate = mSampleRate;
3058 } else if (reqSampleRate > maxSampleRate) {
3059 reqSampleRate = maxSampleRate;
3060 }
Eric Laurent81784c32012-11-19 14:55:58 -08003061 mAudioMixer->setParameter(
3062 name,
3063 AudioMixer::RESAMPLE,
3064 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003065 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003066 mAudioMixer->setParameter(
3067 name,
3068 AudioMixer::TRACK,
3069 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3070 mAudioMixer->setParameter(
3071 name,
3072 AudioMixer::TRACK,
3073 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3074
3075 // reset retry count
3076 track->mRetryCount = kMaxTrackRetries;
3077
3078 // If one track is ready, set the mixer ready if:
3079 // - the mixer was not ready during previous round OR
3080 // - no other track is not ready
3081 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3082 mixerStatus != MIXER_TRACKS_ENABLED) {
3083 mixerStatus = MIXER_TRACKS_READY;
3084 }
3085 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003086 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003087 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003088 }
Eric Laurent81784c32012-11-19 14:55:58 -08003089 // clear effect chain input buffer if an active track underruns to avoid sending
3090 // previous audio buffer again to effects
3091 chain = getEffectChain_l(track->sessionId());
3092 if (chain != 0) {
3093 chain->clearInputBuffer();
3094 }
3095
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003096 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003097 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3098 track->isStopped() || track->isPaused()) {
3099 // We have consumed all the buffers of this track.
3100 // Remove it from the list of active tracks.
3101 // TODO: use actual buffer filling status instead of latency when available from
3102 // audio HAL
3103 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3104 size_t framesWritten = mBytesWritten / mFrameSize;
3105 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3106 if (track->isStopped()) {
3107 track->reset();
3108 }
3109 tracksToRemove->add(track);
3110 }
3111 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003112 // No buffers for this track. Give it a few chances to
3113 // fill a buffer, then remove it from active list.
3114 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003115 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003116 tracksToRemove->add(track);
3117 // indicate to client process that the track was disabled because of underrun;
3118 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003119 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003120 // If one track is not ready, mark the mixer also not ready if:
3121 // - the mixer was ready during previous round OR
3122 // - no other track is ready
3123 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3124 mixerStatus != MIXER_TRACKS_READY) {
3125 mixerStatus = MIXER_TRACKS_ENABLED;
3126 }
3127 }
3128 mAudioMixer->disable(name);
3129 }
3130
3131 } // local variable scope to avoid goto warning
3132track_is_ready: ;
3133
3134 }
3135
3136 // Push the new FastMixer state if necessary
3137 bool pauseAudioWatchdog = false;
3138 if (didModify) {
3139 state->mFastTracksGen++;
3140 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3141 if (kUseFastMixer == FastMixer_Dynamic &&
3142 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3143 state->mCommand = FastMixerState::COLD_IDLE;
3144 state->mColdFutexAddr = &mFastMixerFutex;
3145 state->mColdGen++;
3146 mFastMixerFutex = 0;
3147 if (kUseFastMixer == FastMixer_Dynamic) {
3148 mNormalSink = mOutputSink;
3149 }
3150 // If we go into cold idle, need to wait for acknowledgement
3151 // so that fast mixer stops doing I/O.
3152 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3153 pauseAudioWatchdog = true;
3154 }
Eric Laurent81784c32012-11-19 14:55:58 -08003155 }
3156 if (sq != NULL) {
3157 sq->end(didModify);
3158 sq->push(block);
3159 }
3160#ifdef AUDIO_WATCHDOG
3161 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3162 mAudioWatchdog->pause();
3163 }
3164#endif
3165
3166 // Now perform the deferred reset on fast tracks that have stopped
3167 while (resetMask != 0) {
3168 size_t i = __builtin_ctz(resetMask);
3169 ALOG_ASSERT(i < count);
3170 resetMask &= ~(1 << i);
3171 sp<Track> t = mActiveTracks[i].promote();
3172 if (t == 0) {
3173 continue;
3174 }
3175 Track* track = t.get();
3176 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3177 track->reset();
3178 }
3179
3180 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003182
3183 // mix buffer must be cleared if all tracks are connected to an
3184 // effect chain as in this case the mixer will not write to
3185 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3187 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // FIXME as a performance optimization, should remember previous zero status
3189 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3190 }
3191
3192 // if any fast tracks, then status is ready
3193 mMixerStatusIgnoringFastTracks = mixerStatus;
3194 if (fastTracks > 0) {
3195 mixerStatus = MIXER_TRACKS_READY;
3196 }
3197 return mixerStatus;
3198}
3199
3200// getTrackName_l() must be called with ThreadBase::mLock held
3201int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3202{
3203 return mAudioMixer->getTrackName(channelMask, sessionId);
3204}
3205
3206// deleteTrackName_l() must be called with ThreadBase::mLock held
3207void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3208{
3209 ALOGV("remove track (%d) and delete from mixer", name);
3210 mAudioMixer->deleteTrackName(name);
3211}
3212
3213// checkForNewParameters_l() must be called with ThreadBase::mLock held
3214bool AudioFlinger::MixerThread::checkForNewParameters_l()
3215{
3216 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3217 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3218 bool reconfig = false;
3219
3220 while (!mNewParameters.isEmpty()) {
3221
3222 if (mFastMixer != NULL) {
3223 FastMixerStateQueue *sq = mFastMixer->sq();
3224 FastMixerState *state = sq->begin();
3225 if (!(state->mCommand & FastMixerState::IDLE)) {
3226 previousCommand = state->mCommand;
3227 state->mCommand = FastMixerState::HOT_IDLE;
3228 sq->end();
3229 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3230 } else {
3231 sq->end(false /*didModify*/);
3232 }
3233 }
3234
3235 status_t status = NO_ERROR;
3236 String8 keyValuePair = mNewParameters[0];
3237 AudioParameter param = AudioParameter(keyValuePair);
3238 int value;
3239
3240 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3241 reconfig = true;
3242 }
3243 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3244 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3245 status = BAD_VALUE;
3246 } else {
3247 reconfig = true;
3248 }
3249 }
3250 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003251 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003252 status = BAD_VALUE;
3253 } else {
3254 reconfig = true;
3255 }
3256 }
3257 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3258 // do not accept frame count changes if tracks are open as the track buffer
3259 // size depends on frame count and correct behavior would not be guaranteed
3260 // if frame count is changed after track creation
3261 if (!mTracks.isEmpty()) {
3262 status = INVALID_OPERATION;
3263 } else {
3264 reconfig = true;
3265 }
3266 }
3267 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3268#ifdef ADD_BATTERY_DATA
3269 // when changing the audio output device, call addBatteryData to notify
3270 // the change
3271 if (mOutDevice != value) {
3272 uint32_t params = 0;
3273 // check whether speaker is on
3274 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3275 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3276 }
3277
3278 audio_devices_t deviceWithoutSpeaker
3279 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3280 // check if any other device (except speaker) is on
3281 if (value & deviceWithoutSpeaker ) {
3282 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3283 }
3284
3285 if (params != 0) {
3286 addBatteryData(params);
3287 }
3288 }
3289#endif
3290
3291 // forward device change to effects that have requested to be
3292 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003293 if (value != AUDIO_DEVICE_NONE) {
3294 mOutDevice = value;
3295 for (size_t i = 0; i < mEffectChains.size(); i++) {
3296 mEffectChains[i]->setDevice_l(mOutDevice);
3297 }
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
3299 }
3300
3301 if (status == NO_ERROR) {
3302 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3303 keyValuePair.string());
3304 if (!mStandby && status == INVALID_OPERATION) {
3305 mOutput->stream->common.standby(&mOutput->stream->common);
3306 mStandby = true;
3307 mBytesWritten = 0;
3308 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3309 keyValuePair.string());
3310 }
3311 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003312 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003313 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003314 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3315 for (size_t i = 0; i < mTracks.size() ; i++) {
3316 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3317 if (name < 0) {
3318 break;
3319 }
3320 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003321 }
3322 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3323 }
3324 }
3325
3326 mNewParameters.removeAt(0);
3327
3328 mParamStatus = status;
3329 mParamCond.signal();
3330 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3331 // already timed out waiting for the status and will never signal the condition.
3332 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3333 }
3334
3335 if (!(previousCommand & FastMixerState::IDLE)) {
3336 ALOG_ASSERT(mFastMixer != NULL);
3337 FastMixerStateQueue *sq = mFastMixer->sq();
3338 FastMixerState *state = sq->begin();
3339 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3340 state->mCommand = previousCommand;
3341 sq->end();
3342 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3343 }
3344
3345 return reconfig;
3346}
3347
3348
3349void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3350{
3351 const size_t SIZE = 256;
3352 char buffer[SIZE];
3353 String8 result;
3354
3355 PlaybackThread::dumpInternals(fd, args);
3356
3357 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3358 result.append(buffer);
3359 write(fd, result.string(), result.size());
3360
3361 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003362 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003363 copy.dump(fd);
3364
3365#ifdef STATE_QUEUE_DUMP
3366 // Similar for state queue
3367 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3368 observerCopy.dump(fd);
3369 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3370 mutatorCopy.dump(fd);
3371#endif
3372
Glenn Kasten46909e72013-02-26 09:20:22 -08003373#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003374 // Write the tee output to a .wav file
3375 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003376#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003377
3378#ifdef AUDIO_WATCHDOG
3379 if (mAudioWatchdog != 0) {
3380 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3381 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3382 wdCopy.dump(fd);
3383 }
3384#endif
3385}
3386
3387uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3388{
3389 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3390}
3391
3392uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3393{
3394 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3395}
3396
3397void AudioFlinger::MixerThread::cacheParameters_l()
3398{
3399 PlaybackThread::cacheParameters_l();
3400
3401 // FIXME: Relaxed timing because of a certain device that can't meet latency
3402 // Should be reduced to 2x after the vendor fixes the driver issue
3403 // increase threshold again due to low power audio mode. The way this warning
3404 // threshold is calculated and its usefulness should be reconsidered anyway.
3405 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3406}
3407
3408// ----------------------------------------------------------------------------
3409
3410AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3411 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3412 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3413 // mLeftVolFloat, mRightVolFloat
3414{
3415}
3416
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3418 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3419 ThreadBase::type_t type)
3420 : PlaybackThread(audioFlinger, output, id, device, type)
3421 // mLeftVolFloat, mRightVolFloat
3422{
3423}
3424
Eric Laurent81784c32012-11-19 14:55:58 -08003425AudioFlinger::DirectOutputThread::~DirectOutputThread()
3426{
3427}
3428
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3430{
3431 audio_track_cblk_t* cblk = track->cblk();
3432 float left, right;
3433
3434 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3435 left = right = 0;
3436 } else {
3437 float typeVolume = mStreamTypes[track->streamType()].volume;
3438 float v = mMasterVolume * typeVolume;
3439 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3440 uint32_t vlr = proxy->getVolumeLR();
3441 float v_clamped = v * (vlr & 0xFFFF);
3442 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3443 left = v_clamped/MAX_GAIN;
3444 v_clamped = v * (vlr >> 16);
3445 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3446 right = v_clamped/MAX_GAIN;
3447 }
3448
3449 if (lastTrack) {
3450 if (left != mLeftVolFloat || right != mRightVolFloat) {
3451 mLeftVolFloat = left;
3452 mRightVolFloat = right;
3453
3454 // Convert volumes from float to 8.24
3455 uint32_t vl = (uint32_t)(left * (1 << 24));
3456 uint32_t vr = (uint32_t)(right * (1 << 24));
3457
3458 // Delegate volume control to effect in track effect chain if needed
3459 // only one effect chain can be present on DirectOutputThread, so if
3460 // there is one, the track is connected to it
3461 if (!mEffectChains.isEmpty()) {
3462 mEffectChains[0]->setVolume_l(&vl, &vr);
3463 left = (float)vl / (1 << 24);
3464 right = (float)vr / (1 << 24);
3465 }
3466 if (mOutput->stream->set_volume) {
3467 mOutput->stream->set_volume(mOutput->stream, left, right);
3468 }
3469 }
3470 }
3471}
3472
3473
Eric Laurent81784c32012-11-19 14:55:58 -08003474AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3475 Vector< sp<Track> > *tracksToRemove
3476)
3477{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003478 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003479 mixer_state mixerStatus = MIXER_IDLE;
3480
3481 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003482 for (size_t i = 0; i < count; i++) {
3483 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003484 // The track died recently
3485 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003486 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003487 }
3488
3489 Track* const track = t.get();
3490 audio_track_cblk_t* cblk = track->cblk();
3491
3492 // The first time a track is added we wait
3493 // for all its buffers to be filled before processing it
3494 uint32_t minFrames;
3495 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3496 minFrames = mNormalFrameCount;
3497 } else {
3498 minFrames = 1;
3499 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003500 // Only consider last track started for volume and mixer state control.
3501 // This is the last entry in mActiveTracks unless a track underruns.
3502 // As we only care about the transition phase between two tracks on a
3503 // direct output, it is not a problem to ignore the underrun case.
3504 bool last = (i == (count - 1));
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506 if ((track->framesReady() >= minFrames) && track->isReady() &&
3507 !track->isPaused() && !track->isTerminated())
3508 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003509 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003510
3511 if (track->mFillingUpStatus == Track::FS_FILLED) {
3512 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003513 // make sure processVolume_l() will apply new volume even if 0
3514 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003515 if (track->mState == TrackBase::RESUMING) {
3516 track->mState = TrackBase::ACTIVE;
3517 }
3518 }
3519
3520 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003521 processVolume_l(track, last);
3522 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003523 // reset retry count
3524 track->mRetryCount = kMaxTrackRetriesDirect;
3525 mActiveTrack = t;
3526 mixerStatus = MIXER_TRACKS_READY;
3527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003529 // clear effect chain input buffer if the last active track started underruns
3530 // to avoid sending previous audio buffer again to effects
3531 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003532 mEffectChains[0]->clearInputBuffer();
3533 }
3534
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003535 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003536 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3537 track->isStopped() || track->isPaused()) {
3538 // We have consumed all the buffers of this track.
3539 // Remove it from the list of active tracks.
3540 // TODO: implement behavior for compressed audio
3541 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3542 size_t framesWritten = mBytesWritten / mFrameSize;
3543 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3544 if (track->isStopped()) {
3545 track->reset();
3546 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003547 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003548 }
3549 } else {
3550 // No buffers for this track. Give it a few chances to
3551 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003552 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003553 if (--(track->mRetryCount) <= 0) {
3554 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003555 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003556 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003557 mixerStatus = MIXER_TRACKS_ENABLED;
3558 }
3559 }
3560 }
3561 }
3562
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003565
3566 return mixerStatus;
3567}
3568
3569void AudioFlinger::DirectOutputThread::threadLoop_mix()
3570{
Eric Laurent81784c32012-11-19 14:55:58 -08003571 size_t frameCount = mFrameCount;
3572 int8_t *curBuf = (int8_t *)mMixBuffer;
3573 // output audio to hardware
3574 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003575 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003576 buffer.frameCount = frameCount;
3577 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003578 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003579 memset(curBuf, 0, frameCount * mFrameSize);
3580 break;
3581 }
3582 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3583 frameCount -= buffer.frameCount;
3584 curBuf += buffer.frameCount * mFrameSize;
3585 mActiveTrack->releaseBuffer(&buffer);
3586 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003588 sleepTime = 0;
3589 standbyTime = systemTime() + standbyDelay;
3590 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003591}
3592
3593void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3594{
3595 if (sleepTime == 0) {
3596 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3597 sleepTime = activeSleepTime;
3598 } else {
3599 sleepTime = idleSleepTime;
3600 }
3601 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3602 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3603 sleepTime = 0;
3604 }
3605}
3606
3607// getTrackName_l() must be called with ThreadBase::mLock held
3608int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3609 int sessionId)
3610{
3611 return 0;
3612}
3613
3614// deleteTrackName_l() must be called with ThreadBase::mLock held
3615void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3616{
3617}
3618
3619// checkForNewParameters_l() must be called with ThreadBase::mLock held
3620bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3621{
3622 bool reconfig = false;
3623
3624 while (!mNewParameters.isEmpty()) {
3625 status_t status = NO_ERROR;
3626 String8 keyValuePair = mNewParameters[0];
3627 AudioParameter param = AudioParameter(keyValuePair);
3628 int value;
3629
3630 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3631 // do not accept frame count changes if tracks are open as the track buffer
3632 // size depends on frame count and correct behavior would not be garantied
3633 // if frame count is changed after track creation
3634 if (!mTracks.isEmpty()) {
3635 status = INVALID_OPERATION;
3636 } else {
3637 reconfig = true;
3638 }
3639 }
3640 if (status == NO_ERROR) {
3641 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3642 keyValuePair.string());
3643 if (!mStandby && status == INVALID_OPERATION) {
3644 mOutput->stream->common.standby(&mOutput->stream->common);
3645 mStandby = true;
3646 mBytesWritten = 0;
3647 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3648 keyValuePair.string());
3649 }
3650 if (status == NO_ERROR && reconfig) {
3651 readOutputParameters();
3652 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3653 }
3654 }
3655
3656 mNewParameters.removeAt(0);
3657
3658 mParamStatus = status;
3659 mParamCond.signal();
3660 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3661 // already timed out waiting for the status and will never signal the condition.
3662 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3663 }
3664 return reconfig;
3665}
3666
3667uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3668{
3669 uint32_t time;
3670 if (audio_is_linear_pcm(mFormat)) {
3671 time = PlaybackThread::activeSleepTimeUs();
3672 } else {
3673 time = 10000;
3674 }
3675 return time;
3676}
3677
3678uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3679{
3680 uint32_t time;
3681 if (audio_is_linear_pcm(mFormat)) {
3682 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3683 } else {
3684 time = 10000;
3685 }
3686 return time;
3687}
3688
3689uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3690{
3691 uint32_t time;
3692 if (audio_is_linear_pcm(mFormat)) {
3693 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3694 } else {
3695 time = 10000;
3696 }
3697 return time;
3698}
3699
3700void AudioFlinger::DirectOutputThread::cacheParameters_l()
3701{
3702 PlaybackThread::cacheParameters_l();
3703
3704 // use shorter standby delay as on normal output to release
3705 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003706 if (audio_is_linear_pcm(mFormat)) {
3707 standbyDelay = microseconds(activeSleepTime*2);
3708 } else {
3709 standbyDelay = kOffloadStandbyDelayNs;
3710 }
Eric Laurent81784c32012-11-19 14:55:58 -08003711}
3712
3713// ----------------------------------------------------------------------------
3714
Eric Laurentbfb1b832013-01-07 09:53:42 -08003715AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3716 const sp<AudioFlinger::OffloadThread>& offloadThread)
3717 : Thread(false /*canCallJava*/),
3718 mOffloadThread(offloadThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003719 mWriteAckSequence(0),
3720 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003721{
3722}
3723
3724AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3725{
3726}
3727
3728void AudioFlinger::AsyncCallbackThread::onFirstRef()
3729{
3730 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3731}
3732
3733bool AudioFlinger::AsyncCallbackThread::threadLoop()
3734{
3735 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003736 uint32_t writeAckSequence;
3737 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738
3739 {
3740 Mutex::Autolock _l(mLock);
3741 mWaitWorkCV.wait(mLock);
3742 if (exitPending()) {
3743 break;
3744 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003745 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3746 mWriteAckSequence, mDrainSequence);
3747 writeAckSequence = mWriteAckSequence;
3748 mWriteAckSequence &= ~1;
3749 drainSequence = mDrainSequence;
3750 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003751 }
3752 {
3753 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3754 if (offloadThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003755 if (writeAckSequence & 1) {
3756 offloadThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003757 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003758 if (drainSequence & 1) {
3759 offloadThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003760 }
3761 }
3762 }
3763 }
3764 return false;
3765}
3766
3767void AudioFlinger::AsyncCallbackThread::exit()
3768{
3769 ALOGV("AsyncCallbackThread::exit");
3770 Mutex::Autolock _l(mLock);
3771 requestExit();
3772 mWaitWorkCV.broadcast();
3773}
3774
Eric Laurent3b4529e2013-09-05 18:09:19 -07003775void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003776{
3777 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003778 // bit 0 is cleared
3779 mWriteAckSequence = sequence << 1;
3780}
3781
3782void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3783{
3784 Mutex::Autolock _l(mLock);
3785 // ignore unexpected callbacks
3786 if (mWriteAckSequence & 2) {
3787 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003788 mWaitWorkCV.signal();
3789 }
3790}
3791
Eric Laurent3b4529e2013-09-05 18:09:19 -07003792void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003793{
3794 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003795 // bit 0 is cleared
3796 mDrainSequence = sequence << 1;
3797}
3798
3799void AudioFlinger::AsyncCallbackThread::resetDraining()
3800{
3801 Mutex::Autolock _l(mLock);
3802 // ignore unexpected callbacks
3803 if (mDrainSequence & 2) {
3804 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003805 mWaitWorkCV.signal();
3806 }
3807}
3808
3809
3810// ----------------------------------------------------------------------------
3811AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3812 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3813 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3814 mHwPaused(false),
3815 mPausedBytesRemaining(0)
3816{
3817 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3818}
3819
3820AudioFlinger::OffloadThread::~OffloadThread()
3821{
3822 mPreviousTrack.clear();
3823}
3824
3825void AudioFlinger::OffloadThread::threadLoop_exit()
3826{
3827 if (mFlushPending || mHwPaused) {
3828 // If a flush is pending or track was paused, just discard buffered data
3829 flushHw_l();
3830 } else {
3831 mMixerStatus = MIXER_DRAIN_ALL;
3832 threadLoop_drain();
3833 }
3834 mCallbackThread->exit();
3835 PlaybackThread::threadLoop_exit();
3836}
3837
3838AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3839 Vector< sp<Track> > *tracksToRemove
3840)
3841{
3842 ALOGV("OffloadThread::prepareTracks_l");
3843 size_t count = mActiveTracks.size();
3844
3845 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003846 bool doHwPause = false;
3847 bool doHwResume = false;
3848
Eric Laurentbfb1b832013-01-07 09:53:42 -08003849 // find out which tracks need to be processed
3850 for (size_t i = 0; i < count; i++) {
3851 sp<Track> t = mActiveTracks[i].promote();
3852 // The track died recently
3853 if (t == 0) {
3854 continue;
3855 }
3856 Track* const track = t.get();
3857 audio_track_cblk_t* cblk = track->cblk();
3858 if (mPreviousTrack != NULL) {
3859 if (t != mPreviousTrack) {
3860 // Flush any data still being written from last track
3861 mBytesRemaining = 0;
3862 if (mPausedBytesRemaining) {
3863 // Last track was paused so we also need to flush saved
3864 // mixbuffer state and invalidate track so that it will
3865 // re-submit that unwritten data when it is next resumed
3866 mPausedBytesRemaining = 0;
3867 // Invalidate is a bit drastic - would be more efficient
3868 // to have a flag to tell client that some of the
3869 // previously written data was lost
3870 mPreviousTrack->invalidate();
3871 }
3872 }
3873 }
3874 mPreviousTrack = t;
3875 bool last = (i == (count - 1));
3876 if (track->isPausing()) {
3877 track->setPaused();
3878 if (last) {
3879 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003880 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003881 mHwPaused = true;
3882 }
3883 // If we were part way through writing the mixbuffer to
3884 // the HAL we must save this until we resume
3885 // BUG - this will be wrong if a different track is made active,
3886 // in that case we want to discard the pending data in the
3887 // mixbuffer and tell the client to present it again when the
3888 // track is resumed
3889 mPausedWriteLength = mCurrentWriteLength;
3890 mPausedBytesRemaining = mBytesRemaining;
3891 mBytesRemaining = 0; // stop writing
3892 }
3893 tracksToRemove->add(track);
3894 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003895 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003896 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 if (track->mFillingUpStatus == Track::FS_FILLED) {
3898 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003899 // make sure processVolume_l() will apply new volume even if 0
3900 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901 if (track->mState == TrackBase::RESUMING) {
Glenn Kastenfa319e62013-07-29 17:17:38 -07003902 if (mPausedBytesRemaining) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 // Need to continue write that was interrupted
3904 mCurrentWriteLength = mPausedWriteLength;
3905 mBytesRemaining = mPausedBytesRemaining;
3906 mPausedBytesRemaining = 0;
3907 }
3908 track->mState = TrackBase::ACTIVE;
3909 }
3910 }
3911
3912 if (last) {
3913 if (mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003914 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003915 mHwPaused = false;
3916 // threadLoop_mix() will handle the case that we need to
3917 // resume an interrupted write
3918 }
3919 // reset retry count
3920 track->mRetryCount = kMaxTrackRetriesOffload;
3921 mActiveTrack = t;
3922 mixerStatus = MIXER_TRACKS_READY;
3923 }
3924 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003925 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 if (track->isStopping_1()) {
3927 // Hardware buffer can hold a large amount of audio so we must
3928 // wait for all current track's data to drain before we say
3929 // that the track is stopped.
3930 if (mBytesRemaining == 0) {
3931 // Only start draining when all data in mixbuffer
3932 // has been written
3933 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3934 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3935 sleepTime = 0;
3936 standbyTime = systemTime() + standbyDelay;
3937 if (last) {
3938 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07003939 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003940 if (mHwPaused) {
3941 // It is possible to move from PAUSED to STOPPING_1 without
3942 // a resume so we must ensure hardware is running
3943 mOutput->stream->resume(mOutput->stream);
3944 mHwPaused = false;
3945 }
3946 }
3947 }
3948 } else if (track->isStopping_2()) {
3949 // Drain has completed, signal presentation complete
Eric Laurent3b4529e2013-09-05 18:09:19 -07003950 if (!(mDrainSequence & 1) || !last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003951 track->mState = TrackBase::STOPPED;
3952 size_t audioHALFrames =
3953 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3954 size_t framesWritten =
3955 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3956 track->presentationComplete(framesWritten, audioHALFrames);
3957 track->reset();
3958 tracksToRemove->add(track);
3959 }
3960 } else {
3961 // No buffers for this track. Give it a few chances to
3962 // fill a buffer, then remove it from active list.
3963 if (--(track->mRetryCount) <= 0) {
3964 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3965 track->name());
3966 tracksToRemove->add(track);
3967 } else if (last){
3968 mixerStatus = MIXER_TRACKS_ENABLED;
3969 }
3970 }
3971 }
3972 // compute volume for this track
3973 processVolume_l(track, last);
3974 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07003975
Eric Laurent972a1732013-09-04 09:42:59 -07003976 // make sure the pause/flush/resume sequence is executed in the right order
3977 if (doHwPause) {
3978 mOutput->stream->pause(mOutput->stream);
3979 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07003980 if (mFlushPending) {
3981 flushHw_l();
3982 mFlushPending = false;
3983 }
Eric Laurent972a1732013-09-04 09:42:59 -07003984 if (doHwResume) {
3985 mOutput->stream->resume(mOutput->stream);
3986 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07003987
Eric Laurentbfb1b832013-01-07 09:53:42 -08003988 // remove all the tracks that need to be...
3989 removeTracks_l(*tracksToRemove);
3990
3991 return mixerStatus;
3992}
3993
3994void AudioFlinger::OffloadThread::flushOutput_l()
3995{
3996 mFlushPending = true;
3997}
3998
3999// must be called with thread mutex locked
4000bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4001{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004002 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4003 mWriteAckSequence, mDrainSequence);
4004 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 return true;
4006 }
4007 return false;
4008}
4009
4010// must be called with thread mutex locked
4011bool AudioFlinger::OffloadThread::shouldStandby_l()
4012{
4013 bool TrackPaused = false;
4014
4015 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4016 // after a timeout and we will enter standby then.
4017 if (mTracks.size() > 0) {
4018 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4019 }
4020
4021 return !mStandby && !TrackPaused;
4022}
4023
4024
4025bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4026{
4027 Mutex::Autolock _l(mLock);
4028 return waitingAsyncCallback_l();
4029}
4030
4031void AudioFlinger::OffloadThread::flushHw_l()
4032{
4033 mOutput->stream->flush(mOutput->stream);
4034 // Flush anything still waiting in the mixbuffer
4035 mCurrentWriteLength = 0;
4036 mBytesRemaining = 0;
4037 mPausedWriteLength = 0;
4038 mPausedBytesRemaining = 0;
4039 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004040 // discard any pending drain or write ack by incrementing sequence
4041 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4042 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004043 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004044 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4045 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046 }
4047}
4048
4049// ----------------------------------------------------------------------------
4050
Eric Laurent81784c32012-11-19 14:55:58 -08004051AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4052 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4053 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4054 DUPLICATING),
4055 mWaitTimeMs(UINT_MAX)
4056{
4057 addOutputTrack(mainThread);
4058}
4059
4060AudioFlinger::DuplicatingThread::~DuplicatingThread()
4061{
4062 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4063 mOutputTracks[i]->destroy();
4064 }
4065}
4066
4067void AudioFlinger::DuplicatingThread::threadLoop_mix()
4068{
4069 // mix buffers...
4070 if (outputsReady(outputTracks)) {
4071 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4072 } else {
4073 memset(mMixBuffer, 0, mixBufferSize);
4074 }
4075 sleepTime = 0;
4076 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004078 standbyTime = systemTime() + standbyDelay;
4079}
4080
4081void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4082{
4083 if (sleepTime == 0) {
4084 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4085 sleepTime = activeSleepTime;
4086 } else {
4087 sleepTime = idleSleepTime;
4088 }
4089 } else if (mBytesWritten != 0) {
4090 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4091 writeFrames = mNormalFrameCount;
4092 memset(mMixBuffer, 0, mixBufferSize);
4093 } else {
4094 // flush remaining overflow buffers in output tracks
4095 writeFrames = 0;
4096 }
4097 sleepTime = 0;
4098 }
4099}
4100
Eric Laurentbfb1b832013-01-07 09:53:42 -08004101ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004102{
4103 for (size_t i = 0; i < outputTracks.size(); i++) {
4104 outputTracks[i]->write(mMixBuffer, writeFrames);
4105 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004106 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004107}
4108
4109void AudioFlinger::DuplicatingThread::threadLoop_standby()
4110{
4111 // DuplicatingThread implements standby by stopping all tracks
4112 for (size_t i = 0; i < outputTracks.size(); i++) {
4113 outputTracks[i]->stop();
4114 }
4115}
4116
4117void AudioFlinger::DuplicatingThread::saveOutputTracks()
4118{
4119 outputTracks = mOutputTracks;
4120}
4121
4122void AudioFlinger::DuplicatingThread::clearOutputTracks()
4123{
4124 outputTracks.clear();
4125}
4126
4127void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4128{
4129 Mutex::Autolock _l(mLock);
4130 // FIXME explain this formula
4131 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4132 OutputTrack *outputTrack = new OutputTrack(thread,
4133 this,
4134 mSampleRate,
4135 mFormat,
4136 mChannelMask,
4137 frameCount);
4138 if (outputTrack->cblk() != NULL) {
4139 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4140 mOutputTracks.add(outputTrack);
4141 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4142 updateWaitTime_l();
4143 }
4144}
4145
4146void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4147{
4148 Mutex::Autolock _l(mLock);
4149 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4150 if (mOutputTracks[i]->thread() == thread) {
4151 mOutputTracks[i]->destroy();
4152 mOutputTracks.removeAt(i);
4153 updateWaitTime_l();
4154 return;
4155 }
4156 }
4157 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4158}
4159
4160// caller must hold mLock
4161void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4162{
4163 mWaitTimeMs = UINT_MAX;
4164 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4165 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4166 if (strong != 0) {
4167 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4168 if (waitTimeMs < mWaitTimeMs) {
4169 mWaitTimeMs = waitTimeMs;
4170 }
4171 }
4172 }
4173}
4174
4175
4176bool AudioFlinger::DuplicatingThread::outputsReady(
4177 const SortedVector< sp<OutputTrack> > &outputTracks)
4178{
4179 for (size_t i = 0; i < outputTracks.size(); i++) {
4180 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4181 if (thread == 0) {
4182 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4183 outputTracks[i].get());
4184 return false;
4185 }
4186 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4187 // see note at standby() declaration
4188 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4189 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4190 thread.get());
4191 return false;
4192 }
4193 }
4194 return true;
4195}
4196
4197uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4198{
4199 return (mWaitTimeMs * 1000) / 2;
4200}
4201
4202void AudioFlinger::DuplicatingThread::cacheParameters_l()
4203{
4204 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4205 updateWaitTime_l();
4206
4207 MixerThread::cacheParameters_l();
4208}
4209
4210// ----------------------------------------------------------------------------
4211// Record
4212// ----------------------------------------------------------------------------
4213
4214AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4215 AudioStreamIn *input,
4216 uint32_t sampleRate,
4217 audio_channel_mask_t channelMask,
4218 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004219 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004220 audio_devices_t inDevice
4221#ifdef TEE_SINK
4222 , const sp<NBAIO_Sink>& teeSink
4223#endif
4224 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004225 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004226 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004227 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004228 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004229 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004230 // mBytesRead is only meaningful while active, and so is cleared in start()
4231 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004232#ifdef TEE_SINK
4233 , mTeeSink(teeSink)
4234#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004235{
4236 snprintf(mName, kNameLength, "AudioIn_%X", id);
4237
4238 readInputParameters();
4239
4240}
4241
4242
4243AudioFlinger::RecordThread::~RecordThread()
4244{
4245 delete[] mRsmpInBuffer;
4246 delete mResampler;
4247 delete[] mRsmpOutBuffer;
4248}
4249
4250void AudioFlinger::RecordThread::onFirstRef()
4251{
4252 run(mName, PRIORITY_URGENT_AUDIO);
4253}
4254
4255status_t AudioFlinger::RecordThread::readyToRun()
4256{
4257 status_t status = initCheck();
4258 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4259 return status;
4260}
4261
4262bool AudioFlinger::RecordThread::threadLoop()
4263{
4264 AudioBufferProvider::Buffer buffer;
4265 sp<RecordTrack> activeTrack;
4266 Vector< sp<EffectChain> > effectChains;
4267
4268 nsecs_t lastWarning = 0;
4269
4270 inputStandBy();
4271 acquireWakeLock();
4272
4273 // used to verify we've read at least once before evaluating how many bytes were read
4274 bool readOnce = false;
4275
4276 // start recording
4277 while (!exitPending()) {
4278
4279 processConfigEvents();
4280
4281 { // scope for mLock
4282 Mutex::Autolock _l(mLock);
4283 checkForNewParameters_l();
4284 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4285 standby();
4286
4287 if (exitPending()) {
4288 break;
4289 }
4290
4291 releaseWakeLock_l();
4292 ALOGV("RecordThread: loop stopping");
4293 // go to sleep
4294 mWaitWorkCV.wait(mLock);
4295 ALOGV("RecordThread: loop starting");
4296 acquireWakeLock_l();
4297 continue;
4298 }
4299 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300 if (mActiveTrack->isTerminated()) {
4301 removeTrack_l(mActiveTrack);
4302 mActiveTrack.clear();
4303 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004304 standby();
4305 mActiveTrack.clear();
4306 mStartStopCond.broadcast();
4307 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4308 if (mReqChannelCount != mActiveTrack->channelCount()) {
4309 mActiveTrack.clear();
4310 mStartStopCond.broadcast();
4311 } else if (readOnce) {
4312 // record start succeeds only if first read from audio input
4313 // succeeds
4314 if (mBytesRead >= 0) {
4315 mActiveTrack->mState = TrackBase::ACTIVE;
4316 } else {
4317 mActiveTrack.clear();
4318 }
4319 mStartStopCond.broadcast();
4320 }
4321 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004322 }
4323 }
4324 lockEffectChains_l(effectChains);
4325 }
4326
4327 if (mActiveTrack != 0) {
4328 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4329 mActiveTrack->mState != TrackBase::RESUMING) {
4330 unlockEffectChains(effectChains);
4331 usleep(kRecordThreadSleepUs);
4332 continue;
4333 }
4334 for (size_t i = 0; i < effectChains.size(); i ++) {
4335 effectChains[i]->process_l();
4336 }
4337
4338 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004339 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004340 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004341 readOnce = true;
4342 size_t framesOut = buffer.frameCount;
4343 if (mResampler == NULL) {
4344 // no resampling
4345 while (framesOut) {
4346 size_t framesIn = mFrameCount - mRsmpInIndex;
4347 if (framesIn) {
4348 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4349 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4350 mActiveTrack->mFrameSize;
4351 if (framesIn > framesOut)
4352 framesIn = framesOut;
4353 mRsmpInIndex += framesIn;
4354 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004355 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004356 memcpy(dst, src, framesIn * mFrameSize);
4357 } else {
4358 if (mChannelCount == 1) {
4359 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4360 (int16_t *)src, framesIn);
4361 } else {
4362 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4363 (int16_t *)src, framesIn);
4364 }
4365 }
4366 }
4367 if (framesOut && mFrameCount == mRsmpInIndex) {
4368 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004369 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004370 readInto = buffer.raw;
4371 framesOut = 0;
4372 } else {
4373 readInto = mRsmpInBuffer;
4374 mRsmpInIndex = 0;
4375 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004376 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004377 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004378 if (mBytesRead <= 0) {
4379 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4380 {
4381 ALOGE("Error reading audio input");
4382 // Force input into standby so that it tries to
4383 // recover at next read attempt
4384 inputStandBy();
4385 usleep(kRecordThreadSleepUs);
4386 }
4387 mRsmpInIndex = mFrameCount;
4388 framesOut = 0;
4389 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004390 }
4391#ifdef TEE_SINK
4392 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004393 (void) mTeeSink->write(readInto,
4394 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4395 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004396#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004397 }
4398 }
4399 } else {
4400 // resampling
4401
Glenn Kasten34af0262013-07-30 11:52:39 -07004402 // resampler accumulates, but we only have one source track
4403 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004404 // alter output frame count as if we were expecting stereo samples
4405 if (mChannelCount == 1 && mReqChannelCount == 1) {
4406 framesOut >>= 1;
4407 }
4408 mResampler->resample(mRsmpOutBuffer, framesOut,
4409 this /* AudioBufferProvider* */);
4410 // ditherAndClamp() works as long as all buffers returned by
4411 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4412 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004413 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004414 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4415 // the resampler always outputs stereo samples:
4416 // do post stereo to mono conversion
4417 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4418 framesOut);
4419 } else {
4420 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4421 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004422 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004423
4424 }
4425 if (mFramestoDrop == 0) {
4426 mActiveTrack->releaseBuffer(&buffer);
4427 } else {
4428 if (mFramestoDrop > 0) {
4429 mFramestoDrop -= buffer.frameCount;
4430 if (mFramestoDrop <= 0) {
4431 clearSyncStartEvent();
4432 }
4433 } else {
4434 mFramestoDrop += buffer.frameCount;
4435 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4436 mSyncStartEvent->isCancelled()) {
4437 ALOGW("Synced record %s, session %d, trigger session %d",
4438 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4439 mActiveTrack->sessionId(),
4440 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4441 clearSyncStartEvent();
4442 }
4443 }
4444 }
4445 mActiveTrack->clearOverflow();
4446 }
4447 // client isn't retrieving buffers fast enough
4448 else {
4449 if (!mActiveTrack->setOverflow()) {
4450 nsecs_t now = systemTime();
4451 if ((now - lastWarning) > kWarningThrottleNs) {
4452 ALOGW("RecordThread: buffer overflow");
4453 lastWarning = now;
4454 }
4455 }
4456 // Release the processor for a while before asking for a new buffer.
4457 // This will give the application more chance to read from the buffer and
4458 // clear the overflow.
4459 usleep(kRecordThreadSleepUs);
4460 }
4461 }
4462 // enable changes in effect chain
4463 unlockEffectChains(effectChains);
4464 effectChains.clear();
4465 }
4466
4467 standby();
4468
4469 {
4470 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004471 for (size_t i = 0; i < mTracks.size(); i++) {
4472 sp<RecordTrack> track = mTracks[i];
4473 track->invalidate();
4474 }
Eric Laurent81784c32012-11-19 14:55:58 -08004475 mActiveTrack.clear();
4476 mStartStopCond.broadcast();
4477 }
4478
4479 releaseWakeLock();
4480
4481 ALOGV("RecordThread %p exiting", this);
4482 return false;
4483}
4484
4485void AudioFlinger::RecordThread::standby()
4486{
4487 if (!mStandby) {
4488 inputStandBy();
4489 mStandby = true;
4490 }
4491}
4492
4493void AudioFlinger::RecordThread::inputStandBy()
4494{
4495 mInput->stream->common.standby(&mInput->stream->common);
4496}
4497
4498sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4499 const sp<AudioFlinger::Client>& client,
4500 uint32_t sampleRate,
4501 audio_format_t format,
4502 audio_channel_mask_t channelMask,
4503 size_t frameCount,
4504 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004505 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004506 pid_t tid,
4507 status_t *status)
4508{
4509 sp<RecordTrack> track;
4510 status_t lStatus;
4511
4512 lStatus = initCheck();
4513 if (lStatus != NO_ERROR) {
4514 ALOGE("Audio driver not initialized.");
4515 goto Exit;
4516 }
4517
Glenn Kasten90e58b12013-07-31 16:16:02 -07004518 // client expresses a preference for FAST, but we get the final say
4519 if (*flags & IAudioFlinger::TRACK_FAST) {
4520 if (
4521 // use case: callback handler and frame count is default or at least as large as HAL
4522 (
4523 (tid != -1) &&
4524 ((frameCount == 0) ||
4525 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4526 ) &&
4527 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4528 // mono or stereo
4529 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4530 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4531 // hardware sample rate
4532 (sampleRate == mSampleRate) &&
4533 // record thread has an associated fast recorder
4534 hasFastRecorder()
4535 // FIXME test that RecordThread for this fast track has a capable output HAL
4536 // FIXME add a permission test also?
4537 ) {
4538 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4539 if (frameCount == 0) {
4540 frameCount = mFrameCount * kFastTrackMultiplier;
4541 }
4542 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4543 frameCount, mFrameCount);
4544 } else {
4545 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4546 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4547 "hasFastRecorder=%d tid=%d",
4548 frameCount, mFrameCount, format,
4549 audio_is_linear_pcm(format),
4550 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4551 *flags &= ~IAudioFlinger::TRACK_FAST;
4552 // For compatibility with AudioRecord calculation, buffer depth is forced
4553 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4554 // This is probably too conservative, but legacy application code may depend on it.
4555 // If you change this calculation, also review the start threshold which is related.
4556 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4557 size_t mNormalFrameCount = 2048; // FIXME
4558 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4559 if (minBufCount < 2) {
4560 minBufCount = 2;
4561 }
4562 size_t minFrameCount = mNormalFrameCount * minBufCount;
4563 if (frameCount < minFrameCount) {
4564 frameCount = minFrameCount;
4565 }
4566 }
4567 }
4568
Eric Laurent81784c32012-11-19 14:55:58 -08004569 // FIXME use flags and tid similar to createTrack_l()
4570
4571 { // scope for mLock
4572 Mutex::Autolock _l(mLock);
4573
4574 track = new RecordTrack(this, client, sampleRate,
4575 format, channelMask, frameCount, sessionId);
4576
4577 if (track->getCblk() == 0) {
4578 lStatus = NO_MEMORY;
4579 goto Exit;
4580 }
4581 mTracks.add(track);
4582
4583 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4584 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4585 mAudioFlinger->btNrecIsOff();
4586 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4587 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004588
4589 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4590 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4591 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4592 // so ask activity manager to do this on our behalf
4593 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4594 }
Eric Laurent81784c32012-11-19 14:55:58 -08004595 }
4596 lStatus = NO_ERROR;
4597
4598Exit:
4599 if (status) {
4600 *status = lStatus;
4601 }
4602 return track;
4603}
4604
4605status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4606 AudioSystem::sync_event_t event,
4607 int triggerSession)
4608{
4609 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4610 sp<ThreadBase> strongMe = this;
4611 status_t status = NO_ERROR;
4612
4613 if (event == AudioSystem::SYNC_EVENT_NONE) {
4614 clearSyncStartEvent();
4615 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4616 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4617 triggerSession,
4618 recordTrack->sessionId(),
4619 syncStartEventCallback,
4620 this);
4621 // Sync event can be cancelled by the trigger session if the track is not in a
4622 // compatible state in which case we start record immediately
4623 if (mSyncStartEvent->isCancelled()) {
4624 clearSyncStartEvent();
4625 } else {
4626 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4627 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4628 }
4629 }
4630
4631 {
4632 AutoMutex lock(mLock);
4633 if (mActiveTrack != 0) {
4634 if (recordTrack != mActiveTrack.get()) {
4635 status = -EBUSY;
4636 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4637 mActiveTrack->mState = TrackBase::ACTIVE;
4638 }
4639 return status;
4640 }
4641
4642 recordTrack->mState = TrackBase::IDLE;
4643 mActiveTrack = recordTrack;
4644 mLock.unlock();
4645 status_t status = AudioSystem::startInput(mId);
4646 mLock.lock();
4647 if (status != NO_ERROR) {
4648 mActiveTrack.clear();
4649 clearSyncStartEvent();
4650 return status;
4651 }
4652 mRsmpInIndex = mFrameCount;
4653 mBytesRead = 0;
4654 if (mResampler != NULL) {
4655 mResampler->reset();
4656 }
4657 mActiveTrack->mState = TrackBase::RESUMING;
4658 // signal thread to start
4659 ALOGV("Signal record thread");
4660 mWaitWorkCV.broadcast();
4661 // do not wait for mStartStopCond if exiting
4662 if (exitPending()) {
4663 mActiveTrack.clear();
4664 status = INVALID_OPERATION;
4665 goto startError;
4666 }
4667 mStartStopCond.wait(mLock);
4668 if (mActiveTrack == 0) {
4669 ALOGV("Record failed to start");
4670 status = BAD_VALUE;
4671 goto startError;
4672 }
4673 ALOGV("Record started OK");
4674 return status;
4675 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004676
Eric Laurent81784c32012-11-19 14:55:58 -08004677startError:
4678 AudioSystem::stopInput(mId);
4679 clearSyncStartEvent();
4680 return status;
4681}
4682
4683void AudioFlinger::RecordThread::clearSyncStartEvent()
4684{
4685 if (mSyncStartEvent != 0) {
4686 mSyncStartEvent->cancel();
4687 }
4688 mSyncStartEvent.clear();
4689 mFramestoDrop = 0;
4690}
4691
4692void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4693{
4694 sp<SyncEvent> strongEvent = event.promote();
4695
4696 if (strongEvent != 0) {
4697 RecordThread *me = (RecordThread *)strongEvent->cookie();
4698 me->handleSyncStartEvent(strongEvent);
4699 }
4700}
4701
4702void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4703{
4704 if (event == mSyncStartEvent) {
4705 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4706 // from audio HAL
4707 mFramestoDrop = mFrameCount * 2;
4708 }
4709}
4710
Glenn Kastena8356f62013-07-25 14:37:52 -07004711bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004712 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004713 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004714 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4715 return false;
4716 }
4717 recordTrack->mState = TrackBase::PAUSING;
4718 // do not wait for mStartStopCond if exiting
4719 if (exitPending()) {
4720 return true;
4721 }
4722 mStartStopCond.wait(mLock);
4723 // if we have been restarted, recordTrack == mActiveTrack.get() here
4724 if (exitPending() || recordTrack != mActiveTrack.get()) {
4725 ALOGV("Record stopped OK");
4726 return true;
4727 }
4728 return false;
4729}
4730
4731bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4732{
4733 return false;
4734}
4735
4736status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4737{
4738#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4739 if (!isValidSyncEvent(event)) {
4740 return BAD_VALUE;
4741 }
4742
4743 int eventSession = event->triggerSession();
4744 status_t ret = NAME_NOT_FOUND;
4745
4746 Mutex::Autolock _l(mLock);
4747
4748 for (size_t i = 0; i < mTracks.size(); i++) {
4749 sp<RecordTrack> track = mTracks[i];
4750 if (eventSession == track->sessionId()) {
4751 (void) track->setSyncEvent(event);
4752 ret = NO_ERROR;
4753 }
4754 }
4755 return ret;
4756#else
4757 return BAD_VALUE;
4758#endif
4759}
4760
4761// destroyTrack_l() must be called with ThreadBase::mLock held
4762void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4763{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004764 track->terminate();
4765 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004766 // active tracks are removed by threadLoop()
4767 if (mActiveTrack != track) {
4768 removeTrack_l(track);
4769 }
4770}
4771
4772void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4773{
4774 mTracks.remove(track);
4775 // need anything related to effects here?
4776}
4777
4778void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4779{
4780 dumpInternals(fd, args);
4781 dumpTracks(fd, args);
4782 dumpEffectChains(fd, args);
4783}
4784
4785void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4786{
4787 const size_t SIZE = 256;
4788 char buffer[SIZE];
4789 String8 result;
4790
4791 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4792 result.append(buffer);
4793
4794 if (mActiveTrack != 0) {
4795 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4796 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004797 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004798 result.append(buffer);
4799 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4800 result.append(buffer);
4801 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4802 result.append(buffer);
4803 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4804 result.append(buffer);
4805 } else {
4806 result.append("No active record client\n");
4807 }
4808
4809 write(fd, result.string(), result.size());
4810
4811 dumpBase(fd, args);
4812}
4813
4814void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4815{
4816 const size_t SIZE = 256;
4817 char buffer[SIZE];
4818 String8 result;
4819
4820 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4821 result.append(buffer);
4822 RecordTrack::appendDumpHeader(result);
4823 for (size_t i = 0; i < mTracks.size(); ++i) {
4824 sp<RecordTrack> track = mTracks[i];
4825 if (track != 0) {
4826 track->dump(buffer, SIZE);
4827 result.append(buffer);
4828 }
4829 }
4830
4831 if (mActiveTrack != 0) {
4832 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4833 result.append(buffer);
4834 RecordTrack::appendDumpHeader(result);
4835 mActiveTrack->dump(buffer, SIZE);
4836 result.append(buffer);
4837
4838 }
4839 write(fd, result.string(), result.size());
4840}
4841
4842// AudioBufferProvider interface
4843status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4844{
4845 size_t framesReq = buffer->frameCount;
4846 size_t framesReady = mFrameCount - mRsmpInIndex;
4847 int channelCount;
4848
4849 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004850 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004851 if (mBytesRead <= 0) {
4852 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4853 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4854 // Force input into standby so that it tries to
4855 // recover at next read attempt
4856 inputStandBy();
4857 usleep(kRecordThreadSleepUs);
4858 }
4859 buffer->raw = NULL;
4860 buffer->frameCount = 0;
4861 return NOT_ENOUGH_DATA;
4862 }
4863 mRsmpInIndex = 0;
4864 framesReady = mFrameCount;
4865 }
4866
4867 if (framesReq > framesReady) {
4868 framesReq = framesReady;
4869 }
4870
4871 if (mChannelCount == 1 && mReqChannelCount == 2) {
4872 channelCount = 1;
4873 } else {
4874 channelCount = 2;
4875 }
4876 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4877 buffer->frameCount = framesReq;
4878 return NO_ERROR;
4879}
4880
4881// AudioBufferProvider interface
4882void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4883{
4884 mRsmpInIndex += buffer->frameCount;
4885 buffer->frameCount = 0;
4886}
4887
4888bool AudioFlinger::RecordThread::checkForNewParameters_l()
4889{
4890 bool reconfig = false;
4891
4892 while (!mNewParameters.isEmpty()) {
4893 status_t status = NO_ERROR;
4894 String8 keyValuePair = mNewParameters[0];
4895 AudioParameter param = AudioParameter(keyValuePair);
4896 int value;
4897 audio_format_t reqFormat = mFormat;
4898 uint32_t reqSamplingRate = mReqSampleRate;
4899 uint32_t reqChannelCount = mReqChannelCount;
4900
4901 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4902 reqSamplingRate = value;
4903 reconfig = true;
4904 }
4905 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004906 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4907 status = BAD_VALUE;
4908 } else {
4909 reqFormat = (audio_format_t) value;
4910 reconfig = true;
4911 }
Eric Laurent81784c32012-11-19 14:55:58 -08004912 }
4913 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4914 reqChannelCount = popcount(value);
4915 reconfig = true;
4916 }
4917 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4918 // do not accept frame count changes if tracks are open as the track buffer
4919 // size depends on frame count and correct behavior would not be guaranteed
4920 // if frame count is changed after track creation
4921 if (mActiveTrack != 0) {
4922 status = INVALID_OPERATION;
4923 } else {
4924 reconfig = true;
4925 }
4926 }
4927 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4928 // forward device change to effects that have requested to be
4929 // aware of attached audio device.
4930 for (size_t i = 0; i < mEffectChains.size(); i++) {
4931 mEffectChains[i]->setDevice_l(value);
4932 }
4933
4934 // store input device and output device but do not forward output device to audio HAL.
4935 // Note that status is ignored by the caller for output device
4936 // (see AudioFlinger::setParameters()
4937 if (audio_is_output_devices(value)) {
4938 mOutDevice = value;
4939 status = BAD_VALUE;
4940 } else {
4941 mInDevice = value;
4942 // disable AEC and NS if the device is a BT SCO headset supporting those
4943 // pre processings
4944 if (mTracks.size() > 0) {
4945 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4946 mAudioFlinger->btNrecIsOff();
4947 for (size_t i = 0; i < mTracks.size(); i++) {
4948 sp<RecordTrack> track = mTracks[i];
4949 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4950 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4951 }
4952 }
4953 }
4954 }
4955 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4956 mAudioSource != (audio_source_t)value) {
4957 // forward device change to effects that have requested to be
4958 // aware of attached audio device.
4959 for (size_t i = 0; i < mEffectChains.size(); i++) {
4960 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4961 }
4962 mAudioSource = (audio_source_t)value;
4963 }
4964 if (status == NO_ERROR) {
4965 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4966 keyValuePair.string());
4967 if (status == INVALID_OPERATION) {
4968 inputStandBy();
4969 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4970 keyValuePair.string());
4971 }
4972 if (reconfig) {
4973 if (status == BAD_VALUE &&
4974 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4975 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004976 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004977 <= (2 * reqSamplingRate)) &&
4978 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4979 <= FCC_2 &&
4980 (reqChannelCount <= FCC_2)) {
4981 status = NO_ERROR;
4982 }
4983 if (status == NO_ERROR) {
4984 readInputParameters();
4985 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4986 }
4987 }
4988 }
4989
4990 mNewParameters.removeAt(0);
4991
4992 mParamStatus = status;
4993 mParamCond.signal();
4994 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4995 // already timed out waiting for the status and will never signal the condition.
4996 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4997 }
4998 return reconfig;
4999}
5000
5001String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5002{
Eric Laurent81784c32012-11-19 14:55:58 -08005003 Mutex::Autolock _l(mLock);
5004 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005005 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005006 }
5007
Glenn Kastend8ea6992013-07-16 14:17:15 -07005008 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5009 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005010 free(s);
5011 return out_s8;
5012}
5013
5014void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5015 AudioSystem::OutputDescriptor desc;
5016 void *param2 = NULL;
5017
5018 switch (event) {
5019 case AudioSystem::INPUT_OPENED:
5020 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005021 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 desc.samplingRate = mSampleRate;
5023 desc.format = mFormat;
5024 desc.frameCount = mFrameCount;
5025 desc.latency = 0;
5026 param2 = &desc;
5027 break;
5028
5029 case AudioSystem::INPUT_CLOSED:
5030 default:
5031 break;
5032 }
5033 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5034}
5035
5036void AudioFlinger::RecordThread::readInputParameters()
5037{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005038 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005039 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005040 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005041 mRsmpOutBuffer = NULL;
5042 delete mResampler;
5043 mResampler = NULL;
5044
5045 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5046 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005047 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005048 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005049 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5050 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5051 }
Eric Laurent81784c32012-11-19 14:55:58 -08005052 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005053 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5054 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005055 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5056
5057 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5058 {
5059 int channelCount;
5060 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5061 // stereo to mono post process as the resampler always outputs stereo.
5062 if (mChannelCount == 1 && mReqChannelCount == 2) {
5063 channelCount = 1;
5064 } else {
5065 channelCount = 2;
5066 }
5067 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5068 mResampler->setSampleRate(mSampleRate);
5069 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005070 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005071
5072 // optmization: if mono to mono, alter input frame count as if we were inputing
5073 // stereo samples
5074 if (mChannelCount == 1 && mReqChannelCount == 1) {
5075 mFrameCount >>= 1;
5076 }
5077
5078 }
5079 mRsmpInIndex = mFrameCount;
5080}
5081
5082unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5083{
5084 Mutex::Autolock _l(mLock);
5085 if (initCheck() != NO_ERROR) {
5086 return 0;
5087 }
5088
5089 return mInput->stream->get_input_frames_lost(mInput->stream);
5090}
5091
5092uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5093{
5094 Mutex::Autolock _l(mLock);
5095 uint32_t result = 0;
5096 if (getEffectChain_l(sessionId) != 0) {
5097 result = EFFECT_SESSION;
5098 }
5099
5100 for (size_t i = 0; i < mTracks.size(); ++i) {
5101 if (sessionId == mTracks[i]->sessionId()) {
5102 result |= TRACK_SESSION;
5103 break;
5104 }
5105 }
5106
5107 return result;
5108}
5109
5110KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5111{
5112 KeyedVector<int, bool> ids;
5113 Mutex::Autolock _l(mLock);
5114 for (size_t j = 0; j < mTracks.size(); ++j) {
5115 sp<RecordThread::RecordTrack> track = mTracks[j];
5116 int sessionId = track->sessionId();
5117 if (ids.indexOfKey(sessionId) < 0) {
5118 ids.add(sessionId, true);
5119 }
5120 }
5121 return ids;
5122}
5123
5124AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5125{
5126 Mutex::Autolock _l(mLock);
5127 AudioStreamIn *input = mInput;
5128 mInput = NULL;
5129 return input;
5130}
5131
5132// this method must always be called either with ThreadBase mLock held or inside the thread loop
5133audio_stream_t* AudioFlinger::RecordThread::stream() const
5134{
5135 if (mInput == NULL) {
5136 return NULL;
5137 }
5138 return &mInput->stream->common;
5139}
5140
5141status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5142{
5143 // only one chain per input thread
5144 if (mEffectChains.size() != 0) {
5145 return INVALID_OPERATION;
5146 }
5147 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5148
5149 chain->setInBuffer(NULL);
5150 chain->setOutBuffer(NULL);
5151
5152 checkSuspendOnAddEffectChain_l(chain);
5153
5154 mEffectChains.add(chain);
5155
5156 return NO_ERROR;
5157}
5158
5159size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5160{
5161 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5162 ALOGW_IF(mEffectChains.size() != 1,
5163 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5164 chain.get(), mEffectChains.size(), this);
5165 if (mEffectChains.size() == 1) {
5166 mEffectChains.removeAt(0);
5167 }
5168 return 0;
5169}
5170
5171}; // namespace android