blob: 4471d8281cc70a4777f0074fe15ae6c0e0027d50 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
112// Whether to use fast mixer
113static const enum {
114 FastMixer_Never, // never initialize or use: for debugging only
115 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
116 // normal mixer multiplier is 1
117 FastMixer_Static, // initialize if needed, then use all the time if initialized,
118 // multiplier is calculated based on min & max normal mixer buffer size
119 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
120 // multiplier is calculated based on min & max normal mixer buffer size
121 // FIXME for FastMixer_Dynamic:
122 // Supporting this option will require fixing HALs that can't handle large writes.
123 // For example, one HAL implementation returns an error from a large write,
124 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
125 // We could either fix the HAL implementations, or provide a wrapper that breaks
126 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
127} kUseFastMixer = FastMixer_Static;
128
129// Priorities for requestPriority
130static const int kPriorityAudioApp = 2;
131static const int kPriorityFastMixer = 3;
132
133// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
134// for the track. The client then sub-divides this into smaller buffers for its use.
135// Currently the client uses double-buffering by default, but doesn't tell us about that.
136// So for now we just assume that client is double-buffered.
137// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
138// N-buffering, so AudioFlinger could allocate the right amount of memory.
139// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800140static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800141
142// ----------------------------------------------------------------------------
143
144#ifdef ADD_BATTERY_DATA
145// To collect the amplifier usage
146static void addBatteryData(uint32_t params) {
147 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
148 if (service == NULL) {
149 // it already logged
150 return;
151 }
152
153 service->addBatteryData(params);
154}
155#endif
156
157
158// ----------------------------------------------------------------------------
159// CPU Stats
160// ----------------------------------------------------------------------------
161
162class CpuStats {
163public:
164 CpuStats();
165 void sample(const String8 &title);
166#ifdef DEBUG_CPU_USAGE
167private:
168 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
169 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
170
171 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
172
173 int mCpuNum; // thread's current CPU number
174 int mCpukHz; // frequency of thread's current CPU in kHz
175#endif
176};
177
178CpuStats::CpuStats()
179#ifdef DEBUG_CPU_USAGE
180 : mCpuNum(-1), mCpukHz(-1)
181#endif
182{
183}
184
185void CpuStats::sample(const String8 &title) {
186#ifdef DEBUG_CPU_USAGE
187 // get current thread's delta CPU time in wall clock ns
188 double wcNs;
189 bool valid = mCpuUsage.sampleAndEnable(wcNs);
190
191 // record sample for wall clock statistics
192 if (valid) {
193 mWcStats.sample(wcNs);
194 }
195
196 // get the current CPU number
197 int cpuNum = sched_getcpu();
198
199 // get the current CPU frequency in kHz
200 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
201
202 // check if either CPU number or frequency changed
203 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
204 mCpuNum = cpuNum;
205 mCpukHz = cpukHz;
206 // ignore sample for purposes of cycles
207 valid = false;
208 }
209
210 // if no change in CPU number or frequency, then record sample for cycle statistics
211 if (valid && mCpukHz > 0) {
212 double cycles = wcNs * cpukHz * 0.000001;
213 mHzStats.sample(cycles);
214 }
215
216 unsigned n = mWcStats.n();
217 // mCpuUsage.elapsed() is expensive, so don't call it every loop
218 if ((n & 127) == 1) {
219 long long elapsed = mCpuUsage.elapsed();
220 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
221 double perLoop = elapsed / (double) n;
222 double perLoop100 = perLoop * 0.01;
223 double perLoop1k = perLoop * 0.001;
224 double mean = mWcStats.mean();
225 double stddev = mWcStats.stddev();
226 double minimum = mWcStats.minimum();
227 double maximum = mWcStats.maximum();
228 double meanCycles = mHzStats.mean();
229 double stddevCycles = mHzStats.stddev();
230 double minCycles = mHzStats.minimum();
231 double maxCycles = mHzStats.maximum();
232 mCpuUsage.resetElapsed();
233 mWcStats.reset();
234 mHzStats.reset();
235 ALOGD("CPU usage for %s over past %.1f secs\n"
236 " (%u mixer loops at %.1f mean ms per loop):\n"
237 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
238 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
239 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
240 title.string(),
241 elapsed * .000000001, n, perLoop * .000001,
242 mean * .001,
243 stddev * .001,
244 minimum * .001,
245 maximum * .001,
246 mean / perLoop100,
247 stddev / perLoop100,
248 minimum / perLoop100,
249 maximum / perLoop100,
250 meanCycles / perLoop1k,
251 stddevCycles / perLoop1k,
252 minCycles / perLoop1k,
253 maxCycles / perLoop1k);
254
255 }
256 }
257#endif
258};
259
260// ----------------------------------------------------------------------------
261// ThreadBase
262// ----------------------------------------------------------------------------
263
264AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
265 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
266 : Thread(false /*canCallJava*/),
267 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700268 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700269 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
270 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800271 mParamStatus(NO_ERROR),
272 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
273 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
274 // mName will be set by concrete (non-virtual) subclass
275 mDeathRecipient(new PMDeathRecipient(this))
276{
277}
278
279AudioFlinger::ThreadBase::~ThreadBase()
280{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700281 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
282 for (size_t i = 0; i < mConfigEvents.size(); i++) {
283 delete mConfigEvents[i];
284 }
285 mConfigEvents.clear();
286
Eric Laurent81784c32012-11-19 14:55:58 -0800287 mParamCond.broadcast();
288 // do not lock the mutex in destructor
289 releaseWakeLock_l();
290 if (mPowerManager != 0) {
291 sp<IBinder> binder = mPowerManager->asBinder();
292 binder->unlinkToDeath(mDeathRecipient);
293 }
294}
295
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700296status_t AudioFlinger::ThreadBase::readyToRun()
297{
298 status_t status = initCheck();
299 if (status == NO_ERROR) {
300 ALOGI("AudioFlinger's thread %p ready to run", this);
301 } else {
302 ALOGE("No working audio driver found.");
303 }
304 return status;
305}
306
Eric Laurent81784c32012-11-19 14:55:58 -0800307void AudioFlinger::ThreadBase::exit()
308{
309 ALOGV("ThreadBase::exit");
310 // do any cleanup required for exit to succeed
311 preExit();
312 {
313 // This lock prevents the following race in thread (uniprocessor for illustration):
314 // if (!exitPending()) {
315 // // context switch from here to exit()
316 // // exit() calls requestExit(), what exitPending() observes
317 // // exit() calls signal(), which is dropped since no waiters
318 // // context switch back from exit() to here
319 // mWaitWorkCV.wait(...);
320 // // now thread is hung
321 // }
322 AutoMutex lock(mLock);
323 requestExit();
324 mWaitWorkCV.broadcast();
325 }
326 // When Thread::requestExitAndWait is made virtual and this method is renamed to
327 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
328 requestExitAndWait();
329}
330
331status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
332{
333 status_t status;
334
335 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
336 Mutex::Autolock _l(mLock);
337
338 mNewParameters.add(keyValuePairs);
339 mWaitWorkCV.signal();
340 // wait condition with timeout in case the thread loop has exited
341 // before the request could be processed
342 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
343 status = mParamStatus;
344 mWaitWorkCV.signal();
345 } else {
346 status = TIMED_OUT;
347 }
348 return status;
349}
350
351void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
352{
353 Mutex::Autolock _l(mLock);
354 sendIoConfigEvent_l(event, param);
355}
356
357// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
358void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
359{
360 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
361 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
362 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
363 param);
364 mWaitWorkCV.signal();
365}
366
367// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
368void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
369{
370 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
371 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
372 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
373 mConfigEvents.size(), pid, tid, prio);
374 mWaitWorkCV.signal();
375}
376
377void AudioFlinger::ThreadBase::processConfigEvents()
378{
Glenn Kastenf7773312013-08-13 16:00:42 -0700379 Mutex::Autolock _l(mLock);
380 processConfigEvents_l();
381}
382
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700383// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700384void AudioFlinger::ThreadBase::processConfigEvents_l()
385{
Eric Laurent81784c32012-11-19 14:55:58 -0800386 while (!mConfigEvents.isEmpty()) {
387 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
388 ConfigEvent *event = mConfigEvents[0];
389 mConfigEvents.removeAt(0);
390 // release mLock before locking AudioFlinger mLock: lock order is always
391 // AudioFlinger then ThreadBase to avoid cross deadlock
392 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700393 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700394 case CFG_EVENT_PRIO: {
395 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
396 // FIXME Need to understand why this has be done asynchronously
397 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
398 true /*asynchronous*/);
399 if (err != 0) {
400 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
401 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
402 }
403 } break;
404 case CFG_EVENT_IO: {
405 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700406 {
407 Mutex::Autolock _l(mAudioFlinger->mLock);
408 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
409 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700410 } break;
411 default:
412 ALOGE("processConfigEvents() unknown event type %d", event->type());
413 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800414 }
415 delete event;
416 mLock.lock();
417 }
Eric Laurent81784c32012-11-19 14:55:58 -0800418}
419
420void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
421{
422 const size_t SIZE = 256;
423 char buffer[SIZE];
424 String8 result;
425
426 bool locked = AudioFlinger::dumpTryLock(mLock);
427 if (!locked) {
428 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
429 write(fd, buffer, strlen(buffer));
430 }
431
432 snprintf(buffer, SIZE, "io handle: %d\n", mId);
433 result.append(buffer);
434 snprintf(buffer, SIZE, "TID: %d\n", getTid());
435 result.append(buffer);
436 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
437 result.append(buffer);
438 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
439 result.append(buffer);
440 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
441 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700442 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
443 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700444 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800445 result.append(buffer);
446 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
447 result.append(buffer);
448 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
449 result.append(buffer);
450 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
451 result.append(buffer);
452
453 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
454 result.append(buffer);
455 result.append(" Index Command");
456 for (size_t i = 0; i < mNewParameters.size(); ++i) {
457 snprintf(buffer, SIZE, "\n %02d ", i);
458 result.append(buffer);
459 result.append(mNewParameters[i]);
460 }
461
462 snprintf(buffer, SIZE, "\n\nPending config events: \n");
463 result.append(buffer);
464 for (size_t i = 0; i < mConfigEvents.size(); i++) {
465 mConfigEvents[i]->dump(buffer, SIZE);
466 result.append(buffer);
467 }
468 result.append("\n");
469
470 write(fd, result.string(), result.size());
471
472 if (locked) {
473 mLock.unlock();
474 }
475}
476
477void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
478{
479 const size_t SIZE = 256;
480 char buffer[SIZE];
481 String8 result;
482
483 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
484 write(fd, buffer, strlen(buffer));
485
486 for (size_t i = 0; i < mEffectChains.size(); ++i) {
487 sp<EffectChain> chain = mEffectChains[i];
488 if (chain != 0) {
489 chain->dump(fd, args);
490 }
491 }
492}
493
494void AudioFlinger::ThreadBase::acquireWakeLock()
495{
496 Mutex::Autolock _l(mLock);
497 acquireWakeLock_l();
498}
499
500void AudioFlinger::ThreadBase::acquireWakeLock_l()
501{
502 if (mPowerManager == 0) {
503 // use checkService() to avoid blocking if power service is not up yet
504 sp<IBinder> binder =
505 defaultServiceManager()->checkService(String16("power"));
506 if (binder == 0) {
507 ALOGW("Thread %s cannot connect to the power manager service", mName);
508 } else {
509 mPowerManager = interface_cast<IPowerManager>(binder);
510 binder->linkToDeath(mDeathRecipient);
511 }
512 }
513 if (mPowerManager != 0) {
514 sp<IBinder> binder = new BBinder();
515 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
516 binder,
Dianne Hackborn61d404e2013-05-20 11:22:20 -0700517 String16(mName),
518 String16("media"));
Eric Laurent81784c32012-11-19 14:55:58 -0800519 if (status == NO_ERROR) {
520 mWakeLockToken = binder;
521 }
522 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
523 }
524}
525
526void AudioFlinger::ThreadBase::releaseWakeLock()
527{
528 Mutex::Autolock _l(mLock);
529 releaseWakeLock_l();
530}
531
532void AudioFlinger::ThreadBase::releaseWakeLock_l()
533{
534 if (mWakeLockToken != 0) {
535 ALOGV("releaseWakeLock_l() %s", mName);
536 if (mPowerManager != 0) {
537 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
538 }
539 mWakeLockToken.clear();
540 }
541}
542
543void AudioFlinger::ThreadBase::clearPowerManager()
544{
545 Mutex::Autolock _l(mLock);
546 releaseWakeLock_l();
547 mPowerManager.clear();
548}
549
550void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
551{
552 sp<ThreadBase> thread = mThread.promote();
553 if (thread != 0) {
554 thread->clearPowerManager();
555 }
556 ALOGW("power manager service died !!!");
557}
558
559void AudioFlinger::ThreadBase::setEffectSuspended(
560 const effect_uuid_t *type, bool suspend, int sessionId)
561{
562 Mutex::Autolock _l(mLock);
563 setEffectSuspended_l(type, suspend, sessionId);
564}
565
566void AudioFlinger::ThreadBase::setEffectSuspended_l(
567 const effect_uuid_t *type, bool suspend, int sessionId)
568{
569 sp<EffectChain> chain = getEffectChain_l(sessionId);
570 if (chain != 0) {
571 if (type != NULL) {
572 chain->setEffectSuspended_l(type, suspend);
573 } else {
574 chain->setEffectSuspendedAll_l(suspend);
575 }
576 }
577
578 updateSuspendedSessions_l(type, suspend, sessionId);
579}
580
581void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
582{
583 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
584 if (index < 0) {
585 return;
586 }
587
588 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
589 mSuspendedSessions.valueAt(index);
590
591 for (size_t i = 0; i < sessionEffects.size(); i++) {
592 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
593 for (int j = 0; j < desc->mRefCount; j++) {
594 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
595 chain->setEffectSuspendedAll_l(true);
596 } else {
597 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
598 desc->mType.timeLow);
599 chain->setEffectSuspended_l(&desc->mType, true);
600 }
601 }
602 }
603}
604
605void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
606 bool suspend,
607 int sessionId)
608{
609 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
610
611 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
612
613 if (suspend) {
614 if (index >= 0) {
615 sessionEffects = mSuspendedSessions.valueAt(index);
616 } else {
617 mSuspendedSessions.add(sessionId, sessionEffects);
618 }
619 } else {
620 if (index < 0) {
621 return;
622 }
623 sessionEffects = mSuspendedSessions.valueAt(index);
624 }
625
626
627 int key = EffectChain::kKeyForSuspendAll;
628 if (type != NULL) {
629 key = type->timeLow;
630 }
631 index = sessionEffects.indexOfKey(key);
632
633 sp<SuspendedSessionDesc> desc;
634 if (suspend) {
635 if (index >= 0) {
636 desc = sessionEffects.valueAt(index);
637 } else {
638 desc = new SuspendedSessionDesc();
639 if (type != NULL) {
640 desc->mType = *type;
641 }
642 sessionEffects.add(key, desc);
643 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
644 }
645 desc->mRefCount++;
646 } else {
647 if (index < 0) {
648 return;
649 }
650 desc = sessionEffects.valueAt(index);
651 if (--desc->mRefCount == 0) {
652 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
653 sessionEffects.removeItemsAt(index);
654 if (sessionEffects.isEmpty()) {
655 ALOGV("updateSuspendedSessions_l() restore removing session %d",
656 sessionId);
657 mSuspendedSessions.removeItem(sessionId);
658 }
659 }
660 }
661 if (!sessionEffects.isEmpty()) {
662 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
663 }
664}
665
666void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
667 bool enabled,
668 int sessionId)
669{
670 Mutex::Autolock _l(mLock);
671 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
672}
673
674void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
675 bool enabled,
676 int sessionId)
677{
678 if (mType != RECORD) {
679 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
680 // another session. This gives the priority to well behaved effect control panels
681 // and applications not using global effects.
682 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
683 // global effects
684 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
685 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
686 }
687 }
688
689 sp<EffectChain> chain = getEffectChain_l(sessionId);
690 if (chain != 0) {
691 chain->checkSuspendOnEffectEnabled(effect, enabled);
692 }
693}
694
695// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
696sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
697 const sp<AudioFlinger::Client>& client,
698 const sp<IEffectClient>& effectClient,
699 int32_t priority,
700 int sessionId,
701 effect_descriptor_t *desc,
702 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700703 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800704{
705 sp<EffectModule> effect;
706 sp<EffectHandle> handle;
707 status_t lStatus;
708 sp<EffectChain> chain;
709 bool chainCreated = false;
710 bool effectCreated = false;
711 bool effectRegistered = false;
712
713 lStatus = initCheck();
714 if (lStatus != NO_ERROR) {
715 ALOGW("createEffect_l() Audio driver not initialized.");
716 goto Exit;
717 }
718
719 // Do not allow effects with session ID 0 on direct output or duplicating threads
720 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
721 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
722 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
723 desc->name, sessionId);
724 lStatus = BAD_VALUE;
725 goto Exit;
726 }
727 // Only Pre processor effects are allowed on input threads and only on input threads
728 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
729 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
730 desc->name, desc->flags, mType);
731 lStatus = BAD_VALUE;
732 goto Exit;
733 }
734
735 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
736
737 { // scope for mLock
738 Mutex::Autolock _l(mLock);
739
740 // check for existing effect chain with the requested audio session
741 chain = getEffectChain_l(sessionId);
742 if (chain == 0) {
743 // create a new chain for this session
744 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
745 chain = new EffectChain(this, sessionId);
746 addEffectChain_l(chain);
747 chain->setStrategy(getStrategyForSession_l(sessionId));
748 chainCreated = true;
749 } else {
750 effect = chain->getEffectFromDesc_l(desc);
751 }
752
753 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
754
755 if (effect == 0) {
756 int id = mAudioFlinger->nextUniqueId();
757 // Check CPU and memory usage
758 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
759 if (lStatus != NO_ERROR) {
760 goto Exit;
761 }
762 effectRegistered = true;
763 // create a new effect module if none present in the chain
764 effect = new EffectModule(this, chain, desc, id, sessionId);
765 lStatus = effect->status();
766 if (lStatus != NO_ERROR) {
767 goto Exit;
768 }
769 lStatus = chain->addEffect_l(effect);
770 if (lStatus != NO_ERROR) {
771 goto Exit;
772 }
773 effectCreated = true;
774
775 effect->setDevice(mOutDevice);
776 effect->setDevice(mInDevice);
777 effect->setMode(mAudioFlinger->getMode());
778 effect->setAudioSource(mAudioSource);
779 }
780 // create effect handle and connect it to effect module
781 handle = new EffectHandle(effect, client, effectClient, priority);
782 lStatus = effect->addHandle(handle.get());
783 if (enabled != NULL) {
784 *enabled = (int)effect->isEnabled();
785 }
786 }
787
788Exit:
789 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
790 Mutex::Autolock _l(mLock);
791 if (effectCreated) {
792 chain->removeEffect_l(effect);
793 }
794 if (effectRegistered) {
795 AudioSystem::unregisterEffect(effect->id());
796 }
797 if (chainCreated) {
798 removeEffectChain_l(chain);
799 }
800 handle.clear();
801 }
802
Glenn Kasten9156ef32013-08-06 15:39:08 -0700803 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800804 return handle;
805}
806
807sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
808{
809 Mutex::Autolock _l(mLock);
810 return getEffect_l(sessionId, effectId);
811}
812
813sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
814{
815 sp<EffectChain> chain = getEffectChain_l(sessionId);
816 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
817}
818
819// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
820// PlaybackThread::mLock held
821status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
822{
823 // check for existing effect chain with the requested audio session
824 int sessionId = effect->sessionId();
825 sp<EffectChain> chain = getEffectChain_l(sessionId);
826 bool chainCreated = false;
827
828 if (chain == 0) {
829 // create a new chain for this session
830 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
831 chain = new EffectChain(this, sessionId);
832 addEffectChain_l(chain);
833 chain->setStrategy(getStrategyForSession_l(sessionId));
834 chainCreated = true;
835 }
836 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
837
838 if (chain->getEffectFromId_l(effect->id()) != 0) {
839 ALOGW("addEffect_l() %p effect %s already present in chain %p",
840 this, effect->desc().name, chain.get());
841 return BAD_VALUE;
842 }
843
844 status_t status = chain->addEffect_l(effect);
845 if (status != NO_ERROR) {
846 if (chainCreated) {
847 removeEffectChain_l(chain);
848 }
849 return status;
850 }
851
852 effect->setDevice(mOutDevice);
853 effect->setDevice(mInDevice);
854 effect->setMode(mAudioFlinger->getMode());
855 effect->setAudioSource(mAudioSource);
856 return NO_ERROR;
857}
858
859void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
860
861 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
862 effect_descriptor_t desc = effect->desc();
863 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
864 detachAuxEffect_l(effect->id());
865 }
866
867 sp<EffectChain> chain = effect->chain().promote();
868 if (chain != 0) {
869 // remove effect chain if removing last effect
870 if (chain->removeEffect_l(effect) == 0) {
871 removeEffectChain_l(chain);
872 }
873 } else {
874 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
875 }
876}
877
878void AudioFlinger::ThreadBase::lockEffectChains_l(
879 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
880{
881 effectChains = mEffectChains;
882 for (size_t i = 0; i < mEffectChains.size(); i++) {
883 mEffectChains[i]->lock();
884 }
885}
886
887void AudioFlinger::ThreadBase::unlockEffectChains(
888 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
889{
890 for (size_t i = 0; i < effectChains.size(); i++) {
891 effectChains[i]->unlock();
892 }
893}
894
895sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
896{
897 Mutex::Autolock _l(mLock);
898 return getEffectChain_l(sessionId);
899}
900
901sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
902{
903 size_t size = mEffectChains.size();
904 for (size_t i = 0; i < size; i++) {
905 if (mEffectChains[i]->sessionId() == sessionId) {
906 return mEffectChains[i];
907 }
908 }
909 return 0;
910}
911
912void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
913{
914 Mutex::Autolock _l(mLock);
915 size_t size = mEffectChains.size();
916 for (size_t i = 0; i < size; i++) {
917 mEffectChains[i]->setMode_l(mode);
918 }
919}
920
921void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
922 EffectHandle *handle,
923 bool unpinIfLast) {
924
925 Mutex::Autolock _l(mLock);
926 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
927 // delete the effect module if removing last handle on it
928 if (effect->removeHandle(handle) == 0) {
929 if (!effect->isPinned() || unpinIfLast) {
930 removeEffect_l(effect);
931 AudioSystem::unregisterEffect(effect->id());
932 }
933 }
934}
935
936// ----------------------------------------------------------------------------
937// Playback
938// ----------------------------------------------------------------------------
939
940AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
941 AudioStreamOut* output,
942 audio_io_handle_t id,
943 audio_devices_t device,
944 type_t type)
945 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700946 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700947 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800948 // mStreamTypes[] initialized in constructor body
949 mOutput(output),
950 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
951 mMixerStatus(MIXER_IDLE),
952 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
953 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800954 mBytesRemaining(0),
955 mCurrentWriteLength(0),
956 mUseAsyncWrite(false),
957 mWriteBlocked(false),
958 mDraining(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800959 mScreenState(AudioFlinger::mScreenState),
960 // index 0 is reserved for normal mixer's submix
961 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
962{
963 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800964 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800965
966 // Assumes constructor is called by AudioFlinger with it's mLock held, but
967 // it would be safer to explicitly pass initial masterVolume/masterMute as
968 // parameter.
969 //
970 // If the HAL we are using has support for master volume or master mute,
971 // then do not attenuate or mute during mixing (just leave the volume at 1.0
972 // and the mute set to false).
973 mMasterVolume = audioFlinger->masterVolume_l();
974 mMasterMute = audioFlinger->masterMute_l();
975 if (mOutput && mOutput->audioHwDev) {
976 if (mOutput->audioHwDev->canSetMasterVolume()) {
977 mMasterVolume = 1.0;
978 }
979
980 if (mOutput->audioHwDev->canSetMasterMute()) {
981 mMasterMute = false;
982 }
983 }
984
985 readOutputParameters();
986
987 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
988 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
989 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
990 stream = (audio_stream_type_t) (stream + 1)) {
991 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
992 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
993 }
994 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
995 // because mAudioFlinger doesn't have one to copy from
996}
997
998AudioFlinger::PlaybackThread::~PlaybackThread()
999{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001000 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001001 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001002}
1003
1004void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1005{
1006 dumpInternals(fd, args);
1007 dumpTracks(fd, args);
1008 dumpEffectChains(fd, args);
1009}
1010
1011void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1012{
1013 const size_t SIZE = 256;
1014 char buffer[SIZE];
1015 String8 result;
1016
1017 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1018 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1019 const stream_type_t *st = &mStreamTypes[i];
1020 if (i > 0) {
1021 result.appendFormat(", ");
1022 }
1023 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1024 if (st->mute) {
1025 result.append("M");
1026 }
1027 }
1028 result.append("\n");
1029 write(fd, result.string(), result.length());
1030 result.clear();
1031
1032 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1033 result.append(buffer);
1034 Track::appendDumpHeader(result);
1035 for (size_t i = 0; i < mTracks.size(); ++i) {
1036 sp<Track> track = mTracks[i];
1037 if (track != 0) {
1038 track->dump(buffer, SIZE);
1039 result.append(buffer);
1040 }
1041 }
1042
1043 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1044 result.append(buffer);
1045 Track::appendDumpHeader(result);
1046 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1047 sp<Track> track = mActiveTracks[i].promote();
1048 if (track != 0) {
1049 track->dump(buffer, SIZE);
1050 result.append(buffer);
1051 }
1052 }
1053 write(fd, result.string(), result.size());
1054
1055 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1056 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1057 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1058 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1059}
1060
1061void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1062{
1063 const size_t SIZE = 256;
1064 char buffer[SIZE];
1065 String8 result;
1066
1067 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1068 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001069 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1070 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001071 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1072 ns2ms(systemTime() - mLastWriteTime));
1073 result.append(buffer);
1074 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1075 result.append(buffer);
1076 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1077 result.append(buffer);
1078 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1079 result.append(buffer);
1080 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1081 result.append(buffer);
1082 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1083 result.append(buffer);
1084 write(fd, result.string(), result.size());
1085 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1086
1087 dumpBase(fd, args);
1088}
1089
1090// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001091
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 }
Glenn Kasten03003332013-08-06 15:40:54 -07001256
1257 // new Track always returns non-NULL,
1258 // but TimedTrack::create() is a factory that could fail by returning NULL
1259 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1260 if (lStatus != NO_ERROR) {
1261 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001262 goto Exit;
1263 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001264
Eric Laurent81784c32012-11-19 14:55:58 -08001265 mTracks.add(track);
1266
1267 sp<EffectChain> chain = getEffectChain_l(sessionId);
1268 if (chain != 0) {
1269 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1270 track->setMainBuffer(chain->inBuffer());
1271 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1272 chain->incTrackCnt();
1273 }
1274
1275 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1276 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1277 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1278 // so ask activity manager to do this on our behalf
1279 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1280 }
1281 }
1282
1283 lStatus = NO_ERROR;
1284
1285Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001286 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001287 return track;
1288}
1289
1290uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1291{
1292 return latency;
1293}
1294
1295uint32_t AudioFlinger::PlaybackThread::latency() const
1296{
1297 Mutex::Autolock _l(mLock);
1298 return latency_l();
1299}
1300uint32_t AudioFlinger::PlaybackThread::latency_l() const
1301{
1302 if (initCheck() == NO_ERROR) {
1303 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1304 } else {
1305 return 0;
1306 }
1307}
1308
1309void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1310{
1311 Mutex::Autolock _l(mLock);
1312 // Don't apply master volume in SW if our HAL can do it for us.
1313 if (mOutput && mOutput->audioHwDev &&
1314 mOutput->audioHwDev->canSetMasterVolume()) {
1315 mMasterVolume = 1.0;
1316 } else {
1317 mMasterVolume = value;
1318 }
1319}
1320
1321void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1322{
1323 Mutex::Autolock _l(mLock);
1324 // Don't apply master mute in SW if our HAL can do it for us.
1325 if (mOutput && mOutput->audioHwDev &&
1326 mOutput->audioHwDev->canSetMasterMute()) {
1327 mMasterMute = false;
1328 } else {
1329 mMasterMute = muted;
1330 }
1331}
1332
1333void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1334{
1335 Mutex::Autolock _l(mLock);
1336 mStreamTypes[stream].volume = value;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001337 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001338}
1339
1340void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1341{
1342 Mutex::Autolock _l(mLock);
1343 mStreamTypes[stream].mute = muted;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001344 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001345}
1346
1347float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1348{
1349 Mutex::Autolock _l(mLock);
1350 return mStreamTypes[stream].volume;
1351}
1352
1353// addTrack_l() must be called with ThreadBase::mLock held
1354status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1355{
1356 status_t status = ALREADY_EXISTS;
1357
1358 // set retry count for buffer fill
1359 track->mRetryCount = kMaxTrackStartupRetries;
1360 if (mActiveTracks.indexOf(track) < 0) {
1361 // the track is newly added, make sure it fills up all its
1362 // buffers before playing. This is to ensure the client will
1363 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001364 if (!track->isOutputTrack()) {
1365 TrackBase::track_state state = track->mState;
1366 mLock.unlock();
1367 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1368 mLock.lock();
1369 // abort track was stopped/paused while we released the lock
1370 if (state != track->mState) {
1371 if (status == NO_ERROR) {
1372 mLock.unlock();
1373 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1374 mLock.lock();
1375 }
1376 return INVALID_OPERATION;
1377 }
1378 // abort if start is rejected by audio policy manager
1379 if (status != NO_ERROR) {
1380 return PERMISSION_DENIED;
1381 }
1382#ifdef ADD_BATTERY_DATA
1383 // to track the speaker usage
1384 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1385#endif
1386 }
1387
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001388 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001389 track->mResetDone = false;
1390 track->mPresentationCompleteFrames = 0;
1391 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001392 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1393 if (chain != 0) {
1394 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1395 track->sessionId());
1396 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001397 }
1398
1399 status = NO_ERROR;
1400 }
1401
1402 ALOGV("mWaitWorkCV.broadcast");
1403 mWaitWorkCV.broadcast();
1404
1405 return status;
1406}
1407
Eric Laurentbfb1b832013-01-07 09:53:42 -08001408bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001409{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001410 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001412 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1413 track->mState = TrackBase::STOPPED;
1414 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001415 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001416 } else if (track->isFastTrack() || track->isOffloaded()) {
1417 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001418 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001419
1420 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001421}
1422
1423void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1424{
1425 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1426 mTracks.remove(track);
1427 deleteTrackName_l(track->name());
1428 // redundant as track is about to be destroyed, for dumpsys only
1429 track->mName = -1;
1430 if (track->isFastTrack()) {
1431 int index = track->mFastIndex;
1432 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1433 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1434 mFastTrackAvailMask |= 1 << index;
1435 // redundant as track is about to be destroyed, for dumpsys only
1436 track->mFastIndex = -1;
1437 }
1438 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1439 if (chain != 0) {
1440 chain->decTrackCnt();
1441 }
1442}
1443
Eric Laurentbfb1b832013-01-07 09:53:42 -08001444void AudioFlinger::PlaybackThread::signal_l()
1445{
1446 // Thread could be blocked waiting for async
1447 // so signal it to handle state changes immediately
1448 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1449 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1450 mSignalPending = true;
1451 mWaitWorkCV.signal();
1452}
1453
Eric Laurent81784c32012-11-19 14:55:58 -08001454String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1455{
Eric Laurent81784c32012-11-19 14:55:58 -08001456 Mutex::Autolock _l(mLock);
1457 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001458 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001459 }
1460
Glenn Kastend8ea6992013-07-16 14:17:15 -07001461 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1462 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001463 free(s);
1464 return out_s8;
1465}
1466
1467// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1468void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1469 AudioSystem::OutputDescriptor desc;
1470 void *param2 = NULL;
1471
1472 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1473 param);
1474
1475 switch (event) {
1476 case AudioSystem::OUTPUT_OPENED:
1477 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001478 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001479 desc.samplingRate = mSampleRate;
1480 desc.format = mFormat;
1481 desc.frameCount = mNormalFrameCount; // FIXME see
1482 // AudioFlinger::frameCount(audio_io_handle_t)
1483 desc.latency = latency();
1484 param2 = &desc;
1485 break;
1486
1487 case AudioSystem::STREAM_CONFIG_CHANGED:
1488 param2 = &param;
1489 case AudioSystem::OUTPUT_CLOSED:
1490 default:
1491 break;
1492 }
1493 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1494}
1495
Eric Laurentbfb1b832013-01-07 09:53:42 -08001496void AudioFlinger::PlaybackThread::writeCallback()
1497{
1498 ALOG_ASSERT(mCallbackThread != 0);
1499 mCallbackThread->setWriteBlocked(false);
1500}
1501
1502void AudioFlinger::PlaybackThread::drainCallback()
1503{
1504 ALOG_ASSERT(mCallbackThread != 0);
1505 mCallbackThread->setDraining(false);
1506}
1507
1508void AudioFlinger::PlaybackThread::setWriteBlocked(bool value)
1509{
1510 Mutex::Autolock _l(mLock);
1511 mWriteBlocked = value;
1512 if (!value) {
1513 mWaitWorkCV.signal();
1514 }
1515}
1516
1517void AudioFlinger::PlaybackThread::setDraining(bool value)
1518{
1519 Mutex::Autolock _l(mLock);
1520 mDraining = value;
1521 if (!value) {
1522 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);
Glenn Kasten70949c42013-08-06 07:40:12 -07001569 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1570 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001571 if (mFrameCount & 15) {
1572 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1573 mFrameCount);
1574 }
1575
Eric Laurentbfb1b832013-01-07 09:53:42 -08001576 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1577 (mOutput->stream->set_callback != NULL)) {
1578 if (mOutput->stream->set_callback(mOutput->stream,
1579 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1580 mUseAsyncWrite = true;
1581 }
1582 }
1583
Eric Laurent81784c32012-11-19 14:55:58 -08001584 // Calculate size of normal mix buffer relative to the HAL output buffer size
1585 double multiplier = 1.0;
1586 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1587 kUseFastMixer == FastMixer_Dynamic)) {
1588 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1589 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1590 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1591 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1592 maxNormalFrameCount = maxNormalFrameCount & ~15;
1593 if (maxNormalFrameCount < minNormalFrameCount) {
1594 maxNormalFrameCount = minNormalFrameCount;
1595 }
1596 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1597 if (multiplier <= 1.0) {
1598 multiplier = 1.0;
1599 } else if (multiplier <= 2.0) {
1600 if (2 * mFrameCount <= maxNormalFrameCount) {
1601 multiplier = 2.0;
1602 } else {
1603 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1604 }
1605 } else {
1606 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1607 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1608 // track, but we sometimes have to do this to satisfy the maximum frame count
1609 // constraint)
1610 // FIXME this rounding up should not be done if no HAL SRC
1611 uint32_t truncMult = (uint32_t) multiplier;
1612 if ((truncMult & 1)) {
1613 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1614 ++truncMult;
1615 }
1616 }
1617 multiplier = (double) truncMult;
1618 }
1619 }
1620 mNormalFrameCount = multiplier * mFrameCount;
1621 // round up to nearest 16 frames to satisfy AudioMixer
1622 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1623 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1624 mNormalFrameCount);
1625
Glenn Kastenc1fac192013-08-06 07:41:36 -07001626 delete[] mMixBuffer;
1627 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1628 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1629 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1630 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001631
1632 // force reconfiguration of effect chains and engines to take new buffer size and audio
1633 // parameters into account
1634 // Note that mLock is not held when readOutputParameters() is called from the constructor
1635 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1636 // matter.
1637 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1638 Vector< sp<EffectChain> > effectChains = mEffectChains;
1639 for (size_t i = 0; i < effectChains.size(); i ++) {
1640 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1641 }
1642}
1643
1644
1645status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1646{
1647 if (halFrames == NULL || dspFrames == NULL) {
1648 return BAD_VALUE;
1649 }
1650 Mutex::Autolock _l(mLock);
1651 if (initCheck() != NO_ERROR) {
1652 return INVALID_OPERATION;
1653 }
1654 size_t framesWritten = mBytesWritten / mFrameSize;
1655 *halFrames = framesWritten;
1656
1657 if (isSuspended()) {
1658 // return an estimation of rendered frames when the output is suspended
1659 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1660 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1661 return NO_ERROR;
1662 } else {
1663 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1664 }
1665}
1666
1667uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1668{
1669 Mutex::Autolock _l(mLock);
1670 uint32_t result = 0;
1671 if (getEffectChain_l(sessionId) != 0) {
1672 result = EFFECT_SESSION;
1673 }
1674
1675 for (size_t i = 0; i < mTracks.size(); ++i) {
1676 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001677 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001678 result |= TRACK_SESSION;
1679 break;
1680 }
1681 }
1682
1683 return result;
1684}
1685
1686uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1687{
1688 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1689 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1690 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1691 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1692 }
1693 for (size_t i = 0; i < mTracks.size(); i++) {
1694 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001695 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001696 return AudioSystem::getStrategyForStream(track->streamType());
1697 }
1698 }
1699 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1700}
1701
1702
1703AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1704{
1705 Mutex::Autolock _l(mLock);
1706 return mOutput;
1707}
1708
1709AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1710{
1711 Mutex::Autolock _l(mLock);
1712 AudioStreamOut *output = mOutput;
1713 mOutput = NULL;
1714 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1715 // must push a NULL and wait for ack
1716 mOutputSink.clear();
1717 mPipeSink.clear();
1718 mNormalSink.clear();
1719 return output;
1720}
1721
1722// this method must always be called either with ThreadBase mLock held or inside the thread loop
1723audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1724{
1725 if (mOutput == NULL) {
1726 return NULL;
1727 }
1728 return &mOutput->stream->common;
1729}
1730
1731uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1732{
1733 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1734}
1735
1736status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1737{
1738 if (!isValidSyncEvent(event)) {
1739 return BAD_VALUE;
1740 }
1741
1742 Mutex::Autolock _l(mLock);
1743
1744 for (size_t i = 0; i < mTracks.size(); ++i) {
1745 sp<Track> track = mTracks[i];
1746 if (event->triggerSession() == track->sessionId()) {
1747 (void) track->setSyncEvent(event);
1748 return NO_ERROR;
1749 }
1750 }
1751
1752 return NAME_NOT_FOUND;
1753}
1754
1755bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1756{
1757 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1758}
1759
1760void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1761 const Vector< sp<Track> >& tracksToRemove)
1762{
1763 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001764 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001765 for (size_t i = 0 ; i < count ; i++) {
1766 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001768 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001769#ifdef ADD_BATTERY_DATA
1770 // to track the speaker usage
1771 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1772#endif
1773 if (track->isTerminated()) {
1774 AudioSystem::releaseOutput(mId);
1775 }
Eric Laurent81784c32012-11-19 14:55:58 -08001776 }
1777 }
1778 }
Eric Laurent81784c32012-11-19 14:55:58 -08001779}
1780
1781void AudioFlinger::PlaybackThread::checkSilentMode_l()
1782{
1783 if (!mMasterMute) {
1784 char value[PROPERTY_VALUE_MAX];
1785 if (property_get("ro.audio.silent", value, "0") > 0) {
1786 char *endptr;
1787 unsigned long ul = strtoul(value, &endptr, 0);
1788 if (*endptr == '\0' && ul != 0) {
1789 ALOGD("Silence is golden");
1790 // The setprop command will not allow a property to be changed after
1791 // the first time it is set, so we don't have to worry about un-muting.
1792 setMasterMute_l(true);
1793 }
1794 }
1795 }
1796}
1797
1798// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001799ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
1801 // FIXME rewrite to reduce number of system calls
1802 mLastWriteTime = systemTime();
1803 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001804 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001805
1806 // If an NBAIO sink is present, use it to write the normal mixer's submix
1807 if (mNormalSink != 0) {
1808#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001809 size_t count = mBytesRemaining >> mBitShift;
1810 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001811 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001812 // update the setpoint when AudioFlinger::mScreenState changes
1813 uint32_t screenState = AudioFlinger::mScreenState;
1814 if (screenState != mScreenState) {
1815 mScreenState = screenState;
1816 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1817 if (pipe != NULL) {
1818 pipe->setAvgFrames((mScreenState & 1) ?
1819 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1820 }
1821 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001822 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001823 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001824 if (framesWritten > 0) {
1825 bytesWritten = framesWritten << mBitShift;
1826 } else {
1827 bytesWritten = framesWritten;
1828 }
1829 // otherwise use the HAL / AudioStreamOut directly
1830 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001831 // Direct output and offload threads
1832 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1833 if (mUseAsyncWrite) {
1834 mWriteBlocked = true;
1835 ALOG_ASSERT(mCallbackThread != 0);
1836 mCallbackThread->setWriteBlocked(true);
1837 }
1838 bytesWritten = mOutput->stream->write(mOutput->stream,
1839 mMixBuffer + offset, mBytesRemaining);
1840 if (mUseAsyncWrite &&
1841 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1842 // do not wait for async callback in case of error of full write
1843 mWriteBlocked = false;
1844 ALOG_ASSERT(mCallbackThread != 0);
1845 mCallbackThread->setWriteBlocked(false);
1846 }
Eric Laurent81784c32012-11-19 14:55:58 -08001847 }
1848
Eric Laurent81784c32012-11-19 14:55:58 -08001849 mNumWrites++;
1850 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001851
1852 return bytesWritten;
1853}
1854
1855void AudioFlinger::PlaybackThread::threadLoop_drain()
1856{
1857 if (mOutput->stream->drain) {
1858 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1859 if (mUseAsyncWrite) {
1860 mDraining = true;
1861 ALOG_ASSERT(mCallbackThread != 0);
1862 mCallbackThread->setDraining(true);
1863 }
1864 mOutput->stream->drain(mOutput->stream,
1865 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1866 : AUDIO_DRAIN_ALL);
1867 }
1868}
1869
1870void AudioFlinger::PlaybackThread::threadLoop_exit()
1871{
1872 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001873}
1874
1875/*
1876The derived values that are cached:
1877 - mixBufferSize from frame count * frame size
1878 - activeSleepTime from activeSleepTimeUs()
1879 - idleSleepTime from idleSleepTimeUs()
1880 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1881 - maxPeriod from frame count and sample rate (MIXER only)
1882
1883The parameters that affect these derived values are:
1884 - frame count
1885 - frame size
1886 - sample rate
1887 - device type: A2DP or not
1888 - device latency
1889 - format: PCM or not
1890 - active sleep time
1891 - idle sleep time
1892*/
1893
1894void AudioFlinger::PlaybackThread::cacheParameters_l()
1895{
1896 mixBufferSize = mNormalFrameCount * mFrameSize;
1897 activeSleepTime = activeSleepTimeUs();
1898 idleSleepTime = idleSleepTimeUs();
1899}
1900
1901void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1902{
Glenn Kasten7c027242012-12-26 14:43:16 -08001903 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001904 this, streamType, mTracks.size());
1905 Mutex::Autolock _l(mLock);
1906
1907 size_t size = mTracks.size();
1908 for (size_t i = 0; i < size; i++) {
1909 sp<Track> t = mTracks[i];
1910 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001911 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001912 }
1913 }
1914}
1915
1916status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1917{
1918 int session = chain->sessionId();
1919 int16_t *buffer = mMixBuffer;
1920 bool ownsBuffer = false;
1921
1922 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1923 if (session > 0) {
1924 // Only one effect chain can be present in direct output thread and it uses
1925 // the mix buffer as input
1926 if (mType != DIRECT) {
1927 size_t numSamples = mNormalFrameCount * mChannelCount;
1928 buffer = new int16_t[numSamples];
1929 memset(buffer, 0, numSamples * sizeof(int16_t));
1930 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1931 ownsBuffer = true;
1932 }
1933
1934 // Attach all tracks with same session ID to this chain.
1935 for (size_t i = 0; i < mTracks.size(); ++i) {
1936 sp<Track> track = mTracks[i];
1937 if (session == track->sessionId()) {
1938 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1939 buffer);
1940 track->setMainBuffer(buffer);
1941 chain->incTrackCnt();
1942 }
1943 }
1944
1945 // indicate all active tracks in the chain
1946 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1947 sp<Track> track = mActiveTracks[i].promote();
1948 if (track == 0) {
1949 continue;
1950 }
1951 if (session == track->sessionId()) {
1952 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1953 chain->incActiveTrackCnt();
1954 }
1955 }
1956 }
1957
1958 chain->setInBuffer(buffer, ownsBuffer);
1959 chain->setOutBuffer(mMixBuffer);
1960 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1961 // chains list in order to be processed last as it contains output stage effects
1962 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1963 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1964 // after track specific effects and before output stage
1965 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1966 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1967 // Effect chain for other sessions are inserted at beginning of effect
1968 // chains list to be processed before output mix effects. Relative order between other
1969 // sessions is not important
1970 size_t size = mEffectChains.size();
1971 size_t i = 0;
1972 for (i = 0; i < size; i++) {
1973 if (mEffectChains[i]->sessionId() < session) {
1974 break;
1975 }
1976 }
1977 mEffectChains.insertAt(chain, i);
1978 checkSuspendOnAddEffectChain_l(chain);
1979
1980 return NO_ERROR;
1981}
1982
1983size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1984{
1985 int session = chain->sessionId();
1986
1987 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1988
1989 for (size_t i = 0; i < mEffectChains.size(); i++) {
1990 if (chain == mEffectChains[i]) {
1991 mEffectChains.removeAt(i);
1992 // detach all active tracks from the chain
1993 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1994 sp<Track> track = mActiveTracks[i].promote();
1995 if (track == 0) {
1996 continue;
1997 }
1998 if (session == track->sessionId()) {
1999 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2000 chain.get(), session);
2001 chain->decActiveTrackCnt();
2002 }
2003 }
2004
2005 // detach all tracks with same session ID from this chain
2006 for (size_t i = 0; i < mTracks.size(); ++i) {
2007 sp<Track> track = mTracks[i];
2008 if (session == track->sessionId()) {
2009 track->setMainBuffer(mMixBuffer);
2010 chain->decTrackCnt();
2011 }
2012 }
2013 break;
2014 }
2015 }
2016 return mEffectChains.size();
2017}
2018
2019status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2020 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2021{
2022 Mutex::Autolock _l(mLock);
2023 return attachAuxEffect_l(track, EffectId);
2024}
2025
2026status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2027 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2028{
2029 status_t status = NO_ERROR;
2030
2031 if (EffectId == 0) {
2032 track->setAuxBuffer(0, NULL);
2033 } else {
2034 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2035 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2036 if (effect != 0) {
2037 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2038 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2039 } else {
2040 status = INVALID_OPERATION;
2041 }
2042 } else {
2043 status = BAD_VALUE;
2044 }
2045 }
2046 return status;
2047}
2048
2049void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2050{
2051 for (size_t i = 0; i < mTracks.size(); ++i) {
2052 sp<Track> track = mTracks[i];
2053 if (track->auxEffectId() == effectId) {
2054 attachAuxEffect_l(track, 0);
2055 }
2056 }
2057}
2058
2059bool AudioFlinger::PlaybackThread::threadLoop()
2060{
2061 Vector< sp<Track> > tracksToRemove;
2062
2063 standbyTime = systemTime();
2064
2065 // MIXER
2066 nsecs_t lastWarning = 0;
2067
2068 // DUPLICATING
2069 // FIXME could this be made local to while loop?
2070 writeFrames = 0;
2071
2072 cacheParameters_l();
2073 sleepTime = idleSleepTime;
2074
2075 if (mType == MIXER) {
2076 sleepTimeShift = 0;
2077 }
2078
2079 CpuStats cpuStats;
2080 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2081
2082 acquireWakeLock();
2083
Glenn Kasten9e58b552013-01-18 15:09:48 -08002084 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2085 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2086 // and then that string will be logged at the next convenient opportunity.
2087 const char *logString = NULL;
2088
Eric Laurent81784c32012-11-19 14:55:58 -08002089 while (!exitPending())
2090 {
2091 cpuStats.sample(myName);
2092
2093 Vector< sp<EffectChain> > effectChains;
2094
2095 processConfigEvents();
2096
2097 { // scope for mLock
2098
2099 Mutex::Autolock _l(mLock);
2100
Glenn Kasten9e58b552013-01-18 15:09:48 -08002101 if (logString != NULL) {
2102 mNBLogWriter->logTimestamp();
2103 mNBLogWriter->log(logString);
2104 logString = NULL;
2105 }
2106
Eric Laurent81784c32012-11-19 14:55:58 -08002107 if (checkForNewParameters_l()) {
2108 cacheParameters_l();
2109 }
2110
2111 saveOutputTracks();
2112
Eric Laurentbfb1b832013-01-07 09:53:42 -08002113 if (mSignalPending) {
2114 // A signal was raised while we were unlocked
2115 mSignalPending = false;
2116 } else if (waitingAsyncCallback_l()) {
2117 if (exitPending()) {
2118 break;
2119 }
2120 releaseWakeLock_l();
2121 ALOGV("wait async completion");
2122 mWaitWorkCV.wait(mLock);
2123 ALOGV("async completion/wake");
2124 acquireWakeLock_l();
2125 if (exitPending()) {
2126 break;
2127 }
2128 if (!mActiveTracks.size() && (systemTime() > standbyTime)) {
2129 continue;
2130 }
2131 sleepTime = 0;
2132 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2133 isSuspended()) {
2134 // put audio hardware into standby after short delay
2135 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002136
2137 threadLoop_standby();
2138
2139 mStandby = true;
2140 }
2141
2142 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2143 // we're about to wait, flush the binder command buffer
2144 IPCThreadState::self()->flushCommands();
2145
2146 clearOutputTracks();
2147
2148 if (exitPending()) {
2149 break;
2150 }
2151
2152 releaseWakeLock_l();
2153 // wait until we have something to do...
2154 ALOGV("%s going to sleep", myName.string());
2155 mWaitWorkCV.wait(mLock);
2156 ALOGV("%s waking up", myName.string());
2157 acquireWakeLock_l();
2158
2159 mMixerStatus = MIXER_IDLE;
2160 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2161 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002163 checkSilentMode_l();
2164
2165 standbyTime = systemTime() + standbyDelay;
2166 sleepTime = idleSleepTime;
2167 if (mType == MIXER) {
2168 sleepTimeShift = 0;
2169 }
2170
2171 continue;
2172 }
2173 }
2174
2175 // mMixerStatusIgnoringFastTracks is also updated internally
2176 mMixerStatus = prepareTracks_l(&tracksToRemove);
2177
2178 // prevent any changes in effect chain list and in each effect chain
2179 // during mixing and effect process as the audio buffers could be deleted
2180 // or modified if an effect is created or deleted
2181 lockEffectChains_l(effectChains);
2182 }
2183
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 if (mBytesRemaining == 0) {
2185 mCurrentWriteLength = 0;
2186 if (mMixerStatus == MIXER_TRACKS_READY) {
2187 // threadLoop_mix() sets mCurrentWriteLength
2188 threadLoop_mix();
2189 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2190 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2191 // threadLoop_sleepTime sets sleepTime to 0 if data
2192 // must be written to HAL
2193 threadLoop_sleepTime();
2194 if (sleepTime == 0) {
2195 mCurrentWriteLength = mixBufferSize;
2196 }
2197 }
2198 mBytesRemaining = mCurrentWriteLength;
2199 if (isSuspended()) {
2200 sleepTime = suspendSleepTimeUs();
2201 // simulate write to HAL when suspended
2202 mBytesWritten += mixBufferSize;
2203 mBytesRemaining = 0;
2204 }
Eric Laurent81784c32012-11-19 14:55:58 -08002205
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 // only process effects if we're going to write
2207 if (sleepTime == 0) {
2208 for (size_t i = 0; i < effectChains.size(); i ++) {
2209 effectChains[i]->process_l();
2210 }
Eric Laurent81784c32012-11-19 14:55:58 -08002211 }
2212 }
2213
2214 // enable changes in effect chain
2215 unlockEffectChains(effectChains);
2216
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 if (!waitingAsyncCallback()) {
2218 // sleepTime == 0 means we must write to audio hardware
2219 if (sleepTime == 0) {
2220 if (mBytesRemaining) {
2221 ssize_t ret = threadLoop_write();
2222 if (ret < 0) {
2223 mBytesRemaining = 0;
2224 } else {
2225 mBytesWritten += ret;
2226 mBytesRemaining -= ret;
2227 }
2228 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2229 (mMixerStatus == MIXER_DRAIN_ALL)) {
2230 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002231 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002232if (mType == MIXER) {
2233 // write blocked detection
2234 nsecs_t now = systemTime();
2235 nsecs_t delta = now - mLastWriteTime;
2236 if (!mStandby && delta > maxPeriod) {
2237 mNumDelayedWrites++;
2238 if ((now - lastWarning) > kWarningThrottleNs) {
2239 ATRACE_NAME("underrun");
2240 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2241 ns2ms(delta), mNumDelayedWrites, this);
2242 lastWarning = now;
2243 }
2244 }
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 mStandby = false;
2248 } else {
2249 usleep(sleepTime);
2250 }
Eric Laurent81784c32012-11-19 14:55:58 -08002251 }
2252
2253 // Finally let go of removed track(s), without the lock held
2254 // since we can't guarantee the destructors won't acquire that
2255 // same lock. This will also mutate and push a new fast mixer state.
2256 threadLoop_removeTracks(tracksToRemove);
2257 tracksToRemove.clear();
2258
2259 // FIXME I don't understand the need for this here;
2260 // it was in the original code but maybe the
2261 // assignment in saveOutputTracks() makes this unnecessary?
2262 clearOutputTracks();
2263
2264 // Effect chains will be actually deleted here if they were removed from
2265 // mEffectChains list during mixing or effects processing
2266 effectChains.clear();
2267
2268 // FIXME Note that the above .clear() is no longer necessary since effectChains
2269 // is now local to this block, but will keep it for now (at least until merge done).
2270 }
2271
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272 threadLoop_exit();
2273
Eric Laurent81784c32012-11-19 14:55:58 -08002274 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002276 // put output stream into standby mode
2277 if (!mStandby) {
2278 mOutput->stream->common.standby(&mOutput->stream->common);
2279 }
2280 }
2281
2282 releaseWakeLock();
2283
2284 ALOGV("Thread %p type %d exiting", this, mType);
2285 return false;
2286}
2287
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288// removeTracks_l() must be called with ThreadBase::mLock held
2289void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2290{
2291 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002292 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002293 for (size_t i=0 ; i<count ; i++) {
2294 const sp<Track>& track = tracksToRemove.itemAt(i);
2295 mActiveTracks.remove(track);
2296 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2297 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2298 if (chain != 0) {
2299 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2300 track->sessionId());
2301 chain->decActiveTrackCnt();
2302 }
2303 if (track->isTerminated()) {
2304 removeTrack_l(track);
2305 }
2306 }
2307 }
2308
2309}
Eric Laurent81784c32012-11-19 14:55:58 -08002310
2311// ----------------------------------------------------------------------------
2312
2313AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2314 audio_io_handle_t id, audio_devices_t device, type_t type)
2315 : PlaybackThread(audioFlinger, output, id, device, type),
2316 // mAudioMixer below
2317 // mFastMixer below
2318 mFastMixerFutex(0)
2319 // mOutputSink below
2320 // mPipeSink below
2321 // mNormalSink below
2322{
2323 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002324 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002325 "mFrameCount=%d, mNormalFrameCount=%d",
2326 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2327 mNormalFrameCount);
2328 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2329
2330 // FIXME - Current mixer implementation only supports stereo output
2331 if (mChannelCount != FCC_2) {
2332 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2333 }
2334
2335 // create an NBAIO sink for the HAL output stream, and negotiate
2336 mOutputSink = new AudioStreamOutSink(output->stream);
2337 size_t numCounterOffers = 0;
2338 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2339 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2340 ALOG_ASSERT(index == 0);
2341
2342 // initialize fast mixer depending on configuration
2343 bool initFastMixer;
2344 switch (kUseFastMixer) {
2345 case FastMixer_Never:
2346 initFastMixer = false;
2347 break;
2348 case FastMixer_Always:
2349 initFastMixer = true;
2350 break;
2351 case FastMixer_Static:
2352 case FastMixer_Dynamic:
2353 initFastMixer = mFrameCount < mNormalFrameCount;
2354 break;
2355 }
2356 if (initFastMixer) {
2357
2358 // create a MonoPipe to connect our submix to FastMixer
2359 NBAIO_Format format = mOutputSink->format();
2360 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2361 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2362 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2363 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2364 const NBAIO_Format offers[1] = {format};
2365 size_t numCounterOffers = 0;
2366 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2367 ALOG_ASSERT(index == 0);
2368 monoPipe->setAvgFrames((mScreenState & 1) ?
2369 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2370 mPipeSink = monoPipe;
2371
Glenn Kasten46909e72013-02-26 09:20:22 -08002372#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002373 if (mTeeSinkOutputEnabled) {
2374 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2375 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2376 numCounterOffers = 0;
2377 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2378 ALOG_ASSERT(index == 0);
2379 mTeeSink = teeSink;
2380 PipeReader *teeSource = new PipeReader(*teeSink);
2381 numCounterOffers = 0;
2382 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2383 ALOG_ASSERT(index == 0);
2384 mTeeSource = teeSource;
2385 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002386#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002387
2388 // create fast mixer and configure it initially with just one fast track for our submix
2389 mFastMixer = new FastMixer();
2390 FastMixerStateQueue *sq = mFastMixer->sq();
2391#ifdef STATE_QUEUE_DUMP
2392 sq->setObserverDump(&mStateQueueObserverDump);
2393 sq->setMutatorDump(&mStateQueueMutatorDump);
2394#endif
2395 FastMixerState *state = sq->begin();
2396 FastTrack *fastTrack = &state->mFastTracks[0];
2397 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2398 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2399 fastTrack->mVolumeProvider = NULL;
2400 fastTrack->mGeneration++;
2401 state->mFastTracksGen++;
2402 state->mTrackMask = 1;
2403 // fast mixer will use the HAL output sink
2404 state->mOutputSink = mOutputSink.get();
2405 state->mOutputSinkGen++;
2406 state->mFrameCount = mFrameCount;
2407 state->mCommand = FastMixerState::COLD_IDLE;
2408 // already done in constructor initialization list
2409 //mFastMixerFutex = 0;
2410 state->mColdFutexAddr = &mFastMixerFutex;
2411 state->mColdGen++;
2412 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002413#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002414 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002415#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002416 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2417 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002418 sq->end();
2419 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2420
2421 // start the fast mixer
2422 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2423 pid_t tid = mFastMixer->getTid();
2424 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2425 if (err != 0) {
2426 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2427 kPriorityFastMixer, getpid_cached, tid, err);
2428 }
2429
2430#ifdef AUDIO_WATCHDOG
2431 // create and start the watchdog
2432 mAudioWatchdog = new AudioWatchdog();
2433 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2434 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2435 tid = mAudioWatchdog->getTid();
2436 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2437 if (err != 0) {
2438 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2439 kPriorityFastMixer, getpid_cached, tid, err);
2440 }
2441#endif
2442
2443 } else {
2444 mFastMixer = NULL;
2445 }
2446
2447 switch (kUseFastMixer) {
2448 case FastMixer_Never:
2449 case FastMixer_Dynamic:
2450 mNormalSink = mOutputSink;
2451 break;
2452 case FastMixer_Always:
2453 mNormalSink = mPipeSink;
2454 break;
2455 case FastMixer_Static:
2456 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2457 break;
2458 }
2459}
2460
2461AudioFlinger::MixerThread::~MixerThread()
2462{
2463 if (mFastMixer != NULL) {
2464 FastMixerStateQueue *sq = mFastMixer->sq();
2465 FastMixerState *state = sq->begin();
2466 if (state->mCommand == FastMixerState::COLD_IDLE) {
2467 int32_t old = android_atomic_inc(&mFastMixerFutex);
2468 if (old == -1) {
2469 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2470 }
2471 }
2472 state->mCommand = FastMixerState::EXIT;
2473 sq->end();
2474 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2475 mFastMixer->join();
2476 // Though the fast mixer thread has exited, it's state queue is still valid.
2477 // We'll use that extract the final state which contains one remaining fast track
2478 // corresponding to our sub-mix.
2479 state = sq->begin();
2480 ALOG_ASSERT(state->mTrackMask == 1);
2481 FastTrack *fastTrack = &state->mFastTracks[0];
2482 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2483 delete fastTrack->mBufferProvider;
2484 sq->end(false /*didModify*/);
2485 delete mFastMixer;
2486#ifdef AUDIO_WATCHDOG
2487 if (mAudioWatchdog != 0) {
2488 mAudioWatchdog->requestExit();
2489 mAudioWatchdog->requestExitAndWait();
2490 mAudioWatchdog.clear();
2491 }
2492#endif
2493 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002494 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002495 delete mAudioMixer;
2496}
2497
2498
2499uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2500{
2501 if (mFastMixer != NULL) {
2502 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2503 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2504 }
2505 return latency;
2506}
2507
2508
2509void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2510{
2511 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2512}
2513
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002515{
2516 // FIXME we should only do one push per cycle; confirm this is true
2517 // Start the fast mixer if it's not already running
2518 if (mFastMixer != NULL) {
2519 FastMixerStateQueue *sq = mFastMixer->sq();
2520 FastMixerState *state = sq->begin();
2521 if (state->mCommand != FastMixerState::MIX_WRITE &&
2522 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2523 if (state->mCommand == FastMixerState::COLD_IDLE) {
2524 int32_t old = android_atomic_inc(&mFastMixerFutex);
2525 if (old == -1) {
2526 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2527 }
2528#ifdef AUDIO_WATCHDOG
2529 if (mAudioWatchdog != 0) {
2530 mAudioWatchdog->resume();
2531 }
2532#endif
2533 }
2534 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002535 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2536 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002537 sq->end();
2538 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2539 if (kUseFastMixer == FastMixer_Dynamic) {
2540 mNormalSink = mPipeSink;
2541 }
2542 } else {
2543 sq->end(false /*didModify*/);
2544 }
2545 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002546 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002547}
2548
2549void AudioFlinger::MixerThread::threadLoop_standby()
2550{
2551 // Idle the fast mixer if it's currently running
2552 if (mFastMixer != NULL) {
2553 FastMixerStateQueue *sq = mFastMixer->sq();
2554 FastMixerState *state = sq->begin();
2555 if (!(state->mCommand & FastMixerState::IDLE)) {
2556 state->mCommand = FastMixerState::COLD_IDLE;
2557 state->mColdFutexAddr = &mFastMixerFutex;
2558 state->mColdGen++;
2559 mFastMixerFutex = 0;
2560 sq->end();
2561 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2562 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2563 if (kUseFastMixer == FastMixer_Dynamic) {
2564 mNormalSink = mOutputSink;
2565 }
2566#ifdef AUDIO_WATCHDOG
2567 if (mAudioWatchdog != 0) {
2568 mAudioWatchdog->pause();
2569 }
2570#endif
2571 } else {
2572 sq->end(false /*didModify*/);
2573 }
2574 }
2575 PlaybackThread::threadLoop_standby();
2576}
2577
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578// Empty implementation for standard mixer
2579// Overridden for offloaded playback
2580void AudioFlinger::PlaybackThread::flushOutput_l()
2581{
2582}
2583
2584bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2585{
2586 return false;
2587}
2588
2589bool AudioFlinger::PlaybackThread::shouldStandby_l()
2590{
2591 return !mStandby;
2592}
2593
2594bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2595{
2596 Mutex::Autolock _l(mLock);
2597 return waitingAsyncCallback_l();
2598}
2599
Eric Laurent81784c32012-11-19 14:55:58 -08002600// shared by MIXER and DIRECT, overridden by DUPLICATING
2601void AudioFlinger::PlaybackThread::threadLoop_standby()
2602{
2603 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2604 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605 if (mUseAsyncWrite != 0) {
2606 mWriteBlocked = false;
2607 mDraining = false;
2608 ALOG_ASSERT(mCallbackThread != 0);
2609 mCallbackThread->setWriteBlocked(false);
2610 mCallbackThread->setDraining(false);
2611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612}
2613
2614void AudioFlinger::MixerThread::threadLoop_mix()
2615{
2616 // obtain the presentation timestamp of the next output buffer
2617 int64_t pts;
2618 status_t status = INVALID_OPERATION;
2619
2620 if (mNormalSink != 0) {
2621 status = mNormalSink->getNextWriteTimestamp(&pts);
2622 } else {
2623 status = mOutputSink->getNextWriteTimestamp(&pts);
2624 }
2625
2626 if (status != NO_ERROR) {
2627 pts = AudioBufferProvider::kInvalidPTS;
2628 }
2629
2630 // mix buffers...
2631 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002633 // increase sleep time progressively when application underrun condition clears.
2634 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2635 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2636 // such that we would underrun the audio HAL.
2637 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2638 sleepTimeShift--;
2639 }
2640 sleepTime = 0;
2641 standbyTime = systemTime() + standbyDelay;
2642 //TODO: delay standby when effects have a tail
2643}
2644
2645void AudioFlinger::MixerThread::threadLoop_sleepTime()
2646{
2647 // If no tracks are ready, sleep once for the duration of an output
2648 // buffer size, then write 0s to the output
2649 if (sleepTime == 0) {
2650 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2651 sleepTime = activeSleepTime >> sleepTimeShift;
2652 if (sleepTime < kMinThreadSleepTimeUs) {
2653 sleepTime = kMinThreadSleepTimeUs;
2654 }
2655 // reduce sleep time in case of consecutive application underruns to avoid
2656 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2657 // duration we would end up writing less data than needed by the audio HAL if
2658 // the condition persists.
2659 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2660 sleepTimeShift++;
2661 }
2662 } else {
2663 sleepTime = idleSleepTime;
2664 }
2665 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002666 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002667 sleepTime = 0;
2668 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2669 "anticipated start");
2670 }
2671 // TODO add standby time extension fct of effect tail
2672}
2673
2674// prepareTracks_l() must be called with ThreadBase::mLock held
2675AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2676 Vector< sp<Track> > *tracksToRemove)
2677{
2678
2679 mixer_state mixerStatus = MIXER_IDLE;
2680 // find out which tracks need to be processed
2681 size_t count = mActiveTracks.size();
2682 size_t mixedTracks = 0;
2683 size_t tracksWithEffect = 0;
2684 // counts only _active_ fast tracks
2685 size_t fastTracks = 0;
2686 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2687
2688 float masterVolume = mMasterVolume;
2689 bool masterMute = mMasterMute;
2690
2691 if (masterMute) {
2692 masterVolume = 0;
2693 }
2694 // Delegate master volume control to effect in output mix effect chain if needed
2695 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2696 if (chain != 0) {
2697 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2698 chain->setVolume_l(&v, &v);
2699 masterVolume = (float)((v + (1 << 23)) >> 24);
2700 chain.clear();
2701 }
2702
2703 // prepare a new state to push
2704 FastMixerStateQueue *sq = NULL;
2705 FastMixerState *state = NULL;
2706 bool didModify = false;
2707 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2708 if (mFastMixer != NULL) {
2709 sq = mFastMixer->sq();
2710 state = sq->begin();
2711 }
2712
2713 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002714 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002715 if (t == 0) {
2716 continue;
2717 }
2718
2719 // this const just means the local variable doesn't change
2720 Track* const track = t.get();
2721
2722 // process fast tracks
2723 if (track->isFastTrack()) {
2724
2725 // It's theoretically possible (though unlikely) for a fast track to be created
2726 // and then removed within the same normal mix cycle. This is not a problem, as
2727 // the track never becomes active so it's fast mixer slot is never touched.
2728 // The converse, of removing an (active) track and then creating a new track
2729 // at the identical fast mixer slot within the same normal mix cycle,
2730 // is impossible because the slot isn't marked available until the end of each cycle.
2731 int j = track->mFastIndex;
2732 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2733 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2734 FastTrack *fastTrack = &state->mFastTracks[j];
2735
2736 // Determine whether the track is currently in underrun condition,
2737 // and whether it had a recent underrun.
2738 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2739 FastTrackUnderruns underruns = ftDump->mUnderruns;
2740 uint32_t recentFull = (underruns.mBitFields.mFull -
2741 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2742 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2743 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2744 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2745 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2746 uint32_t recentUnderruns = recentPartial + recentEmpty;
2747 track->mObservedUnderruns = underruns;
2748 // don't count underruns that occur while stopping or pausing
2749 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002750 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2751 recentUnderruns > 0) {
2752 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2753 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002754 }
2755
2756 // This is similar to the state machine for normal tracks,
2757 // with a few modifications for fast tracks.
2758 bool isActive = true;
2759 switch (track->mState) {
2760 case TrackBase::STOPPING_1:
2761 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002763 track->mState = TrackBase::STOPPING_2;
2764 }
2765 break;
2766 case TrackBase::PAUSING:
2767 // ramp down is not yet implemented
2768 track->setPaused();
2769 break;
2770 case TrackBase::RESUMING:
2771 // ramp up is not yet implemented
2772 track->mState = TrackBase::ACTIVE;
2773 break;
2774 case TrackBase::ACTIVE:
2775 if (recentFull > 0 || recentPartial > 0) {
2776 // track has provided at least some frames recently: reset retry count
2777 track->mRetryCount = kMaxTrackRetries;
2778 }
2779 if (recentUnderruns == 0) {
2780 // no recent underruns: stay active
2781 break;
2782 }
2783 // there has recently been an underrun of some kind
2784 if (track->sharedBuffer() == 0) {
2785 // were any of the recent underruns "empty" (no frames available)?
2786 if (recentEmpty == 0) {
2787 // no, then ignore the partial underruns as they are allowed indefinitely
2788 break;
2789 }
2790 // there has recently been an "empty" underrun: decrement the retry counter
2791 if (--(track->mRetryCount) > 0) {
2792 break;
2793 }
2794 // indicate to client process that the track was disabled because of underrun;
2795 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002796 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002797 // remove from active list, but state remains ACTIVE [confusing but true]
2798 isActive = false;
2799 break;
2800 }
2801 // fall through
2802 case TrackBase::STOPPING_2:
2803 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002804 case TrackBase::STOPPED:
2805 case TrackBase::FLUSHED: // flush() while active
2806 // Check for presentation complete if track is inactive
2807 // We have consumed all the buffers of this track.
2808 // This would be incomplete if we auto-paused on underrun
2809 {
2810 size_t audioHALFrames =
2811 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2812 size_t framesWritten = mBytesWritten / mFrameSize;
2813 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2814 // track stays in active list until presentation is complete
2815 break;
2816 }
2817 }
2818 if (track->isStopping_2()) {
2819 track->mState = TrackBase::STOPPED;
2820 }
2821 if (track->isStopped()) {
2822 // Can't reset directly, as fast mixer is still polling this track
2823 // track->reset();
2824 // So instead mark this track as needing to be reset after push with ack
2825 resetMask |= 1 << i;
2826 }
2827 isActive = false;
2828 break;
2829 case TrackBase::IDLE:
2830 default:
2831 LOG_FATAL("unexpected track state %d", track->mState);
2832 }
2833
2834 if (isActive) {
2835 // was it previously inactive?
2836 if (!(state->mTrackMask & (1 << j))) {
2837 ExtendedAudioBufferProvider *eabp = track;
2838 VolumeProvider *vp = track;
2839 fastTrack->mBufferProvider = eabp;
2840 fastTrack->mVolumeProvider = vp;
2841 fastTrack->mSampleRate = track->mSampleRate;
2842 fastTrack->mChannelMask = track->mChannelMask;
2843 fastTrack->mGeneration++;
2844 state->mTrackMask |= 1 << j;
2845 didModify = true;
2846 // no acknowledgement required for newly active tracks
2847 }
2848 // cache the combined master volume and stream type volume for fast mixer; this
2849 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002850 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002851 ++fastTracks;
2852 } else {
2853 // was it previously active?
2854 if (state->mTrackMask & (1 << j)) {
2855 fastTrack->mBufferProvider = NULL;
2856 fastTrack->mGeneration++;
2857 state->mTrackMask &= ~(1 << j);
2858 didModify = true;
2859 // If any fast tracks were removed, we must wait for acknowledgement
2860 // because we're about to decrement the last sp<> on those tracks.
2861 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2862 } else {
2863 LOG_FATAL("fast track %d should have been active", j);
2864 }
2865 tracksToRemove->add(track);
2866 // Avoids a misleading display in dumpsys
2867 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2868 }
2869 continue;
2870 }
2871
2872 { // local variable scope to avoid goto warning
2873
2874 audio_track_cblk_t* cblk = track->cblk();
2875
2876 // The first time a track is added we wait
2877 // for all its buffers to be filled before processing it
2878 int name = track->name();
2879 // make sure that we have enough frames to mix one full buffer.
2880 // enforce this condition only once to enable draining the buffer in case the client
2881 // app does not call stop() and relies on underrun to stop:
2882 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2883 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002884 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002885 uint32_t sr = track->sampleRate();
2886 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002887 desiredFrames = mNormalFrameCount;
2888 } else {
2889 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002890 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002891 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002892 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002893 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2894 // the minimum track buffer size is normally twice the number of frames necessary
2895 // to fill one buffer and the resampler should not leave more than one buffer worth
2896 // of unreleased frames after each pass, but just in case...
2897 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2898 }
Eric Laurent81784c32012-11-19 14:55:58 -08002899 uint32_t minFrames = 1;
2900 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2901 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002902 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002903 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002904 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2905 size_t framesReady;
2906 if (track->sharedBuffer() == 0) {
2907 framesReady = track->framesReady();
2908 } else if (track->isStopped()) {
2909 framesReady = 0;
2910 } else {
2911 framesReady = 1;
2912 }
2913 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002914 !track->isPaused() && !track->isTerminated())
2915 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002916 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002917
2918 mixedTracks++;
2919
2920 // track->mainBuffer() != mMixBuffer means there is an effect chain
2921 // connected to the track
2922 chain.clear();
2923 if (track->mainBuffer() != mMixBuffer) {
2924 chain = getEffectChain_l(track->sessionId());
2925 // Delegate volume control to effect in track effect chain if needed
2926 if (chain != 0) {
2927 tracksWithEffect++;
2928 } else {
2929 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2930 "session %d",
2931 name, track->sessionId());
2932 }
2933 }
2934
2935
2936 int param = AudioMixer::VOLUME;
2937 if (track->mFillingUpStatus == Track::FS_FILLED) {
2938 // no ramp for the first volume setting
2939 track->mFillingUpStatus = Track::FS_ACTIVE;
2940 if (track->mState == TrackBase::RESUMING) {
2941 track->mState = TrackBase::ACTIVE;
2942 param = AudioMixer::RAMP_VOLUME;
2943 }
2944 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002945 // FIXME should not make a decision based on mServer
2946 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002947 // If the track is stopped before the first frame was mixed,
2948 // do not apply ramp
2949 param = AudioMixer::RAMP_VOLUME;
2950 }
2951
2952 // compute volume for this track
2953 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002954 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002955 vl = vr = va = 0;
2956 if (track->isPausing()) {
2957 track->setPaused();
2958 }
2959 } else {
2960
2961 // read original volumes with volume control
2962 float typeVolume = mStreamTypes[track->streamType()].volume;
2963 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002964 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002965 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002966 vl = vlr & 0xFFFF;
2967 vr = vlr >> 16;
2968 // track volumes come from shared memory, so can't be trusted and must be clamped
2969 if (vl > MAX_GAIN_INT) {
2970 ALOGV("Track left volume out of range: %04X", vl);
2971 vl = MAX_GAIN_INT;
2972 }
2973 if (vr > MAX_GAIN_INT) {
2974 ALOGV("Track right volume out of range: %04X", vr);
2975 vr = MAX_GAIN_INT;
2976 }
2977 // now apply the master volume and stream type volume
2978 vl = (uint32_t)(v * vl) << 12;
2979 vr = (uint32_t)(v * vr) << 12;
2980 // assuming master volume and stream type volume each go up to 1.0,
2981 // vl and vr are now in 8.24 format
2982
Glenn Kastene3aa6592012-12-04 12:22:46 -08002983 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08002984 // send level comes from shared memory and so may be corrupt
2985 if (sendLevel > MAX_GAIN_INT) {
2986 ALOGV("Track send level out of range: %04X", sendLevel);
2987 sendLevel = MAX_GAIN_INT;
2988 }
2989 va = (uint32_t)(v * sendLevel);
2990 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002991
Eric Laurent81784c32012-11-19 14:55:58 -08002992 // Delegate volume control to effect in track effect chain if needed
2993 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2994 // Do not ramp volume if volume is controlled by effect
2995 param = AudioMixer::VOLUME;
2996 track->mHasVolumeController = true;
2997 } else {
2998 // force no volume ramp when volume controller was just disabled or removed
2999 // from effect chain to avoid volume spike
3000 if (track->mHasVolumeController) {
3001 param = AudioMixer::VOLUME;
3002 }
3003 track->mHasVolumeController = false;
3004 }
3005
3006 // Convert volumes from 8.24 to 4.12 format
3007 // This additional clamping is needed in case chain->setVolume_l() overshot
3008 vl = (vl + (1 << 11)) >> 12;
3009 if (vl > MAX_GAIN_INT) {
3010 vl = MAX_GAIN_INT;
3011 }
3012 vr = (vr + (1 << 11)) >> 12;
3013 if (vr > MAX_GAIN_INT) {
3014 vr = MAX_GAIN_INT;
3015 }
3016
3017 if (va > MAX_GAIN_INT) {
3018 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3019 }
3020
3021 // XXX: these things DON'T need to be done each time
3022 mAudioMixer->setBufferProvider(name, track);
3023 mAudioMixer->enable(name);
3024
3025 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3026 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3027 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3028 mAudioMixer->setParameter(
3029 name,
3030 AudioMixer::TRACK,
3031 AudioMixer::FORMAT, (void *)track->format());
3032 mAudioMixer->setParameter(
3033 name,
3034 AudioMixer::TRACK,
3035 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003036 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3037 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003038 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003039 if (reqSampleRate == 0) {
3040 reqSampleRate = mSampleRate;
3041 } else if (reqSampleRate > maxSampleRate) {
3042 reqSampleRate = maxSampleRate;
3043 }
Eric Laurent81784c32012-11-19 14:55:58 -08003044 mAudioMixer->setParameter(
3045 name,
3046 AudioMixer::RESAMPLE,
3047 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003048 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003049 mAudioMixer->setParameter(
3050 name,
3051 AudioMixer::TRACK,
3052 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3053 mAudioMixer->setParameter(
3054 name,
3055 AudioMixer::TRACK,
3056 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3057
3058 // reset retry count
3059 track->mRetryCount = kMaxTrackRetries;
3060
3061 // If one track is ready, set the mixer ready if:
3062 // - the mixer was not ready during previous round OR
3063 // - no other track is not ready
3064 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3065 mixerStatus != MIXER_TRACKS_ENABLED) {
3066 mixerStatus = MIXER_TRACKS_READY;
3067 }
3068 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003069 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003070 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003071 }
Eric Laurent81784c32012-11-19 14:55:58 -08003072 // clear effect chain input buffer if an active track underruns to avoid sending
3073 // previous audio buffer again to effects
3074 chain = getEffectChain_l(track->sessionId());
3075 if (chain != 0) {
3076 chain->clearInputBuffer();
3077 }
3078
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003079 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003080 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3081 track->isStopped() || track->isPaused()) {
3082 // We have consumed all the buffers of this track.
3083 // Remove it from the list of active tracks.
3084 // TODO: use actual buffer filling status instead of latency when available from
3085 // audio HAL
3086 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3087 size_t framesWritten = mBytesWritten / mFrameSize;
3088 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3089 if (track->isStopped()) {
3090 track->reset();
3091 }
3092 tracksToRemove->add(track);
3093 }
3094 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003095 // No buffers for this track. Give it a few chances to
3096 // fill a buffer, then remove it from active list.
3097 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003098 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003099 tracksToRemove->add(track);
3100 // indicate to client process that the track was disabled because of underrun;
3101 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003102 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003103 // If one track is not ready, mark the mixer also not ready if:
3104 // - the mixer was ready during previous round OR
3105 // - no other track is ready
3106 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3107 mixerStatus != MIXER_TRACKS_READY) {
3108 mixerStatus = MIXER_TRACKS_ENABLED;
3109 }
3110 }
3111 mAudioMixer->disable(name);
3112 }
3113
3114 } // local variable scope to avoid goto warning
3115track_is_ready: ;
3116
3117 }
3118
3119 // Push the new FastMixer state if necessary
3120 bool pauseAudioWatchdog = false;
3121 if (didModify) {
3122 state->mFastTracksGen++;
3123 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3124 if (kUseFastMixer == FastMixer_Dynamic &&
3125 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3126 state->mCommand = FastMixerState::COLD_IDLE;
3127 state->mColdFutexAddr = &mFastMixerFutex;
3128 state->mColdGen++;
3129 mFastMixerFutex = 0;
3130 if (kUseFastMixer == FastMixer_Dynamic) {
3131 mNormalSink = mOutputSink;
3132 }
3133 // If we go into cold idle, need to wait for acknowledgement
3134 // so that fast mixer stops doing I/O.
3135 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3136 pauseAudioWatchdog = true;
3137 }
Eric Laurent81784c32012-11-19 14:55:58 -08003138 }
3139 if (sq != NULL) {
3140 sq->end(didModify);
3141 sq->push(block);
3142 }
3143#ifdef AUDIO_WATCHDOG
3144 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3145 mAudioWatchdog->pause();
3146 }
3147#endif
3148
3149 // Now perform the deferred reset on fast tracks that have stopped
3150 while (resetMask != 0) {
3151 size_t i = __builtin_ctz(resetMask);
3152 ALOG_ASSERT(i < count);
3153 resetMask &= ~(1 << i);
3154 sp<Track> t = mActiveTracks[i].promote();
3155 if (t == 0) {
3156 continue;
3157 }
3158 Track* track = t.get();
3159 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3160 track->reset();
3161 }
3162
3163 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003165
3166 // mix buffer must be cleared if all tracks are connected to an
3167 // effect chain as in this case the mixer will not write to
3168 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3170 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003171 // FIXME as a performance optimization, should remember previous zero status
3172 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3173 }
3174
3175 // if any fast tracks, then status is ready
3176 mMixerStatusIgnoringFastTracks = mixerStatus;
3177 if (fastTracks > 0) {
3178 mixerStatus = MIXER_TRACKS_READY;
3179 }
3180 return mixerStatus;
3181}
3182
3183// getTrackName_l() must be called with ThreadBase::mLock held
3184int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3185{
3186 return mAudioMixer->getTrackName(channelMask, sessionId);
3187}
3188
3189// deleteTrackName_l() must be called with ThreadBase::mLock held
3190void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3191{
3192 ALOGV("remove track (%d) and delete from mixer", name);
3193 mAudioMixer->deleteTrackName(name);
3194}
3195
3196// checkForNewParameters_l() must be called with ThreadBase::mLock held
3197bool AudioFlinger::MixerThread::checkForNewParameters_l()
3198{
3199 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3200 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3201 bool reconfig = false;
3202
3203 while (!mNewParameters.isEmpty()) {
3204
3205 if (mFastMixer != NULL) {
3206 FastMixerStateQueue *sq = mFastMixer->sq();
3207 FastMixerState *state = sq->begin();
3208 if (!(state->mCommand & FastMixerState::IDLE)) {
3209 previousCommand = state->mCommand;
3210 state->mCommand = FastMixerState::HOT_IDLE;
3211 sq->end();
3212 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3213 } else {
3214 sq->end(false /*didModify*/);
3215 }
3216 }
3217
3218 status_t status = NO_ERROR;
3219 String8 keyValuePair = mNewParameters[0];
3220 AudioParameter param = AudioParameter(keyValuePair);
3221 int value;
3222
3223 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3224 reconfig = true;
3225 }
3226 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3227 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3228 status = BAD_VALUE;
3229 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003230 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003231 reconfig = true;
3232 }
3233 }
3234 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003235 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003236 status = BAD_VALUE;
3237 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003238 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003239 reconfig = true;
3240 }
3241 }
3242 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3243 // do not accept frame count changes if tracks are open as the track buffer
3244 // size depends on frame count and correct behavior would not be guaranteed
3245 // if frame count is changed after track creation
3246 if (!mTracks.isEmpty()) {
3247 status = INVALID_OPERATION;
3248 } else {
3249 reconfig = true;
3250 }
3251 }
3252 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3253#ifdef ADD_BATTERY_DATA
3254 // when changing the audio output device, call addBatteryData to notify
3255 // the change
3256 if (mOutDevice != value) {
3257 uint32_t params = 0;
3258 // check whether speaker is on
3259 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3260 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3261 }
3262
3263 audio_devices_t deviceWithoutSpeaker
3264 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3265 // check if any other device (except speaker) is on
3266 if (value & deviceWithoutSpeaker ) {
3267 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3268 }
3269
3270 if (params != 0) {
3271 addBatteryData(params);
3272 }
3273 }
3274#endif
3275
3276 // forward device change to effects that have requested to be
3277 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003278 if (value != AUDIO_DEVICE_NONE) {
3279 mOutDevice = value;
3280 for (size_t i = 0; i < mEffectChains.size(); i++) {
3281 mEffectChains[i]->setDevice_l(mOutDevice);
3282 }
Eric Laurent81784c32012-11-19 14:55:58 -08003283 }
3284 }
3285
3286 if (status == NO_ERROR) {
3287 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3288 keyValuePair.string());
3289 if (!mStandby && status == INVALID_OPERATION) {
3290 mOutput->stream->common.standby(&mOutput->stream->common);
3291 mStandby = true;
3292 mBytesWritten = 0;
3293 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3294 keyValuePair.string());
3295 }
3296 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003297 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003298 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003299 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3300 for (size_t i = 0; i < mTracks.size() ; i++) {
3301 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3302 if (name < 0) {
3303 break;
3304 }
3305 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3308 }
3309 }
3310
3311 mNewParameters.removeAt(0);
3312
3313 mParamStatus = status;
3314 mParamCond.signal();
3315 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3316 // already timed out waiting for the status and will never signal the condition.
3317 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3318 }
3319
3320 if (!(previousCommand & FastMixerState::IDLE)) {
3321 ALOG_ASSERT(mFastMixer != NULL);
3322 FastMixerStateQueue *sq = mFastMixer->sq();
3323 FastMixerState *state = sq->begin();
3324 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3325 state->mCommand = previousCommand;
3326 sq->end();
3327 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3328 }
3329
3330 return reconfig;
3331}
3332
3333
3334void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3335{
3336 const size_t SIZE = 256;
3337 char buffer[SIZE];
3338 String8 result;
3339
3340 PlaybackThread::dumpInternals(fd, args);
3341
3342 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3343 result.append(buffer);
3344 write(fd, result.string(), result.size());
3345
3346 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003347 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003348 copy.dump(fd);
3349
3350#ifdef STATE_QUEUE_DUMP
3351 // Similar for state queue
3352 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3353 observerCopy.dump(fd);
3354 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3355 mutatorCopy.dump(fd);
3356#endif
3357
Glenn Kasten46909e72013-02-26 09:20:22 -08003358#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003359 // Write the tee output to a .wav file
3360 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003361#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003362
3363#ifdef AUDIO_WATCHDOG
3364 if (mAudioWatchdog != 0) {
3365 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3366 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3367 wdCopy.dump(fd);
3368 }
3369#endif
3370}
3371
3372uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3373{
3374 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3375}
3376
3377uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3378{
3379 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3380}
3381
3382void AudioFlinger::MixerThread::cacheParameters_l()
3383{
3384 PlaybackThread::cacheParameters_l();
3385
3386 // FIXME: Relaxed timing because of a certain device that can't meet latency
3387 // Should be reduced to 2x after the vendor fixes the driver issue
3388 // increase threshold again due to low power audio mode. The way this warning
3389 // threshold is calculated and its usefulness should be reconsidered anyway.
3390 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3391}
3392
3393// ----------------------------------------------------------------------------
3394
3395AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3396 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3397 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3398 // mLeftVolFloat, mRightVolFloat
3399{
3400}
3401
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3403 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3404 ThreadBase::type_t type)
3405 : PlaybackThread(audioFlinger, output, id, device, type)
3406 // mLeftVolFloat, mRightVolFloat
3407{
3408}
3409
Eric Laurent81784c32012-11-19 14:55:58 -08003410AudioFlinger::DirectOutputThread::~DirectOutputThread()
3411{
3412}
3413
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3415{
3416 audio_track_cblk_t* cblk = track->cblk();
3417 float left, right;
3418
3419 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3420 left = right = 0;
3421 } else {
3422 float typeVolume = mStreamTypes[track->streamType()].volume;
3423 float v = mMasterVolume * typeVolume;
3424 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3425 uint32_t vlr = proxy->getVolumeLR();
3426 float v_clamped = v * (vlr & 0xFFFF);
3427 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3428 left = v_clamped/MAX_GAIN;
3429 v_clamped = v * (vlr >> 16);
3430 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3431 right = v_clamped/MAX_GAIN;
3432 }
3433
3434 if (lastTrack) {
3435 if (left != mLeftVolFloat || right != mRightVolFloat) {
3436 mLeftVolFloat = left;
3437 mRightVolFloat = right;
3438
3439 // Convert volumes from float to 8.24
3440 uint32_t vl = (uint32_t)(left * (1 << 24));
3441 uint32_t vr = (uint32_t)(right * (1 << 24));
3442
3443 // Delegate volume control to effect in track effect chain if needed
3444 // only one effect chain can be present on DirectOutputThread, so if
3445 // there is one, the track is connected to it
3446 if (!mEffectChains.isEmpty()) {
3447 mEffectChains[0]->setVolume_l(&vl, &vr);
3448 left = (float)vl / (1 << 24);
3449 right = (float)vr / (1 << 24);
3450 }
3451 if (mOutput->stream->set_volume) {
3452 mOutput->stream->set_volume(mOutput->stream, left, right);
3453 }
3454 }
3455 }
3456}
3457
3458
Eric Laurent81784c32012-11-19 14:55:58 -08003459AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3460 Vector< sp<Track> > *tracksToRemove
3461)
3462{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003463 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003464 mixer_state mixerStatus = MIXER_IDLE;
3465
3466 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003467 for (size_t i = 0; i < count; i++) {
3468 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003469 // The track died recently
3470 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003471 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473
3474 Track* const track = t.get();
3475 audio_track_cblk_t* cblk = track->cblk();
3476
3477 // The first time a track is added we wait
3478 // for all its buffers to be filled before processing it
3479 uint32_t minFrames;
3480 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3481 minFrames = mNormalFrameCount;
3482 } else {
3483 minFrames = 1;
3484 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003485 // Only consider last track started for volume and mixer state control.
3486 // This is the last entry in mActiveTracks unless a track underruns.
3487 // As we only care about the transition phase between two tracks on a
3488 // direct output, it is not a problem to ignore the underrun case.
3489 bool last = (i == (count - 1));
3490
Eric Laurent81784c32012-11-19 14:55:58 -08003491 if ((track->framesReady() >= minFrames) && track->isReady() &&
3492 !track->isPaused() && !track->isTerminated())
3493 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003494 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003495
3496 if (track->mFillingUpStatus == Track::FS_FILLED) {
3497 track->mFillingUpStatus = Track::FS_ACTIVE;
3498 mLeftVolFloat = mRightVolFloat = 0;
3499 if (track->mState == TrackBase::RESUMING) {
3500 track->mState = TrackBase::ACTIVE;
3501 }
3502 }
3503
3504 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003505 processVolume_l(track, last);
3506 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003507 // reset retry count
3508 track->mRetryCount = kMaxTrackRetriesDirect;
3509 mActiveTrack = t;
3510 mixerStatus = MIXER_TRACKS_READY;
3511 }
Eric Laurent81784c32012-11-19 14:55:58 -08003512 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003513 // clear effect chain input buffer if the last active track started underruns
3514 // to avoid sending previous audio buffer again to effects
3515 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003516 mEffectChains[0]->clearInputBuffer();
3517 }
3518
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003519 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003520 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3521 track->isStopped() || track->isPaused()) {
3522 // We have consumed all the buffers of this track.
3523 // Remove it from the list of active tracks.
3524 // TODO: implement behavior for compressed audio
3525 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3526 size_t framesWritten = mBytesWritten / mFrameSize;
3527 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3528 if (track->isStopped()) {
3529 track->reset();
3530 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003531 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003532 }
3533 } else {
3534 // No buffers for this track. Give it a few chances to
3535 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003536 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003537 if (--(track->mRetryCount) <= 0) {
3538 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003539 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003540 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003541 mixerStatus = MIXER_TRACKS_ENABLED;
3542 }
3543 }
3544 }
3545 }
3546
Eric Laurent81784c32012-11-19 14:55:58 -08003547 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003548 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003549
3550 return mixerStatus;
3551}
3552
3553void AudioFlinger::DirectOutputThread::threadLoop_mix()
3554{
Eric Laurent81784c32012-11-19 14:55:58 -08003555 size_t frameCount = mFrameCount;
3556 int8_t *curBuf = (int8_t *)mMixBuffer;
3557 // output audio to hardware
3558 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003559 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003560 buffer.frameCount = frameCount;
3561 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003562 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003563 memset(curBuf, 0, frameCount * mFrameSize);
3564 break;
3565 }
3566 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3567 frameCount -= buffer.frameCount;
3568 curBuf += buffer.frameCount * mFrameSize;
3569 mActiveTrack->releaseBuffer(&buffer);
3570 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003572 sleepTime = 0;
3573 standbyTime = systemTime() + standbyDelay;
3574 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003575}
3576
3577void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3578{
3579 if (sleepTime == 0) {
3580 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3581 sleepTime = activeSleepTime;
3582 } else {
3583 sleepTime = idleSleepTime;
3584 }
3585 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3586 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3587 sleepTime = 0;
3588 }
3589}
3590
3591// getTrackName_l() must be called with ThreadBase::mLock held
3592int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3593 int sessionId)
3594{
3595 return 0;
3596}
3597
3598// deleteTrackName_l() must be called with ThreadBase::mLock held
3599void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3600{
3601}
3602
3603// checkForNewParameters_l() must be called with ThreadBase::mLock held
3604bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3605{
3606 bool reconfig = false;
3607
3608 while (!mNewParameters.isEmpty()) {
3609 status_t status = NO_ERROR;
3610 String8 keyValuePair = mNewParameters[0];
3611 AudioParameter param = AudioParameter(keyValuePair);
3612 int value;
3613
3614 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3615 // do not accept frame count changes if tracks are open as the track buffer
3616 // size depends on frame count and correct behavior would not be garantied
3617 // if frame count is changed after track creation
3618 if (!mTracks.isEmpty()) {
3619 status = INVALID_OPERATION;
3620 } else {
3621 reconfig = true;
3622 }
3623 }
3624 if (status == NO_ERROR) {
3625 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3626 keyValuePair.string());
3627 if (!mStandby && status == INVALID_OPERATION) {
3628 mOutput->stream->common.standby(&mOutput->stream->common);
3629 mStandby = true;
3630 mBytesWritten = 0;
3631 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3632 keyValuePair.string());
3633 }
3634 if (status == NO_ERROR && reconfig) {
3635 readOutputParameters();
3636 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3637 }
3638 }
3639
3640 mNewParameters.removeAt(0);
3641
3642 mParamStatus = status;
3643 mParamCond.signal();
3644 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3645 // already timed out waiting for the status and will never signal the condition.
3646 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3647 }
3648 return reconfig;
3649}
3650
3651uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3652{
3653 uint32_t time;
3654 if (audio_is_linear_pcm(mFormat)) {
3655 time = PlaybackThread::activeSleepTimeUs();
3656 } else {
3657 time = 10000;
3658 }
3659 return time;
3660}
3661
3662uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3663{
3664 uint32_t time;
3665 if (audio_is_linear_pcm(mFormat)) {
3666 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3667 } else {
3668 time = 10000;
3669 }
3670 return time;
3671}
3672
3673uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3674{
3675 uint32_t time;
3676 if (audio_is_linear_pcm(mFormat)) {
3677 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3678 } else {
3679 time = 10000;
3680 }
3681 return time;
3682}
3683
3684void AudioFlinger::DirectOutputThread::cacheParameters_l()
3685{
3686 PlaybackThread::cacheParameters_l();
3687
3688 // use shorter standby delay as on normal output to release
3689 // hardware resources as soon as possible
3690 standbyDelay = microseconds(activeSleepTime*2);
3691}
3692
3693// ----------------------------------------------------------------------------
3694
Eric Laurentbfb1b832013-01-07 09:53:42 -08003695AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3696 const sp<AudioFlinger::OffloadThread>& offloadThread)
3697 : Thread(false /*canCallJava*/),
3698 mOffloadThread(offloadThread),
3699 mWriteBlocked(false),
3700 mDraining(false)
3701{
3702}
3703
3704AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3705{
3706}
3707
3708void AudioFlinger::AsyncCallbackThread::onFirstRef()
3709{
3710 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3711}
3712
3713bool AudioFlinger::AsyncCallbackThread::threadLoop()
3714{
3715 while (!exitPending()) {
3716 bool writeBlocked;
3717 bool draining;
3718
3719 {
3720 Mutex::Autolock _l(mLock);
3721 mWaitWorkCV.wait(mLock);
3722 if (exitPending()) {
3723 break;
3724 }
3725 writeBlocked = mWriteBlocked;
3726 draining = mDraining;
3727 ALOGV("AsyncCallbackThread mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3728 }
3729 {
3730 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3731 if (offloadThread != 0) {
3732 if (writeBlocked == false) {
3733 offloadThread->setWriteBlocked(false);
3734 }
3735 if (draining == false) {
3736 offloadThread->setDraining(false);
3737 }
3738 }
3739 }
3740 }
3741 return false;
3742}
3743
3744void AudioFlinger::AsyncCallbackThread::exit()
3745{
3746 ALOGV("AsyncCallbackThread::exit");
3747 Mutex::Autolock _l(mLock);
3748 requestExit();
3749 mWaitWorkCV.broadcast();
3750}
3751
3752void AudioFlinger::AsyncCallbackThread::setWriteBlocked(bool value)
3753{
3754 Mutex::Autolock _l(mLock);
3755 mWriteBlocked = value;
3756 if (!value) {
3757 mWaitWorkCV.signal();
3758 }
3759}
3760
3761void AudioFlinger::AsyncCallbackThread::setDraining(bool value)
3762{
3763 Mutex::Autolock _l(mLock);
3764 mDraining = value;
3765 if (!value) {
3766 mWaitWorkCV.signal();
3767 }
3768}
3769
3770
3771// ----------------------------------------------------------------------------
3772AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3773 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3774 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3775 mHwPaused(false),
3776 mPausedBytesRemaining(0)
3777{
3778 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3779}
3780
3781AudioFlinger::OffloadThread::~OffloadThread()
3782{
3783 mPreviousTrack.clear();
3784}
3785
3786void AudioFlinger::OffloadThread::threadLoop_exit()
3787{
3788 if (mFlushPending || mHwPaused) {
3789 // If a flush is pending or track was paused, just discard buffered data
3790 flushHw_l();
3791 } else {
3792 mMixerStatus = MIXER_DRAIN_ALL;
3793 threadLoop_drain();
3794 }
3795 mCallbackThread->exit();
3796 PlaybackThread::threadLoop_exit();
3797}
3798
3799AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3800 Vector< sp<Track> > *tracksToRemove
3801)
3802{
3803 ALOGV("OffloadThread::prepareTracks_l");
3804 size_t count = mActiveTracks.size();
3805
3806 mixer_state mixerStatus = MIXER_IDLE;
3807 if (mFlushPending) {
3808 flushHw_l();
3809 mFlushPending = false;
3810 }
3811 // find out which tracks need to be processed
3812 for (size_t i = 0; i < count; i++) {
3813 sp<Track> t = mActiveTracks[i].promote();
3814 // The track died recently
3815 if (t == 0) {
3816 continue;
3817 }
3818 Track* const track = t.get();
3819 audio_track_cblk_t* cblk = track->cblk();
3820 if (mPreviousTrack != NULL) {
3821 if (t != mPreviousTrack) {
3822 // Flush any data still being written from last track
3823 mBytesRemaining = 0;
3824 if (mPausedBytesRemaining) {
3825 // Last track was paused so we also need to flush saved
3826 // mixbuffer state and invalidate track so that it will
3827 // re-submit that unwritten data when it is next resumed
3828 mPausedBytesRemaining = 0;
3829 // Invalidate is a bit drastic - would be more efficient
3830 // to have a flag to tell client that some of the
3831 // previously written data was lost
3832 mPreviousTrack->invalidate();
3833 }
3834 }
3835 }
3836 mPreviousTrack = t;
3837 bool last = (i == (count - 1));
3838 if (track->isPausing()) {
3839 track->setPaused();
3840 if (last) {
3841 if (!mHwPaused) {
3842 mOutput->stream->pause(mOutput->stream);
3843 mHwPaused = true;
3844 }
3845 // If we were part way through writing the mixbuffer to
3846 // the HAL we must save this until we resume
3847 // BUG - this will be wrong if a different track is made active,
3848 // in that case we want to discard the pending data in the
3849 // mixbuffer and tell the client to present it again when the
3850 // track is resumed
3851 mPausedWriteLength = mCurrentWriteLength;
3852 mPausedBytesRemaining = mBytesRemaining;
3853 mBytesRemaining = 0; // stop writing
3854 }
3855 tracksToRemove->add(track);
3856 } else if (track->framesReady() && track->isReady() &&
3857 !track->isPaused() && !track->isTerminated()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003858 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 if (track->mFillingUpStatus == Track::FS_FILLED) {
3860 track->mFillingUpStatus = Track::FS_ACTIVE;
3861 mLeftVolFloat = mRightVolFloat = 0;
3862 if (track->mState == TrackBase::RESUMING) {
Glenn Kastenfa319e62013-07-29 17:17:38 -07003863 if (mPausedBytesRemaining) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 // Need to continue write that was interrupted
3865 mCurrentWriteLength = mPausedWriteLength;
3866 mBytesRemaining = mPausedBytesRemaining;
3867 mPausedBytesRemaining = 0;
3868 }
3869 track->mState = TrackBase::ACTIVE;
3870 }
3871 }
3872
3873 if (last) {
3874 if (mHwPaused) {
3875 mOutput->stream->resume(mOutput->stream);
3876 mHwPaused = false;
3877 // threadLoop_mix() will handle the case that we need to
3878 // resume an interrupted write
3879 }
3880 // reset retry count
3881 track->mRetryCount = kMaxTrackRetriesOffload;
3882 mActiveTrack = t;
3883 mixerStatus = MIXER_TRACKS_READY;
3884 }
3885 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003886 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003887 if (track->isStopping_1()) {
3888 // Hardware buffer can hold a large amount of audio so we must
3889 // wait for all current track's data to drain before we say
3890 // that the track is stopped.
3891 if (mBytesRemaining == 0) {
3892 // Only start draining when all data in mixbuffer
3893 // has been written
3894 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3895 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3896 sleepTime = 0;
3897 standbyTime = systemTime() + standbyDelay;
3898 if (last) {
3899 mixerStatus = MIXER_DRAIN_TRACK;
3900 if (mHwPaused) {
3901 // It is possible to move from PAUSED to STOPPING_1 without
3902 // a resume so we must ensure hardware is running
3903 mOutput->stream->resume(mOutput->stream);
3904 mHwPaused = false;
3905 }
3906 }
3907 }
3908 } else if (track->isStopping_2()) {
3909 // Drain has completed, signal presentation complete
3910 if (!mDraining || !last) {
3911 track->mState = TrackBase::STOPPED;
3912 size_t audioHALFrames =
3913 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3914 size_t framesWritten =
3915 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3916 track->presentationComplete(framesWritten, audioHALFrames);
3917 track->reset();
3918 tracksToRemove->add(track);
3919 }
3920 } else {
3921 // No buffers for this track. Give it a few chances to
3922 // fill a buffer, then remove it from active list.
3923 if (--(track->mRetryCount) <= 0) {
3924 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3925 track->name());
3926 tracksToRemove->add(track);
3927 } else if (last){
3928 mixerStatus = MIXER_TRACKS_ENABLED;
3929 }
3930 }
3931 }
3932 // compute volume for this track
3933 processVolume_l(track, last);
3934 }
3935 // remove all the tracks that need to be...
3936 removeTracks_l(*tracksToRemove);
3937
3938 return mixerStatus;
3939}
3940
3941void AudioFlinger::OffloadThread::flushOutput_l()
3942{
3943 mFlushPending = true;
3944}
3945
3946// must be called with thread mutex locked
3947bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
3948{
3949 ALOGV("waitingAsyncCallback_l mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3950 if (mUseAsyncWrite && (mWriteBlocked || mDraining)) {
3951 return true;
3952 }
3953 return false;
3954}
3955
3956// must be called with thread mutex locked
3957bool AudioFlinger::OffloadThread::shouldStandby_l()
3958{
3959 bool TrackPaused = false;
3960
3961 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
3962 // after a timeout and we will enter standby then.
3963 if (mTracks.size() > 0) {
3964 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
3965 }
3966
3967 return !mStandby && !TrackPaused;
3968}
3969
3970
3971bool AudioFlinger::OffloadThread::waitingAsyncCallback()
3972{
3973 Mutex::Autolock _l(mLock);
3974 return waitingAsyncCallback_l();
3975}
3976
3977void AudioFlinger::OffloadThread::flushHw_l()
3978{
3979 mOutput->stream->flush(mOutput->stream);
3980 // Flush anything still waiting in the mixbuffer
3981 mCurrentWriteLength = 0;
3982 mBytesRemaining = 0;
3983 mPausedWriteLength = 0;
3984 mPausedBytesRemaining = 0;
3985 if (mUseAsyncWrite) {
3986 mWriteBlocked = false;
3987 mDraining = false;
3988 ALOG_ASSERT(mCallbackThread != 0);
3989 mCallbackThread->setWriteBlocked(false);
3990 mCallbackThread->setDraining(false);
3991 }
3992}
3993
3994// ----------------------------------------------------------------------------
3995
Eric Laurent81784c32012-11-19 14:55:58 -08003996AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3997 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3998 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3999 DUPLICATING),
4000 mWaitTimeMs(UINT_MAX)
4001{
4002 addOutputTrack(mainThread);
4003}
4004
4005AudioFlinger::DuplicatingThread::~DuplicatingThread()
4006{
4007 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4008 mOutputTracks[i]->destroy();
4009 }
4010}
4011
4012void AudioFlinger::DuplicatingThread::threadLoop_mix()
4013{
4014 // mix buffers...
4015 if (outputsReady(outputTracks)) {
4016 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4017 } else {
4018 memset(mMixBuffer, 0, mixBufferSize);
4019 }
4020 sleepTime = 0;
4021 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004022 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004023 standbyTime = systemTime() + standbyDelay;
4024}
4025
4026void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4027{
4028 if (sleepTime == 0) {
4029 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4030 sleepTime = activeSleepTime;
4031 } else {
4032 sleepTime = idleSleepTime;
4033 }
4034 } else if (mBytesWritten != 0) {
4035 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4036 writeFrames = mNormalFrameCount;
4037 memset(mMixBuffer, 0, mixBufferSize);
4038 } else {
4039 // flush remaining overflow buffers in output tracks
4040 writeFrames = 0;
4041 }
4042 sleepTime = 0;
4043 }
4044}
4045
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004047{
4048 for (size_t i = 0; i < outputTracks.size(); i++) {
4049 outputTracks[i]->write(mMixBuffer, writeFrames);
4050 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004052}
4053
4054void AudioFlinger::DuplicatingThread::threadLoop_standby()
4055{
4056 // DuplicatingThread implements standby by stopping all tracks
4057 for (size_t i = 0; i < outputTracks.size(); i++) {
4058 outputTracks[i]->stop();
4059 }
4060}
4061
4062void AudioFlinger::DuplicatingThread::saveOutputTracks()
4063{
4064 outputTracks = mOutputTracks;
4065}
4066
4067void AudioFlinger::DuplicatingThread::clearOutputTracks()
4068{
4069 outputTracks.clear();
4070}
4071
4072void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4073{
4074 Mutex::Autolock _l(mLock);
4075 // FIXME explain this formula
4076 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4077 OutputTrack *outputTrack = new OutputTrack(thread,
4078 this,
4079 mSampleRate,
4080 mFormat,
4081 mChannelMask,
4082 frameCount);
4083 if (outputTrack->cblk() != NULL) {
4084 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4085 mOutputTracks.add(outputTrack);
4086 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4087 updateWaitTime_l();
4088 }
4089}
4090
4091void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4092{
4093 Mutex::Autolock _l(mLock);
4094 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4095 if (mOutputTracks[i]->thread() == thread) {
4096 mOutputTracks[i]->destroy();
4097 mOutputTracks.removeAt(i);
4098 updateWaitTime_l();
4099 return;
4100 }
4101 }
4102 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4103}
4104
4105// caller must hold mLock
4106void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4107{
4108 mWaitTimeMs = UINT_MAX;
4109 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4110 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4111 if (strong != 0) {
4112 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4113 if (waitTimeMs < mWaitTimeMs) {
4114 mWaitTimeMs = waitTimeMs;
4115 }
4116 }
4117 }
4118}
4119
4120
4121bool AudioFlinger::DuplicatingThread::outputsReady(
4122 const SortedVector< sp<OutputTrack> > &outputTracks)
4123{
4124 for (size_t i = 0; i < outputTracks.size(); i++) {
4125 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4126 if (thread == 0) {
4127 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4128 outputTracks[i].get());
4129 return false;
4130 }
4131 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4132 // see note at standby() declaration
4133 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4134 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4135 thread.get());
4136 return false;
4137 }
4138 }
4139 return true;
4140}
4141
4142uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4143{
4144 return (mWaitTimeMs * 1000) / 2;
4145}
4146
4147void AudioFlinger::DuplicatingThread::cacheParameters_l()
4148{
4149 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4150 updateWaitTime_l();
4151
4152 MixerThread::cacheParameters_l();
4153}
4154
4155// ----------------------------------------------------------------------------
4156// Record
4157// ----------------------------------------------------------------------------
4158
4159AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4160 AudioStreamIn *input,
4161 uint32_t sampleRate,
4162 audio_channel_mask_t channelMask,
4163 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004164 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004165 audio_devices_t inDevice
4166#ifdef TEE_SINK
4167 , const sp<NBAIO_Sink>& teeSink
4168#endif
4169 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004170 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004171 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004172 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004173 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004174 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004175 // mBytesRead is only meaningful while active, and so is cleared in start()
4176 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004177#ifdef TEE_SINK
4178 , mTeeSink(teeSink)
4179#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004180{
4181 snprintf(mName, kNameLength, "AudioIn_%X", id);
4182
4183 readInputParameters();
4184
4185}
4186
4187
4188AudioFlinger::RecordThread::~RecordThread()
4189{
4190 delete[] mRsmpInBuffer;
4191 delete mResampler;
4192 delete[] mRsmpOutBuffer;
4193}
4194
4195void AudioFlinger::RecordThread::onFirstRef()
4196{
4197 run(mName, PRIORITY_URGENT_AUDIO);
4198}
4199
Eric Laurent81784c32012-11-19 14:55:58 -08004200bool AudioFlinger::RecordThread::threadLoop()
4201{
4202 AudioBufferProvider::Buffer buffer;
4203 sp<RecordTrack> activeTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004204
4205 nsecs_t lastWarning = 0;
4206
4207 inputStandBy();
4208 acquireWakeLock();
4209
4210 // used to verify we've read at least once before evaluating how many bytes were read
4211 bool readOnce = false;
4212
4213 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004214 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004215 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004216
Eric Laurent81784c32012-11-19 14:55:58 -08004217 { // scope for mLock
4218 Mutex::Autolock _l(mLock);
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004219 if (exitPending()) {
4220 break;
4221 }
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004222 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004223 // return value 'reconfig' is currently unused
4224 bool reconfig = checkForNewParameters_l();
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004225 if (mActiveTrack == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004226 standby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004227 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004228 releaseWakeLock_l();
4229 ALOGV("RecordThread: loop stopping");
4230 // go to sleep
4231 mWaitWorkCV.wait(mLock);
4232 ALOGV("RecordThread: loop starting");
4233 acquireWakeLock_l();
4234 continue;
4235 }
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004236 if (mActiveTrack->isTerminated()) {
4237 removeTrack_l(mActiveTrack);
4238 mActiveTrack.clear();
4239 } else {
4240 switch (mActiveTrack->mState) {
4241 case TrackBase::PAUSING:
4242 standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 mActiveTrack.clear();
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004244 mStartStopCond.broadcast();
4245 break;
4246
4247 case TrackBase::RESUMING:
4248 if (mReqChannelCount != mActiveTrack->channelCount()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004249 mActiveTrack.clear();
4250 mStartStopCond.broadcast();
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004251 } else if (readOnce) {
4252 // record start succeeds only if first read from audio input
4253 // succeeds
4254 if (mBytesRead >= 0) {
4255 mActiveTrack->mState = TrackBase::ACTIVE;
4256 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004257 mActiveTrack.clear();
4258 }
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004259 mStartStopCond.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08004260 }
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004261 mStandby = false;
4262 break;
Glenn Kasten2d944262013-08-13 13:54:08 -07004263
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004264 case TrackBase::ACTIVE:
4265 break;
4266
4267 case TrackBase::IDLE:
4268 break;
4269
4270 default:
4271 LOG_FATAL("Unexpected mActiveTrack->mState %d", mActiveTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004272 }
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004273
Eric Laurent81784c32012-11-19 14:55:58 -08004274 }
4275 lockEffectChains_l(effectChains);
4276 }
4277
Glenn Kasten47c20702013-08-13 15:37:35 -07004278 // thread mutex is now unlocked
4279 // FIXME RecordThread::start assigns to mActiveTrack under lock, but we read without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004280 if (mActiveTrack != 0) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004281 // FIXME RecordThread::stop assigns to mState under lock, but we read without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004282 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4283 mActiveTrack->mState != TrackBase::RESUMING) {
4284 unlockEffectChains(effectChains);
4285 usleep(kRecordThreadSleepUs);
4286 continue;
4287 }
4288 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004289 // thread mutex is not locked, but effect chain is locked
Eric Laurent81784c32012-11-19 14:55:58 -08004290 effectChains[i]->process_l();
4291 }
4292
4293 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004294 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004295 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004296 readOnce = true;
4297 size_t framesOut = buffer.frameCount;
4298 if (mResampler == NULL) {
4299 // no resampling
4300 while (framesOut) {
4301 size_t framesIn = mFrameCount - mRsmpInIndex;
Glenn Kasten34fca342013-08-13 09:48:14 -07004302 if (framesIn > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004303 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4304 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4305 mActiveTrack->mFrameSize;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004306 if (framesIn > framesOut) {
Eric Laurent81784c32012-11-19 14:55:58 -08004307 framesIn = framesOut;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004308 }
Eric Laurent81784c32012-11-19 14:55:58 -08004309 mRsmpInIndex += framesIn;
4310 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004311 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004312 memcpy(dst, src, framesIn * mFrameSize);
4313 } else {
4314 if (mChannelCount == 1) {
4315 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4316 (int16_t *)src, framesIn);
4317 } else {
4318 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4319 (int16_t *)src, framesIn);
4320 }
4321 }
4322 }
Glenn Kasten34fca342013-08-13 09:48:14 -07004323 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
Eric Laurent81784c32012-11-19 14:55:58 -08004324 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004325 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004326 readInto = buffer.raw;
4327 framesOut = 0;
4328 } else {
4329 readInto = mRsmpInBuffer;
4330 mRsmpInIndex = 0;
4331 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004332 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004333 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004334 if (mBytesRead <= 0) {
Glenn Kasten47c20702013-08-13 15:37:35 -07004335 // FIXME read mState without lock
Eric Laurent81784c32012-11-19 14:55:58 -08004336 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4337 {
4338 ALOGE("Error reading audio input");
4339 // Force input into standby so that it tries to
4340 // recover at next read attempt
4341 inputStandBy();
Glenn Kasten47c20702013-08-13 15:37:35 -07004342 // FIXME sleep with effect chains locked
Eric Laurent81784c32012-11-19 14:55:58 -08004343 usleep(kRecordThreadSleepUs);
4344 }
4345 mRsmpInIndex = mFrameCount;
4346 framesOut = 0;
4347 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004348 }
4349#ifdef TEE_SINK
4350 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004351 (void) mTeeSink->write(readInto,
4352 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4353 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004354#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004355 }
4356 }
4357 } else {
4358 // resampling
4359
Glenn Kasten34af0262013-07-30 11:52:39 -07004360 // resampler accumulates, but we only have one source track
4361 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004362 // alter output frame count as if we were expecting stereo samples
4363 if (mChannelCount == 1 && mReqChannelCount == 1) {
4364 framesOut >>= 1;
4365 }
4366 mResampler->resample(mRsmpOutBuffer, framesOut,
4367 this /* AudioBufferProvider* */);
4368 // ditherAndClamp() works as long as all buffers returned by
4369 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4370 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004371 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004372 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4373 // the resampler always outputs stereo samples:
4374 // do post stereo to mono conversion
4375 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4376 framesOut);
4377 } else {
4378 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4379 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004380 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004381
4382 }
4383 if (mFramestoDrop == 0) {
4384 mActiveTrack->releaseBuffer(&buffer);
4385 } else {
4386 if (mFramestoDrop > 0) {
4387 mFramestoDrop -= buffer.frameCount;
4388 if (mFramestoDrop <= 0) {
4389 clearSyncStartEvent();
4390 }
4391 } else {
4392 mFramestoDrop += buffer.frameCount;
4393 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4394 mSyncStartEvent->isCancelled()) {
4395 ALOGW("Synced record %s, session %d, trigger session %d",
4396 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4397 mActiveTrack->sessionId(),
4398 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4399 clearSyncStartEvent();
4400 }
4401 }
4402 }
4403 mActiveTrack->clearOverflow();
4404 }
4405 // client isn't retrieving buffers fast enough
4406 else {
4407 if (!mActiveTrack->setOverflow()) {
4408 nsecs_t now = systemTime();
4409 if ((now - lastWarning) > kWarningThrottleNs) {
4410 ALOGW("RecordThread: buffer overflow");
4411 lastWarning = now;
4412 }
4413 }
4414 // Release the processor for a while before asking for a new buffer.
4415 // This will give the application more chance to read from the buffer and
4416 // clear the overflow.
Glenn Kasten47c20702013-08-13 15:37:35 -07004417 // FIXME sleep with effect chains locked
Eric Laurent81784c32012-11-19 14:55:58 -08004418 usleep(kRecordThreadSleepUs);
4419 }
4420 }
4421 // enable changes in effect chain
4422 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004423 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004424 }
4425
4426 standby();
4427
4428 {
4429 Mutex::Autolock _l(mLock);
4430 mActiveTrack.clear();
4431 mStartStopCond.broadcast();
4432 }
4433
4434 releaseWakeLock();
4435
4436 ALOGV("RecordThread %p exiting", this);
4437 return false;
4438}
4439
4440void AudioFlinger::RecordThread::standby()
4441{
4442 if (!mStandby) {
4443 inputStandBy();
4444 mStandby = true;
4445 }
4446}
4447
4448void AudioFlinger::RecordThread::inputStandBy()
4449{
4450 mInput->stream->common.standby(&mInput->stream->common);
4451}
4452
Glenn Kastene198c362013-08-13 09:13:36 -07004453sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004454 const sp<AudioFlinger::Client>& client,
4455 uint32_t sampleRate,
4456 audio_format_t format,
4457 audio_channel_mask_t channelMask,
4458 size_t frameCount,
4459 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004460 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004461 pid_t tid,
4462 status_t *status)
4463{
4464 sp<RecordTrack> track;
4465 status_t lStatus;
4466
4467 lStatus = initCheck();
4468 if (lStatus != NO_ERROR) {
4469 ALOGE("Audio driver not initialized.");
4470 goto Exit;
4471 }
4472
Glenn Kasten90e58b12013-07-31 16:16:02 -07004473 // client expresses a preference for FAST, but we get the final say
4474 if (*flags & IAudioFlinger::TRACK_FAST) {
4475 if (
4476 // use case: callback handler and frame count is default or at least as large as HAL
4477 (
4478 (tid != -1) &&
4479 ((frameCount == 0) ||
4480 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4481 ) &&
4482 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4483 // mono or stereo
4484 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4485 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4486 // hardware sample rate
4487 (sampleRate == mSampleRate) &&
4488 // record thread has an associated fast recorder
4489 hasFastRecorder()
4490 // FIXME test that RecordThread for this fast track has a capable output HAL
4491 // FIXME add a permission test also?
4492 ) {
4493 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4494 if (frameCount == 0) {
4495 frameCount = mFrameCount * kFastTrackMultiplier;
4496 }
4497 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4498 frameCount, mFrameCount);
4499 } else {
4500 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4501 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4502 "hasFastRecorder=%d tid=%d",
4503 frameCount, mFrameCount, format,
4504 audio_is_linear_pcm(format),
4505 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4506 *flags &= ~IAudioFlinger::TRACK_FAST;
4507 // For compatibility with AudioRecord calculation, buffer depth is forced
4508 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4509 // This is probably too conservative, but legacy application code may depend on it.
4510 // If you change this calculation, also review the start threshold which is related.
4511 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4512 size_t mNormalFrameCount = 2048; // FIXME
4513 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4514 if (minBufCount < 2) {
4515 minBufCount = 2;
4516 }
4517 size_t minFrameCount = mNormalFrameCount * minBufCount;
4518 if (frameCount < minFrameCount) {
4519 frameCount = minFrameCount;
4520 }
4521 }
4522 }
4523
Eric Laurent81784c32012-11-19 14:55:58 -08004524 // FIXME use flags and tid similar to createTrack_l()
4525
4526 { // scope for mLock
4527 Mutex::Autolock _l(mLock);
4528
4529 track = new RecordTrack(this, client, sampleRate,
4530 format, channelMask, frameCount, sessionId);
4531
Glenn Kasten03003332013-08-06 15:40:54 -07004532 lStatus = track->initCheck();
4533 if (lStatus != NO_ERROR) {
4534 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004535 goto Exit;
4536 }
4537 mTracks.add(track);
4538
4539 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4540 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4541 mAudioFlinger->btNrecIsOff();
4542 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4543 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004544
4545 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4546 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4547 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4548 // so ask activity manager to do this on our behalf
4549 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4550 }
Eric Laurent81784c32012-11-19 14:55:58 -08004551 }
4552 lStatus = NO_ERROR;
4553
4554Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004555 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004556 return track;
4557}
4558
4559status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4560 AudioSystem::sync_event_t event,
4561 int triggerSession)
4562{
4563 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4564 sp<ThreadBase> strongMe = this;
4565 status_t status = NO_ERROR;
4566
4567 if (event == AudioSystem::SYNC_EVENT_NONE) {
4568 clearSyncStartEvent();
4569 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4570 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4571 triggerSession,
4572 recordTrack->sessionId(),
4573 syncStartEventCallback,
4574 this);
4575 // Sync event can be cancelled by the trigger session if the track is not in a
4576 // compatible state in which case we start record immediately
4577 if (mSyncStartEvent->isCancelled()) {
4578 clearSyncStartEvent();
4579 } else {
4580 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4581 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4582 }
4583 }
4584
4585 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004586 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004587 AutoMutex lock(mLock);
4588 if (mActiveTrack != 0) {
4589 if (recordTrack != mActiveTrack.get()) {
4590 status = -EBUSY;
4591 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4592 mActiveTrack->mState = TrackBase::ACTIVE;
4593 }
4594 return status;
4595 }
4596
Glenn Kasten47c20702013-08-13 15:37:35 -07004597 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004598 recordTrack->mState = TrackBase::IDLE;
4599 mActiveTrack = recordTrack;
4600 mLock.unlock();
4601 status_t status = AudioSystem::startInput(mId);
4602 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004603 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004604 if (status != NO_ERROR) {
4605 mActiveTrack.clear();
4606 clearSyncStartEvent();
4607 return status;
4608 }
4609 mRsmpInIndex = mFrameCount;
4610 mBytesRead = 0;
4611 if (mResampler != NULL) {
4612 mResampler->reset();
4613 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004614 // FIXME hijacking a playback track state name which was intended for start after pause;
4615 // here 'STARTING_2' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004616 mActiveTrack->mState = TrackBase::RESUMING;
4617 // signal thread to start
4618 ALOGV("Signal record thread");
4619 mWaitWorkCV.broadcast();
4620 // do not wait for mStartStopCond if exiting
4621 if (exitPending()) {
4622 mActiveTrack.clear();
4623 status = INVALID_OPERATION;
4624 goto startError;
4625 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004626 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004627 mStartStopCond.wait(mLock);
4628 if (mActiveTrack == 0) {
4629 ALOGV("Record failed to start");
4630 status = BAD_VALUE;
4631 goto startError;
4632 }
4633 ALOGV("Record started OK");
4634 return status;
4635 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004636
Eric Laurent81784c32012-11-19 14:55:58 -08004637startError:
4638 AudioSystem::stopInput(mId);
4639 clearSyncStartEvent();
4640 return status;
4641}
4642
4643void AudioFlinger::RecordThread::clearSyncStartEvent()
4644{
4645 if (mSyncStartEvent != 0) {
4646 mSyncStartEvent->cancel();
4647 }
4648 mSyncStartEvent.clear();
4649 mFramestoDrop = 0;
4650}
4651
4652void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4653{
4654 sp<SyncEvent> strongEvent = event.promote();
4655
4656 if (strongEvent != 0) {
4657 RecordThread *me = (RecordThread *)strongEvent->cookie();
4658 me->handleSyncStartEvent(strongEvent);
4659 }
4660}
4661
4662void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4663{
4664 if (event == mSyncStartEvent) {
4665 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4666 // from audio HAL
4667 mFramestoDrop = mFrameCount * 2;
4668 }
4669}
4670
Glenn Kastena8356f62013-07-25 14:37:52 -07004671bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004672 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004673 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004674 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4675 return false;
4676 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004677 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08004678 recordTrack->mState = TrackBase::PAUSING;
4679 // do not wait for mStartStopCond if exiting
4680 if (exitPending()) {
4681 return true;
4682 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004683 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004684 mStartStopCond.wait(mLock);
4685 // if we have been restarted, recordTrack == mActiveTrack.get() here
4686 if (exitPending() || recordTrack != mActiveTrack.get()) {
4687 ALOGV("Record stopped OK");
4688 return true;
4689 }
4690 return false;
4691}
4692
4693bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4694{
4695 return false;
4696}
4697
4698status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4699{
4700#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4701 if (!isValidSyncEvent(event)) {
4702 return BAD_VALUE;
4703 }
4704
4705 int eventSession = event->triggerSession();
4706 status_t ret = NAME_NOT_FOUND;
4707
4708 Mutex::Autolock _l(mLock);
4709
4710 for (size_t i = 0; i < mTracks.size(); i++) {
4711 sp<RecordTrack> track = mTracks[i];
4712 if (eventSession == track->sessionId()) {
4713 (void) track->setSyncEvent(event);
4714 ret = NO_ERROR;
4715 }
4716 }
4717 return ret;
4718#else
4719 return BAD_VALUE;
4720#endif
4721}
4722
4723// destroyTrack_l() must be called with ThreadBase::mLock held
4724void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4725{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004726 track->terminate();
4727 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004728 // active tracks are removed by threadLoop()
4729 if (mActiveTrack != track) {
4730 removeTrack_l(track);
4731 }
4732}
4733
4734void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4735{
4736 mTracks.remove(track);
4737 // need anything related to effects here?
4738}
4739
4740void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4741{
4742 dumpInternals(fd, args);
4743 dumpTracks(fd, args);
4744 dumpEffectChains(fd, args);
4745}
4746
4747void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4748{
4749 const size_t SIZE = 256;
4750 char buffer[SIZE];
4751 String8 result;
4752
4753 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4754 result.append(buffer);
4755
4756 if (mActiveTrack != 0) {
4757 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4758 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004759 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004760 result.append(buffer);
4761 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4762 result.append(buffer);
4763 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4764 result.append(buffer);
4765 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4766 result.append(buffer);
4767 } else {
4768 result.append("No active record client\n");
4769 }
4770
4771 write(fd, result.string(), result.size());
4772
4773 dumpBase(fd, args);
4774}
4775
4776void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4777{
4778 const size_t SIZE = 256;
4779 char buffer[SIZE];
4780 String8 result;
4781
4782 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4783 result.append(buffer);
4784 RecordTrack::appendDumpHeader(result);
4785 for (size_t i = 0; i < mTracks.size(); ++i) {
4786 sp<RecordTrack> track = mTracks[i];
4787 if (track != 0) {
4788 track->dump(buffer, SIZE);
4789 result.append(buffer);
4790 }
4791 }
4792
4793 if (mActiveTrack != 0) {
4794 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4795 result.append(buffer);
4796 RecordTrack::appendDumpHeader(result);
4797 mActiveTrack->dump(buffer, SIZE);
4798 result.append(buffer);
4799
4800 }
4801 write(fd, result.string(), result.size());
4802}
4803
4804// AudioBufferProvider interface
4805status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4806{
4807 size_t framesReq = buffer->frameCount;
4808 size_t framesReady = mFrameCount - mRsmpInIndex;
4809 int channelCount;
4810
4811 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004812 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004813 if (mBytesRead <= 0) {
4814 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4815 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4816 // Force input into standby so that it tries to
4817 // recover at next read attempt
4818 inputStandBy();
4819 usleep(kRecordThreadSleepUs);
4820 }
4821 buffer->raw = NULL;
4822 buffer->frameCount = 0;
4823 return NOT_ENOUGH_DATA;
4824 }
4825 mRsmpInIndex = 0;
4826 framesReady = mFrameCount;
4827 }
4828
4829 if (framesReq > framesReady) {
4830 framesReq = framesReady;
4831 }
4832
4833 if (mChannelCount == 1 && mReqChannelCount == 2) {
4834 channelCount = 1;
4835 } else {
4836 channelCount = 2;
4837 }
4838 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4839 buffer->frameCount = framesReq;
4840 return NO_ERROR;
4841}
4842
4843// AudioBufferProvider interface
4844void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4845{
4846 mRsmpInIndex += buffer->frameCount;
4847 buffer->frameCount = 0;
4848}
4849
4850bool AudioFlinger::RecordThread::checkForNewParameters_l()
4851{
4852 bool reconfig = false;
4853
4854 while (!mNewParameters.isEmpty()) {
4855 status_t status = NO_ERROR;
4856 String8 keyValuePair = mNewParameters[0];
4857 AudioParameter param = AudioParameter(keyValuePair);
4858 int value;
4859 audio_format_t reqFormat = mFormat;
4860 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07004861 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004862
4863 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4864 reqSamplingRate = value;
4865 reconfig = true;
4866 }
4867 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004868 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4869 status = BAD_VALUE;
4870 } else {
4871 reqFormat = (audio_format_t) value;
4872 reconfig = true;
4873 }
Eric Laurent81784c32012-11-19 14:55:58 -08004874 }
4875 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07004876 audio_channel_mask_t mask = (audio_channel_mask_t) value;
4877 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
4878 status = BAD_VALUE;
4879 } else {
4880 reqChannelMask = mask;
4881 reconfig = true;
4882 }
Eric Laurent81784c32012-11-19 14:55:58 -08004883 }
4884 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4885 // do not accept frame count changes if tracks are open as the track buffer
4886 // size depends on frame count and correct behavior would not be guaranteed
4887 // if frame count is changed after track creation
4888 if (mActiveTrack != 0) {
4889 status = INVALID_OPERATION;
4890 } else {
4891 reconfig = true;
4892 }
4893 }
4894 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4895 // forward device change to effects that have requested to be
4896 // aware of attached audio device.
4897 for (size_t i = 0; i < mEffectChains.size(); i++) {
4898 mEffectChains[i]->setDevice_l(value);
4899 }
4900
4901 // store input device and output device but do not forward output device to audio HAL.
4902 // Note that status is ignored by the caller for output device
4903 // (see AudioFlinger::setParameters()
4904 if (audio_is_output_devices(value)) {
4905 mOutDevice = value;
4906 status = BAD_VALUE;
4907 } else {
4908 mInDevice = value;
4909 // disable AEC and NS if the device is a BT SCO headset supporting those
4910 // pre processings
4911 if (mTracks.size() > 0) {
4912 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4913 mAudioFlinger->btNrecIsOff();
4914 for (size_t i = 0; i < mTracks.size(); i++) {
4915 sp<RecordTrack> track = mTracks[i];
4916 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4917 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4918 }
4919 }
4920 }
4921 }
4922 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4923 mAudioSource != (audio_source_t)value) {
4924 // forward device change to effects that have requested to be
4925 // aware of attached audio device.
4926 for (size_t i = 0; i < mEffectChains.size(); i++) {
4927 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4928 }
4929 mAudioSource = (audio_source_t)value;
4930 }
Glenn Kastene198c362013-08-13 09:13:36 -07004931
Eric Laurent81784c32012-11-19 14:55:58 -08004932 if (status == NO_ERROR) {
4933 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4934 keyValuePair.string());
4935 if (status == INVALID_OPERATION) {
4936 inputStandBy();
4937 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4938 keyValuePair.string());
4939 }
4940 if (reconfig) {
4941 if (status == BAD_VALUE &&
4942 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4943 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004944 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004945 <= (2 * reqSamplingRate)) &&
4946 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4947 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07004948 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
4949 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004950 status = NO_ERROR;
4951 }
4952 if (status == NO_ERROR) {
4953 readInputParameters();
4954 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4955 }
4956 }
4957 }
4958
4959 mNewParameters.removeAt(0);
4960
4961 mParamStatus = status;
4962 mParamCond.signal();
4963 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4964 // already timed out waiting for the status and will never signal the condition.
4965 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4966 }
4967 return reconfig;
4968}
4969
4970String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4971{
Eric Laurent81784c32012-11-19 14:55:58 -08004972 Mutex::Autolock _l(mLock);
4973 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07004974 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08004975 }
4976
Glenn Kastend8ea6992013-07-16 14:17:15 -07004977 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4978 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08004979 free(s);
4980 return out_s8;
4981}
4982
4983void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4984 AudioSystem::OutputDescriptor desc;
4985 void *param2 = NULL;
4986
4987 switch (event) {
4988 case AudioSystem::INPUT_OPENED:
4989 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07004990 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004991 desc.samplingRate = mSampleRate;
4992 desc.format = mFormat;
4993 desc.frameCount = mFrameCount;
4994 desc.latency = 0;
4995 param2 = &desc;
4996 break;
4997
4998 case AudioSystem::INPUT_CLOSED:
4999 default:
5000 break;
5001 }
5002 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5003}
5004
5005void AudioFlinger::RecordThread::readInputParameters()
5006{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005007 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005008 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005009 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005010 mRsmpOutBuffer = NULL;
5011 delete mResampler;
5012 mResampler = NULL;
5013
5014 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5015 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005016 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005017 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005018 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5019 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5020 }
Eric Laurent81784c32012-11-19 14:55:58 -08005021 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005022 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5023 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005024 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5025
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005026 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005027 int channelCount;
5028 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5029 // stereo to mono post process as the resampler always outputs stereo.
5030 if (mChannelCount == 1 && mReqChannelCount == 2) {
5031 channelCount = 1;
5032 } else {
5033 channelCount = 2;
5034 }
5035 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5036 mResampler->setSampleRate(mSampleRate);
5037 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005038 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005039
5040 // optmization: if mono to mono, alter input frame count as if we were inputing
5041 // stereo samples
5042 if (mChannelCount == 1 && mReqChannelCount == 1) {
5043 mFrameCount >>= 1;
5044 }
5045
5046 }
5047 mRsmpInIndex = mFrameCount;
5048}
5049
5050unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5051{
5052 Mutex::Autolock _l(mLock);
5053 if (initCheck() != NO_ERROR) {
5054 return 0;
5055 }
5056
5057 return mInput->stream->get_input_frames_lost(mInput->stream);
5058}
5059
5060uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5061{
5062 Mutex::Autolock _l(mLock);
5063 uint32_t result = 0;
5064 if (getEffectChain_l(sessionId) != 0) {
5065 result = EFFECT_SESSION;
5066 }
5067
5068 for (size_t i = 0; i < mTracks.size(); ++i) {
5069 if (sessionId == mTracks[i]->sessionId()) {
5070 result |= TRACK_SESSION;
5071 break;
5072 }
5073 }
5074
5075 return result;
5076}
5077
5078KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5079{
5080 KeyedVector<int, bool> ids;
5081 Mutex::Autolock _l(mLock);
5082 for (size_t j = 0; j < mTracks.size(); ++j) {
5083 sp<RecordThread::RecordTrack> track = mTracks[j];
5084 int sessionId = track->sessionId();
5085 if (ids.indexOfKey(sessionId) < 0) {
5086 ids.add(sessionId, true);
5087 }
5088 }
5089 return ids;
5090}
5091
5092AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5093{
5094 Mutex::Autolock _l(mLock);
5095 AudioStreamIn *input = mInput;
5096 mInput = NULL;
5097 return input;
5098}
5099
5100// this method must always be called either with ThreadBase mLock held or inside the thread loop
5101audio_stream_t* AudioFlinger::RecordThread::stream() const
5102{
5103 if (mInput == NULL) {
5104 return NULL;
5105 }
5106 return &mInput->stream->common;
5107}
5108
5109status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5110{
5111 // only one chain per input thread
5112 if (mEffectChains.size() != 0) {
5113 return INVALID_OPERATION;
5114 }
5115 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5116
5117 chain->setInBuffer(NULL);
5118 chain->setOutBuffer(NULL);
5119
5120 checkSuspendOnAddEffectChain_l(chain);
5121
5122 mEffectChains.add(chain);
5123
5124 return NO_ERROR;
5125}
5126
5127size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5128{
5129 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5130 ALOGW_IF(mEffectChains.size() != 1,
5131 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5132 chain.get(), mEffectChains.size(), this);
5133 if (mEffectChains.size() == 1) {
5134 mEffectChains.removeAt(0);
5135 }
5136 return 0;
5137}
5138
5139}; // namespace android