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