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