blob: 9c17574b67be60c14f963b1b706a277846b5705a [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{
379 mLock.lock();
380 while (!mConfigEvents.isEmpty()) {
381 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
382 ConfigEvent *event = mConfigEvents[0];
383 mConfigEvents.removeAt(0);
384 // release mLock before locking AudioFlinger mLock: lock order is always
385 // AudioFlinger then ThreadBase to avoid cross deadlock
386 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700387 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700388 case CFG_EVENT_PRIO: {
389 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
390 // FIXME Need to understand why this has be done asynchronously
391 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
392 true /*asynchronous*/);
393 if (err != 0) {
394 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
395 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
396 }
397 } break;
398 case CFG_EVENT_IO: {
399 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
400 mAudioFlinger->mLock.lock();
401 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
402 mAudioFlinger->mLock.unlock();
403 } break;
404 default:
405 ALOGE("processConfigEvents() unknown event type %d", event->type());
406 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800407 }
408 delete event;
409 mLock.lock();
410 }
411 mLock.unlock();
412}
413
414void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
415{
416 const size_t SIZE = 256;
417 char buffer[SIZE];
418 String8 result;
419
420 bool locked = AudioFlinger::dumpTryLock(mLock);
421 if (!locked) {
422 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
423 write(fd, buffer, strlen(buffer));
424 }
425
426 snprintf(buffer, SIZE, "io handle: %d\n", mId);
427 result.append(buffer);
428 snprintf(buffer, SIZE, "TID: %d\n", getTid());
429 result.append(buffer);
430 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
431 result.append(buffer);
432 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
433 result.append(buffer);
434 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
435 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700436 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
437 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700438 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800439 result.append(buffer);
440 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
441 result.append(buffer);
442 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
443 result.append(buffer);
444 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
445 result.append(buffer);
446
447 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
448 result.append(buffer);
449 result.append(" Index Command");
450 for (size_t i = 0; i < mNewParameters.size(); ++i) {
451 snprintf(buffer, SIZE, "\n %02d ", i);
452 result.append(buffer);
453 result.append(mNewParameters[i]);
454 }
455
456 snprintf(buffer, SIZE, "\n\nPending config events: \n");
457 result.append(buffer);
458 for (size_t i = 0; i < mConfigEvents.size(); i++) {
459 mConfigEvents[i]->dump(buffer, SIZE);
460 result.append(buffer);
461 }
462 result.append("\n");
463
464 write(fd, result.string(), result.size());
465
466 if (locked) {
467 mLock.unlock();
468 }
469}
470
471void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
472{
473 const size_t SIZE = 256;
474 char buffer[SIZE];
475 String8 result;
476
477 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
478 write(fd, buffer, strlen(buffer));
479
480 for (size_t i = 0; i < mEffectChains.size(); ++i) {
481 sp<EffectChain> chain = mEffectChains[i];
482 if (chain != 0) {
483 chain->dump(fd, args);
484 }
485 }
486}
487
488void AudioFlinger::ThreadBase::acquireWakeLock()
489{
490 Mutex::Autolock _l(mLock);
491 acquireWakeLock_l();
492}
493
494void AudioFlinger::ThreadBase::acquireWakeLock_l()
495{
496 if (mPowerManager == 0) {
497 // use checkService() to avoid blocking if power service is not up yet
498 sp<IBinder> binder =
499 defaultServiceManager()->checkService(String16("power"));
500 if (binder == 0) {
501 ALOGW("Thread %s cannot connect to the power manager service", mName);
502 } else {
503 mPowerManager = interface_cast<IPowerManager>(binder);
504 binder->linkToDeath(mDeathRecipient);
505 }
506 }
507 if (mPowerManager != 0) {
508 sp<IBinder> binder = new BBinder();
509 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
510 binder,
Dianne Hackborn61d404e2013-05-20 11:22:20 -0700511 String16(mName),
512 String16("media"));
Eric Laurent81784c32012-11-19 14:55:58 -0800513 if (status == NO_ERROR) {
514 mWakeLockToken = binder;
515 }
516 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
517 }
518}
519
520void AudioFlinger::ThreadBase::releaseWakeLock()
521{
522 Mutex::Autolock _l(mLock);
523 releaseWakeLock_l();
524}
525
526void AudioFlinger::ThreadBase::releaseWakeLock_l()
527{
528 if (mWakeLockToken != 0) {
529 ALOGV("releaseWakeLock_l() %s", mName);
530 if (mPowerManager != 0) {
531 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
532 }
533 mWakeLockToken.clear();
534 }
535}
536
537void AudioFlinger::ThreadBase::clearPowerManager()
538{
539 Mutex::Autolock _l(mLock);
540 releaseWakeLock_l();
541 mPowerManager.clear();
542}
543
544void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
545{
546 sp<ThreadBase> thread = mThread.promote();
547 if (thread != 0) {
548 thread->clearPowerManager();
549 }
550 ALOGW("power manager service died !!!");
551}
552
553void AudioFlinger::ThreadBase::setEffectSuspended(
554 const effect_uuid_t *type, bool suspend, int sessionId)
555{
556 Mutex::Autolock _l(mLock);
557 setEffectSuspended_l(type, suspend, sessionId);
558}
559
560void AudioFlinger::ThreadBase::setEffectSuspended_l(
561 const effect_uuid_t *type, bool suspend, int sessionId)
562{
563 sp<EffectChain> chain = getEffectChain_l(sessionId);
564 if (chain != 0) {
565 if (type != NULL) {
566 chain->setEffectSuspended_l(type, suspend);
567 } else {
568 chain->setEffectSuspendedAll_l(suspend);
569 }
570 }
571
572 updateSuspendedSessions_l(type, suspend, sessionId);
573}
574
575void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
576{
577 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
578 if (index < 0) {
579 return;
580 }
581
582 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
583 mSuspendedSessions.valueAt(index);
584
585 for (size_t i = 0; i < sessionEffects.size(); i++) {
586 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
587 for (int j = 0; j < desc->mRefCount; j++) {
588 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
589 chain->setEffectSuspendedAll_l(true);
590 } else {
591 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
592 desc->mType.timeLow);
593 chain->setEffectSuspended_l(&desc->mType, true);
594 }
595 }
596 }
597}
598
599void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
600 bool suspend,
601 int sessionId)
602{
603 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
604
605 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
606
607 if (suspend) {
608 if (index >= 0) {
609 sessionEffects = mSuspendedSessions.valueAt(index);
610 } else {
611 mSuspendedSessions.add(sessionId, sessionEffects);
612 }
613 } else {
614 if (index < 0) {
615 return;
616 }
617 sessionEffects = mSuspendedSessions.valueAt(index);
618 }
619
620
621 int key = EffectChain::kKeyForSuspendAll;
622 if (type != NULL) {
623 key = type->timeLow;
624 }
625 index = sessionEffects.indexOfKey(key);
626
627 sp<SuspendedSessionDesc> desc;
628 if (suspend) {
629 if (index >= 0) {
630 desc = sessionEffects.valueAt(index);
631 } else {
632 desc = new SuspendedSessionDesc();
633 if (type != NULL) {
634 desc->mType = *type;
635 }
636 sessionEffects.add(key, desc);
637 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
638 }
639 desc->mRefCount++;
640 } else {
641 if (index < 0) {
642 return;
643 }
644 desc = sessionEffects.valueAt(index);
645 if (--desc->mRefCount == 0) {
646 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
647 sessionEffects.removeItemsAt(index);
648 if (sessionEffects.isEmpty()) {
649 ALOGV("updateSuspendedSessions_l() restore removing session %d",
650 sessionId);
651 mSuspendedSessions.removeItem(sessionId);
652 }
653 }
654 }
655 if (!sessionEffects.isEmpty()) {
656 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
657 }
658}
659
660void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
661 bool enabled,
662 int sessionId)
663{
664 Mutex::Autolock _l(mLock);
665 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
666}
667
668void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
669 bool enabled,
670 int sessionId)
671{
672 if (mType != RECORD) {
673 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
674 // another session. This gives the priority to well behaved effect control panels
675 // and applications not using global effects.
676 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
677 // global effects
678 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
679 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
680 }
681 }
682
683 sp<EffectChain> chain = getEffectChain_l(sessionId);
684 if (chain != 0) {
685 chain->checkSuspendOnEffectEnabled(effect, enabled);
686 }
687}
688
689// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
690sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
691 const sp<AudioFlinger::Client>& client,
692 const sp<IEffectClient>& effectClient,
693 int32_t priority,
694 int sessionId,
695 effect_descriptor_t *desc,
696 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700697 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
699 sp<EffectModule> effect;
700 sp<EffectHandle> handle;
701 status_t lStatus;
702 sp<EffectChain> chain;
703 bool chainCreated = false;
704 bool effectCreated = false;
705 bool effectRegistered = false;
706
707 lStatus = initCheck();
708 if (lStatus != NO_ERROR) {
709 ALOGW("createEffect_l() Audio driver not initialized.");
710 goto Exit;
711 }
712
713 // Do not allow effects with session ID 0 on direct output or duplicating threads
714 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
715 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
716 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
717 desc->name, sessionId);
718 lStatus = BAD_VALUE;
719 goto Exit;
720 }
721 // Only Pre processor effects are allowed on input threads and only on input threads
722 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
723 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
724 desc->name, desc->flags, mType);
725 lStatus = BAD_VALUE;
726 goto Exit;
727 }
728
729 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
730
731 { // scope for mLock
732 Mutex::Autolock _l(mLock);
733
734 // check for existing effect chain with the requested audio session
735 chain = getEffectChain_l(sessionId);
736 if (chain == 0) {
737 // create a new chain for this session
738 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
739 chain = new EffectChain(this, sessionId);
740 addEffectChain_l(chain);
741 chain->setStrategy(getStrategyForSession_l(sessionId));
742 chainCreated = true;
743 } else {
744 effect = chain->getEffectFromDesc_l(desc);
745 }
746
747 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
748
749 if (effect == 0) {
750 int id = mAudioFlinger->nextUniqueId();
751 // Check CPU and memory usage
752 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
753 if (lStatus != NO_ERROR) {
754 goto Exit;
755 }
756 effectRegistered = true;
757 // create a new effect module if none present in the chain
758 effect = new EffectModule(this, chain, desc, id, sessionId);
759 lStatus = effect->status();
760 if (lStatus != NO_ERROR) {
761 goto Exit;
762 }
763 lStatus = chain->addEffect_l(effect);
764 if (lStatus != NO_ERROR) {
765 goto Exit;
766 }
767 effectCreated = true;
768
769 effect->setDevice(mOutDevice);
770 effect->setDevice(mInDevice);
771 effect->setMode(mAudioFlinger->getMode());
772 effect->setAudioSource(mAudioSource);
773 }
774 // create effect handle and connect it to effect module
775 handle = new EffectHandle(effect, client, effectClient, priority);
776 lStatus = effect->addHandle(handle.get());
777 if (enabled != NULL) {
778 *enabled = (int)effect->isEnabled();
779 }
780 }
781
782Exit:
783 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
784 Mutex::Autolock _l(mLock);
785 if (effectCreated) {
786 chain->removeEffect_l(effect);
787 }
788 if (effectRegistered) {
789 AudioSystem::unregisterEffect(effect->id());
790 }
791 if (chainCreated) {
792 removeEffectChain_l(chain);
793 }
794 handle.clear();
795 }
796
Glenn Kasten9156ef32013-08-06 15:39:08 -0700797 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800798 return handle;
799}
800
801sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
802{
803 Mutex::Autolock _l(mLock);
804 return getEffect_l(sessionId, effectId);
805}
806
807sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
808{
809 sp<EffectChain> chain = getEffectChain_l(sessionId);
810 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
811}
812
813// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
814// PlaybackThread::mLock held
815status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
816{
817 // check for existing effect chain with the requested audio session
818 int sessionId = effect->sessionId();
819 sp<EffectChain> chain = getEffectChain_l(sessionId);
820 bool chainCreated = false;
821
822 if (chain == 0) {
823 // create a new chain for this session
824 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
825 chain = new EffectChain(this, sessionId);
826 addEffectChain_l(chain);
827 chain->setStrategy(getStrategyForSession_l(sessionId));
828 chainCreated = true;
829 }
830 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
831
832 if (chain->getEffectFromId_l(effect->id()) != 0) {
833 ALOGW("addEffect_l() %p effect %s already present in chain %p",
834 this, effect->desc().name, chain.get());
835 return BAD_VALUE;
836 }
837
838 status_t status = chain->addEffect_l(effect);
839 if (status != NO_ERROR) {
840 if (chainCreated) {
841 removeEffectChain_l(chain);
842 }
843 return status;
844 }
845
846 effect->setDevice(mOutDevice);
847 effect->setDevice(mInDevice);
848 effect->setMode(mAudioFlinger->getMode());
849 effect->setAudioSource(mAudioSource);
850 return NO_ERROR;
851}
852
853void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
854
855 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
856 effect_descriptor_t desc = effect->desc();
857 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
858 detachAuxEffect_l(effect->id());
859 }
860
861 sp<EffectChain> chain = effect->chain().promote();
862 if (chain != 0) {
863 // remove effect chain if removing last effect
864 if (chain->removeEffect_l(effect) == 0) {
865 removeEffectChain_l(chain);
866 }
867 } else {
868 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
869 }
870}
871
872void AudioFlinger::ThreadBase::lockEffectChains_l(
873 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
874{
875 effectChains = mEffectChains;
876 for (size_t i = 0; i < mEffectChains.size(); i++) {
877 mEffectChains[i]->lock();
878 }
879}
880
881void AudioFlinger::ThreadBase::unlockEffectChains(
882 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
883{
884 for (size_t i = 0; i < effectChains.size(); i++) {
885 effectChains[i]->unlock();
886 }
887}
888
889sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
890{
891 Mutex::Autolock _l(mLock);
892 return getEffectChain_l(sessionId);
893}
894
895sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
896{
897 size_t size = mEffectChains.size();
898 for (size_t i = 0; i < size; i++) {
899 if (mEffectChains[i]->sessionId() == sessionId) {
900 return mEffectChains[i];
901 }
902 }
903 return 0;
904}
905
906void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
907{
908 Mutex::Autolock _l(mLock);
909 size_t size = mEffectChains.size();
910 for (size_t i = 0; i < size; i++) {
911 mEffectChains[i]->setMode_l(mode);
912 }
913}
914
915void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
916 EffectHandle *handle,
917 bool unpinIfLast) {
918
919 Mutex::Autolock _l(mLock);
920 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
921 // delete the effect module if removing last handle on it
922 if (effect->removeHandle(handle) == 0) {
923 if (!effect->isPinned() || unpinIfLast) {
924 removeEffect_l(effect);
925 AudioSystem::unregisterEffect(effect->id());
926 }
927 }
928}
929
930// ----------------------------------------------------------------------------
931// Playback
932// ----------------------------------------------------------------------------
933
934AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
935 AudioStreamOut* output,
936 audio_io_handle_t id,
937 audio_devices_t device,
938 type_t type)
939 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700940 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700941 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800942 // mStreamTypes[] initialized in constructor body
943 mOutput(output),
944 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
945 mMixerStatus(MIXER_IDLE),
946 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
947 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800948 mBytesRemaining(0),
949 mCurrentWriteLength(0),
950 mUseAsyncWrite(false),
951 mWriteBlocked(false),
952 mDraining(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800953 mScreenState(AudioFlinger::mScreenState),
954 // index 0 is reserved for normal mixer's submix
955 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
956{
957 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800958 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800959
960 // Assumes constructor is called by AudioFlinger with it's mLock held, but
961 // it would be safer to explicitly pass initial masterVolume/masterMute as
962 // parameter.
963 //
964 // If the HAL we are using has support for master volume or master mute,
965 // then do not attenuate or mute during mixing (just leave the volume at 1.0
966 // and the mute set to false).
967 mMasterVolume = audioFlinger->masterVolume_l();
968 mMasterMute = audioFlinger->masterMute_l();
969 if (mOutput && mOutput->audioHwDev) {
970 if (mOutput->audioHwDev->canSetMasterVolume()) {
971 mMasterVolume = 1.0;
972 }
973
974 if (mOutput->audioHwDev->canSetMasterMute()) {
975 mMasterMute = false;
976 }
977 }
978
979 readOutputParameters();
980
981 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
982 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
983 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
984 stream = (audio_stream_type_t) (stream + 1)) {
985 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
986 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
987 }
988 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
989 // because mAudioFlinger doesn't have one to copy from
990}
991
992AudioFlinger::PlaybackThread::~PlaybackThread()
993{
Glenn Kasten9e58b552013-01-18 15:09:48 -0800994 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -0700995 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -0800996}
997
998void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
999{
1000 dumpInternals(fd, args);
1001 dumpTracks(fd, args);
1002 dumpEffectChains(fd, args);
1003}
1004
1005void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1006{
1007 const size_t SIZE = 256;
1008 char buffer[SIZE];
1009 String8 result;
1010
1011 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1012 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1013 const stream_type_t *st = &mStreamTypes[i];
1014 if (i > 0) {
1015 result.appendFormat(", ");
1016 }
1017 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1018 if (st->mute) {
1019 result.append("M");
1020 }
1021 }
1022 result.append("\n");
1023 write(fd, result.string(), result.length());
1024 result.clear();
1025
1026 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1027 result.append(buffer);
1028 Track::appendDumpHeader(result);
1029 for (size_t i = 0; i < mTracks.size(); ++i) {
1030 sp<Track> track = mTracks[i];
1031 if (track != 0) {
1032 track->dump(buffer, SIZE);
1033 result.append(buffer);
1034 }
1035 }
1036
1037 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1038 result.append(buffer);
1039 Track::appendDumpHeader(result);
1040 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1041 sp<Track> track = mActiveTracks[i].promote();
1042 if (track != 0) {
1043 track->dump(buffer, SIZE);
1044 result.append(buffer);
1045 }
1046 }
1047 write(fd, result.string(), result.size());
1048
1049 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1050 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1051 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1052 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1053}
1054
1055void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1056{
1057 const size_t SIZE = 256;
1058 char buffer[SIZE];
1059 String8 result;
1060
1061 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1062 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001063 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1064 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1066 ns2ms(systemTime() - mLastWriteTime));
1067 result.append(buffer);
1068 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1069 result.append(buffer);
1070 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1071 result.append(buffer);
1072 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1073 result.append(buffer);
1074 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1075 result.append(buffer);
1076 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1077 result.append(buffer);
1078 write(fd, result.string(), result.size());
1079 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1080
1081 dumpBase(fd, args);
1082}
1083
1084// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001085
1086void AudioFlinger::PlaybackThread::onFirstRef()
1087{
1088 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1089}
1090
1091// ThreadBase virtuals
1092void AudioFlinger::PlaybackThread::preExit()
1093{
1094 ALOGV(" preExit()");
1095 // FIXME this is using hard-coded strings but in the future, this functionality will be
1096 // converted to use audio HAL extensions required to support tunneling
1097 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1098}
1099
1100// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1101sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1102 const sp<AudioFlinger::Client>& client,
1103 audio_stream_type_t streamType,
1104 uint32_t sampleRate,
1105 audio_format_t format,
1106 audio_channel_mask_t channelMask,
1107 size_t frameCount,
1108 const sp<IMemory>& sharedBuffer,
1109 int sessionId,
1110 IAudioFlinger::track_flags_t *flags,
1111 pid_t tid,
1112 status_t *status)
1113{
1114 sp<Track> track;
1115 status_t lStatus;
1116
1117 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1118
1119 // client expresses a preference for FAST, but we get the final say
1120 if (*flags & IAudioFlinger::TRACK_FAST) {
1121 if (
1122 // not timed
1123 (!isTimed) &&
1124 // either of these use cases:
1125 (
1126 // use case 1: shared buffer with any frame count
1127 (
1128 (sharedBuffer != 0)
1129 ) ||
1130 // use case 2: callback handler and frame count is default or at least as large as HAL
1131 (
1132 (tid != -1) &&
1133 ((frameCount == 0) ||
1134 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1135 )
1136 ) &&
1137 // PCM data
1138 audio_is_linear_pcm(format) &&
1139 // mono or stereo
1140 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1141 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1142#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1143 // hardware sample rate
1144 (sampleRate == mSampleRate) &&
1145#endif
1146 // normal mixer has an associated fast mixer
1147 hasFastMixer() &&
1148 // there are sufficient fast track slots available
1149 (mFastTrackAvailMask != 0)
1150 // FIXME test that MixerThread for this fast track has a capable output HAL
1151 // FIXME add a permission test also?
1152 ) {
1153 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1154 if (frameCount == 0) {
1155 frameCount = mFrameCount * kFastTrackMultiplier;
1156 }
1157 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1158 frameCount, mFrameCount);
1159 } else {
1160 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1161 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1162 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1163 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1164 audio_is_linear_pcm(format),
1165 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1166 *flags &= ~IAudioFlinger::TRACK_FAST;
1167 // For compatibility with AudioTrack calculation, buffer depth is forced
1168 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1169 // This is probably too conservative, but legacy application code may depend on it.
1170 // If you change this calculation, also review the start threshold which is related.
1171 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1172 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1173 if (minBufCount < 2) {
1174 minBufCount = 2;
1175 }
1176 size_t minFrameCount = mNormalFrameCount * minBufCount;
1177 if (frameCount < minFrameCount) {
1178 frameCount = minFrameCount;
1179 }
1180 }
1181 }
1182
1183 if (mType == DIRECT) {
1184 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1185 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1186 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1187 "for output %p with format %d",
1188 sampleRate, format, channelMask, mOutput, mFormat);
1189 lStatus = BAD_VALUE;
1190 goto Exit;
1191 }
1192 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001193 } else if (mType == OFFLOAD) {
1194 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1195 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1196 "for output %p with format %d",
1197 sampleRate, format, channelMask, mOutput, mFormat);
1198 lStatus = BAD_VALUE;
1199 goto Exit;
1200 }
Eric Laurent81784c32012-11-19 14:55:58 -08001201 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001202 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1203 ALOGE("createTrack_l() Bad parameter: format %d \""
1204 "for output %p with format %d",
1205 format, mOutput, mFormat);
1206 lStatus = BAD_VALUE;
1207 goto Exit;
1208 }
Eric Laurent81784c32012-11-19 14:55:58 -08001209 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1210 if (sampleRate > mSampleRate*2) {
1211 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1212 lStatus = BAD_VALUE;
1213 goto Exit;
1214 }
1215 }
1216
1217 lStatus = initCheck();
1218 if (lStatus != NO_ERROR) {
1219 ALOGE("Audio driver not initialized.");
1220 goto Exit;
1221 }
1222
1223 { // scope for mLock
1224 Mutex::Autolock _l(mLock);
1225
1226 // all tracks in same audio session must share the same routing strategy otherwise
1227 // conflicts will happen when tracks are moved from one output to another by audio policy
1228 // manager
1229 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1230 for (size_t i = 0; i < mTracks.size(); ++i) {
1231 sp<Track> t = mTracks[i];
1232 if (t != 0 && !t->isOutputTrack()) {
1233 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1234 if (sessionId == t->sessionId() && strategy != actual) {
1235 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1236 strategy, actual);
1237 lStatus = BAD_VALUE;
1238 goto Exit;
1239 }
1240 }
1241 }
1242
1243 if (!isTimed) {
1244 track = new Track(this, client, streamType, sampleRate, format,
1245 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1246 } else {
1247 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1248 channelMask, frameCount, sharedBuffer, sessionId);
1249 }
Glenn Kasten03003332013-08-06 15:40:54 -07001250
1251 // new Track always returns non-NULL,
1252 // but TimedTrack::create() is a factory that could fail by returning NULL
1253 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1254 if (lStatus != NO_ERROR) {
1255 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001256 goto Exit;
1257 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001258
Eric Laurent81784c32012-11-19 14:55:58 -08001259 mTracks.add(track);
1260
1261 sp<EffectChain> chain = getEffectChain_l(sessionId);
1262 if (chain != 0) {
1263 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1264 track->setMainBuffer(chain->inBuffer());
1265 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1266 chain->incTrackCnt();
1267 }
1268
1269 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1270 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1271 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1272 // so ask activity manager to do this on our behalf
1273 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1274 }
1275 }
1276
1277 lStatus = NO_ERROR;
1278
1279Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001280 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001281 return track;
1282}
1283
1284uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1285{
1286 return latency;
1287}
1288
1289uint32_t AudioFlinger::PlaybackThread::latency() const
1290{
1291 Mutex::Autolock _l(mLock);
1292 return latency_l();
1293}
1294uint32_t AudioFlinger::PlaybackThread::latency_l() const
1295{
1296 if (initCheck() == NO_ERROR) {
1297 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1298 } else {
1299 return 0;
1300 }
1301}
1302
1303void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1304{
1305 Mutex::Autolock _l(mLock);
1306 // Don't apply master volume in SW if our HAL can do it for us.
1307 if (mOutput && mOutput->audioHwDev &&
1308 mOutput->audioHwDev->canSetMasterVolume()) {
1309 mMasterVolume = 1.0;
1310 } else {
1311 mMasterVolume = value;
1312 }
1313}
1314
1315void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1316{
1317 Mutex::Autolock _l(mLock);
1318 // Don't apply master mute in SW if our HAL can do it for us.
1319 if (mOutput && mOutput->audioHwDev &&
1320 mOutput->audioHwDev->canSetMasterMute()) {
1321 mMasterMute = false;
1322 } else {
1323 mMasterMute = muted;
1324 }
1325}
1326
1327void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1328{
1329 Mutex::Autolock _l(mLock);
1330 mStreamTypes[stream].volume = value;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001331 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001332}
1333
1334void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1335{
1336 Mutex::Autolock _l(mLock);
1337 mStreamTypes[stream].mute = muted;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001338 signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001339}
1340
1341float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1342{
1343 Mutex::Autolock _l(mLock);
1344 return mStreamTypes[stream].volume;
1345}
1346
1347// addTrack_l() must be called with ThreadBase::mLock held
1348status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1349{
1350 status_t status = ALREADY_EXISTS;
1351
1352 // set retry count for buffer fill
1353 track->mRetryCount = kMaxTrackStartupRetries;
1354 if (mActiveTracks.indexOf(track) < 0) {
1355 // the track is newly added, make sure it fills up all its
1356 // buffers before playing. This is to ensure the client will
1357 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001358 if (!track->isOutputTrack()) {
1359 TrackBase::track_state state = track->mState;
1360 mLock.unlock();
1361 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1362 mLock.lock();
1363 // abort track was stopped/paused while we released the lock
1364 if (state != track->mState) {
1365 if (status == NO_ERROR) {
1366 mLock.unlock();
1367 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1368 mLock.lock();
1369 }
1370 return INVALID_OPERATION;
1371 }
1372 // abort if start is rejected by audio policy manager
1373 if (status != NO_ERROR) {
1374 return PERMISSION_DENIED;
1375 }
1376#ifdef ADD_BATTERY_DATA
1377 // to track the speaker usage
1378 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1379#endif
1380 }
1381
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001382 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001383 track->mResetDone = false;
1384 track->mPresentationCompleteFrames = 0;
1385 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001386 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1387 if (chain != 0) {
1388 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1389 track->sessionId());
1390 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001391 }
1392
1393 status = NO_ERROR;
1394 }
1395
1396 ALOGV("mWaitWorkCV.broadcast");
1397 mWaitWorkCV.broadcast();
1398
1399 return status;
1400}
1401
Eric Laurentbfb1b832013-01-07 09:53:42 -08001402bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001403{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001404 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001405 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001406 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1407 track->mState = TrackBase::STOPPED;
1408 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001409 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001410 } else if (track->isFastTrack() || track->isOffloaded()) {
1411 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001412 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001413
1414 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001415}
1416
1417void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1418{
1419 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1420 mTracks.remove(track);
1421 deleteTrackName_l(track->name());
1422 // redundant as track is about to be destroyed, for dumpsys only
1423 track->mName = -1;
1424 if (track->isFastTrack()) {
1425 int index = track->mFastIndex;
1426 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1427 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1428 mFastTrackAvailMask |= 1 << index;
1429 // redundant as track is about to be destroyed, for dumpsys only
1430 track->mFastIndex = -1;
1431 }
1432 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1433 if (chain != 0) {
1434 chain->decTrackCnt();
1435 }
1436}
1437
Eric Laurentbfb1b832013-01-07 09:53:42 -08001438void AudioFlinger::PlaybackThread::signal_l()
1439{
1440 // Thread could be blocked waiting for async
1441 // so signal it to handle state changes immediately
1442 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1443 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1444 mSignalPending = true;
1445 mWaitWorkCV.signal();
1446}
1447
Eric Laurent81784c32012-11-19 14:55:58 -08001448String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1449{
Eric Laurent81784c32012-11-19 14:55:58 -08001450 Mutex::Autolock _l(mLock);
1451 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001452 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001453 }
1454
Glenn Kastend8ea6992013-07-16 14:17:15 -07001455 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1456 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001457 free(s);
1458 return out_s8;
1459}
1460
1461// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1462void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1463 AudioSystem::OutputDescriptor desc;
1464 void *param2 = NULL;
1465
1466 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1467 param);
1468
1469 switch (event) {
1470 case AudioSystem::OUTPUT_OPENED:
1471 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001472 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001473 desc.samplingRate = mSampleRate;
1474 desc.format = mFormat;
1475 desc.frameCount = mNormalFrameCount; // FIXME see
1476 // AudioFlinger::frameCount(audio_io_handle_t)
1477 desc.latency = latency();
1478 param2 = &desc;
1479 break;
1480
1481 case AudioSystem::STREAM_CONFIG_CHANGED:
1482 param2 = &param;
1483 case AudioSystem::OUTPUT_CLOSED:
1484 default:
1485 break;
1486 }
1487 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1488}
1489
Eric Laurentbfb1b832013-01-07 09:53:42 -08001490void AudioFlinger::PlaybackThread::writeCallback()
1491{
1492 ALOG_ASSERT(mCallbackThread != 0);
1493 mCallbackThread->setWriteBlocked(false);
1494}
1495
1496void AudioFlinger::PlaybackThread::drainCallback()
1497{
1498 ALOG_ASSERT(mCallbackThread != 0);
1499 mCallbackThread->setDraining(false);
1500}
1501
1502void AudioFlinger::PlaybackThread::setWriteBlocked(bool value)
1503{
1504 Mutex::Autolock _l(mLock);
1505 mWriteBlocked = value;
1506 if (!value) {
1507 mWaitWorkCV.signal();
1508 }
1509}
1510
1511void AudioFlinger::PlaybackThread::setDraining(bool value)
1512{
1513 Mutex::Autolock _l(mLock);
1514 mDraining = value;
1515 if (!value) {
1516 mWaitWorkCV.signal();
1517 }
1518}
1519
1520// static
1521int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1522 void *param,
1523 void *cookie)
1524{
1525 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1526 ALOGV("asyncCallback() event %d", event);
1527 switch (event) {
1528 case STREAM_CBK_EVENT_WRITE_READY:
1529 me->writeCallback();
1530 break;
1531 case STREAM_CBK_EVENT_DRAIN_READY:
1532 me->drainCallback();
1533 break;
1534 default:
1535 ALOGW("asyncCallback() unknown event %d", event);
1536 break;
1537 }
1538 return 0;
1539}
1540
Eric Laurent81784c32012-11-19 14:55:58 -08001541void AudioFlinger::PlaybackThread::readOutputParameters()
1542{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001543 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001544 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1545 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001546 if (!audio_is_output_channel(mChannelMask)) {
1547 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1548 }
1549 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1550 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1551 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1552 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001553 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001554 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001555 if (!audio_is_valid_format(mFormat)) {
1556 LOG_FATAL("HAL format %d not valid for output", mFormat);
1557 }
1558 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1559 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1560 mFormat);
1561 }
Eric Laurent81784c32012-11-19 14:55:58 -08001562 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001563 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1564 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001565 if (mFrameCount & 15) {
1566 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1567 mFrameCount);
1568 }
1569
Eric Laurentbfb1b832013-01-07 09:53:42 -08001570 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1571 (mOutput->stream->set_callback != NULL)) {
1572 if (mOutput->stream->set_callback(mOutput->stream,
1573 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1574 mUseAsyncWrite = true;
1575 }
1576 }
1577
Eric Laurent81784c32012-11-19 14:55:58 -08001578 // Calculate size of normal mix buffer relative to the HAL output buffer size
1579 double multiplier = 1.0;
1580 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1581 kUseFastMixer == FastMixer_Dynamic)) {
1582 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1583 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1584 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1585 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1586 maxNormalFrameCount = maxNormalFrameCount & ~15;
1587 if (maxNormalFrameCount < minNormalFrameCount) {
1588 maxNormalFrameCount = minNormalFrameCount;
1589 }
1590 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1591 if (multiplier <= 1.0) {
1592 multiplier = 1.0;
1593 } else if (multiplier <= 2.0) {
1594 if (2 * mFrameCount <= maxNormalFrameCount) {
1595 multiplier = 2.0;
1596 } else {
1597 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1598 }
1599 } else {
1600 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1601 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1602 // track, but we sometimes have to do this to satisfy the maximum frame count
1603 // constraint)
1604 // FIXME this rounding up should not be done if no HAL SRC
1605 uint32_t truncMult = (uint32_t) multiplier;
1606 if ((truncMult & 1)) {
1607 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1608 ++truncMult;
1609 }
1610 }
1611 multiplier = (double) truncMult;
1612 }
1613 }
1614 mNormalFrameCount = multiplier * mFrameCount;
1615 // round up to nearest 16 frames to satisfy AudioMixer
1616 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1617 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1618 mNormalFrameCount);
1619
Glenn Kastenc1fac192013-08-06 07:41:36 -07001620 delete[] mMixBuffer;
1621 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1622 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1623 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1624 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001625
1626 // force reconfiguration of effect chains and engines to take new buffer size and audio
1627 // parameters into account
1628 // Note that mLock is not held when readOutputParameters() is called from the constructor
1629 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1630 // matter.
1631 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1632 Vector< sp<EffectChain> > effectChains = mEffectChains;
1633 for (size_t i = 0; i < effectChains.size(); i ++) {
1634 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1635 }
1636}
1637
1638
1639status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1640{
1641 if (halFrames == NULL || dspFrames == NULL) {
1642 return BAD_VALUE;
1643 }
1644 Mutex::Autolock _l(mLock);
1645 if (initCheck() != NO_ERROR) {
1646 return INVALID_OPERATION;
1647 }
1648 size_t framesWritten = mBytesWritten / mFrameSize;
1649 *halFrames = framesWritten;
1650
1651 if (isSuspended()) {
1652 // return an estimation of rendered frames when the output is suspended
1653 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1654 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1655 return NO_ERROR;
1656 } else {
1657 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1658 }
1659}
1660
1661uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1662{
1663 Mutex::Autolock _l(mLock);
1664 uint32_t result = 0;
1665 if (getEffectChain_l(sessionId) != 0) {
1666 result = EFFECT_SESSION;
1667 }
1668
1669 for (size_t i = 0; i < mTracks.size(); ++i) {
1670 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001671 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001672 result |= TRACK_SESSION;
1673 break;
1674 }
1675 }
1676
1677 return result;
1678}
1679
1680uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1681{
1682 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1683 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1684 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1685 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1686 }
1687 for (size_t i = 0; i < mTracks.size(); i++) {
1688 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001689 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001690 return AudioSystem::getStrategyForStream(track->streamType());
1691 }
1692 }
1693 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1694}
1695
1696
1697AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1698{
1699 Mutex::Autolock _l(mLock);
1700 return mOutput;
1701}
1702
1703AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1704{
1705 Mutex::Autolock _l(mLock);
1706 AudioStreamOut *output = mOutput;
1707 mOutput = NULL;
1708 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1709 // must push a NULL and wait for ack
1710 mOutputSink.clear();
1711 mPipeSink.clear();
1712 mNormalSink.clear();
1713 return output;
1714}
1715
1716// this method must always be called either with ThreadBase mLock held or inside the thread loop
1717audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1718{
1719 if (mOutput == NULL) {
1720 return NULL;
1721 }
1722 return &mOutput->stream->common;
1723}
1724
1725uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1726{
1727 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1728}
1729
1730status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1731{
1732 if (!isValidSyncEvent(event)) {
1733 return BAD_VALUE;
1734 }
1735
1736 Mutex::Autolock _l(mLock);
1737
1738 for (size_t i = 0; i < mTracks.size(); ++i) {
1739 sp<Track> track = mTracks[i];
1740 if (event->triggerSession() == track->sessionId()) {
1741 (void) track->setSyncEvent(event);
1742 return NO_ERROR;
1743 }
1744 }
1745
1746 return NAME_NOT_FOUND;
1747}
1748
1749bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1750{
1751 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1752}
1753
1754void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1755 const Vector< sp<Track> >& tracksToRemove)
1756{
1757 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001758 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001759 for (size_t i = 0 ; i < count ; i++) {
1760 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001761 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001762 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001763#ifdef ADD_BATTERY_DATA
1764 // to track the speaker usage
1765 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1766#endif
1767 if (track->isTerminated()) {
1768 AudioSystem::releaseOutput(mId);
1769 }
Eric Laurent81784c32012-11-19 14:55:58 -08001770 }
1771 }
1772 }
Eric Laurent81784c32012-11-19 14:55:58 -08001773}
1774
1775void AudioFlinger::PlaybackThread::checkSilentMode_l()
1776{
1777 if (!mMasterMute) {
1778 char value[PROPERTY_VALUE_MAX];
1779 if (property_get("ro.audio.silent", value, "0") > 0) {
1780 char *endptr;
1781 unsigned long ul = strtoul(value, &endptr, 0);
1782 if (*endptr == '\0' && ul != 0) {
1783 ALOGD("Silence is golden");
1784 // The setprop command will not allow a property to be changed after
1785 // the first time it is set, so we don't have to worry about un-muting.
1786 setMasterMute_l(true);
1787 }
1788 }
1789 }
1790}
1791
1792// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001793ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001794{
1795 // FIXME rewrite to reduce number of system calls
1796 mLastWriteTime = systemTime();
1797 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001798 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001799
1800 // If an NBAIO sink is present, use it to write the normal mixer's submix
1801 if (mNormalSink != 0) {
1802#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001803 size_t count = mBytesRemaining >> mBitShift;
1804 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001805 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001806 // update the setpoint when AudioFlinger::mScreenState changes
1807 uint32_t screenState = AudioFlinger::mScreenState;
1808 if (screenState != mScreenState) {
1809 mScreenState = screenState;
1810 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1811 if (pipe != NULL) {
1812 pipe->setAvgFrames((mScreenState & 1) ?
1813 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1814 }
1815 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001816 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001817 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001818 if (framesWritten > 0) {
1819 bytesWritten = framesWritten << mBitShift;
1820 } else {
1821 bytesWritten = framesWritten;
1822 }
1823 // otherwise use the HAL / AudioStreamOut directly
1824 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001825 // Direct output and offload threads
1826 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1827 if (mUseAsyncWrite) {
1828 mWriteBlocked = true;
1829 ALOG_ASSERT(mCallbackThread != 0);
1830 mCallbackThread->setWriteBlocked(true);
1831 }
1832 bytesWritten = mOutput->stream->write(mOutput->stream,
1833 mMixBuffer + offset, mBytesRemaining);
1834 if (mUseAsyncWrite &&
1835 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1836 // do not wait for async callback in case of error of full write
1837 mWriteBlocked = false;
1838 ALOG_ASSERT(mCallbackThread != 0);
1839 mCallbackThread->setWriteBlocked(false);
1840 }
Eric Laurent81784c32012-11-19 14:55:58 -08001841 }
1842
Eric Laurent81784c32012-11-19 14:55:58 -08001843 mNumWrites++;
1844 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845
1846 return bytesWritten;
1847}
1848
1849void AudioFlinger::PlaybackThread::threadLoop_drain()
1850{
1851 if (mOutput->stream->drain) {
1852 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1853 if (mUseAsyncWrite) {
1854 mDraining = true;
1855 ALOG_ASSERT(mCallbackThread != 0);
1856 mCallbackThread->setDraining(true);
1857 }
1858 mOutput->stream->drain(mOutput->stream,
1859 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1860 : AUDIO_DRAIN_ALL);
1861 }
1862}
1863
1864void AudioFlinger::PlaybackThread::threadLoop_exit()
1865{
1866 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869/*
1870The derived values that are cached:
1871 - mixBufferSize from frame count * frame size
1872 - activeSleepTime from activeSleepTimeUs()
1873 - idleSleepTime from idleSleepTimeUs()
1874 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1875 - maxPeriod from frame count and sample rate (MIXER only)
1876
1877The parameters that affect these derived values are:
1878 - frame count
1879 - frame size
1880 - sample rate
1881 - device type: A2DP or not
1882 - device latency
1883 - format: PCM or not
1884 - active sleep time
1885 - idle sleep time
1886*/
1887
1888void AudioFlinger::PlaybackThread::cacheParameters_l()
1889{
1890 mixBufferSize = mNormalFrameCount * mFrameSize;
1891 activeSleepTime = activeSleepTimeUs();
1892 idleSleepTime = idleSleepTimeUs();
1893}
1894
1895void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1896{
Glenn Kasten7c027242012-12-26 14:43:16 -08001897 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001898 this, streamType, mTracks.size());
1899 Mutex::Autolock _l(mLock);
1900
1901 size_t size = mTracks.size();
1902 for (size_t i = 0; i < size; i++) {
1903 sp<Track> t = mTracks[i];
1904 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001905 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001906 }
1907 }
1908}
1909
1910status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1911{
1912 int session = chain->sessionId();
1913 int16_t *buffer = mMixBuffer;
1914 bool ownsBuffer = false;
1915
1916 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1917 if (session > 0) {
1918 // Only one effect chain can be present in direct output thread and it uses
1919 // the mix buffer as input
1920 if (mType != DIRECT) {
1921 size_t numSamples = mNormalFrameCount * mChannelCount;
1922 buffer = new int16_t[numSamples];
1923 memset(buffer, 0, numSamples * sizeof(int16_t));
1924 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1925 ownsBuffer = true;
1926 }
1927
1928 // Attach all tracks with same session ID to this chain.
1929 for (size_t i = 0; i < mTracks.size(); ++i) {
1930 sp<Track> track = mTracks[i];
1931 if (session == track->sessionId()) {
1932 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1933 buffer);
1934 track->setMainBuffer(buffer);
1935 chain->incTrackCnt();
1936 }
1937 }
1938
1939 // indicate all active tracks in the chain
1940 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1941 sp<Track> track = mActiveTracks[i].promote();
1942 if (track == 0) {
1943 continue;
1944 }
1945 if (session == track->sessionId()) {
1946 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1947 chain->incActiveTrackCnt();
1948 }
1949 }
1950 }
1951
1952 chain->setInBuffer(buffer, ownsBuffer);
1953 chain->setOutBuffer(mMixBuffer);
1954 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1955 // chains list in order to be processed last as it contains output stage effects
1956 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1957 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1958 // after track specific effects and before output stage
1959 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1960 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1961 // Effect chain for other sessions are inserted at beginning of effect
1962 // chains list to be processed before output mix effects. Relative order between other
1963 // sessions is not important
1964 size_t size = mEffectChains.size();
1965 size_t i = 0;
1966 for (i = 0; i < size; i++) {
1967 if (mEffectChains[i]->sessionId() < session) {
1968 break;
1969 }
1970 }
1971 mEffectChains.insertAt(chain, i);
1972 checkSuspendOnAddEffectChain_l(chain);
1973
1974 return NO_ERROR;
1975}
1976
1977size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1978{
1979 int session = chain->sessionId();
1980
1981 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1982
1983 for (size_t i = 0; i < mEffectChains.size(); i++) {
1984 if (chain == mEffectChains[i]) {
1985 mEffectChains.removeAt(i);
1986 // detach all active tracks from the chain
1987 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1988 sp<Track> track = mActiveTracks[i].promote();
1989 if (track == 0) {
1990 continue;
1991 }
1992 if (session == track->sessionId()) {
1993 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1994 chain.get(), session);
1995 chain->decActiveTrackCnt();
1996 }
1997 }
1998
1999 // detach all tracks with same session ID from this chain
2000 for (size_t i = 0; i < mTracks.size(); ++i) {
2001 sp<Track> track = mTracks[i];
2002 if (session == track->sessionId()) {
2003 track->setMainBuffer(mMixBuffer);
2004 chain->decTrackCnt();
2005 }
2006 }
2007 break;
2008 }
2009 }
2010 return mEffectChains.size();
2011}
2012
2013status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2015{
2016 Mutex::Autolock _l(mLock);
2017 return attachAuxEffect_l(track, EffectId);
2018}
2019
2020status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2021 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2022{
2023 status_t status = NO_ERROR;
2024
2025 if (EffectId == 0) {
2026 track->setAuxBuffer(0, NULL);
2027 } else {
2028 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2029 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2030 if (effect != 0) {
2031 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2032 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2033 } else {
2034 status = INVALID_OPERATION;
2035 }
2036 } else {
2037 status = BAD_VALUE;
2038 }
2039 }
2040 return status;
2041}
2042
2043void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2044{
2045 for (size_t i = 0; i < mTracks.size(); ++i) {
2046 sp<Track> track = mTracks[i];
2047 if (track->auxEffectId() == effectId) {
2048 attachAuxEffect_l(track, 0);
2049 }
2050 }
2051}
2052
2053bool AudioFlinger::PlaybackThread::threadLoop()
2054{
2055 Vector< sp<Track> > tracksToRemove;
2056
2057 standbyTime = systemTime();
2058
2059 // MIXER
2060 nsecs_t lastWarning = 0;
2061
2062 // DUPLICATING
2063 // FIXME could this be made local to while loop?
2064 writeFrames = 0;
2065
2066 cacheParameters_l();
2067 sleepTime = idleSleepTime;
2068
2069 if (mType == MIXER) {
2070 sleepTimeShift = 0;
2071 }
2072
2073 CpuStats cpuStats;
2074 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2075
2076 acquireWakeLock();
2077
Glenn Kasten9e58b552013-01-18 15:09:48 -08002078 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2079 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2080 // and then that string will be logged at the next convenient opportunity.
2081 const char *logString = NULL;
2082
Eric Laurent81784c32012-11-19 14:55:58 -08002083 while (!exitPending())
2084 {
2085 cpuStats.sample(myName);
2086
2087 Vector< sp<EffectChain> > effectChains;
2088
2089 processConfigEvents();
2090
2091 { // scope for mLock
2092
2093 Mutex::Autolock _l(mLock);
2094
Glenn Kasten9e58b552013-01-18 15:09:48 -08002095 if (logString != NULL) {
2096 mNBLogWriter->logTimestamp();
2097 mNBLogWriter->log(logString);
2098 logString = NULL;
2099 }
2100
Eric Laurent81784c32012-11-19 14:55:58 -08002101 if (checkForNewParameters_l()) {
2102 cacheParameters_l();
2103 }
2104
2105 saveOutputTracks();
2106
Eric Laurentbfb1b832013-01-07 09:53:42 -08002107 if (mSignalPending) {
2108 // A signal was raised while we were unlocked
2109 mSignalPending = false;
2110 } else if (waitingAsyncCallback_l()) {
2111 if (exitPending()) {
2112 break;
2113 }
2114 releaseWakeLock_l();
2115 ALOGV("wait async completion");
2116 mWaitWorkCV.wait(mLock);
2117 ALOGV("async completion/wake");
2118 acquireWakeLock_l();
2119 if (exitPending()) {
2120 break;
2121 }
2122 if (!mActiveTracks.size() && (systemTime() > standbyTime)) {
2123 continue;
2124 }
2125 sleepTime = 0;
2126 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2127 isSuspended()) {
2128 // put audio hardware into standby after short delay
2129 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002130
2131 threadLoop_standby();
2132
2133 mStandby = true;
2134 }
2135
2136 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2137 // we're about to wait, flush the binder command buffer
2138 IPCThreadState::self()->flushCommands();
2139
2140 clearOutputTracks();
2141
2142 if (exitPending()) {
2143 break;
2144 }
2145
2146 releaseWakeLock_l();
2147 // wait until we have something to do...
2148 ALOGV("%s going to sleep", myName.string());
2149 mWaitWorkCV.wait(mLock);
2150 ALOGV("%s waking up", myName.string());
2151 acquireWakeLock_l();
2152
2153 mMixerStatus = MIXER_IDLE;
2154 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2155 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002157 checkSilentMode_l();
2158
2159 standbyTime = systemTime() + standbyDelay;
2160 sleepTime = idleSleepTime;
2161 if (mType == MIXER) {
2162 sleepTimeShift = 0;
2163 }
2164
2165 continue;
2166 }
2167 }
2168
2169 // mMixerStatusIgnoringFastTracks is also updated internally
2170 mMixerStatus = prepareTracks_l(&tracksToRemove);
2171
2172 // prevent any changes in effect chain list and in each effect chain
2173 // during mixing and effect process as the audio buffers could be deleted
2174 // or modified if an effect is created or deleted
2175 lockEffectChains_l(effectChains);
2176 }
2177
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 if (mBytesRemaining == 0) {
2179 mCurrentWriteLength = 0;
2180 if (mMixerStatus == MIXER_TRACKS_READY) {
2181 // threadLoop_mix() sets mCurrentWriteLength
2182 threadLoop_mix();
2183 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2184 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2185 // threadLoop_sleepTime sets sleepTime to 0 if data
2186 // must be written to HAL
2187 threadLoop_sleepTime();
2188 if (sleepTime == 0) {
2189 mCurrentWriteLength = mixBufferSize;
2190 }
2191 }
2192 mBytesRemaining = mCurrentWriteLength;
2193 if (isSuspended()) {
2194 sleepTime = suspendSleepTimeUs();
2195 // simulate write to HAL when suspended
2196 mBytesWritten += mixBufferSize;
2197 mBytesRemaining = 0;
2198 }
Eric Laurent81784c32012-11-19 14:55:58 -08002199
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 // only process effects if we're going to write
2201 if (sleepTime == 0) {
2202 for (size_t i = 0; i < effectChains.size(); i ++) {
2203 effectChains[i]->process_l();
2204 }
Eric Laurent81784c32012-11-19 14:55:58 -08002205 }
2206 }
2207
2208 // enable changes in effect chain
2209 unlockEffectChains(effectChains);
2210
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 if (!waitingAsyncCallback()) {
2212 // sleepTime == 0 means we must write to audio hardware
2213 if (sleepTime == 0) {
2214 if (mBytesRemaining) {
2215 ssize_t ret = threadLoop_write();
2216 if (ret < 0) {
2217 mBytesRemaining = 0;
2218 } else {
2219 mBytesWritten += ret;
2220 mBytesRemaining -= ret;
2221 }
2222 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2223 (mMixerStatus == MIXER_DRAIN_ALL)) {
2224 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002225 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226if (mType == MIXER) {
2227 // write blocked detection
2228 nsecs_t now = systemTime();
2229 nsecs_t delta = now - mLastWriteTime;
2230 if (!mStandby && delta > maxPeriod) {
2231 mNumDelayedWrites++;
2232 if ((now - lastWarning) > kWarningThrottleNs) {
2233 ATRACE_NAME("underrun");
2234 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2235 ns2ms(delta), mNumDelayedWrites, this);
2236 lastWarning = now;
2237 }
2238 }
Eric Laurent81784c32012-11-19 14:55:58 -08002239}
2240
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 mStandby = false;
2242 } else {
2243 usleep(sleepTime);
2244 }
Eric Laurent81784c32012-11-19 14:55:58 -08002245 }
2246
2247 // Finally let go of removed track(s), without the lock held
2248 // since we can't guarantee the destructors won't acquire that
2249 // same lock. This will also mutate and push a new fast mixer state.
2250 threadLoop_removeTracks(tracksToRemove);
2251 tracksToRemove.clear();
2252
2253 // FIXME I don't understand the need for this here;
2254 // it was in the original code but maybe the
2255 // assignment in saveOutputTracks() makes this unnecessary?
2256 clearOutputTracks();
2257
2258 // Effect chains will be actually deleted here if they were removed from
2259 // mEffectChains list during mixing or effects processing
2260 effectChains.clear();
2261
2262 // FIXME Note that the above .clear() is no longer necessary since effectChains
2263 // is now local to this block, but will keep it for now (at least until merge done).
2264 }
2265
Eric Laurentbfb1b832013-01-07 09:53:42 -08002266 threadLoop_exit();
2267
Eric Laurent81784c32012-11-19 14:55:58 -08002268 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002270 // put output stream into standby mode
2271 if (!mStandby) {
2272 mOutput->stream->common.standby(&mOutput->stream->common);
2273 }
2274 }
2275
2276 releaseWakeLock();
2277
2278 ALOGV("Thread %p type %d exiting", this, mType);
2279 return false;
2280}
2281
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282// removeTracks_l() must be called with ThreadBase::mLock held
2283void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2284{
2285 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002286 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002287 for (size_t i=0 ; i<count ; i++) {
2288 const sp<Track>& track = tracksToRemove.itemAt(i);
2289 mActiveTracks.remove(track);
2290 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2291 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2292 if (chain != 0) {
2293 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2294 track->sessionId());
2295 chain->decActiveTrackCnt();
2296 }
2297 if (track->isTerminated()) {
2298 removeTrack_l(track);
2299 }
2300 }
2301 }
2302
2303}
Eric Laurent81784c32012-11-19 14:55:58 -08002304
2305// ----------------------------------------------------------------------------
2306
2307AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2308 audio_io_handle_t id, audio_devices_t device, type_t type)
2309 : PlaybackThread(audioFlinger, output, id, device, type),
2310 // mAudioMixer below
2311 // mFastMixer below
2312 mFastMixerFutex(0)
2313 // mOutputSink below
2314 // mPipeSink below
2315 // mNormalSink below
2316{
2317 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002318 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002319 "mFrameCount=%d, mNormalFrameCount=%d",
2320 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2321 mNormalFrameCount);
2322 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2323
2324 // FIXME - Current mixer implementation only supports stereo output
2325 if (mChannelCount != FCC_2) {
2326 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2327 }
2328
2329 // create an NBAIO sink for the HAL output stream, and negotiate
2330 mOutputSink = new AudioStreamOutSink(output->stream);
2331 size_t numCounterOffers = 0;
2332 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2333 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2334 ALOG_ASSERT(index == 0);
2335
2336 // initialize fast mixer depending on configuration
2337 bool initFastMixer;
2338 switch (kUseFastMixer) {
2339 case FastMixer_Never:
2340 initFastMixer = false;
2341 break;
2342 case FastMixer_Always:
2343 initFastMixer = true;
2344 break;
2345 case FastMixer_Static:
2346 case FastMixer_Dynamic:
2347 initFastMixer = mFrameCount < mNormalFrameCount;
2348 break;
2349 }
2350 if (initFastMixer) {
2351
2352 // create a MonoPipe to connect our submix to FastMixer
2353 NBAIO_Format format = mOutputSink->format();
2354 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2355 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2356 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2357 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2358 const NBAIO_Format offers[1] = {format};
2359 size_t numCounterOffers = 0;
2360 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2361 ALOG_ASSERT(index == 0);
2362 monoPipe->setAvgFrames((mScreenState & 1) ?
2363 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2364 mPipeSink = monoPipe;
2365
Glenn Kasten46909e72013-02-26 09:20:22 -08002366#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002367 if (mTeeSinkOutputEnabled) {
2368 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2369 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2370 numCounterOffers = 0;
2371 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2372 ALOG_ASSERT(index == 0);
2373 mTeeSink = teeSink;
2374 PipeReader *teeSource = new PipeReader(*teeSink);
2375 numCounterOffers = 0;
2376 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2377 ALOG_ASSERT(index == 0);
2378 mTeeSource = teeSource;
2379 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002380#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002381
2382 // create fast mixer and configure it initially with just one fast track for our submix
2383 mFastMixer = new FastMixer();
2384 FastMixerStateQueue *sq = mFastMixer->sq();
2385#ifdef STATE_QUEUE_DUMP
2386 sq->setObserverDump(&mStateQueueObserverDump);
2387 sq->setMutatorDump(&mStateQueueMutatorDump);
2388#endif
2389 FastMixerState *state = sq->begin();
2390 FastTrack *fastTrack = &state->mFastTracks[0];
2391 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2392 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2393 fastTrack->mVolumeProvider = NULL;
2394 fastTrack->mGeneration++;
2395 state->mFastTracksGen++;
2396 state->mTrackMask = 1;
2397 // fast mixer will use the HAL output sink
2398 state->mOutputSink = mOutputSink.get();
2399 state->mOutputSinkGen++;
2400 state->mFrameCount = mFrameCount;
2401 state->mCommand = FastMixerState::COLD_IDLE;
2402 // already done in constructor initialization list
2403 //mFastMixerFutex = 0;
2404 state->mColdFutexAddr = &mFastMixerFutex;
2405 state->mColdGen++;
2406 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002407#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002408 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002409#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002410 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2411 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002412 sq->end();
2413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2414
2415 // start the fast mixer
2416 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2417 pid_t tid = mFastMixer->getTid();
2418 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2419 if (err != 0) {
2420 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2421 kPriorityFastMixer, getpid_cached, tid, err);
2422 }
2423
2424#ifdef AUDIO_WATCHDOG
2425 // create and start the watchdog
2426 mAudioWatchdog = new AudioWatchdog();
2427 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2428 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2429 tid = mAudioWatchdog->getTid();
2430 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2431 if (err != 0) {
2432 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2433 kPriorityFastMixer, getpid_cached, tid, err);
2434 }
2435#endif
2436
2437 } else {
2438 mFastMixer = NULL;
2439 }
2440
2441 switch (kUseFastMixer) {
2442 case FastMixer_Never:
2443 case FastMixer_Dynamic:
2444 mNormalSink = mOutputSink;
2445 break;
2446 case FastMixer_Always:
2447 mNormalSink = mPipeSink;
2448 break;
2449 case FastMixer_Static:
2450 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2451 break;
2452 }
2453}
2454
2455AudioFlinger::MixerThread::~MixerThread()
2456{
2457 if (mFastMixer != NULL) {
2458 FastMixerStateQueue *sq = mFastMixer->sq();
2459 FastMixerState *state = sq->begin();
2460 if (state->mCommand == FastMixerState::COLD_IDLE) {
2461 int32_t old = android_atomic_inc(&mFastMixerFutex);
2462 if (old == -1) {
2463 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2464 }
2465 }
2466 state->mCommand = FastMixerState::EXIT;
2467 sq->end();
2468 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2469 mFastMixer->join();
2470 // Though the fast mixer thread has exited, it's state queue is still valid.
2471 // We'll use that extract the final state which contains one remaining fast track
2472 // corresponding to our sub-mix.
2473 state = sq->begin();
2474 ALOG_ASSERT(state->mTrackMask == 1);
2475 FastTrack *fastTrack = &state->mFastTracks[0];
2476 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2477 delete fastTrack->mBufferProvider;
2478 sq->end(false /*didModify*/);
2479 delete mFastMixer;
2480#ifdef AUDIO_WATCHDOG
2481 if (mAudioWatchdog != 0) {
2482 mAudioWatchdog->requestExit();
2483 mAudioWatchdog->requestExitAndWait();
2484 mAudioWatchdog.clear();
2485 }
2486#endif
2487 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002488 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002489 delete mAudioMixer;
2490}
2491
2492
2493uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2494{
2495 if (mFastMixer != NULL) {
2496 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2497 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2498 }
2499 return latency;
2500}
2501
2502
2503void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2504{
2505 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2506}
2507
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002509{
2510 // FIXME we should only do one push per cycle; confirm this is true
2511 // Start the fast mixer if it's not already running
2512 if (mFastMixer != NULL) {
2513 FastMixerStateQueue *sq = mFastMixer->sq();
2514 FastMixerState *state = sq->begin();
2515 if (state->mCommand != FastMixerState::MIX_WRITE &&
2516 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2517 if (state->mCommand == FastMixerState::COLD_IDLE) {
2518 int32_t old = android_atomic_inc(&mFastMixerFutex);
2519 if (old == -1) {
2520 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2521 }
2522#ifdef AUDIO_WATCHDOG
2523 if (mAudioWatchdog != 0) {
2524 mAudioWatchdog->resume();
2525 }
2526#endif
2527 }
2528 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002529 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2530 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002531 sq->end();
2532 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2533 if (kUseFastMixer == FastMixer_Dynamic) {
2534 mNormalSink = mPipeSink;
2535 }
2536 } else {
2537 sq->end(false /*didModify*/);
2538 }
2539 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002541}
2542
2543void AudioFlinger::MixerThread::threadLoop_standby()
2544{
2545 // Idle the fast mixer if it's currently running
2546 if (mFastMixer != NULL) {
2547 FastMixerStateQueue *sq = mFastMixer->sq();
2548 FastMixerState *state = sq->begin();
2549 if (!(state->mCommand & FastMixerState::IDLE)) {
2550 state->mCommand = FastMixerState::COLD_IDLE;
2551 state->mColdFutexAddr = &mFastMixerFutex;
2552 state->mColdGen++;
2553 mFastMixerFutex = 0;
2554 sq->end();
2555 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2556 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2557 if (kUseFastMixer == FastMixer_Dynamic) {
2558 mNormalSink = mOutputSink;
2559 }
2560#ifdef AUDIO_WATCHDOG
2561 if (mAudioWatchdog != 0) {
2562 mAudioWatchdog->pause();
2563 }
2564#endif
2565 } else {
2566 sq->end(false /*didModify*/);
2567 }
2568 }
2569 PlaybackThread::threadLoop_standby();
2570}
2571
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572// Empty implementation for standard mixer
2573// Overridden for offloaded playback
2574void AudioFlinger::PlaybackThread::flushOutput_l()
2575{
2576}
2577
2578bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2579{
2580 return false;
2581}
2582
2583bool AudioFlinger::PlaybackThread::shouldStandby_l()
2584{
2585 return !mStandby;
2586}
2587
2588bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2589{
2590 Mutex::Autolock _l(mLock);
2591 return waitingAsyncCallback_l();
2592}
2593
Eric Laurent81784c32012-11-19 14:55:58 -08002594// shared by MIXER and DIRECT, overridden by DUPLICATING
2595void AudioFlinger::PlaybackThread::threadLoop_standby()
2596{
2597 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2598 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 if (mUseAsyncWrite != 0) {
2600 mWriteBlocked = false;
2601 mDraining = false;
2602 ALOG_ASSERT(mCallbackThread != 0);
2603 mCallbackThread->setWriteBlocked(false);
2604 mCallbackThread->setDraining(false);
2605 }
Eric Laurent81784c32012-11-19 14:55:58 -08002606}
2607
2608void AudioFlinger::MixerThread::threadLoop_mix()
2609{
2610 // obtain the presentation timestamp of the next output buffer
2611 int64_t pts;
2612 status_t status = INVALID_OPERATION;
2613
2614 if (mNormalSink != 0) {
2615 status = mNormalSink->getNextWriteTimestamp(&pts);
2616 } else {
2617 status = mOutputSink->getNextWriteTimestamp(&pts);
2618 }
2619
2620 if (status != NO_ERROR) {
2621 pts = AudioBufferProvider::kInvalidPTS;
2622 }
2623
2624 // mix buffers...
2625 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002626 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002627 // increase sleep time progressively when application underrun condition clears.
2628 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2629 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2630 // such that we would underrun the audio HAL.
2631 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2632 sleepTimeShift--;
2633 }
2634 sleepTime = 0;
2635 standbyTime = systemTime() + standbyDelay;
2636 //TODO: delay standby when effects have a tail
2637}
2638
2639void AudioFlinger::MixerThread::threadLoop_sleepTime()
2640{
2641 // If no tracks are ready, sleep once for the duration of an output
2642 // buffer size, then write 0s to the output
2643 if (sleepTime == 0) {
2644 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2645 sleepTime = activeSleepTime >> sleepTimeShift;
2646 if (sleepTime < kMinThreadSleepTimeUs) {
2647 sleepTime = kMinThreadSleepTimeUs;
2648 }
2649 // reduce sleep time in case of consecutive application underruns to avoid
2650 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2651 // duration we would end up writing less data than needed by the audio HAL if
2652 // the condition persists.
2653 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2654 sleepTimeShift++;
2655 }
2656 } else {
2657 sleepTime = idleSleepTime;
2658 }
2659 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002660 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002661 sleepTime = 0;
2662 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2663 "anticipated start");
2664 }
2665 // TODO add standby time extension fct of effect tail
2666}
2667
2668// prepareTracks_l() must be called with ThreadBase::mLock held
2669AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2670 Vector< sp<Track> > *tracksToRemove)
2671{
2672
2673 mixer_state mixerStatus = MIXER_IDLE;
2674 // find out which tracks need to be processed
2675 size_t count = mActiveTracks.size();
2676 size_t mixedTracks = 0;
2677 size_t tracksWithEffect = 0;
2678 // counts only _active_ fast tracks
2679 size_t fastTracks = 0;
2680 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2681
2682 float masterVolume = mMasterVolume;
2683 bool masterMute = mMasterMute;
2684
2685 if (masterMute) {
2686 masterVolume = 0;
2687 }
2688 // Delegate master volume control to effect in output mix effect chain if needed
2689 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2690 if (chain != 0) {
2691 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2692 chain->setVolume_l(&v, &v);
2693 masterVolume = (float)((v + (1 << 23)) >> 24);
2694 chain.clear();
2695 }
2696
2697 // prepare a new state to push
2698 FastMixerStateQueue *sq = NULL;
2699 FastMixerState *state = NULL;
2700 bool didModify = false;
2701 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2702 if (mFastMixer != NULL) {
2703 sq = mFastMixer->sq();
2704 state = sq->begin();
2705 }
2706
2707 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002708 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002709 if (t == 0) {
2710 continue;
2711 }
2712
2713 // this const just means the local variable doesn't change
2714 Track* const track = t.get();
2715
2716 // process fast tracks
2717 if (track->isFastTrack()) {
2718
2719 // It's theoretically possible (though unlikely) for a fast track to be created
2720 // and then removed within the same normal mix cycle. This is not a problem, as
2721 // the track never becomes active so it's fast mixer slot is never touched.
2722 // The converse, of removing an (active) track and then creating a new track
2723 // at the identical fast mixer slot within the same normal mix cycle,
2724 // is impossible because the slot isn't marked available until the end of each cycle.
2725 int j = track->mFastIndex;
2726 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2727 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2728 FastTrack *fastTrack = &state->mFastTracks[j];
2729
2730 // Determine whether the track is currently in underrun condition,
2731 // and whether it had a recent underrun.
2732 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2733 FastTrackUnderruns underruns = ftDump->mUnderruns;
2734 uint32_t recentFull = (underruns.mBitFields.mFull -
2735 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2736 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2737 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2738 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2739 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2740 uint32_t recentUnderruns = recentPartial + recentEmpty;
2741 track->mObservedUnderruns = underruns;
2742 // don't count underruns that occur while stopping or pausing
2743 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002744 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2745 recentUnderruns > 0) {
2746 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2747 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002748 }
2749
2750 // This is similar to the state machine for normal tracks,
2751 // with a few modifications for fast tracks.
2752 bool isActive = true;
2753 switch (track->mState) {
2754 case TrackBase::STOPPING_1:
2755 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002756 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002757 track->mState = TrackBase::STOPPING_2;
2758 }
2759 break;
2760 case TrackBase::PAUSING:
2761 // ramp down is not yet implemented
2762 track->setPaused();
2763 break;
2764 case TrackBase::RESUMING:
2765 // ramp up is not yet implemented
2766 track->mState = TrackBase::ACTIVE;
2767 break;
2768 case TrackBase::ACTIVE:
2769 if (recentFull > 0 || recentPartial > 0) {
2770 // track has provided at least some frames recently: reset retry count
2771 track->mRetryCount = kMaxTrackRetries;
2772 }
2773 if (recentUnderruns == 0) {
2774 // no recent underruns: stay active
2775 break;
2776 }
2777 // there has recently been an underrun of some kind
2778 if (track->sharedBuffer() == 0) {
2779 // were any of the recent underruns "empty" (no frames available)?
2780 if (recentEmpty == 0) {
2781 // no, then ignore the partial underruns as they are allowed indefinitely
2782 break;
2783 }
2784 // there has recently been an "empty" underrun: decrement the retry counter
2785 if (--(track->mRetryCount) > 0) {
2786 break;
2787 }
2788 // indicate to client process that the track was disabled because of underrun;
2789 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002790 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002791 // remove from active list, but state remains ACTIVE [confusing but true]
2792 isActive = false;
2793 break;
2794 }
2795 // fall through
2796 case TrackBase::STOPPING_2:
2797 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002798 case TrackBase::STOPPED:
2799 case TrackBase::FLUSHED: // flush() while active
2800 // Check for presentation complete if track is inactive
2801 // We have consumed all the buffers of this track.
2802 // This would be incomplete if we auto-paused on underrun
2803 {
2804 size_t audioHALFrames =
2805 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2806 size_t framesWritten = mBytesWritten / mFrameSize;
2807 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2808 // track stays in active list until presentation is complete
2809 break;
2810 }
2811 }
2812 if (track->isStopping_2()) {
2813 track->mState = TrackBase::STOPPED;
2814 }
2815 if (track->isStopped()) {
2816 // Can't reset directly, as fast mixer is still polling this track
2817 // track->reset();
2818 // So instead mark this track as needing to be reset after push with ack
2819 resetMask |= 1 << i;
2820 }
2821 isActive = false;
2822 break;
2823 case TrackBase::IDLE:
2824 default:
2825 LOG_FATAL("unexpected track state %d", track->mState);
2826 }
2827
2828 if (isActive) {
2829 // was it previously inactive?
2830 if (!(state->mTrackMask & (1 << j))) {
2831 ExtendedAudioBufferProvider *eabp = track;
2832 VolumeProvider *vp = track;
2833 fastTrack->mBufferProvider = eabp;
2834 fastTrack->mVolumeProvider = vp;
2835 fastTrack->mSampleRate = track->mSampleRate;
2836 fastTrack->mChannelMask = track->mChannelMask;
2837 fastTrack->mGeneration++;
2838 state->mTrackMask |= 1 << j;
2839 didModify = true;
2840 // no acknowledgement required for newly active tracks
2841 }
2842 // cache the combined master volume and stream type volume for fast mixer; this
2843 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002844 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002845 ++fastTracks;
2846 } else {
2847 // was it previously active?
2848 if (state->mTrackMask & (1 << j)) {
2849 fastTrack->mBufferProvider = NULL;
2850 fastTrack->mGeneration++;
2851 state->mTrackMask &= ~(1 << j);
2852 didModify = true;
2853 // If any fast tracks were removed, we must wait for acknowledgement
2854 // because we're about to decrement the last sp<> on those tracks.
2855 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2856 } else {
2857 LOG_FATAL("fast track %d should have been active", j);
2858 }
2859 tracksToRemove->add(track);
2860 // Avoids a misleading display in dumpsys
2861 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2862 }
2863 continue;
2864 }
2865
2866 { // local variable scope to avoid goto warning
2867
2868 audio_track_cblk_t* cblk = track->cblk();
2869
2870 // The first time a track is added we wait
2871 // for all its buffers to be filled before processing it
2872 int name = track->name();
2873 // make sure that we have enough frames to mix one full buffer.
2874 // enforce this condition only once to enable draining the buffer in case the client
2875 // app does not call stop() and relies on underrun to stop:
2876 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2877 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002878 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002879 uint32_t sr = track->sampleRate();
2880 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002881 desiredFrames = mNormalFrameCount;
2882 } else {
2883 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002884 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002885 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002886 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002887 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2888 // the minimum track buffer size is normally twice the number of frames necessary
2889 // to fill one buffer and the resampler should not leave more than one buffer worth
2890 // of unreleased frames after each pass, but just in case...
2891 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2892 }
Eric Laurent81784c32012-11-19 14:55:58 -08002893 uint32_t minFrames = 1;
2894 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2895 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002896 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002897 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002898 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2899 size_t framesReady;
2900 if (track->sharedBuffer() == 0) {
2901 framesReady = track->framesReady();
2902 } else if (track->isStopped()) {
2903 framesReady = 0;
2904 } else {
2905 framesReady = 1;
2906 }
2907 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002908 !track->isPaused() && !track->isTerminated())
2909 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002910 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002911
2912 mixedTracks++;
2913
2914 // track->mainBuffer() != mMixBuffer means there is an effect chain
2915 // connected to the track
2916 chain.clear();
2917 if (track->mainBuffer() != mMixBuffer) {
2918 chain = getEffectChain_l(track->sessionId());
2919 // Delegate volume control to effect in track effect chain if needed
2920 if (chain != 0) {
2921 tracksWithEffect++;
2922 } else {
2923 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2924 "session %d",
2925 name, track->sessionId());
2926 }
2927 }
2928
2929
2930 int param = AudioMixer::VOLUME;
2931 if (track->mFillingUpStatus == Track::FS_FILLED) {
2932 // no ramp for the first volume setting
2933 track->mFillingUpStatus = Track::FS_ACTIVE;
2934 if (track->mState == TrackBase::RESUMING) {
2935 track->mState = TrackBase::ACTIVE;
2936 param = AudioMixer::RAMP_VOLUME;
2937 }
2938 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002939 // FIXME should not make a decision based on mServer
2940 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002941 // If the track is stopped before the first frame was mixed,
2942 // do not apply ramp
2943 param = AudioMixer::RAMP_VOLUME;
2944 }
2945
2946 // compute volume for this track
2947 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08002948 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08002949 vl = vr = va = 0;
2950 if (track->isPausing()) {
2951 track->setPaused();
2952 }
2953 } else {
2954
2955 // read original volumes with volume control
2956 float typeVolume = mStreamTypes[track->streamType()].volume;
2957 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002958 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08002959 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08002960 vl = vlr & 0xFFFF;
2961 vr = vlr >> 16;
2962 // track volumes come from shared memory, so can't be trusted and must be clamped
2963 if (vl > MAX_GAIN_INT) {
2964 ALOGV("Track left volume out of range: %04X", vl);
2965 vl = MAX_GAIN_INT;
2966 }
2967 if (vr > MAX_GAIN_INT) {
2968 ALOGV("Track right volume out of range: %04X", vr);
2969 vr = MAX_GAIN_INT;
2970 }
2971 // now apply the master volume and stream type volume
2972 vl = (uint32_t)(v * vl) << 12;
2973 vr = (uint32_t)(v * vr) << 12;
2974 // assuming master volume and stream type volume each go up to 1.0,
2975 // vl and vr are now in 8.24 format
2976
Glenn Kastene3aa6592012-12-04 12:22:46 -08002977 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08002978 // send level comes from shared memory and so may be corrupt
2979 if (sendLevel > MAX_GAIN_INT) {
2980 ALOGV("Track send level out of range: %04X", sendLevel);
2981 sendLevel = MAX_GAIN_INT;
2982 }
2983 va = (uint32_t)(v * sendLevel);
2984 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985
Eric Laurent81784c32012-11-19 14:55:58 -08002986 // Delegate volume control to effect in track effect chain if needed
2987 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2988 // Do not ramp volume if volume is controlled by effect
2989 param = AudioMixer::VOLUME;
2990 track->mHasVolumeController = true;
2991 } else {
2992 // force no volume ramp when volume controller was just disabled or removed
2993 // from effect chain to avoid volume spike
2994 if (track->mHasVolumeController) {
2995 param = AudioMixer::VOLUME;
2996 }
2997 track->mHasVolumeController = false;
2998 }
2999
3000 // Convert volumes from 8.24 to 4.12 format
3001 // This additional clamping is needed in case chain->setVolume_l() overshot
3002 vl = (vl + (1 << 11)) >> 12;
3003 if (vl > MAX_GAIN_INT) {
3004 vl = MAX_GAIN_INT;
3005 }
3006 vr = (vr + (1 << 11)) >> 12;
3007 if (vr > MAX_GAIN_INT) {
3008 vr = MAX_GAIN_INT;
3009 }
3010
3011 if (va > MAX_GAIN_INT) {
3012 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3013 }
3014
3015 // XXX: these things DON'T need to be done each time
3016 mAudioMixer->setBufferProvider(name, track);
3017 mAudioMixer->enable(name);
3018
3019 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3020 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3021 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3022 mAudioMixer->setParameter(
3023 name,
3024 AudioMixer::TRACK,
3025 AudioMixer::FORMAT, (void *)track->format());
3026 mAudioMixer->setParameter(
3027 name,
3028 AudioMixer::TRACK,
3029 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003030 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3031 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003032 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003033 if (reqSampleRate == 0) {
3034 reqSampleRate = mSampleRate;
3035 } else if (reqSampleRate > maxSampleRate) {
3036 reqSampleRate = maxSampleRate;
3037 }
Eric Laurent81784c32012-11-19 14:55:58 -08003038 mAudioMixer->setParameter(
3039 name,
3040 AudioMixer::RESAMPLE,
3041 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003042 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003043 mAudioMixer->setParameter(
3044 name,
3045 AudioMixer::TRACK,
3046 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3047 mAudioMixer->setParameter(
3048 name,
3049 AudioMixer::TRACK,
3050 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3051
3052 // reset retry count
3053 track->mRetryCount = kMaxTrackRetries;
3054
3055 // If one track is ready, set the mixer ready if:
3056 // - the mixer was not ready during previous round OR
3057 // - no other track is not ready
3058 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3059 mixerStatus != MIXER_TRACKS_ENABLED) {
3060 mixerStatus = MIXER_TRACKS_READY;
3061 }
3062 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003063 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003064 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003065 }
Eric Laurent81784c32012-11-19 14:55:58 -08003066 // clear effect chain input buffer if an active track underruns to avoid sending
3067 // previous audio buffer again to effects
3068 chain = getEffectChain_l(track->sessionId());
3069 if (chain != 0) {
3070 chain->clearInputBuffer();
3071 }
3072
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003073 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003074 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3075 track->isStopped() || track->isPaused()) {
3076 // We have consumed all the buffers of this track.
3077 // Remove it from the list of active tracks.
3078 // TODO: use actual buffer filling status instead of latency when available from
3079 // audio HAL
3080 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3081 size_t framesWritten = mBytesWritten / mFrameSize;
3082 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3083 if (track->isStopped()) {
3084 track->reset();
3085 }
3086 tracksToRemove->add(track);
3087 }
3088 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003089 // No buffers for this track. Give it a few chances to
3090 // fill a buffer, then remove it from active list.
3091 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003092 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003093 tracksToRemove->add(track);
3094 // indicate to client process that the track was disabled because of underrun;
3095 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003096 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003097 // If one track is not ready, mark the mixer also not ready if:
3098 // - the mixer was ready during previous round OR
3099 // - no other track is ready
3100 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3101 mixerStatus != MIXER_TRACKS_READY) {
3102 mixerStatus = MIXER_TRACKS_ENABLED;
3103 }
3104 }
3105 mAudioMixer->disable(name);
3106 }
3107
3108 } // local variable scope to avoid goto warning
3109track_is_ready: ;
3110
3111 }
3112
3113 // Push the new FastMixer state if necessary
3114 bool pauseAudioWatchdog = false;
3115 if (didModify) {
3116 state->mFastTracksGen++;
3117 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3118 if (kUseFastMixer == FastMixer_Dynamic &&
3119 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3120 state->mCommand = FastMixerState::COLD_IDLE;
3121 state->mColdFutexAddr = &mFastMixerFutex;
3122 state->mColdGen++;
3123 mFastMixerFutex = 0;
3124 if (kUseFastMixer == FastMixer_Dynamic) {
3125 mNormalSink = mOutputSink;
3126 }
3127 // If we go into cold idle, need to wait for acknowledgement
3128 // so that fast mixer stops doing I/O.
3129 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3130 pauseAudioWatchdog = true;
3131 }
Eric Laurent81784c32012-11-19 14:55:58 -08003132 }
3133 if (sq != NULL) {
3134 sq->end(didModify);
3135 sq->push(block);
3136 }
3137#ifdef AUDIO_WATCHDOG
3138 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3139 mAudioWatchdog->pause();
3140 }
3141#endif
3142
3143 // Now perform the deferred reset on fast tracks that have stopped
3144 while (resetMask != 0) {
3145 size_t i = __builtin_ctz(resetMask);
3146 ALOG_ASSERT(i < count);
3147 resetMask &= ~(1 << i);
3148 sp<Track> t = mActiveTracks[i].promote();
3149 if (t == 0) {
3150 continue;
3151 }
3152 Track* track = t.get();
3153 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3154 track->reset();
3155 }
3156
3157 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003159
3160 // mix buffer must be cleared if all tracks are connected to an
3161 // effect chain as in this case the mixer will not write to
3162 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3164 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003165 // FIXME as a performance optimization, should remember previous zero status
3166 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3167 }
3168
3169 // if any fast tracks, then status is ready
3170 mMixerStatusIgnoringFastTracks = mixerStatus;
3171 if (fastTracks > 0) {
3172 mixerStatus = MIXER_TRACKS_READY;
3173 }
3174 return mixerStatus;
3175}
3176
3177// getTrackName_l() must be called with ThreadBase::mLock held
3178int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3179{
3180 return mAudioMixer->getTrackName(channelMask, sessionId);
3181}
3182
3183// deleteTrackName_l() must be called with ThreadBase::mLock held
3184void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3185{
3186 ALOGV("remove track (%d) and delete from mixer", name);
3187 mAudioMixer->deleteTrackName(name);
3188}
3189
3190// checkForNewParameters_l() must be called with ThreadBase::mLock held
3191bool AudioFlinger::MixerThread::checkForNewParameters_l()
3192{
3193 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3194 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3195 bool reconfig = false;
3196
3197 while (!mNewParameters.isEmpty()) {
3198
3199 if (mFastMixer != NULL) {
3200 FastMixerStateQueue *sq = mFastMixer->sq();
3201 FastMixerState *state = sq->begin();
3202 if (!(state->mCommand & FastMixerState::IDLE)) {
3203 previousCommand = state->mCommand;
3204 state->mCommand = FastMixerState::HOT_IDLE;
3205 sq->end();
3206 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3207 } else {
3208 sq->end(false /*didModify*/);
3209 }
3210 }
3211
3212 status_t status = NO_ERROR;
3213 String8 keyValuePair = mNewParameters[0];
3214 AudioParameter param = AudioParameter(keyValuePair);
3215 int value;
3216
3217 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3218 reconfig = true;
3219 }
3220 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3221 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3222 status = BAD_VALUE;
3223 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003224 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003225 reconfig = true;
3226 }
3227 }
3228 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003229 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003230 status = BAD_VALUE;
3231 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003232 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003233 reconfig = true;
3234 }
3235 }
3236 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3237 // do not accept frame count changes if tracks are open as the track buffer
3238 // size depends on frame count and correct behavior would not be guaranteed
3239 // if frame count is changed after track creation
3240 if (!mTracks.isEmpty()) {
3241 status = INVALID_OPERATION;
3242 } else {
3243 reconfig = true;
3244 }
3245 }
3246 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3247#ifdef ADD_BATTERY_DATA
3248 // when changing the audio output device, call addBatteryData to notify
3249 // the change
3250 if (mOutDevice != value) {
3251 uint32_t params = 0;
3252 // check whether speaker is on
3253 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3254 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3255 }
3256
3257 audio_devices_t deviceWithoutSpeaker
3258 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3259 // check if any other device (except speaker) is on
3260 if (value & deviceWithoutSpeaker ) {
3261 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3262 }
3263
3264 if (params != 0) {
3265 addBatteryData(params);
3266 }
3267 }
3268#endif
3269
3270 // forward device change to effects that have requested to be
3271 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003272 if (value != AUDIO_DEVICE_NONE) {
3273 mOutDevice = value;
3274 for (size_t i = 0; i < mEffectChains.size(); i++) {
3275 mEffectChains[i]->setDevice_l(mOutDevice);
3276 }
Eric Laurent81784c32012-11-19 14:55:58 -08003277 }
3278 }
3279
3280 if (status == NO_ERROR) {
3281 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3282 keyValuePair.string());
3283 if (!mStandby && status == INVALID_OPERATION) {
3284 mOutput->stream->common.standby(&mOutput->stream->common);
3285 mStandby = true;
3286 mBytesWritten = 0;
3287 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3288 keyValuePair.string());
3289 }
3290 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003291 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003292 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003293 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3294 for (size_t i = 0; i < mTracks.size() ; i++) {
3295 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3296 if (name < 0) {
3297 break;
3298 }
3299 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003300 }
3301 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3302 }
3303 }
3304
3305 mNewParameters.removeAt(0);
3306
3307 mParamStatus = status;
3308 mParamCond.signal();
3309 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3310 // already timed out waiting for the status and will never signal the condition.
3311 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3312 }
3313
3314 if (!(previousCommand & FastMixerState::IDLE)) {
3315 ALOG_ASSERT(mFastMixer != NULL);
3316 FastMixerStateQueue *sq = mFastMixer->sq();
3317 FastMixerState *state = sq->begin();
3318 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3319 state->mCommand = previousCommand;
3320 sq->end();
3321 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3322 }
3323
3324 return reconfig;
3325}
3326
3327
3328void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3329{
3330 const size_t SIZE = 256;
3331 char buffer[SIZE];
3332 String8 result;
3333
3334 PlaybackThread::dumpInternals(fd, args);
3335
3336 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3337 result.append(buffer);
3338 write(fd, result.string(), result.size());
3339
3340 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003341 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003342 copy.dump(fd);
3343
3344#ifdef STATE_QUEUE_DUMP
3345 // Similar for state queue
3346 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3347 observerCopy.dump(fd);
3348 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3349 mutatorCopy.dump(fd);
3350#endif
3351
Glenn Kasten46909e72013-02-26 09:20:22 -08003352#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003353 // Write the tee output to a .wav file
3354 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003355#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003356
3357#ifdef AUDIO_WATCHDOG
3358 if (mAudioWatchdog != 0) {
3359 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3360 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3361 wdCopy.dump(fd);
3362 }
3363#endif
3364}
3365
3366uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3367{
3368 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3369}
3370
3371uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3372{
3373 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3374}
3375
3376void AudioFlinger::MixerThread::cacheParameters_l()
3377{
3378 PlaybackThread::cacheParameters_l();
3379
3380 // FIXME: Relaxed timing because of a certain device that can't meet latency
3381 // Should be reduced to 2x after the vendor fixes the driver issue
3382 // increase threshold again due to low power audio mode. The way this warning
3383 // threshold is calculated and its usefulness should be reconsidered anyway.
3384 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3385}
3386
3387// ----------------------------------------------------------------------------
3388
3389AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3390 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3391 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3392 // mLeftVolFloat, mRightVolFloat
3393{
3394}
3395
Eric Laurentbfb1b832013-01-07 09:53:42 -08003396AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3397 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3398 ThreadBase::type_t type)
3399 : PlaybackThread(audioFlinger, output, id, device, type)
3400 // mLeftVolFloat, mRightVolFloat
3401{
3402}
3403
Eric Laurent81784c32012-11-19 14:55:58 -08003404AudioFlinger::DirectOutputThread::~DirectOutputThread()
3405{
3406}
3407
Eric Laurentbfb1b832013-01-07 09:53:42 -08003408void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3409{
3410 audio_track_cblk_t* cblk = track->cblk();
3411 float left, right;
3412
3413 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3414 left = right = 0;
3415 } else {
3416 float typeVolume = mStreamTypes[track->streamType()].volume;
3417 float v = mMasterVolume * typeVolume;
3418 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3419 uint32_t vlr = proxy->getVolumeLR();
3420 float v_clamped = v * (vlr & 0xFFFF);
3421 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3422 left = v_clamped/MAX_GAIN;
3423 v_clamped = v * (vlr >> 16);
3424 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3425 right = v_clamped/MAX_GAIN;
3426 }
3427
3428 if (lastTrack) {
3429 if (left != mLeftVolFloat || right != mRightVolFloat) {
3430 mLeftVolFloat = left;
3431 mRightVolFloat = right;
3432
3433 // Convert volumes from float to 8.24
3434 uint32_t vl = (uint32_t)(left * (1 << 24));
3435 uint32_t vr = (uint32_t)(right * (1 << 24));
3436
3437 // Delegate volume control to effect in track effect chain if needed
3438 // only one effect chain can be present on DirectOutputThread, so if
3439 // there is one, the track is connected to it
3440 if (!mEffectChains.isEmpty()) {
3441 mEffectChains[0]->setVolume_l(&vl, &vr);
3442 left = (float)vl / (1 << 24);
3443 right = (float)vr / (1 << 24);
3444 }
3445 if (mOutput->stream->set_volume) {
3446 mOutput->stream->set_volume(mOutput->stream, left, right);
3447 }
3448 }
3449 }
3450}
3451
3452
Eric Laurent81784c32012-11-19 14:55:58 -08003453AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3454 Vector< sp<Track> > *tracksToRemove
3455)
3456{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003457 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003458 mixer_state mixerStatus = MIXER_IDLE;
3459
3460 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003461 for (size_t i = 0; i < count; i++) {
3462 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003463 // The track died recently
3464 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003465 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
3467
3468 Track* const track = t.get();
3469 audio_track_cblk_t* cblk = track->cblk();
3470
3471 // The first time a track is added we wait
3472 // for all its buffers to be filled before processing it
3473 uint32_t minFrames;
3474 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3475 minFrames = mNormalFrameCount;
3476 } else {
3477 minFrames = 1;
3478 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003479 // Only consider last track started for volume and mixer state control.
3480 // This is the last entry in mActiveTracks unless a track underruns.
3481 // As we only care about the transition phase between two tracks on a
3482 // direct output, it is not a problem to ignore the underrun case.
3483 bool last = (i == (count - 1));
3484
Eric Laurent81784c32012-11-19 14:55:58 -08003485 if ((track->framesReady() >= minFrames) && track->isReady() &&
3486 !track->isPaused() && !track->isTerminated())
3487 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003488 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003489
3490 if (track->mFillingUpStatus == Track::FS_FILLED) {
3491 track->mFillingUpStatus = Track::FS_ACTIVE;
3492 mLeftVolFloat = mRightVolFloat = 0;
3493 if (track->mState == TrackBase::RESUMING) {
3494 track->mState = TrackBase::ACTIVE;
3495 }
3496 }
3497
3498 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003499 processVolume_l(track, last);
3500 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003501 // reset retry count
3502 track->mRetryCount = kMaxTrackRetriesDirect;
3503 mActiveTrack = t;
3504 mixerStatus = MIXER_TRACKS_READY;
3505 }
Eric Laurent81784c32012-11-19 14:55:58 -08003506 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003507 // clear effect chain input buffer if the last active track started underruns
3508 // to avoid sending previous audio buffer again to effects
3509 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003510 mEffectChains[0]->clearInputBuffer();
3511 }
3512
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003513 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003514 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3515 track->isStopped() || track->isPaused()) {
3516 // We have consumed all the buffers of this track.
3517 // Remove it from the list of active tracks.
3518 // TODO: implement behavior for compressed audio
3519 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3520 size_t framesWritten = mBytesWritten / mFrameSize;
3521 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3522 if (track->isStopped()) {
3523 track->reset();
3524 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003525 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003526 }
3527 } else {
3528 // No buffers for this track. Give it a few chances to
3529 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003530 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003531 if (--(track->mRetryCount) <= 0) {
3532 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003533 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003534 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003535 mixerStatus = MIXER_TRACKS_ENABLED;
3536 }
3537 }
3538 }
3539 }
3540
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003542 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003543
3544 return mixerStatus;
3545}
3546
3547void AudioFlinger::DirectOutputThread::threadLoop_mix()
3548{
Eric Laurent81784c32012-11-19 14:55:58 -08003549 size_t frameCount = mFrameCount;
3550 int8_t *curBuf = (int8_t *)mMixBuffer;
3551 // output audio to hardware
3552 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003553 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003554 buffer.frameCount = frameCount;
3555 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003556 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003557 memset(curBuf, 0, frameCount * mFrameSize);
3558 break;
3559 }
3560 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3561 frameCount -= buffer.frameCount;
3562 curBuf += buffer.frameCount * mFrameSize;
3563 mActiveTrack->releaseBuffer(&buffer);
3564 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003566 sleepTime = 0;
3567 standbyTime = systemTime() + standbyDelay;
3568 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003569}
3570
3571void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3572{
3573 if (sleepTime == 0) {
3574 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3575 sleepTime = activeSleepTime;
3576 } else {
3577 sleepTime = idleSleepTime;
3578 }
3579 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3580 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3581 sleepTime = 0;
3582 }
3583}
3584
3585// getTrackName_l() must be called with ThreadBase::mLock held
3586int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3587 int sessionId)
3588{
3589 return 0;
3590}
3591
3592// deleteTrackName_l() must be called with ThreadBase::mLock held
3593void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3594{
3595}
3596
3597// checkForNewParameters_l() must be called with ThreadBase::mLock held
3598bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3599{
3600 bool reconfig = false;
3601
3602 while (!mNewParameters.isEmpty()) {
3603 status_t status = NO_ERROR;
3604 String8 keyValuePair = mNewParameters[0];
3605 AudioParameter param = AudioParameter(keyValuePair);
3606 int value;
3607
3608 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3609 // do not accept frame count changes if tracks are open as the track buffer
3610 // size depends on frame count and correct behavior would not be garantied
3611 // if frame count is changed after track creation
3612 if (!mTracks.isEmpty()) {
3613 status = INVALID_OPERATION;
3614 } else {
3615 reconfig = true;
3616 }
3617 }
3618 if (status == NO_ERROR) {
3619 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3620 keyValuePair.string());
3621 if (!mStandby && status == INVALID_OPERATION) {
3622 mOutput->stream->common.standby(&mOutput->stream->common);
3623 mStandby = true;
3624 mBytesWritten = 0;
3625 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3626 keyValuePair.string());
3627 }
3628 if (status == NO_ERROR && reconfig) {
3629 readOutputParameters();
3630 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3631 }
3632 }
3633
3634 mNewParameters.removeAt(0);
3635
3636 mParamStatus = status;
3637 mParamCond.signal();
3638 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3639 // already timed out waiting for the status and will never signal the condition.
3640 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3641 }
3642 return reconfig;
3643}
3644
3645uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3646{
3647 uint32_t time;
3648 if (audio_is_linear_pcm(mFormat)) {
3649 time = PlaybackThread::activeSleepTimeUs();
3650 } else {
3651 time = 10000;
3652 }
3653 return time;
3654}
3655
3656uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3657{
3658 uint32_t time;
3659 if (audio_is_linear_pcm(mFormat)) {
3660 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3661 } else {
3662 time = 10000;
3663 }
3664 return time;
3665}
3666
3667uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3668{
3669 uint32_t time;
3670 if (audio_is_linear_pcm(mFormat)) {
3671 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3672 } else {
3673 time = 10000;
3674 }
3675 return time;
3676}
3677
3678void AudioFlinger::DirectOutputThread::cacheParameters_l()
3679{
3680 PlaybackThread::cacheParameters_l();
3681
3682 // use shorter standby delay as on normal output to release
3683 // hardware resources as soon as possible
3684 standbyDelay = microseconds(activeSleepTime*2);
3685}
3686
3687// ----------------------------------------------------------------------------
3688
Eric Laurentbfb1b832013-01-07 09:53:42 -08003689AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3690 const sp<AudioFlinger::OffloadThread>& offloadThread)
3691 : Thread(false /*canCallJava*/),
3692 mOffloadThread(offloadThread),
3693 mWriteBlocked(false),
3694 mDraining(false)
3695{
3696}
3697
3698AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3699{
3700}
3701
3702void AudioFlinger::AsyncCallbackThread::onFirstRef()
3703{
3704 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3705}
3706
3707bool AudioFlinger::AsyncCallbackThread::threadLoop()
3708{
3709 while (!exitPending()) {
3710 bool writeBlocked;
3711 bool draining;
3712
3713 {
3714 Mutex::Autolock _l(mLock);
3715 mWaitWorkCV.wait(mLock);
3716 if (exitPending()) {
3717 break;
3718 }
3719 writeBlocked = mWriteBlocked;
3720 draining = mDraining;
3721 ALOGV("AsyncCallbackThread mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3722 }
3723 {
3724 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3725 if (offloadThread != 0) {
3726 if (writeBlocked == false) {
3727 offloadThread->setWriteBlocked(false);
3728 }
3729 if (draining == false) {
3730 offloadThread->setDraining(false);
3731 }
3732 }
3733 }
3734 }
3735 return false;
3736}
3737
3738void AudioFlinger::AsyncCallbackThread::exit()
3739{
3740 ALOGV("AsyncCallbackThread::exit");
3741 Mutex::Autolock _l(mLock);
3742 requestExit();
3743 mWaitWorkCV.broadcast();
3744}
3745
3746void AudioFlinger::AsyncCallbackThread::setWriteBlocked(bool value)
3747{
3748 Mutex::Autolock _l(mLock);
3749 mWriteBlocked = value;
3750 if (!value) {
3751 mWaitWorkCV.signal();
3752 }
3753}
3754
3755void AudioFlinger::AsyncCallbackThread::setDraining(bool value)
3756{
3757 Mutex::Autolock _l(mLock);
3758 mDraining = value;
3759 if (!value) {
3760 mWaitWorkCV.signal();
3761 }
3762}
3763
3764
3765// ----------------------------------------------------------------------------
3766AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3767 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3768 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3769 mHwPaused(false),
3770 mPausedBytesRemaining(0)
3771{
3772 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3773}
3774
3775AudioFlinger::OffloadThread::~OffloadThread()
3776{
3777 mPreviousTrack.clear();
3778}
3779
3780void AudioFlinger::OffloadThread::threadLoop_exit()
3781{
3782 if (mFlushPending || mHwPaused) {
3783 // If a flush is pending or track was paused, just discard buffered data
3784 flushHw_l();
3785 } else {
3786 mMixerStatus = MIXER_DRAIN_ALL;
3787 threadLoop_drain();
3788 }
3789 mCallbackThread->exit();
3790 PlaybackThread::threadLoop_exit();
3791}
3792
3793AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3794 Vector< sp<Track> > *tracksToRemove
3795)
3796{
3797 ALOGV("OffloadThread::prepareTracks_l");
3798 size_t count = mActiveTracks.size();
3799
3800 mixer_state mixerStatus = MIXER_IDLE;
3801 if (mFlushPending) {
3802 flushHw_l();
3803 mFlushPending = false;
3804 }
3805 // find out which tracks need to be processed
3806 for (size_t i = 0; i < count; i++) {
3807 sp<Track> t = mActiveTracks[i].promote();
3808 // The track died recently
3809 if (t == 0) {
3810 continue;
3811 }
3812 Track* const track = t.get();
3813 audio_track_cblk_t* cblk = track->cblk();
3814 if (mPreviousTrack != NULL) {
3815 if (t != mPreviousTrack) {
3816 // Flush any data still being written from last track
3817 mBytesRemaining = 0;
3818 if (mPausedBytesRemaining) {
3819 // Last track was paused so we also need to flush saved
3820 // mixbuffer state and invalidate track so that it will
3821 // re-submit that unwritten data when it is next resumed
3822 mPausedBytesRemaining = 0;
3823 // Invalidate is a bit drastic - would be more efficient
3824 // to have a flag to tell client that some of the
3825 // previously written data was lost
3826 mPreviousTrack->invalidate();
3827 }
3828 }
3829 }
3830 mPreviousTrack = t;
3831 bool last = (i == (count - 1));
3832 if (track->isPausing()) {
3833 track->setPaused();
3834 if (last) {
3835 if (!mHwPaused) {
3836 mOutput->stream->pause(mOutput->stream);
3837 mHwPaused = true;
3838 }
3839 // If we were part way through writing the mixbuffer to
3840 // the HAL we must save this until we resume
3841 // BUG - this will be wrong if a different track is made active,
3842 // in that case we want to discard the pending data in the
3843 // mixbuffer and tell the client to present it again when the
3844 // track is resumed
3845 mPausedWriteLength = mCurrentWriteLength;
3846 mPausedBytesRemaining = mBytesRemaining;
3847 mBytesRemaining = 0; // stop writing
3848 }
3849 tracksToRemove->add(track);
3850 } else if (track->framesReady() && track->isReady() &&
3851 !track->isPaused() && !track->isTerminated()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003852 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003853 if (track->mFillingUpStatus == Track::FS_FILLED) {
3854 track->mFillingUpStatus = Track::FS_ACTIVE;
3855 mLeftVolFloat = mRightVolFloat = 0;
3856 if (track->mState == TrackBase::RESUMING) {
Glenn Kastenfa319e62013-07-29 17:17:38 -07003857 if (mPausedBytesRemaining) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003858 // Need to continue write that was interrupted
3859 mCurrentWriteLength = mPausedWriteLength;
3860 mBytesRemaining = mPausedBytesRemaining;
3861 mPausedBytesRemaining = 0;
3862 }
3863 track->mState = TrackBase::ACTIVE;
3864 }
3865 }
3866
3867 if (last) {
3868 if (mHwPaused) {
3869 mOutput->stream->resume(mOutput->stream);
3870 mHwPaused = false;
3871 // threadLoop_mix() will handle the case that we need to
3872 // resume an interrupted write
3873 }
3874 // reset retry count
3875 track->mRetryCount = kMaxTrackRetriesOffload;
3876 mActiveTrack = t;
3877 mixerStatus = MIXER_TRACKS_READY;
3878 }
3879 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003880 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003881 if (track->isStopping_1()) {
3882 // Hardware buffer can hold a large amount of audio so we must
3883 // wait for all current track's data to drain before we say
3884 // that the track is stopped.
3885 if (mBytesRemaining == 0) {
3886 // Only start draining when all data in mixbuffer
3887 // has been written
3888 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3889 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3890 sleepTime = 0;
3891 standbyTime = systemTime() + standbyDelay;
3892 if (last) {
3893 mixerStatus = MIXER_DRAIN_TRACK;
3894 if (mHwPaused) {
3895 // It is possible to move from PAUSED to STOPPING_1 without
3896 // a resume so we must ensure hardware is running
3897 mOutput->stream->resume(mOutput->stream);
3898 mHwPaused = false;
3899 }
3900 }
3901 }
3902 } else if (track->isStopping_2()) {
3903 // Drain has completed, signal presentation complete
3904 if (!mDraining || !last) {
3905 track->mState = TrackBase::STOPPED;
3906 size_t audioHALFrames =
3907 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3908 size_t framesWritten =
3909 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3910 track->presentationComplete(framesWritten, audioHALFrames);
3911 track->reset();
3912 tracksToRemove->add(track);
3913 }
3914 } else {
3915 // No buffers for this track. Give it a few chances to
3916 // fill a buffer, then remove it from active list.
3917 if (--(track->mRetryCount) <= 0) {
3918 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3919 track->name());
3920 tracksToRemove->add(track);
3921 } else if (last){
3922 mixerStatus = MIXER_TRACKS_ENABLED;
3923 }
3924 }
3925 }
3926 // compute volume for this track
3927 processVolume_l(track, last);
3928 }
3929 // remove all the tracks that need to be...
3930 removeTracks_l(*tracksToRemove);
3931
3932 return mixerStatus;
3933}
3934
3935void AudioFlinger::OffloadThread::flushOutput_l()
3936{
3937 mFlushPending = true;
3938}
3939
3940// must be called with thread mutex locked
3941bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
3942{
3943 ALOGV("waitingAsyncCallback_l mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3944 if (mUseAsyncWrite && (mWriteBlocked || mDraining)) {
3945 return true;
3946 }
3947 return false;
3948}
3949
3950// must be called with thread mutex locked
3951bool AudioFlinger::OffloadThread::shouldStandby_l()
3952{
3953 bool TrackPaused = false;
3954
3955 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
3956 // after a timeout and we will enter standby then.
3957 if (mTracks.size() > 0) {
3958 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
3959 }
3960
3961 return !mStandby && !TrackPaused;
3962}
3963
3964
3965bool AudioFlinger::OffloadThread::waitingAsyncCallback()
3966{
3967 Mutex::Autolock _l(mLock);
3968 return waitingAsyncCallback_l();
3969}
3970
3971void AudioFlinger::OffloadThread::flushHw_l()
3972{
3973 mOutput->stream->flush(mOutput->stream);
3974 // Flush anything still waiting in the mixbuffer
3975 mCurrentWriteLength = 0;
3976 mBytesRemaining = 0;
3977 mPausedWriteLength = 0;
3978 mPausedBytesRemaining = 0;
3979 if (mUseAsyncWrite) {
3980 mWriteBlocked = false;
3981 mDraining = false;
3982 ALOG_ASSERT(mCallbackThread != 0);
3983 mCallbackThread->setWriteBlocked(false);
3984 mCallbackThread->setDraining(false);
3985 }
3986}
3987
3988// ----------------------------------------------------------------------------
3989
Eric Laurent81784c32012-11-19 14:55:58 -08003990AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3991 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3992 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3993 DUPLICATING),
3994 mWaitTimeMs(UINT_MAX)
3995{
3996 addOutputTrack(mainThread);
3997}
3998
3999AudioFlinger::DuplicatingThread::~DuplicatingThread()
4000{
4001 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4002 mOutputTracks[i]->destroy();
4003 }
4004}
4005
4006void AudioFlinger::DuplicatingThread::threadLoop_mix()
4007{
4008 // mix buffers...
4009 if (outputsReady(outputTracks)) {
4010 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4011 } else {
4012 memset(mMixBuffer, 0, mixBufferSize);
4013 }
4014 sleepTime = 0;
4015 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004016 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004017 standbyTime = systemTime() + standbyDelay;
4018}
4019
4020void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4021{
4022 if (sleepTime == 0) {
4023 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4024 sleepTime = activeSleepTime;
4025 } else {
4026 sleepTime = idleSleepTime;
4027 }
4028 } else if (mBytesWritten != 0) {
4029 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4030 writeFrames = mNormalFrameCount;
4031 memset(mMixBuffer, 0, mixBufferSize);
4032 } else {
4033 // flush remaining overflow buffers in output tracks
4034 writeFrames = 0;
4035 }
4036 sleepTime = 0;
4037 }
4038}
4039
Eric Laurentbfb1b832013-01-07 09:53:42 -08004040ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004041{
4042 for (size_t i = 0; i < outputTracks.size(); i++) {
4043 outputTracks[i]->write(mMixBuffer, writeFrames);
4044 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004046}
4047
4048void AudioFlinger::DuplicatingThread::threadLoop_standby()
4049{
4050 // DuplicatingThread implements standby by stopping all tracks
4051 for (size_t i = 0; i < outputTracks.size(); i++) {
4052 outputTracks[i]->stop();
4053 }
4054}
4055
4056void AudioFlinger::DuplicatingThread::saveOutputTracks()
4057{
4058 outputTracks = mOutputTracks;
4059}
4060
4061void AudioFlinger::DuplicatingThread::clearOutputTracks()
4062{
4063 outputTracks.clear();
4064}
4065
4066void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4067{
4068 Mutex::Autolock _l(mLock);
4069 // FIXME explain this formula
4070 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4071 OutputTrack *outputTrack = new OutputTrack(thread,
4072 this,
4073 mSampleRate,
4074 mFormat,
4075 mChannelMask,
4076 frameCount);
4077 if (outputTrack->cblk() != NULL) {
4078 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4079 mOutputTracks.add(outputTrack);
4080 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4081 updateWaitTime_l();
4082 }
4083}
4084
4085void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4086{
4087 Mutex::Autolock _l(mLock);
4088 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4089 if (mOutputTracks[i]->thread() == thread) {
4090 mOutputTracks[i]->destroy();
4091 mOutputTracks.removeAt(i);
4092 updateWaitTime_l();
4093 return;
4094 }
4095 }
4096 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4097}
4098
4099// caller must hold mLock
4100void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4101{
4102 mWaitTimeMs = UINT_MAX;
4103 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4104 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4105 if (strong != 0) {
4106 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4107 if (waitTimeMs < mWaitTimeMs) {
4108 mWaitTimeMs = waitTimeMs;
4109 }
4110 }
4111 }
4112}
4113
4114
4115bool AudioFlinger::DuplicatingThread::outputsReady(
4116 const SortedVector< sp<OutputTrack> > &outputTracks)
4117{
4118 for (size_t i = 0; i < outputTracks.size(); i++) {
4119 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4120 if (thread == 0) {
4121 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4122 outputTracks[i].get());
4123 return false;
4124 }
4125 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4126 // see note at standby() declaration
4127 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4128 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4129 thread.get());
4130 return false;
4131 }
4132 }
4133 return true;
4134}
4135
4136uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4137{
4138 return (mWaitTimeMs * 1000) / 2;
4139}
4140
4141void AudioFlinger::DuplicatingThread::cacheParameters_l()
4142{
4143 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4144 updateWaitTime_l();
4145
4146 MixerThread::cacheParameters_l();
4147}
4148
4149// ----------------------------------------------------------------------------
4150// Record
4151// ----------------------------------------------------------------------------
4152
4153AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4154 AudioStreamIn *input,
4155 uint32_t sampleRate,
4156 audio_channel_mask_t channelMask,
4157 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004158 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004159 audio_devices_t inDevice
4160#ifdef TEE_SINK
4161 , const sp<NBAIO_Sink>& teeSink
4162#endif
4163 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004164 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004165 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004166 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004167 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004168 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004169 // mBytesRead is only meaningful while active, and so is cleared in start()
4170 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004171#ifdef TEE_SINK
4172 , mTeeSink(teeSink)
4173#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004174{
4175 snprintf(mName, kNameLength, "AudioIn_%X", id);
4176
4177 readInputParameters();
4178
4179}
4180
4181
4182AudioFlinger::RecordThread::~RecordThread()
4183{
4184 delete[] mRsmpInBuffer;
4185 delete mResampler;
4186 delete[] mRsmpOutBuffer;
4187}
4188
4189void AudioFlinger::RecordThread::onFirstRef()
4190{
4191 run(mName, PRIORITY_URGENT_AUDIO);
4192}
4193
Eric Laurent81784c32012-11-19 14:55:58 -08004194bool AudioFlinger::RecordThread::threadLoop()
4195{
4196 AudioBufferProvider::Buffer buffer;
4197 sp<RecordTrack> activeTrack;
4198 Vector< sp<EffectChain> > effectChains;
4199
4200 nsecs_t lastWarning = 0;
4201
4202 inputStandBy();
4203 acquireWakeLock();
4204
4205 // used to verify we've read at least once before evaluating how many bytes were read
4206 bool readOnce = false;
4207
4208 // start recording
4209 while (!exitPending()) {
4210
4211 processConfigEvents();
4212
4213 { // scope for mLock
4214 Mutex::Autolock _l(mLock);
4215 checkForNewParameters_l();
4216 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4217 standby();
4218
4219 if (exitPending()) {
4220 break;
4221 }
4222
4223 releaseWakeLock_l();
4224 ALOGV("RecordThread: loop stopping");
4225 // go to sleep
4226 mWaitWorkCV.wait(mLock);
4227 ALOGV("RecordThread: loop starting");
4228 acquireWakeLock_l();
4229 continue;
4230 }
4231 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004232 if (mActiveTrack->isTerminated()) {
4233 removeTrack_l(mActiveTrack);
4234 mActiveTrack.clear();
Glenn Kasten2d944262013-08-13 13:54:08 -07004235 } else {
4236 switch (mActiveTrack->mState) {
4237 case TrackBase::PAUSING:
4238 standby();
Eric Laurent81784c32012-11-19 14:55:58 -08004239 mActiveTrack.clear();
4240 mStartStopCond.broadcast();
Glenn Kasten2d944262013-08-13 13:54:08 -07004241 break;
4242
4243 case TrackBase::RESUMING:
4244 if (mReqChannelCount != mActiveTrack->channelCount()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004245 mActiveTrack.clear();
Glenn Kasten2d944262013-08-13 13:54:08 -07004246 mStartStopCond.broadcast();
4247 } else if (readOnce) {
4248 // record start succeeds only if first read from audio input
4249 // succeeds
4250 if (mBytesRead >= 0) {
4251 mActiveTrack->mState = TrackBase::ACTIVE;
4252 } else {
4253 mActiveTrack.clear();
4254 }
4255 mStartStopCond.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08004256 }
Glenn Kasten2d944262013-08-13 13:54:08 -07004257 mStandby = false;
4258 break;
4259
4260 case TrackBase::ACTIVE:
4261 break;
4262
4263 case TrackBase::IDLE:
4264 break;
4265
4266 default:
4267 LOG_FATAL("Unexpected mActiveTrack->mState %d", mActiveTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004268 }
Glenn Kasten2d944262013-08-13 13:54:08 -07004269
Eric Laurent81784c32012-11-19 14:55:58 -08004270 }
4271 }
4272 lockEffectChains_l(effectChains);
4273 }
4274
4275 if (mActiveTrack != 0) {
4276 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4277 mActiveTrack->mState != TrackBase::RESUMING) {
4278 unlockEffectChains(effectChains);
4279 usleep(kRecordThreadSleepUs);
4280 continue;
4281 }
4282 for (size_t i = 0; i < effectChains.size(); i ++) {
4283 effectChains[i]->process_l();
4284 }
4285
4286 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004287 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004288 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004289 readOnce = true;
4290 size_t framesOut = buffer.frameCount;
4291 if (mResampler == NULL) {
4292 // no resampling
4293 while (framesOut) {
4294 size_t framesIn = mFrameCount - mRsmpInIndex;
Glenn Kasten34fca342013-08-13 09:48:14 -07004295 if (framesIn > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004296 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4297 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4298 mActiveTrack->mFrameSize;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004299 if (framesIn > framesOut) {
Eric Laurent81784c32012-11-19 14:55:58 -08004300 framesIn = framesOut;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07004301 }
Eric Laurent81784c32012-11-19 14:55:58 -08004302 mRsmpInIndex += framesIn;
4303 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004304 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004305 memcpy(dst, src, framesIn * mFrameSize);
4306 } else {
4307 if (mChannelCount == 1) {
4308 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4309 (int16_t *)src, framesIn);
4310 } else {
4311 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4312 (int16_t *)src, framesIn);
4313 }
4314 }
4315 }
Glenn Kasten34fca342013-08-13 09:48:14 -07004316 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
Eric Laurent81784c32012-11-19 14:55:58 -08004317 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004318 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004319 readInto = buffer.raw;
4320 framesOut = 0;
4321 } else {
4322 readInto = mRsmpInBuffer;
4323 mRsmpInIndex = 0;
4324 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004325 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004326 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004327 if (mBytesRead <= 0) {
4328 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4329 {
4330 ALOGE("Error reading audio input");
4331 // Force input into standby so that it tries to
4332 // recover at next read attempt
4333 inputStandBy();
4334 usleep(kRecordThreadSleepUs);
4335 }
4336 mRsmpInIndex = mFrameCount;
4337 framesOut = 0;
4338 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004339 }
4340#ifdef TEE_SINK
4341 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004342 (void) mTeeSink->write(readInto,
4343 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4344 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004345#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004346 }
4347 }
4348 } else {
4349 // resampling
4350
Glenn Kasten34af0262013-07-30 11:52:39 -07004351 // resampler accumulates, but we only have one source track
4352 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004353 // alter output frame count as if we were expecting stereo samples
4354 if (mChannelCount == 1 && mReqChannelCount == 1) {
4355 framesOut >>= 1;
4356 }
4357 mResampler->resample(mRsmpOutBuffer, framesOut,
4358 this /* AudioBufferProvider* */);
4359 // ditherAndClamp() works as long as all buffers returned by
4360 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4361 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004362 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004363 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4364 // the resampler always outputs stereo samples:
4365 // do post stereo to mono conversion
4366 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4367 framesOut);
4368 } else {
4369 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4370 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004371 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004372
4373 }
4374 if (mFramestoDrop == 0) {
4375 mActiveTrack->releaseBuffer(&buffer);
4376 } else {
4377 if (mFramestoDrop > 0) {
4378 mFramestoDrop -= buffer.frameCount;
4379 if (mFramestoDrop <= 0) {
4380 clearSyncStartEvent();
4381 }
4382 } else {
4383 mFramestoDrop += buffer.frameCount;
4384 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4385 mSyncStartEvent->isCancelled()) {
4386 ALOGW("Synced record %s, session %d, trigger session %d",
4387 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4388 mActiveTrack->sessionId(),
4389 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4390 clearSyncStartEvent();
4391 }
4392 }
4393 }
4394 mActiveTrack->clearOverflow();
4395 }
4396 // client isn't retrieving buffers fast enough
4397 else {
4398 if (!mActiveTrack->setOverflow()) {
4399 nsecs_t now = systemTime();
4400 if ((now - lastWarning) > kWarningThrottleNs) {
4401 ALOGW("RecordThread: buffer overflow");
4402 lastWarning = now;
4403 }
4404 }
4405 // Release the processor for a while before asking for a new buffer.
4406 // This will give the application more chance to read from the buffer and
4407 // clear the overflow.
4408 usleep(kRecordThreadSleepUs);
4409 }
4410 }
4411 // enable changes in effect chain
4412 unlockEffectChains(effectChains);
4413 effectChains.clear();
4414 }
4415
4416 standby();
4417
4418 {
4419 Mutex::Autolock _l(mLock);
4420 mActiveTrack.clear();
4421 mStartStopCond.broadcast();
4422 }
4423
4424 releaseWakeLock();
4425
4426 ALOGV("RecordThread %p exiting", this);
4427 return false;
4428}
4429
4430void AudioFlinger::RecordThread::standby()
4431{
4432 if (!mStandby) {
4433 inputStandBy();
4434 mStandby = true;
4435 }
4436}
4437
4438void AudioFlinger::RecordThread::inputStandBy()
4439{
4440 mInput->stream->common.standby(&mInput->stream->common);
4441}
4442
Glenn Kastene198c362013-08-13 09:13:36 -07004443sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004444 const sp<AudioFlinger::Client>& client,
4445 uint32_t sampleRate,
4446 audio_format_t format,
4447 audio_channel_mask_t channelMask,
4448 size_t frameCount,
4449 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004450 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004451 pid_t tid,
4452 status_t *status)
4453{
4454 sp<RecordTrack> track;
4455 status_t lStatus;
4456
4457 lStatus = initCheck();
4458 if (lStatus != NO_ERROR) {
4459 ALOGE("Audio driver not initialized.");
4460 goto Exit;
4461 }
4462
Glenn Kasten90e58b12013-07-31 16:16:02 -07004463 // client expresses a preference for FAST, but we get the final say
4464 if (*flags & IAudioFlinger::TRACK_FAST) {
4465 if (
4466 // use case: callback handler and frame count is default or at least as large as HAL
4467 (
4468 (tid != -1) &&
4469 ((frameCount == 0) ||
4470 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4471 ) &&
4472 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4473 // mono or stereo
4474 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4475 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4476 // hardware sample rate
4477 (sampleRate == mSampleRate) &&
4478 // record thread has an associated fast recorder
4479 hasFastRecorder()
4480 // FIXME test that RecordThread for this fast track has a capable output HAL
4481 // FIXME add a permission test also?
4482 ) {
4483 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4484 if (frameCount == 0) {
4485 frameCount = mFrameCount * kFastTrackMultiplier;
4486 }
4487 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4488 frameCount, mFrameCount);
4489 } else {
4490 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4491 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4492 "hasFastRecorder=%d tid=%d",
4493 frameCount, mFrameCount, format,
4494 audio_is_linear_pcm(format),
4495 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4496 *flags &= ~IAudioFlinger::TRACK_FAST;
4497 // For compatibility with AudioRecord calculation, buffer depth is forced
4498 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4499 // This is probably too conservative, but legacy application code may depend on it.
4500 // If you change this calculation, also review the start threshold which is related.
4501 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4502 size_t mNormalFrameCount = 2048; // FIXME
4503 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4504 if (minBufCount < 2) {
4505 minBufCount = 2;
4506 }
4507 size_t minFrameCount = mNormalFrameCount * minBufCount;
4508 if (frameCount < minFrameCount) {
4509 frameCount = minFrameCount;
4510 }
4511 }
4512 }
4513
Eric Laurent81784c32012-11-19 14:55:58 -08004514 // FIXME use flags and tid similar to createTrack_l()
4515
4516 { // scope for mLock
4517 Mutex::Autolock _l(mLock);
4518
4519 track = new RecordTrack(this, client, sampleRate,
4520 format, channelMask, frameCount, sessionId);
4521
Glenn Kasten03003332013-08-06 15:40:54 -07004522 lStatus = track->initCheck();
4523 if (lStatus != NO_ERROR) {
4524 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004525 goto Exit;
4526 }
4527 mTracks.add(track);
4528
4529 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4530 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4531 mAudioFlinger->btNrecIsOff();
4532 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4533 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004534
4535 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4536 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4537 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4538 // so ask activity manager to do this on our behalf
4539 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4540 }
Eric Laurent81784c32012-11-19 14:55:58 -08004541 }
4542 lStatus = NO_ERROR;
4543
4544Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004545 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004546 return track;
4547}
4548
4549status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4550 AudioSystem::sync_event_t event,
4551 int triggerSession)
4552{
4553 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4554 sp<ThreadBase> strongMe = this;
4555 status_t status = NO_ERROR;
4556
4557 if (event == AudioSystem::SYNC_EVENT_NONE) {
4558 clearSyncStartEvent();
4559 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4560 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4561 triggerSession,
4562 recordTrack->sessionId(),
4563 syncStartEventCallback,
4564 this);
4565 // Sync event can be cancelled by the trigger session if the track is not in a
4566 // compatible state in which case we start record immediately
4567 if (mSyncStartEvent->isCancelled()) {
4568 clearSyncStartEvent();
4569 } else {
4570 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4571 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4572 }
4573 }
4574
4575 {
4576 AutoMutex lock(mLock);
4577 if (mActiveTrack != 0) {
4578 if (recordTrack != mActiveTrack.get()) {
4579 status = -EBUSY;
4580 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4581 mActiveTrack->mState = TrackBase::ACTIVE;
4582 }
4583 return status;
4584 }
4585
4586 recordTrack->mState = TrackBase::IDLE;
4587 mActiveTrack = recordTrack;
4588 mLock.unlock();
4589 status_t status = AudioSystem::startInput(mId);
4590 mLock.lock();
4591 if (status != NO_ERROR) {
4592 mActiveTrack.clear();
4593 clearSyncStartEvent();
4594 return status;
4595 }
4596 mRsmpInIndex = mFrameCount;
4597 mBytesRead = 0;
4598 if (mResampler != NULL) {
4599 mResampler->reset();
4600 }
4601 mActiveTrack->mState = TrackBase::RESUMING;
4602 // signal thread to start
4603 ALOGV("Signal record thread");
4604 mWaitWorkCV.broadcast();
4605 // do not wait for mStartStopCond if exiting
4606 if (exitPending()) {
4607 mActiveTrack.clear();
4608 status = INVALID_OPERATION;
4609 goto startError;
4610 }
4611 mStartStopCond.wait(mLock);
4612 if (mActiveTrack == 0) {
4613 ALOGV("Record failed to start");
4614 status = BAD_VALUE;
4615 goto startError;
4616 }
4617 ALOGV("Record started OK");
4618 return status;
4619 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004620
Eric Laurent81784c32012-11-19 14:55:58 -08004621startError:
4622 AudioSystem::stopInput(mId);
4623 clearSyncStartEvent();
4624 return status;
4625}
4626
4627void AudioFlinger::RecordThread::clearSyncStartEvent()
4628{
4629 if (mSyncStartEvent != 0) {
4630 mSyncStartEvent->cancel();
4631 }
4632 mSyncStartEvent.clear();
4633 mFramestoDrop = 0;
4634}
4635
4636void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4637{
4638 sp<SyncEvent> strongEvent = event.promote();
4639
4640 if (strongEvent != 0) {
4641 RecordThread *me = (RecordThread *)strongEvent->cookie();
4642 me->handleSyncStartEvent(strongEvent);
4643 }
4644}
4645
4646void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4647{
4648 if (event == mSyncStartEvent) {
4649 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4650 // from audio HAL
4651 mFramestoDrop = mFrameCount * 2;
4652 }
4653}
4654
Glenn Kastena8356f62013-07-25 14:37:52 -07004655bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004656 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004657 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004658 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4659 return false;
4660 }
4661 recordTrack->mState = TrackBase::PAUSING;
4662 // do not wait for mStartStopCond if exiting
4663 if (exitPending()) {
4664 return true;
4665 }
4666 mStartStopCond.wait(mLock);
4667 // if we have been restarted, recordTrack == mActiveTrack.get() here
4668 if (exitPending() || recordTrack != mActiveTrack.get()) {
4669 ALOGV("Record stopped OK");
4670 return true;
4671 }
4672 return false;
4673}
4674
4675bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4676{
4677 return false;
4678}
4679
4680status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4681{
4682#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4683 if (!isValidSyncEvent(event)) {
4684 return BAD_VALUE;
4685 }
4686
4687 int eventSession = event->triggerSession();
4688 status_t ret = NAME_NOT_FOUND;
4689
4690 Mutex::Autolock _l(mLock);
4691
4692 for (size_t i = 0; i < mTracks.size(); i++) {
4693 sp<RecordTrack> track = mTracks[i];
4694 if (eventSession == track->sessionId()) {
4695 (void) track->setSyncEvent(event);
4696 ret = NO_ERROR;
4697 }
4698 }
4699 return ret;
4700#else
4701 return BAD_VALUE;
4702#endif
4703}
4704
4705// destroyTrack_l() must be called with ThreadBase::mLock held
4706void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4707{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 track->terminate();
4709 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004710 // active tracks are removed by threadLoop()
4711 if (mActiveTrack != track) {
4712 removeTrack_l(track);
4713 }
4714}
4715
4716void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4717{
4718 mTracks.remove(track);
4719 // need anything related to effects here?
4720}
4721
4722void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4723{
4724 dumpInternals(fd, args);
4725 dumpTracks(fd, args);
4726 dumpEffectChains(fd, args);
4727}
4728
4729void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4730{
4731 const size_t SIZE = 256;
4732 char buffer[SIZE];
4733 String8 result;
4734
4735 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4736 result.append(buffer);
4737
4738 if (mActiveTrack != 0) {
4739 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4740 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004741 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004742 result.append(buffer);
4743 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4744 result.append(buffer);
4745 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4746 result.append(buffer);
4747 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4748 result.append(buffer);
4749 } else {
4750 result.append("No active record client\n");
4751 }
4752
4753 write(fd, result.string(), result.size());
4754
4755 dumpBase(fd, args);
4756}
4757
4758void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4759{
4760 const size_t SIZE = 256;
4761 char buffer[SIZE];
4762 String8 result;
4763
4764 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4765 result.append(buffer);
4766 RecordTrack::appendDumpHeader(result);
4767 for (size_t i = 0; i < mTracks.size(); ++i) {
4768 sp<RecordTrack> track = mTracks[i];
4769 if (track != 0) {
4770 track->dump(buffer, SIZE);
4771 result.append(buffer);
4772 }
4773 }
4774
4775 if (mActiveTrack != 0) {
4776 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4777 result.append(buffer);
4778 RecordTrack::appendDumpHeader(result);
4779 mActiveTrack->dump(buffer, SIZE);
4780 result.append(buffer);
4781
4782 }
4783 write(fd, result.string(), result.size());
4784}
4785
4786// AudioBufferProvider interface
4787status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4788{
4789 size_t framesReq = buffer->frameCount;
4790 size_t framesReady = mFrameCount - mRsmpInIndex;
4791 int channelCount;
4792
4793 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004794 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004795 if (mBytesRead <= 0) {
4796 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4797 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4798 // Force input into standby so that it tries to
4799 // recover at next read attempt
4800 inputStandBy();
4801 usleep(kRecordThreadSleepUs);
4802 }
4803 buffer->raw = NULL;
4804 buffer->frameCount = 0;
4805 return NOT_ENOUGH_DATA;
4806 }
4807 mRsmpInIndex = 0;
4808 framesReady = mFrameCount;
4809 }
4810
4811 if (framesReq > framesReady) {
4812 framesReq = framesReady;
4813 }
4814
4815 if (mChannelCount == 1 && mReqChannelCount == 2) {
4816 channelCount = 1;
4817 } else {
4818 channelCount = 2;
4819 }
4820 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4821 buffer->frameCount = framesReq;
4822 return NO_ERROR;
4823}
4824
4825// AudioBufferProvider interface
4826void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4827{
4828 mRsmpInIndex += buffer->frameCount;
4829 buffer->frameCount = 0;
4830}
4831
4832bool AudioFlinger::RecordThread::checkForNewParameters_l()
4833{
4834 bool reconfig = false;
4835
4836 while (!mNewParameters.isEmpty()) {
4837 status_t status = NO_ERROR;
4838 String8 keyValuePair = mNewParameters[0];
4839 AudioParameter param = AudioParameter(keyValuePair);
4840 int value;
4841 audio_format_t reqFormat = mFormat;
4842 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07004843 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004844
4845 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4846 reqSamplingRate = value;
4847 reconfig = true;
4848 }
4849 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004850 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4851 status = BAD_VALUE;
4852 } else {
4853 reqFormat = (audio_format_t) value;
4854 reconfig = true;
4855 }
Eric Laurent81784c32012-11-19 14:55:58 -08004856 }
4857 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07004858 audio_channel_mask_t mask = (audio_channel_mask_t) value;
4859 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
4860 status = BAD_VALUE;
4861 } else {
4862 reqChannelMask = mask;
4863 reconfig = true;
4864 }
Eric Laurent81784c32012-11-19 14:55:58 -08004865 }
4866 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4867 // do not accept frame count changes if tracks are open as the track buffer
4868 // size depends on frame count and correct behavior would not be guaranteed
4869 // if frame count is changed after track creation
4870 if (mActiveTrack != 0) {
4871 status = INVALID_OPERATION;
4872 } else {
4873 reconfig = true;
4874 }
4875 }
4876 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4877 // forward device change to effects that have requested to be
4878 // aware of attached audio device.
4879 for (size_t i = 0; i < mEffectChains.size(); i++) {
4880 mEffectChains[i]->setDevice_l(value);
4881 }
4882
4883 // store input device and output device but do not forward output device to audio HAL.
4884 // Note that status is ignored by the caller for output device
4885 // (see AudioFlinger::setParameters()
4886 if (audio_is_output_devices(value)) {
4887 mOutDevice = value;
4888 status = BAD_VALUE;
4889 } else {
4890 mInDevice = value;
4891 // disable AEC and NS if the device is a BT SCO headset supporting those
4892 // pre processings
4893 if (mTracks.size() > 0) {
4894 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4895 mAudioFlinger->btNrecIsOff();
4896 for (size_t i = 0; i < mTracks.size(); i++) {
4897 sp<RecordTrack> track = mTracks[i];
4898 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4899 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4900 }
4901 }
4902 }
4903 }
4904 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4905 mAudioSource != (audio_source_t)value) {
4906 // forward device change to effects that have requested to be
4907 // aware of attached audio device.
4908 for (size_t i = 0; i < mEffectChains.size(); i++) {
4909 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4910 }
4911 mAudioSource = (audio_source_t)value;
4912 }
Glenn Kastene198c362013-08-13 09:13:36 -07004913
Eric Laurent81784c32012-11-19 14:55:58 -08004914 if (status == NO_ERROR) {
4915 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4916 keyValuePair.string());
4917 if (status == INVALID_OPERATION) {
4918 inputStandBy();
4919 status = mInput->stream->common.set_parameters(&mInput->stream->common,
4920 keyValuePair.string());
4921 }
4922 if (reconfig) {
4923 if (status == BAD_VALUE &&
4924 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4925 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08004926 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08004927 <= (2 * reqSamplingRate)) &&
4928 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4929 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07004930 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
4931 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004932 status = NO_ERROR;
4933 }
4934 if (status == NO_ERROR) {
4935 readInputParameters();
4936 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4937 }
4938 }
4939 }
4940
4941 mNewParameters.removeAt(0);
4942
4943 mParamStatus = status;
4944 mParamCond.signal();
4945 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4946 // already timed out waiting for the status and will never signal the condition.
4947 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4948 }
4949 return reconfig;
4950}
4951
4952String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4953{
Eric Laurent81784c32012-11-19 14:55:58 -08004954 Mutex::Autolock _l(mLock);
4955 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07004956 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08004957 }
4958
Glenn Kastend8ea6992013-07-16 14:17:15 -07004959 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4960 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08004961 free(s);
4962 return out_s8;
4963}
4964
4965void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4966 AudioSystem::OutputDescriptor desc;
4967 void *param2 = NULL;
4968
4969 switch (event) {
4970 case AudioSystem::INPUT_OPENED:
4971 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07004972 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004973 desc.samplingRate = mSampleRate;
4974 desc.format = mFormat;
4975 desc.frameCount = mFrameCount;
4976 desc.latency = 0;
4977 param2 = &desc;
4978 break;
4979
4980 case AudioSystem::INPUT_CLOSED:
4981 default:
4982 break;
4983 }
4984 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4985}
4986
4987void AudioFlinger::RecordThread::readInputParameters()
4988{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02004989 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004990 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02004991 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004992 mRsmpOutBuffer = NULL;
4993 delete mResampler;
4994 mResampler = NULL;
4995
4996 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4997 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07004998 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004999 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005000 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5001 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5002 }
Eric Laurent81784c32012-11-19 14:55:58 -08005003 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005004 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5005 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005006 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5007
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005008 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005009 int channelCount;
5010 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5011 // stereo to mono post process as the resampler always outputs stereo.
5012 if (mChannelCount == 1 && mReqChannelCount == 2) {
5013 channelCount = 1;
5014 } else {
5015 channelCount = 2;
5016 }
5017 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5018 mResampler->setSampleRate(mSampleRate);
5019 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005020 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005021
5022 // optmization: if mono to mono, alter input frame count as if we were inputing
5023 // stereo samples
5024 if (mChannelCount == 1 && mReqChannelCount == 1) {
5025 mFrameCount >>= 1;
5026 }
5027
5028 }
5029 mRsmpInIndex = mFrameCount;
5030}
5031
5032unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5033{
5034 Mutex::Autolock _l(mLock);
5035 if (initCheck() != NO_ERROR) {
5036 return 0;
5037 }
5038
5039 return mInput->stream->get_input_frames_lost(mInput->stream);
5040}
5041
5042uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5043{
5044 Mutex::Autolock _l(mLock);
5045 uint32_t result = 0;
5046 if (getEffectChain_l(sessionId) != 0) {
5047 result = EFFECT_SESSION;
5048 }
5049
5050 for (size_t i = 0; i < mTracks.size(); ++i) {
5051 if (sessionId == mTracks[i]->sessionId()) {
5052 result |= TRACK_SESSION;
5053 break;
5054 }
5055 }
5056
5057 return result;
5058}
5059
5060KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5061{
5062 KeyedVector<int, bool> ids;
5063 Mutex::Autolock _l(mLock);
5064 for (size_t j = 0; j < mTracks.size(); ++j) {
5065 sp<RecordThread::RecordTrack> track = mTracks[j];
5066 int sessionId = track->sessionId();
5067 if (ids.indexOfKey(sessionId) < 0) {
5068 ids.add(sessionId, true);
5069 }
5070 }
5071 return ids;
5072}
5073
5074AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5075{
5076 Mutex::Autolock _l(mLock);
5077 AudioStreamIn *input = mInput;
5078 mInput = NULL;
5079 return input;
5080}
5081
5082// this method must always be called either with ThreadBase mLock held or inside the thread loop
5083audio_stream_t* AudioFlinger::RecordThread::stream() const
5084{
5085 if (mInput == NULL) {
5086 return NULL;
5087 }
5088 return &mInput->stream->common;
5089}
5090
5091status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5092{
5093 // only one chain per input thread
5094 if (mEffectChains.size() != 0) {
5095 return INVALID_OPERATION;
5096 }
5097 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5098
5099 chain->setInBuffer(NULL);
5100 chain->setOutBuffer(NULL);
5101
5102 checkSuspendOnAddEffectChain_l(chain);
5103
5104 mEffectChains.add(chain);
5105
5106 return NO_ERROR;
5107}
5108
5109size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5110{
5111 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5112 ALOGW_IF(mEffectChains.size() != 1,
5113 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5114 chain.get(), mEffectChains.size(), this);
5115 if (mEffectChains.size() == 1) {
5116 mEffectChains.removeAt(0);
5117 }
5118 return 0;
5119}
5120
5121}; // namespace android