blob: 5e41dd2258790f732cd7079b341d82f56f48d5fd [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
138// Currently the client uses double-buffering by default, but doesn't tell us about that.
139// So for now we just assume that client is double-buffered.
140// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
141// N-buffering, so AudioFlinger could allocate the right amount of memory.
142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
188void CpuStats::sample(const String8 &title) {
189#ifdef DEBUG_CPU_USAGE
190 // get current thread's delta CPU time in wall clock ns
191 double wcNs;
192 bool valid = mCpuUsage.sampleAndEnable(wcNs);
193
194 // record sample for wall clock statistics
195 if (valid) {
196 mWcStats.sample(wcNs);
197 }
198
199 // get the current CPU number
200 int cpuNum = sched_getcpu();
201
202 // get the current CPU frequency in kHz
203 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
204
205 // check if either CPU number or frequency changed
206 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
207 mCpuNum = cpuNum;
208 mCpukHz = cpukHz;
209 // ignore sample for purposes of cycles
210 valid = false;
211 }
212
213 // if no change in CPU number or frequency, then record sample for cycle statistics
214 if (valid && mCpukHz > 0) {
215 double cycles = wcNs * cpukHz * 0.000001;
216 mHzStats.sample(cycles);
217 }
218
219 unsigned n = mWcStats.n();
220 // mCpuUsage.elapsed() is expensive, so don't call it every loop
221 if ((n & 127) == 1) {
222 long long elapsed = mCpuUsage.elapsed();
223 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
224 double perLoop = elapsed / (double) n;
225 double perLoop100 = perLoop * 0.01;
226 double perLoop1k = perLoop * 0.001;
227 double mean = mWcStats.mean();
228 double stddev = mWcStats.stddev();
229 double minimum = mWcStats.minimum();
230 double maximum = mWcStats.maximum();
231 double meanCycles = mHzStats.mean();
232 double stddevCycles = mHzStats.stddev();
233 double minCycles = mHzStats.minimum();
234 double maxCycles = mHzStats.maximum();
235 mCpuUsage.resetElapsed();
236 mWcStats.reset();
237 mHzStats.reset();
238 ALOGD("CPU usage for %s over past %.1f secs\n"
239 " (%u mixer loops at %.1f mean ms per loop):\n"
240 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
241 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
242 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
243 title.string(),
244 elapsed * .000000001, n, perLoop * .000001,
245 mean * .001,
246 stddev * .001,
247 minimum * .001,
248 maximum * .001,
249 mean / perLoop100,
250 stddev / perLoop100,
251 minimum / perLoop100,
252 maximum / perLoop100,
253 meanCycles / perLoop1k,
254 stddevCycles / perLoop1k,
255 minCycles / perLoop1k,
256 maxCycles / perLoop1k);
257
258 }
259 }
260#endif
261};
262
263// ----------------------------------------------------------------------------
264// ThreadBase
265// ----------------------------------------------------------------------------
266
267AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
268 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
269 : Thread(false /*canCallJava*/),
270 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700271 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700272 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
273 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800274 mParamStatus(NO_ERROR),
275 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
276 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
277 // mName will be set by concrete (non-virtual) subclass
278 mDeathRecipient(new PMDeathRecipient(this))
279{
280}
281
282AudioFlinger::ThreadBase::~ThreadBase()
283{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700284 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
285 for (size_t i = 0; i < mConfigEvents.size(); i++) {
286 delete mConfigEvents[i];
287 }
288 mConfigEvents.clear();
289
Eric Laurent81784c32012-11-19 14:55:58 -0800290 mParamCond.broadcast();
291 // do not lock the mutex in destructor
292 releaseWakeLock_l();
293 if (mPowerManager != 0) {
294 sp<IBinder> binder = mPowerManager->asBinder();
295 binder->unlinkToDeath(mDeathRecipient);
296 }
297}
298
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700299status_t AudioFlinger::ThreadBase::readyToRun()
300{
301 status_t status = initCheck();
302 if (status == NO_ERROR) {
303 ALOGI("AudioFlinger's thread %p ready to run", this);
304 } else {
305 ALOGE("No working audio driver found.");
306 }
307 return status;
308}
309
Eric Laurent81784c32012-11-19 14:55:58 -0800310void AudioFlinger::ThreadBase::exit()
311{
312 ALOGV("ThreadBase::exit");
313 // do any cleanup required for exit to succeed
314 preExit();
315 {
316 // This lock prevents the following race in thread (uniprocessor for illustration):
317 // if (!exitPending()) {
318 // // context switch from here to exit()
319 // // exit() calls requestExit(), what exitPending() observes
320 // // exit() calls signal(), which is dropped since no waiters
321 // // context switch back from exit() to here
322 // mWaitWorkCV.wait(...);
323 // // now thread is hung
324 // }
325 AutoMutex lock(mLock);
326 requestExit();
327 mWaitWorkCV.broadcast();
328 }
329 // When Thread::requestExitAndWait is made virtual and this method is renamed to
330 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
331 requestExitAndWait();
332}
333
334status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
335{
336 status_t status;
337
338 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
339 Mutex::Autolock _l(mLock);
340
341 mNewParameters.add(keyValuePairs);
342 mWaitWorkCV.signal();
343 // wait condition with timeout in case the thread loop has exited
344 // before the request could be processed
345 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
346 status = mParamStatus;
347 mWaitWorkCV.signal();
348 } else {
349 status = TIMED_OUT;
350 }
351 return status;
352}
353
354void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
355{
356 Mutex::Autolock _l(mLock);
357 sendIoConfigEvent_l(event, param);
358}
359
360// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
361void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
362{
363 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
364 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
365 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
366 param);
367 mWaitWorkCV.signal();
368}
369
370// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
371void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
372{
373 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
374 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
375 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
376 mConfigEvents.size(), pid, tid, prio);
377 mWaitWorkCV.signal();
378}
379
380void AudioFlinger::ThreadBase::processConfigEvents()
381{
Glenn Kastenf7773312013-08-13 16:00:42 -0700382 Mutex::Autolock _l(mLock);
383 processConfigEvents_l();
384}
385
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700386// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700387void AudioFlinger::ThreadBase::processConfigEvents_l()
388{
Eric Laurent81784c32012-11-19 14:55:58 -0800389 while (!mConfigEvents.isEmpty()) {
390 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
391 ConfigEvent *event = mConfigEvents[0];
392 mConfigEvents.removeAt(0);
393 // release mLock before locking AudioFlinger mLock: lock order is always
394 // AudioFlinger then ThreadBase to avoid cross deadlock
395 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700396 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700397 case CFG_EVENT_PRIO: {
398 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
399 // FIXME Need to understand why this has be done asynchronously
400 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
401 true /*asynchronous*/);
402 if (err != 0) {
403 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
404 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
405 }
406 } break;
407 case CFG_EVENT_IO: {
408 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700409 {
410 Mutex::Autolock _l(mAudioFlinger->mLock);
411 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
412 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700413 } break;
414 default:
415 ALOGE("processConfigEvents() unknown event type %d", event->type());
416 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800417 }
418 delete event;
419 mLock.lock();
420 }
Eric Laurent81784c32012-11-19 14:55:58 -0800421}
422
423void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
428
429 bool locked = AudioFlinger::dumpTryLock(mLock);
430 if (!locked) {
431 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
432 write(fd, buffer, strlen(buffer));
433 }
434
435 snprintf(buffer, SIZE, "io handle: %d\n", mId);
436 result.append(buffer);
437 snprintf(buffer, SIZE, "TID: %d\n", getTid());
438 result.append(buffer);
439 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
440 result.append(buffer);
441 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
442 result.append(buffer);
443 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
444 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700445 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
446 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700447 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800448 result.append(buffer);
449 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
450 result.append(buffer);
451 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
452 result.append(buffer);
453 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
454 result.append(buffer);
455
456 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
457 result.append(buffer);
458 result.append(" Index Command");
459 for (size_t i = 0; i < mNewParameters.size(); ++i) {
460 snprintf(buffer, SIZE, "\n %02d ", i);
461 result.append(buffer);
462 result.append(mNewParameters[i]);
463 }
464
465 snprintf(buffer, SIZE, "\n\nPending config events: \n");
466 result.append(buffer);
467 for (size_t i = 0; i < mConfigEvents.size(); i++) {
468 mConfigEvents[i]->dump(buffer, SIZE);
469 result.append(buffer);
470 }
471 result.append("\n");
472
473 write(fd, result.string(), result.size());
474
475 if (locked) {
476 mLock.unlock();
477 }
478}
479
480void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
481{
482 const size_t SIZE = 256;
483 char buffer[SIZE];
484 String8 result;
485
486 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
487 write(fd, buffer, strlen(buffer));
488
489 for (size_t i = 0; i < mEffectChains.size(); ++i) {
490 sp<EffectChain> chain = mEffectChains[i];
491 if (chain != 0) {
492 chain->dump(fd, args);
493 }
494 }
495}
496
Marco Nelissene14a5d62013-10-03 08:51:24 -0700497void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800498{
499 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700500 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800501}
502
Marco Nelissene14a5d62013-10-03 08:51:24 -0700503void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800504{
505 if (mPowerManager == 0) {
506 // use checkService() to avoid blocking if power service is not up yet
507 sp<IBinder> binder =
508 defaultServiceManager()->checkService(String16("power"));
509 if (binder == 0) {
510 ALOGW("Thread %s cannot connect to the power manager service", mName);
511 } else {
512 mPowerManager = interface_cast<IPowerManager>(binder);
513 binder->linkToDeath(mDeathRecipient);
514 }
515 }
516 if (mPowerManager != 0) {
517 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700518 status_t status;
519 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700520 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700521 binder,
522 String16(mName),
523 String16("media"),
524 uid);
525 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700526 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700527 binder,
528 String16(mName),
529 String16("media"));
530 }
Eric Laurent81784c32012-11-19 14:55:58 -0800531 if (status == NO_ERROR) {
532 mWakeLockToken = binder;
533 }
534 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
535 }
536}
537
538void AudioFlinger::ThreadBase::releaseWakeLock()
539{
540 Mutex::Autolock _l(mLock);
541 releaseWakeLock_l();
542}
543
544void AudioFlinger::ThreadBase::releaseWakeLock_l()
545{
546 if (mWakeLockToken != 0) {
547 ALOGV("releaseWakeLock_l() %s", mName);
548 if (mPowerManager != 0) {
549 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
550 }
551 mWakeLockToken.clear();
552 }
553}
554
555void AudioFlinger::ThreadBase::clearPowerManager()
556{
557 Mutex::Autolock _l(mLock);
558 releaseWakeLock_l();
559 mPowerManager.clear();
560}
561
562void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
563{
564 sp<ThreadBase> thread = mThread.promote();
565 if (thread != 0) {
566 thread->clearPowerManager();
567 }
568 ALOGW("power manager service died !!!");
569}
570
571void AudioFlinger::ThreadBase::setEffectSuspended(
572 const effect_uuid_t *type, bool suspend, int sessionId)
573{
574 Mutex::Autolock _l(mLock);
575 setEffectSuspended_l(type, suspend, sessionId);
576}
577
578void AudioFlinger::ThreadBase::setEffectSuspended_l(
579 const effect_uuid_t *type, bool suspend, int sessionId)
580{
581 sp<EffectChain> chain = getEffectChain_l(sessionId);
582 if (chain != 0) {
583 if (type != NULL) {
584 chain->setEffectSuspended_l(type, suspend);
585 } else {
586 chain->setEffectSuspendedAll_l(suspend);
587 }
588 }
589
590 updateSuspendedSessions_l(type, suspend, sessionId);
591}
592
593void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
594{
595 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
596 if (index < 0) {
597 return;
598 }
599
600 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
601 mSuspendedSessions.valueAt(index);
602
603 for (size_t i = 0; i < sessionEffects.size(); i++) {
604 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
605 for (int j = 0; j < desc->mRefCount; j++) {
606 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
607 chain->setEffectSuspendedAll_l(true);
608 } else {
609 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
610 desc->mType.timeLow);
611 chain->setEffectSuspended_l(&desc->mType, true);
612 }
613 }
614 }
615}
616
617void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
618 bool suspend,
619 int sessionId)
620{
621 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
622
623 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
624
625 if (suspend) {
626 if (index >= 0) {
627 sessionEffects = mSuspendedSessions.valueAt(index);
628 } else {
629 mSuspendedSessions.add(sessionId, sessionEffects);
630 }
631 } else {
632 if (index < 0) {
633 return;
634 }
635 sessionEffects = mSuspendedSessions.valueAt(index);
636 }
637
638
639 int key = EffectChain::kKeyForSuspendAll;
640 if (type != NULL) {
641 key = type->timeLow;
642 }
643 index = sessionEffects.indexOfKey(key);
644
645 sp<SuspendedSessionDesc> desc;
646 if (suspend) {
647 if (index >= 0) {
648 desc = sessionEffects.valueAt(index);
649 } else {
650 desc = new SuspendedSessionDesc();
651 if (type != NULL) {
652 desc->mType = *type;
653 }
654 sessionEffects.add(key, desc);
655 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
656 }
657 desc->mRefCount++;
658 } else {
659 if (index < 0) {
660 return;
661 }
662 desc = sessionEffects.valueAt(index);
663 if (--desc->mRefCount == 0) {
664 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
665 sessionEffects.removeItemsAt(index);
666 if (sessionEffects.isEmpty()) {
667 ALOGV("updateSuspendedSessions_l() restore removing session %d",
668 sessionId);
669 mSuspendedSessions.removeItem(sessionId);
670 }
671 }
672 }
673 if (!sessionEffects.isEmpty()) {
674 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
675 }
676}
677
678void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
679 bool enabled,
680 int sessionId)
681{
682 Mutex::Autolock _l(mLock);
683 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
684}
685
686void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
687 bool enabled,
688 int sessionId)
689{
690 if (mType != RECORD) {
691 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
692 // another session. This gives the priority to well behaved effect control panels
693 // and applications not using global effects.
694 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
695 // global effects
696 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
697 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
698 }
699 }
700
701 sp<EffectChain> chain = getEffectChain_l(sessionId);
702 if (chain != 0) {
703 chain->checkSuspendOnEffectEnabled(effect, enabled);
704 }
705}
706
707// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
708sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
709 const sp<AudioFlinger::Client>& client,
710 const sp<IEffectClient>& effectClient,
711 int32_t priority,
712 int sessionId,
713 effect_descriptor_t *desc,
714 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700715 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800716{
717 sp<EffectModule> effect;
718 sp<EffectHandle> handle;
719 status_t lStatus;
720 sp<EffectChain> chain;
721 bool chainCreated = false;
722 bool effectCreated = false;
723 bool effectRegistered = false;
724
725 lStatus = initCheck();
726 if (lStatus != NO_ERROR) {
727 ALOGW("createEffect_l() Audio driver not initialized.");
728 goto Exit;
729 }
730
Eric Laurent5baf2af2013-09-12 17:37:00 -0700731 // Allow global effects only on offloaded and mixer threads
732 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
733 switch (mType) {
734 case MIXER:
735 case OFFLOAD:
736 break;
737 case DIRECT:
738 case DUPLICATING:
739 case RECORD:
740 default:
741 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
742 lStatus = BAD_VALUE;
743 goto Exit;
744 }
Eric Laurent81784c32012-11-19 14:55:58 -0800745 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700746
Eric Laurent81784c32012-11-19 14:55:58 -0800747 // Only Pre processor effects are allowed on input threads and only on input threads
748 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
749 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
750 desc->name, desc->flags, mType);
751 lStatus = BAD_VALUE;
752 goto Exit;
753 }
754
755 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
756
757 { // scope for mLock
758 Mutex::Autolock _l(mLock);
759
760 // check for existing effect chain with the requested audio session
761 chain = getEffectChain_l(sessionId);
762 if (chain == 0) {
763 // create a new chain for this session
764 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
765 chain = new EffectChain(this, sessionId);
766 addEffectChain_l(chain);
767 chain->setStrategy(getStrategyForSession_l(sessionId));
768 chainCreated = true;
769 } else {
770 effect = chain->getEffectFromDesc_l(desc);
771 }
772
773 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
774
775 if (effect == 0) {
776 int id = mAudioFlinger->nextUniqueId();
777 // Check CPU and memory usage
778 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
779 if (lStatus != NO_ERROR) {
780 goto Exit;
781 }
782 effectRegistered = true;
783 // create a new effect module if none present in the chain
784 effect = new EffectModule(this, chain, desc, id, sessionId);
785 lStatus = effect->status();
786 if (lStatus != NO_ERROR) {
787 goto Exit;
788 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700789 effect->setOffloaded(mType == OFFLOAD, mId);
790
Eric Laurent81784c32012-11-19 14:55:58 -0800791 lStatus = chain->addEffect_l(effect);
792 if (lStatus != NO_ERROR) {
793 goto Exit;
794 }
795 effectCreated = true;
796
797 effect->setDevice(mOutDevice);
798 effect->setDevice(mInDevice);
799 effect->setMode(mAudioFlinger->getMode());
800 effect->setAudioSource(mAudioSource);
801 }
802 // create effect handle and connect it to effect module
803 handle = new EffectHandle(effect, client, effectClient, priority);
804 lStatus = effect->addHandle(handle.get());
805 if (enabled != NULL) {
806 *enabled = (int)effect->isEnabled();
807 }
808 }
809
810Exit:
811 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
812 Mutex::Autolock _l(mLock);
813 if (effectCreated) {
814 chain->removeEffect_l(effect);
815 }
816 if (effectRegistered) {
817 AudioSystem::unregisterEffect(effect->id());
818 }
819 if (chainCreated) {
820 removeEffectChain_l(chain);
821 }
822 handle.clear();
823 }
824
Glenn Kasten9156ef32013-08-06 15:39:08 -0700825 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800826 return handle;
827}
828
829sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
830{
831 Mutex::Autolock _l(mLock);
832 return getEffect_l(sessionId, effectId);
833}
834
835sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
836{
837 sp<EffectChain> chain = getEffectChain_l(sessionId);
838 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
839}
840
841// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
842// PlaybackThread::mLock held
843status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
844{
845 // check for existing effect chain with the requested audio session
846 int sessionId = effect->sessionId();
847 sp<EffectChain> chain = getEffectChain_l(sessionId);
848 bool chainCreated = false;
849
Eric Laurent5baf2af2013-09-12 17:37:00 -0700850 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
851 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
852 this, effect->desc().name, effect->desc().flags);
853
Eric Laurent81784c32012-11-19 14:55:58 -0800854 if (chain == 0) {
855 // create a new chain for this session
856 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
857 chain = new EffectChain(this, sessionId);
858 addEffectChain_l(chain);
859 chain->setStrategy(getStrategyForSession_l(sessionId));
860 chainCreated = true;
861 }
862 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
863
864 if (chain->getEffectFromId_l(effect->id()) != 0) {
865 ALOGW("addEffect_l() %p effect %s already present in chain %p",
866 this, effect->desc().name, chain.get());
867 return BAD_VALUE;
868 }
869
Eric Laurent5baf2af2013-09-12 17:37:00 -0700870 effect->setOffloaded(mType == OFFLOAD, mId);
871
Eric Laurent81784c32012-11-19 14:55:58 -0800872 status_t status = chain->addEffect_l(effect);
873 if (status != NO_ERROR) {
874 if (chainCreated) {
875 removeEffectChain_l(chain);
876 }
877 return status;
878 }
879
880 effect->setDevice(mOutDevice);
881 effect->setDevice(mInDevice);
882 effect->setMode(mAudioFlinger->getMode());
883 effect->setAudioSource(mAudioSource);
884 return NO_ERROR;
885}
886
887void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
888
889 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
890 effect_descriptor_t desc = effect->desc();
891 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
892 detachAuxEffect_l(effect->id());
893 }
894
895 sp<EffectChain> chain = effect->chain().promote();
896 if (chain != 0) {
897 // remove effect chain if removing last effect
898 if (chain->removeEffect_l(effect) == 0) {
899 removeEffectChain_l(chain);
900 }
901 } else {
902 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
903 }
904}
905
906void AudioFlinger::ThreadBase::lockEffectChains_l(
907 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
908{
909 effectChains = mEffectChains;
910 for (size_t i = 0; i < mEffectChains.size(); i++) {
911 mEffectChains[i]->lock();
912 }
913}
914
915void AudioFlinger::ThreadBase::unlockEffectChains(
916 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
917{
918 for (size_t i = 0; i < effectChains.size(); i++) {
919 effectChains[i]->unlock();
920 }
921}
922
923sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
924{
925 Mutex::Autolock _l(mLock);
926 return getEffectChain_l(sessionId);
927}
928
929sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
930{
931 size_t size = mEffectChains.size();
932 for (size_t i = 0; i < size; i++) {
933 if (mEffectChains[i]->sessionId() == sessionId) {
934 return mEffectChains[i];
935 }
936 }
937 return 0;
938}
939
940void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
941{
942 Mutex::Autolock _l(mLock);
943 size_t size = mEffectChains.size();
944 for (size_t i = 0; i < size; i++) {
945 mEffectChains[i]->setMode_l(mode);
946 }
947}
948
949void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
950 EffectHandle *handle,
951 bool unpinIfLast) {
952
953 Mutex::Autolock _l(mLock);
954 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
955 // delete the effect module if removing last handle on it
956 if (effect->removeHandle(handle) == 0) {
957 if (!effect->isPinned() || unpinIfLast) {
958 removeEffect_l(effect);
959 AudioSystem::unregisterEffect(effect->id());
960 }
961 }
962}
963
964// ----------------------------------------------------------------------------
965// Playback
966// ----------------------------------------------------------------------------
967
968AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
969 AudioStreamOut* output,
970 audio_io_handle_t id,
971 audio_devices_t device,
972 type_t type)
973 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700974 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700975 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800976 // mStreamTypes[] initialized in constructor body
977 mOutput(output),
978 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
979 mMixerStatus(MIXER_IDLE),
980 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
981 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800982 mBytesRemaining(0),
983 mCurrentWriteLength(0),
984 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -0700985 mWriteAckSequence(0),
986 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -0700987 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800988 mScreenState(AudioFlinger::mScreenState),
989 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700990 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
991 // mLatchD, mLatchQ,
992 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800993{
994 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800995 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800996
997 // Assumes constructor is called by AudioFlinger with it's mLock held, but
998 // it would be safer to explicitly pass initial masterVolume/masterMute as
999 // parameter.
1000 //
1001 // If the HAL we are using has support for master volume or master mute,
1002 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1003 // and the mute set to false).
1004 mMasterVolume = audioFlinger->masterVolume_l();
1005 mMasterMute = audioFlinger->masterMute_l();
1006 if (mOutput && mOutput->audioHwDev) {
1007 if (mOutput->audioHwDev->canSetMasterVolume()) {
1008 mMasterVolume = 1.0;
1009 }
1010
1011 if (mOutput->audioHwDev->canSetMasterMute()) {
1012 mMasterMute = false;
1013 }
1014 }
1015
1016 readOutputParameters();
1017
1018 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1019 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1020 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1021 stream = (audio_stream_type_t) (stream + 1)) {
1022 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1023 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1024 }
1025 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1026 // because mAudioFlinger doesn't have one to copy from
1027}
1028
1029AudioFlinger::PlaybackThread::~PlaybackThread()
1030{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001031 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001032 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001033}
1034
1035void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1036{
1037 dumpInternals(fd, args);
1038 dumpTracks(fd, args);
1039 dumpEffectChains(fd, args);
1040}
1041
1042void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1043{
1044 const size_t SIZE = 256;
1045 char buffer[SIZE];
1046 String8 result;
1047
1048 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1049 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1050 const stream_type_t *st = &mStreamTypes[i];
1051 if (i > 0) {
1052 result.appendFormat(", ");
1053 }
1054 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1055 if (st->mute) {
1056 result.append("M");
1057 }
1058 }
1059 result.append("\n");
1060 write(fd, result.string(), result.length());
1061 result.clear();
1062
1063 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1064 result.append(buffer);
1065 Track::appendDumpHeader(result);
1066 for (size_t i = 0; i < mTracks.size(); ++i) {
1067 sp<Track> track = mTracks[i];
1068 if (track != 0) {
1069 track->dump(buffer, SIZE);
1070 result.append(buffer);
1071 }
1072 }
1073
1074 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1075 result.append(buffer);
1076 Track::appendDumpHeader(result);
1077 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1078 sp<Track> track = mActiveTracks[i].promote();
1079 if (track != 0) {
1080 track->dump(buffer, SIZE);
1081 result.append(buffer);
1082 }
1083 }
1084 write(fd, result.string(), result.size());
1085
1086 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1087 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1088 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1089 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1090}
1091
1092void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1093{
1094 const size_t SIZE = 256;
1095 char buffer[SIZE];
1096 String8 result;
1097
1098 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1099 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001100 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1101 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001102 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1103 ns2ms(systemTime() - mLastWriteTime));
1104 result.append(buffer);
1105 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1106 result.append(buffer);
1107 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1108 result.append(buffer);
1109 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1114 result.append(buffer);
1115 write(fd, result.string(), result.size());
1116 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1117
1118 dumpBase(fd, args);
1119}
1120
1121// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001122
1123void AudioFlinger::PlaybackThread::onFirstRef()
1124{
1125 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1126}
1127
1128// ThreadBase virtuals
1129void AudioFlinger::PlaybackThread::preExit()
1130{
1131 ALOGV(" preExit()");
1132 // FIXME this is using hard-coded strings but in the future, this functionality will be
1133 // converted to use audio HAL extensions required to support tunneling
1134 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1135}
1136
1137// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1138sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1139 const sp<AudioFlinger::Client>& client,
1140 audio_stream_type_t streamType,
1141 uint32_t sampleRate,
1142 audio_format_t format,
1143 audio_channel_mask_t channelMask,
1144 size_t frameCount,
1145 const sp<IMemory>& sharedBuffer,
1146 int sessionId,
1147 IAudioFlinger::track_flags_t *flags,
1148 pid_t tid,
1149 status_t *status)
1150{
1151 sp<Track> track;
1152 status_t lStatus;
1153
1154 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1155
1156 // client expresses a preference for FAST, but we get the final say
1157 if (*flags & IAudioFlinger::TRACK_FAST) {
1158 if (
1159 // not timed
1160 (!isTimed) &&
1161 // either of these use cases:
1162 (
1163 // use case 1: shared buffer with any frame count
1164 (
1165 (sharedBuffer != 0)
1166 ) ||
1167 // use case 2: callback handler and frame count is default or at least as large as HAL
1168 (
1169 (tid != -1) &&
1170 ((frameCount == 0) ||
1171 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1172 )
1173 ) &&
1174 // PCM data
1175 audio_is_linear_pcm(format) &&
1176 // mono or stereo
1177 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1178 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1179#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1180 // hardware sample rate
1181 (sampleRate == mSampleRate) &&
1182#endif
1183 // normal mixer has an associated fast mixer
1184 hasFastMixer() &&
1185 // there are sufficient fast track slots available
1186 (mFastTrackAvailMask != 0)
1187 // FIXME test that MixerThread for this fast track has a capable output HAL
1188 // FIXME add a permission test also?
1189 ) {
1190 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1191 if (frameCount == 0) {
1192 frameCount = mFrameCount * kFastTrackMultiplier;
1193 }
1194 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1195 frameCount, mFrameCount);
1196 } else {
1197 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1198 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1199 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1200 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1201 audio_is_linear_pcm(format),
1202 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1203 *flags &= ~IAudioFlinger::TRACK_FAST;
1204 // For compatibility with AudioTrack calculation, buffer depth is forced
1205 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1206 // This is probably too conservative, but legacy application code may depend on it.
1207 // If you change this calculation, also review the start threshold which is related.
1208 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1209 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1210 if (minBufCount < 2) {
1211 minBufCount = 2;
1212 }
1213 size_t minFrameCount = mNormalFrameCount * minBufCount;
1214 if (frameCount < minFrameCount) {
1215 frameCount = minFrameCount;
1216 }
1217 }
1218 }
1219
1220 if (mType == DIRECT) {
1221 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1222 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1223 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1224 "for output %p with format %d",
1225 sampleRate, format, channelMask, mOutput, mFormat);
1226 lStatus = BAD_VALUE;
1227 goto Exit;
1228 }
1229 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001230 } else if (mType == OFFLOAD) {
1231 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1232 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1233 "for output %p with format %d",
1234 sampleRate, format, channelMask, mOutput, mFormat);
1235 lStatus = BAD_VALUE;
1236 goto Exit;
1237 }
Eric Laurent81784c32012-11-19 14:55:58 -08001238 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001239 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1240 ALOGE("createTrack_l() Bad parameter: format %d \""
1241 "for output %p with format %d",
1242 format, mOutput, mFormat);
1243 lStatus = BAD_VALUE;
1244 goto Exit;
1245 }
Eric Laurent81784c32012-11-19 14:55:58 -08001246 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1247 if (sampleRate > mSampleRate*2) {
1248 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1249 lStatus = BAD_VALUE;
1250 goto Exit;
1251 }
1252 }
1253
1254 lStatus = initCheck();
1255 if (lStatus != NO_ERROR) {
1256 ALOGE("Audio driver not initialized.");
1257 goto Exit;
1258 }
1259
1260 { // scope for mLock
1261 Mutex::Autolock _l(mLock);
1262
1263 // all tracks in same audio session must share the same routing strategy otherwise
1264 // conflicts will happen when tracks are moved from one output to another by audio policy
1265 // manager
1266 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1267 for (size_t i = 0; i < mTracks.size(); ++i) {
1268 sp<Track> t = mTracks[i];
1269 if (t != 0 && !t->isOutputTrack()) {
1270 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1271 if (sessionId == t->sessionId() && strategy != actual) {
1272 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1273 strategy, actual);
1274 lStatus = BAD_VALUE;
1275 goto Exit;
1276 }
1277 }
1278 }
1279
1280 if (!isTimed) {
1281 track = new Track(this, client, streamType, sampleRate, format,
1282 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1283 } else {
1284 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1285 channelMask, frameCount, sharedBuffer, sessionId);
1286 }
Glenn Kasten03003332013-08-06 15:40:54 -07001287
1288 // new Track always returns non-NULL,
1289 // but TimedTrack::create() is a factory that could fail by returning NULL
1290 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1291 if (lStatus != NO_ERROR) {
1292 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001293 goto Exit;
1294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001295
Eric Laurent81784c32012-11-19 14:55:58 -08001296 mTracks.add(track);
1297
1298 sp<EffectChain> chain = getEffectChain_l(sessionId);
1299 if (chain != 0) {
1300 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1301 track->setMainBuffer(chain->inBuffer());
1302 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1303 chain->incTrackCnt();
1304 }
1305
1306 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1307 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1308 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1309 // so ask activity manager to do this on our behalf
1310 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1311 }
1312 }
1313
1314 lStatus = NO_ERROR;
1315
1316Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001317 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001318 return track;
1319}
1320
1321uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1322{
1323 return latency;
1324}
1325
1326uint32_t AudioFlinger::PlaybackThread::latency() const
1327{
1328 Mutex::Autolock _l(mLock);
1329 return latency_l();
1330}
1331uint32_t AudioFlinger::PlaybackThread::latency_l() const
1332{
1333 if (initCheck() == NO_ERROR) {
1334 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1335 } else {
1336 return 0;
1337 }
1338}
1339
1340void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1341{
1342 Mutex::Autolock _l(mLock);
1343 // Don't apply master volume in SW if our HAL can do it for us.
1344 if (mOutput && mOutput->audioHwDev &&
1345 mOutput->audioHwDev->canSetMasterVolume()) {
1346 mMasterVolume = 1.0;
1347 } else {
1348 mMasterVolume = value;
1349 }
1350}
1351
1352void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1353{
1354 Mutex::Autolock _l(mLock);
1355 // Don't apply master mute in SW if our HAL can do it for us.
1356 if (mOutput && mOutput->audioHwDev &&
1357 mOutput->audioHwDev->canSetMasterMute()) {
1358 mMasterMute = false;
1359 } else {
1360 mMasterMute = muted;
1361 }
1362}
1363
1364void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1365{
1366 Mutex::Autolock _l(mLock);
1367 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001368 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001369}
1370
1371void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1372{
1373 Mutex::Autolock _l(mLock);
1374 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001375 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001376}
1377
1378float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1379{
1380 Mutex::Autolock _l(mLock);
1381 return mStreamTypes[stream].volume;
1382}
1383
1384// addTrack_l() must be called with ThreadBase::mLock held
1385status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1386{
1387 status_t status = ALREADY_EXISTS;
1388
1389 // set retry count for buffer fill
1390 track->mRetryCount = kMaxTrackStartupRetries;
1391 if (mActiveTracks.indexOf(track) < 0) {
1392 // the track is newly added, make sure it fills up all its
1393 // buffers before playing. This is to ensure the client will
1394 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001395 if (!track->isOutputTrack()) {
1396 TrackBase::track_state state = track->mState;
1397 mLock.unlock();
1398 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1399 mLock.lock();
1400 // abort track was stopped/paused while we released the lock
1401 if (state != track->mState) {
1402 if (status == NO_ERROR) {
1403 mLock.unlock();
1404 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1405 mLock.lock();
1406 }
1407 return INVALID_OPERATION;
1408 }
1409 // abort if start is rejected by audio policy manager
1410 if (status != NO_ERROR) {
1411 return PERMISSION_DENIED;
1412 }
1413#ifdef ADD_BATTERY_DATA
1414 // to track the speaker usage
1415 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1416#endif
1417 }
1418
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001419 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001420 track->mResetDone = false;
1421 track->mPresentationCompleteFrames = 0;
1422 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001423 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1424 if (chain != 0) {
1425 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1426 track->sessionId());
1427 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
1429
1430 status = NO_ERROR;
1431 }
1432
Eric Laurentede6c3b2013-09-19 14:37:46 -07001433 ALOGV("signal playback thread");
1434 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001435
1436 return status;
1437}
1438
Eric Laurentbfb1b832013-01-07 09:53:42 -08001439bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001440{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001441 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001442 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001443 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1444 track->mState = TrackBase::STOPPED;
1445 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001446 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001447 } else if (track->isFastTrack() || track->isOffloaded()) {
1448 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001449 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001450
1451 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001452}
1453
1454void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1455{
1456 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1457 mTracks.remove(track);
1458 deleteTrackName_l(track->name());
1459 // redundant as track is about to be destroyed, for dumpsys only
1460 track->mName = -1;
1461 if (track->isFastTrack()) {
1462 int index = track->mFastIndex;
1463 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1464 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1465 mFastTrackAvailMask |= 1 << index;
1466 // redundant as track is about to be destroyed, for dumpsys only
1467 track->mFastIndex = -1;
1468 }
1469 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1470 if (chain != 0) {
1471 chain->decTrackCnt();
1472 }
1473}
1474
Eric Laurentede6c3b2013-09-19 14:37:46 -07001475void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001476{
1477 // Thread could be blocked waiting for async
1478 // so signal it to handle state changes immediately
1479 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1480 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1481 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001482 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001483}
1484
Eric Laurent81784c32012-11-19 14:55:58 -08001485String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1486{
Eric Laurent81784c32012-11-19 14:55:58 -08001487 Mutex::Autolock _l(mLock);
1488 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001489 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001490 }
1491
Glenn Kastend8ea6992013-07-16 14:17:15 -07001492 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1493 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001494 free(s);
1495 return out_s8;
1496}
1497
1498// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1499void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1500 AudioSystem::OutputDescriptor desc;
1501 void *param2 = NULL;
1502
1503 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1504 param);
1505
1506 switch (event) {
1507 case AudioSystem::OUTPUT_OPENED:
1508 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001509 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001510 desc.samplingRate = mSampleRate;
1511 desc.format = mFormat;
1512 desc.frameCount = mNormalFrameCount; // FIXME see
1513 // AudioFlinger::frameCount(audio_io_handle_t)
1514 desc.latency = latency();
1515 param2 = &desc;
1516 break;
1517
1518 case AudioSystem::STREAM_CONFIG_CHANGED:
1519 param2 = &param;
1520 case AudioSystem::OUTPUT_CLOSED:
1521 default:
1522 break;
1523 }
1524 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1525}
1526
Eric Laurentbfb1b832013-01-07 09:53:42 -08001527void AudioFlinger::PlaybackThread::writeCallback()
1528{
1529 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001530 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001531}
1532
1533void AudioFlinger::PlaybackThread::drainCallback()
1534{
1535 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001536 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001537}
1538
Eric Laurent3b4529e2013-09-05 18:09:19 -07001539void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001540{
1541 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001542 // reject out of sequence requests
1543 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1544 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001545 mWaitWorkCV.signal();
1546 }
1547}
1548
Eric Laurent3b4529e2013-09-05 18:09:19 -07001549void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001550{
1551 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001552 // reject out of sequence requests
1553 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1554 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001555 mWaitWorkCV.signal();
1556 }
1557}
1558
1559// static
1560int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1561 void *param,
1562 void *cookie)
1563{
1564 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1565 ALOGV("asyncCallback() event %d", event);
1566 switch (event) {
1567 case STREAM_CBK_EVENT_WRITE_READY:
1568 me->writeCallback();
1569 break;
1570 case STREAM_CBK_EVENT_DRAIN_READY:
1571 me->drainCallback();
1572 break;
1573 default:
1574 ALOGW("asyncCallback() unknown event %d", event);
1575 break;
1576 }
1577 return 0;
1578}
1579
Eric Laurent81784c32012-11-19 14:55:58 -08001580void AudioFlinger::PlaybackThread::readOutputParameters()
1581{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001582 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001583 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1584 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001585 if (!audio_is_output_channel(mChannelMask)) {
1586 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1587 }
1588 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1589 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1590 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1591 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001592 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001593 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001594 if (!audio_is_valid_format(mFormat)) {
1595 LOG_FATAL("HAL format %d not valid for output", mFormat);
1596 }
1597 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1598 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1599 mFormat);
1600 }
Eric Laurent81784c32012-11-19 14:55:58 -08001601 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001602 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1603 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001604 if (mFrameCount & 15) {
1605 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1606 mFrameCount);
1607 }
1608
Eric Laurentbfb1b832013-01-07 09:53:42 -08001609 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1610 (mOutput->stream->set_callback != NULL)) {
1611 if (mOutput->stream->set_callback(mOutput->stream,
1612 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1613 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001614 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001615 }
1616 }
1617
Eric Laurent81784c32012-11-19 14:55:58 -08001618 // Calculate size of normal mix buffer relative to the HAL output buffer size
1619 double multiplier = 1.0;
1620 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1621 kUseFastMixer == FastMixer_Dynamic)) {
1622 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1623 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1624 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1625 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1626 maxNormalFrameCount = maxNormalFrameCount & ~15;
1627 if (maxNormalFrameCount < minNormalFrameCount) {
1628 maxNormalFrameCount = minNormalFrameCount;
1629 }
1630 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1631 if (multiplier <= 1.0) {
1632 multiplier = 1.0;
1633 } else if (multiplier <= 2.0) {
1634 if (2 * mFrameCount <= maxNormalFrameCount) {
1635 multiplier = 2.0;
1636 } else {
1637 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1638 }
1639 } else {
1640 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1641 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1642 // track, but we sometimes have to do this to satisfy the maximum frame count
1643 // constraint)
1644 // FIXME this rounding up should not be done if no HAL SRC
1645 uint32_t truncMult = (uint32_t) multiplier;
1646 if ((truncMult & 1)) {
1647 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1648 ++truncMult;
1649 }
1650 }
1651 multiplier = (double) truncMult;
1652 }
1653 }
1654 mNormalFrameCount = multiplier * mFrameCount;
1655 // round up to nearest 16 frames to satisfy AudioMixer
1656 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1657 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1658 mNormalFrameCount);
1659
Glenn Kastenc1fac192013-08-06 07:41:36 -07001660 delete[] mMixBuffer;
1661 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1662 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1663 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1664 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001665
1666 // force reconfiguration of effect chains and engines to take new buffer size and audio
1667 // parameters into account
1668 // Note that mLock is not held when readOutputParameters() is called from the constructor
1669 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1670 // matter.
1671 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1672 Vector< sp<EffectChain> > effectChains = mEffectChains;
1673 for (size_t i = 0; i < effectChains.size(); i ++) {
1674 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1675 }
1676}
1677
1678
1679status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1680{
1681 if (halFrames == NULL || dspFrames == NULL) {
1682 return BAD_VALUE;
1683 }
1684 Mutex::Autolock _l(mLock);
1685 if (initCheck() != NO_ERROR) {
1686 return INVALID_OPERATION;
1687 }
1688 size_t framesWritten = mBytesWritten / mFrameSize;
1689 *halFrames = framesWritten;
1690
1691 if (isSuspended()) {
1692 // return an estimation of rendered frames when the output is suspended
1693 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1694 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1695 return NO_ERROR;
1696 } else {
1697 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1698 }
1699}
1700
1701uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1702{
1703 Mutex::Autolock _l(mLock);
1704 uint32_t result = 0;
1705 if (getEffectChain_l(sessionId) != 0) {
1706 result = EFFECT_SESSION;
1707 }
1708
1709 for (size_t i = 0; i < mTracks.size(); ++i) {
1710 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001711 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001712 result |= TRACK_SESSION;
1713 break;
1714 }
1715 }
1716
1717 return result;
1718}
1719
1720uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1721{
1722 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1723 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1724 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1725 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1726 }
1727 for (size_t i = 0; i < mTracks.size(); i++) {
1728 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001729 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001730 return AudioSystem::getStrategyForStream(track->streamType());
1731 }
1732 }
1733 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1734}
1735
1736
1737AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1738{
1739 Mutex::Autolock _l(mLock);
1740 return mOutput;
1741}
1742
1743AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1744{
1745 Mutex::Autolock _l(mLock);
1746 AudioStreamOut *output = mOutput;
1747 mOutput = NULL;
1748 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1749 // must push a NULL and wait for ack
1750 mOutputSink.clear();
1751 mPipeSink.clear();
1752 mNormalSink.clear();
1753 return output;
1754}
1755
1756// this method must always be called either with ThreadBase mLock held or inside the thread loop
1757audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1758{
1759 if (mOutput == NULL) {
1760 return NULL;
1761 }
1762 return &mOutput->stream->common;
1763}
1764
1765uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1766{
1767 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1768}
1769
1770status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1771{
1772 if (!isValidSyncEvent(event)) {
1773 return BAD_VALUE;
1774 }
1775
1776 Mutex::Autolock _l(mLock);
1777
1778 for (size_t i = 0; i < mTracks.size(); ++i) {
1779 sp<Track> track = mTracks[i];
1780 if (event->triggerSession() == track->sessionId()) {
1781 (void) track->setSyncEvent(event);
1782 return NO_ERROR;
1783 }
1784 }
1785
1786 return NAME_NOT_FOUND;
1787}
1788
1789bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1790{
1791 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1792}
1793
1794void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1795 const Vector< sp<Track> >& tracksToRemove)
1796{
1797 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001798 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001799 for (size_t i = 0 ; i < count ; i++) {
1800 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001801 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001802 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001803#ifdef ADD_BATTERY_DATA
1804 // to track the speaker usage
1805 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1806#endif
1807 if (track->isTerminated()) {
1808 AudioSystem::releaseOutput(mId);
1809 }
Eric Laurent81784c32012-11-19 14:55:58 -08001810 }
1811 }
1812 }
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
1815void AudioFlinger::PlaybackThread::checkSilentMode_l()
1816{
1817 if (!mMasterMute) {
1818 char value[PROPERTY_VALUE_MAX];
1819 if (property_get("ro.audio.silent", value, "0") > 0) {
1820 char *endptr;
1821 unsigned long ul = strtoul(value, &endptr, 0);
1822 if (*endptr == '\0' && ul != 0) {
1823 ALOGD("Silence is golden");
1824 // The setprop command will not allow a property to be changed after
1825 // the first time it is set, so we don't have to worry about un-muting.
1826 setMasterMute_l(true);
1827 }
1828 }
1829 }
1830}
1831
1832// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001834{
1835 // FIXME rewrite to reduce number of system calls
1836 mLastWriteTime = systemTime();
1837 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001838 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001839
1840 // If an NBAIO sink is present, use it to write the normal mixer's submix
1841 if (mNormalSink != 0) {
1842#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843 size_t count = mBytesRemaining >> mBitShift;
1844 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001845 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001846 // update the setpoint when AudioFlinger::mScreenState changes
1847 uint32_t screenState = AudioFlinger::mScreenState;
1848 if (screenState != mScreenState) {
1849 mScreenState = screenState;
1850 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1851 if (pipe != NULL) {
1852 pipe->setAvgFrames((mScreenState & 1) ?
1853 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1854 }
1855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001857 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001858 if (framesWritten > 0) {
1859 bytesWritten = framesWritten << mBitShift;
1860 } else {
1861 bytesWritten = framesWritten;
1862 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001863 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001864 if (status == NO_ERROR) {
1865 size_t totalFramesWritten = mNormalSink->framesWritten();
1866 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1867 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1868 mLatchDValid = true;
1869 }
1870 }
Eric Laurent81784c32012-11-19 14:55:58 -08001871 // otherwise use the HAL / AudioStreamOut directly
1872 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873 // Direct output and offload threads
1874 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1875 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001876 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1877 mWriteAckSequence += 2;
1878 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001879 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001880 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001881 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001882 // FIXME We should have an implementation of timestamps for direct output threads.
1883 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001884 bytesWritten = mOutput->stream->write(mOutput->stream,
1885 mMixBuffer + offset, mBytesRemaining);
1886 if (mUseAsyncWrite &&
1887 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1888 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001889 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001890 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001891 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892 }
Eric Laurent81784c32012-11-19 14:55:58 -08001893 }
1894
Eric Laurent81784c32012-11-19 14:55:58 -08001895 mNumWrites++;
1896 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001897
1898 return bytesWritten;
1899}
1900
1901void AudioFlinger::PlaybackThread::threadLoop_drain()
1902{
1903 if (mOutput->stream->drain) {
1904 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1905 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001906 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1907 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001909 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001910 }
1911 mOutput->stream->drain(mOutput->stream,
1912 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1913 : AUDIO_DRAIN_ALL);
1914 }
1915}
1916
1917void AudioFlinger::PlaybackThread::threadLoop_exit()
1918{
1919 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001920}
1921
1922/*
1923The derived values that are cached:
1924 - mixBufferSize from frame count * frame size
1925 - activeSleepTime from activeSleepTimeUs()
1926 - idleSleepTime from idleSleepTimeUs()
1927 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1928 - maxPeriod from frame count and sample rate (MIXER only)
1929
1930The parameters that affect these derived values are:
1931 - frame count
1932 - frame size
1933 - sample rate
1934 - device type: A2DP or not
1935 - device latency
1936 - format: PCM or not
1937 - active sleep time
1938 - idle sleep time
1939*/
1940
1941void AudioFlinger::PlaybackThread::cacheParameters_l()
1942{
1943 mixBufferSize = mNormalFrameCount * mFrameSize;
1944 activeSleepTime = activeSleepTimeUs();
1945 idleSleepTime = idleSleepTimeUs();
1946}
1947
1948void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1949{
Glenn Kasten7c027242012-12-26 14:43:16 -08001950 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001951 this, streamType, mTracks.size());
1952 Mutex::Autolock _l(mLock);
1953
1954 size_t size = mTracks.size();
1955 for (size_t i = 0; i < size; i++) {
1956 sp<Track> t = mTracks[i];
1957 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001958 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001959 }
1960 }
1961}
1962
1963status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1964{
1965 int session = chain->sessionId();
1966 int16_t *buffer = mMixBuffer;
1967 bool ownsBuffer = false;
1968
1969 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1970 if (session > 0) {
1971 // Only one effect chain can be present in direct output thread and it uses
1972 // the mix buffer as input
1973 if (mType != DIRECT) {
1974 size_t numSamples = mNormalFrameCount * mChannelCount;
1975 buffer = new int16_t[numSamples];
1976 memset(buffer, 0, numSamples * sizeof(int16_t));
1977 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1978 ownsBuffer = true;
1979 }
1980
1981 // Attach all tracks with same session ID to this chain.
1982 for (size_t i = 0; i < mTracks.size(); ++i) {
1983 sp<Track> track = mTracks[i];
1984 if (session == track->sessionId()) {
1985 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1986 buffer);
1987 track->setMainBuffer(buffer);
1988 chain->incTrackCnt();
1989 }
1990 }
1991
1992 // indicate all active tracks in the chain
1993 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1994 sp<Track> track = mActiveTracks[i].promote();
1995 if (track == 0) {
1996 continue;
1997 }
1998 if (session == track->sessionId()) {
1999 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2000 chain->incActiveTrackCnt();
2001 }
2002 }
2003 }
2004
2005 chain->setInBuffer(buffer, ownsBuffer);
2006 chain->setOutBuffer(mMixBuffer);
2007 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2008 // chains list in order to be processed last as it contains output stage effects
2009 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2010 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2011 // after track specific effects and before output stage
2012 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2013 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2014 // Effect chain for other sessions are inserted at beginning of effect
2015 // chains list to be processed before output mix effects. Relative order between other
2016 // sessions is not important
2017 size_t size = mEffectChains.size();
2018 size_t i = 0;
2019 for (i = 0; i < size; i++) {
2020 if (mEffectChains[i]->sessionId() < session) {
2021 break;
2022 }
2023 }
2024 mEffectChains.insertAt(chain, i);
2025 checkSuspendOnAddEffectChain_l(chain);
2026
2027 return NO_ERROR;
2028}
2029
2030size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2031{
2032 int session = chain->sessionId();
2033
2034 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2035
2036 for (size_t i = 0; i < mEffectChains.size(); i++) {
2037 if (chain == mEffectChains[i]) {
2038 mEffectChains.removeAt(i);
2039 // detach all active tracks from the chain
2040 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2041 sp<Track> track = mActiveTracks[i].promote();
2042 if (track == 0) {
2043 continue;
2044 }
2045 if (session == track->sessionId()) {
2046 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2047 chain.get(), session);
2048 chain->decActiveTrackCnt();
2049 }
2050 }
2051
2052 // detach all tracks with same session ID from this chain
2053 for (size_t i = 0; i < mTracks.size(); ++i) {
2054 sp<Track> track = mTracks[i];
2055 if (session == track->sessionId()) {
2056 track->setMainBuffer(mMixBuffer);
2057 chain->decTrackCnt();
2058 }
2059 }
2060 break;
2061 }
2062 }
2063 return mEffectChains.size();
2064}
2065
2066status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2067 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2068{
2069 Mutex::Autolock _l(mLock);
2070 return attachAuxEffect_l(track, EffectId);
2071}
2072
2073status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2074 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2075{
2076 status_t status = NO_ERROR;
2077
2078 if (EffectId == 0) {
2079 track->setAuxBuffer(0, NULL);
2080 } else {
2081 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2082 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2083 if (effect != 0) {
2084 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2085 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2086 } else {
2087 status = INVALID_OPERATION;
2088 }
2089 } else {
2090 status = BAD_VALUE;
2091 }
2092 }
2093 return status;
2094}
2095
2096void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2097{
2098 for (size_t i = 0; i < mTracks.size(); ++i) {
2099 sp<Track> track = mTracks[i];
2100 if (track->auxEffectId() == effectId) {
2101 attachAuxEffect_l(track, 0);
2102 }
2103 }
2104}
2105
2106bool AudioFlinger::PlaybackThread::threadLoop()
2107{
2108 Vector< sp<Track> > tracksToRemove;
2109
2110 standbyTime = systemTime();
2111
2112 // MIXER
2113 nsecs_t lastWarning = 0;
2114
2115 // DUPLICATING
2116 // FIXME could this be made local to while loop?
2117 writeFrames = 0;
2118
2119 cacheParameters_l();
2120 sleepTime = idleSleepTime;
2121
2122 if (mType == MIXER) {
2123 sleepTimeShift = 0;
2124 }
2125
2126 CpuStats cpuStats;
2127 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2128
2129 acquireWakeLock();
2130
Glenn Kasten9e58b552013-01-18 15:09:48 -08002131 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2132 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2133 // and then that string will be logged at the next convenient opportunity.
2134 const char *logString = NULL;
2135
Eric Laurent664539d2013-09-23 18:24:31 -07002136 checkSilentMode_l();
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138 while (!exitPending())
2139 {
2140 cpuStats.sample(myName);
2141
2142 Vector< sp<EffectChain> > effectChains;
2143
2144 processConfigEvents();
2145
2146 { // scope for mLock
2147
2148 Mutex::Autolock _l(mLock);
2149
Glenn Kasten9e58b552013-01-18 15:09:48 -08002150 if (logString != NULL) {
2151 mNBLogWriter->logTimestamp();
2152 mNBLogWriter->log(logString);
2153 logString = NULL;
2154 }
2155
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002156 if (mLatchDValid) {
2157 mLatchQ = mLatchD;
2158 mLatchDValid = false;
2159 mLatchQValid = true;
2160 }
2161
Eric Laurent81784c32012-11-19 14:55:58 -08002162 if (checkForNewParameters_l()) {
2163 cacheParameters_l();
2164 }
2165
2166 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167 if (mSignalPending) {
2168 // A signal was raised while we were unlocked
2169 mSignalPending = false;
2170 } else if (waitingAsyncCallback_l()) {
2171 if (exitPending()) {
2172 break;
2173 }
2174 releaseWakeLock_l();
2175 ALOGV("wait async completion");
2176 mWaitWorkCV.wait(mLock);
2177 ALOGV("async completion/wake");
2178 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002179 standbyTime = systemTime() + standbyDelay;
2180 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002181
2182 continue;
2183 }
2184 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185 isSuspended()) {
2186 // put audio hardware into standby after short delay
2187 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002188
2189 threadLoop_standby();
2190
2191 mStandby = true;
2192 }
2193
2194 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2195 // we're about to wait, flush the binder command buffer
2196 IPCThreadState::self()->flushCommands();
2197
2198 clearOutputTracks();
2199
2200 if (exitPending()) {
2201 break;
2202 }
2203
2204 releaseWakeLock_l();
2205 // wait until we have something to do...
2206 ALOGV("%s going to sleep", myName.string());
2207 mWaitWorkCV.wait(mLock);
2208 ALOGV("%s waking up", myName.string());
2209 acquireWakeLock_l();
2210
2211 mMixerStatus = MIXER_IDLE;
2212 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2213 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002214 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002215 checkSilentMode_l();
2216
2217 standbyTime = systemTime() + standbyDelay;
2218 sleepTime = idleSleepTime;
2219 if (mType == MIXER) {
2220 sleepTimeShift = 0;
2221 }
2222
2223 continue;
2224 }
2225 }
Eric Laurent81784c32012-11-19 14:55:58 -08002226 // mMixerStatusIgnoringFastTracks is also updated internally
2227 mMixerStatus = prepareTracks_l(&tracksToRemove);
2228
2229 // prevent any changes in effect chain list and in each effect chain
2230 // during mixing and effect process as the audio buffers could be deleted
2231 // or modified if an effect is created or deleted
2232 lockEffectChains_l(effectChains);
2233 }
2234
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 if (mBytesRemaining == 0) {
2236 mCurrentWriteLength = 0;
2237 if (mMixerStatus == MIXER_TRACKS_READY) {
2238 // threadLoop_mix() sets mCurrentWriteLength
2239 threadLoop_mix();
2240 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2241 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2242 // threadLoop_sleepTime sets sleepTime to 0 if data
2243 // must be written to HAL
2244 threadLoop_sleepTime();
2245 if (sleepTime == 0) {
2246 mCurrentWriteLength = mixBufferSize;
2247 }
2248 }
2249 mBytesRemaining = mCurrentWriteLength;
2250 if (isSuspended()) {
2251 sleepTime = suspendSleepTimeUs();
2252 // simulate write to HAL when suspended
2253 mBytesWritten += mixBufferSize;
2254 mBytesRemaining = 0;
2255 }
Eric Laurent81784c32012-11-19 14:55:58 -08002256
Eric Laurentbfb1b832013-01-07 09:53:42 -08002257 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002258 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002259 for (size_t i = 0; i < effectChains.size(); i ++) {
2260 effectChains[i]->process_l();
2261 }
Eric Laurent81784c32012-11-19 14:55:58 -08002262 }
2263 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002264 // Process effect chains for offloaded thread even if no audio
2265 // was read from audio track: process only updates effect state
2266 // and thus does have to be synchronized with audio writes but may have
2267 // to be called while waiting for async write callback
2268 if (mType == OFFLOAD) {
2269 for (size_t i = 0; i < effectChains.size(); i ++) {
2270 effectChains[i]->process_l();
2271 }
2272 }
Eric Laurent81784c32012-11-19 14:55:58 -08002273
2274 // enable changes in effect chain
2275 unlockEffectChains(effectChains);
2276
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277 if (!waitingAsyncCallback()) {
2278 // sleepTime == 0 means we must write to audio hardware
2279 if (sleepTime == 0) {
2280 if (mBytesRemaining) {
2281 ssize_t ret = threadLoop_write();
2282 if (ret < 0) {
2283 mBytesRemaining = 0;
2284 } else {
2285 mBytesWritten += ret;
2286 mBytesRemaining -= ret;
2287 }
2288 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2289 (mMixerStatus == MIXER_DRAIN_ALL)) {
2290 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002291 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292if (mType == MIXER) {
2293 // write blocked detection
2294 nsecs_t now = systemTime();
2295 nsecs_t delta = now - mLastWriteTime;
2296 if (!mStandby && delta > maxPeriod) {
2297 mNumDelayedWrites++;
2298 if ((now - lastWarning) > kWarningThrottleNs) {
2299 ATRACE_NAME("underrun");
2300 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2301 ns2ms(delta), mNumDelayedWrites, this);
2302 lastWarning = now;
2303 }
2304 }
Eric Laurent81784c32012-11-19 14:55:58 -08002305}
2306
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307 mStandby = false;
2308 } else {
2309 usleep(sleepTime);
2310 }
Eric Laurent81784c32012-11-19 14:55:58 -08002311 }
2312
2313 // Finally let go of removed track(s), without the lock held
2314 // since we can't guarantee the destructors won't acquire that
2315 // same lock. This will also mutate and push a new fast mixer state.
2316 threadLoop_removeTracks(tracksToRemove);
2317 tracksToRemove.clear();
2318
2319 // FIXME I don't understand the need for this here;
2320 // it was in the original code but maybe the
2321 // assignment in saveOutputTracks() makes this unnecessary?
2322 clearOutputTracks();
2323
2324 // Effect chains will be actually deleted here if they were removed from
2325 // mEffectChains list during mixing or effects processing
2326 effectChains.clear();
2327
2328 // FIXME Note that the above .clear() is no longer necessary since effectChains
2329 // is now local to this block, but will keep it for now (at least until merge done).
2330 }
2331
Eric Laurentbfb1b832013-01-07 09:53:42 -08002332 threadLoop_exit();
2333
Eric Laurent81784c32012-11-19 14:55:58 -08002334 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002336 // put output stream into standby mode
2337 if (!mStandby) {
2338 mOutput->stream->common.standby(&mOutput->stream->common);
2339 }
2340 }
2341
2342 releaseWakeLock();
2343
2344 ALOGV("Thread %p type %d exiting", this, mType);
2345 return false;
2346}
2347
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348// removeTracks_l() must be called with ThreadBase::mLock held
2349void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2350{
2351 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002352 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 for (size_t i=0 ; i<count ; i++) {
2354 const sp<Track>& track = tracksToRemove.itemAt(i);
2355 mActiveTracks.remove(track);
2356 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2357 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2358 if (chain != 0) {
2359 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2360 track->sessionId());
2361 chain->decActiveTrackCnt();
2362 }
2363 if (track->isTerminated()) {
2364 removeTrack_l(track);
2365 }
2366 }
2367 }
2368
2369}
Eric Laurent81784c32012-11-19 14:55:58 -08002370
Eric Laurentaccc1472013-09-20 09:36:34 -07002371status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2372{
2373 if (mNormalSink != 0) {
2374 return mNormalSink->getTimestamp(timestamp);
2375 }
2376 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2377 uint64_t position64;
2378 int ret = mOutput->stream->get_presentation_position(
2379 mOutput->stream, &position64, &timestamp.mTime);
2380 if (ret == 0) {
2381 timestamp.mPosition = (uint32_t)position64;
2382 return NO_ERROR;
2383 }
2384 }
2385 return INVALID_OPERATION;
2386}
Eric Laurent81784c32012-11-19 14:55:58 -08002387// ----------------------------------------------------------------------------
2388
2389AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2390 audio_io_handle_t id, audio_devices_t device, type_t type)
2391 : PlaybackThread(audioFlinger, output, id, device, type),
2392 // mAudioMixer below
2393 // mFastMixer below
2394 mFastMixerFutex(0)
2395 // mOutputSink below
2396 // mPipeSink below
2397 // mNormalSink below
2398{
2399 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002400 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002401 "mFrameCount=%d, mNormalFrameCount=%d",
2402 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2403 mNormalFrameCount);
2404 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2405
2406 // FIXME - Current mixer implementation only supports stereo output
2407 if (mChannelCount != FCC_2) {
2408 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2409 }
2410
2411 // create an NBAIO sink for the HAL output stream, and negotiate
2412 mOutputSink = new AudioStreamOutSink(output->stream);
2413 size_t numCounterOffers = 0;
2414 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2415 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2416 ALOG_ASSERT(index == 0);
2417
2418 // initialize fast mixer depending on configuration
2419 bool initFastMixer;
2420 switch (kUseFastMixer) {
2421 case FastMixer_Never:
2422 initFastMixer = false;
2423 break;
2424 case FastMixer_Always:
2425 initFastMixer = true;
2426 break;
2427 case FastMixer_Static:
2428 case FastMixer_Dynamic:
2429 initFastMixer = mFrameCount < mNormalFrameCount;
2430 break;
2431 }
2432 if (initFastMixer) {
2433
2434 // create a MonoPipe to connect our submix to FastMixer
2435 NBAIO_Format format = mOutputSink->format();
2436 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2437 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2438 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2439 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2440 const NBAIO_Format offers[1] = {format};
2441 size_t numCounterOffers = 0;
2442 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2443 ALOG_ASSERT(index == 0);
2444 monoPipe->setAvgFrames((mScreenState & 1) ?
2445 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2446 mPipeSink = monoPipe;
2447
Glenn Kasten46909e72013-02-26 09:20:22 -08002448#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002449 if (mTeeSinkOutputEnabled) {
2450 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2451 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2452 numCounterOffers = 0;
2453 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2454 ALOG_ASSERT(index == 0);
2455 mTeeSink = teeSink;
2456 PipeReader *teeSource = new PipeReader(*teeSink);
2457 numCounterOffers = 0;
2458 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2459 ALOG_ASSERT(index == 0);
2460 mTeeSource = teeSource;
2461 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002462#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002463
2464 // create fast mixer and configure it initially with just one fast track for our submix
2465 mFastMixer = new FastMixer();
2466 FastMixerStateQueue *sq = mFastMixer->sq();
2467#ifdef STATE_QUEUE_DUMP
2468 sq->setObserverDump(&mStateQueueObserverDump);
2469 sq->setMutatorDump(&mStateQueueMutatorDump);
2470#endif
2471 FastMixerState *state = sq->begin();
2472 FastTrack *fastTrack = &state->mFastTracks[0];
2473 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2474 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2475 fastTrack->mVolumeProvider = NULL;
2476 fastTrack->mGeneration++;
2477 state->mFastTracksGen++;
2478 state->mTrackMask = 1;
2479 // fast mixer will use the HAL output sink
2480 state->mOutputSink = mOutputSink.get();
2481 state->mOutputSinkGen++;
2482 state->mFrameCount = mFrameCount;
2483 state->mCommand = FastMixerState::COLD_IDLE;
2484 // already done in constructor initialization list
2485 //mFastMixerFutex = 0;
2486 state->mColdFutexAddr = &mFastMixerFutex;
2487 state->mColdGen++;
2488 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002489#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002490 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002491#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002492 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2493 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002494 sq->end();
2495 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2496
2497 // start the fast mixer
2498 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2499 pid_t tid = mFastMixer->getTid();
2500 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2501 if (err != 0) {
2502 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2503 kPriorityFastMixer, getpid_cached, tid, err);
2504 }
2505
2506#ifdef AUDIO_WATCHDOG
2507 // create and start the watchdog
2508 mAudioWatchdog = new AudioWatchdog();
2509 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2510 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2511 tid = mAudioWatchdog->getTid();
2512 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2513 if (err != 0) {
2514 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2515 kPriorityFastMixer, getpid_cached, tid, err);
2516 }
2517#endif
2518
2519 } else {
2520 mFastMixer = NULL;
2521 }
2522
2523 switch (kUseFastMixer) {
2524 case FastMixer_Never:
2525 case FastMixer_Dynamic:
2526 mNormalSink = mOutputSink;
2527 break;
2528 case FastMixer_Always:
2529 mNormalSink = mPipeSink;
2530 break;
2531 case FastMixer_Static:
2532 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2533 break;
2534 }
2535}
2536
2537AudioFlinger::MixerThread::~MixerThread()
2538{
2539 if (mFastMixer != NULL) {
2540 FastMixerStateQueue *sq = mFastMixer->sq();
2541 FastMixerState *state = sq->begin();
2542 if (state->mCommand == FastMixerState::COLD_IDLE) {
2543 int32_t old = android_atomic_inc(&mFastMixerFutex);
2544 if (old == -1) {
2545 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2546 }
2547 }
2548 state->mCommand = FastMixerState::EXIT;
2549 sq->end();
2550 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2551 mFastMixer->join();
2552 // Though the fast mixer thread has exited, it's state queue is still valid.
2553 // We'll use that extract the final state which contains one remaining fast track
2554 // corresponding to our sub-mix.
2555 state = sq->begin();
2556 ALOG_ASSERT(state->mTrackMask == 1);
2557 FastTrack *fastTrack = &state->mFastTracks[0];
2558 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2559 delete fastTrack->mBufferProvider;
2560 sq->end(false /*didModify*/);
2561 delete mFastMixer;
2562#ifdef AUDIO_WATCHDOG
2563 if (mAudioWatchdog != 0) {
2564 mAudioWatchdog->requestExit();
2565 mAudioWatchdog->requestExitAndWait();
2566 mAudioWatchdog.clear();
2567 }
2568#endif
2569 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002570 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002571 delete mAudioMixer;
2572}
2573
2574
2575uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2576{
2577 if (mFastMixer != NULL) {
2578 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2579 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2580 }
2581 return latency;
2582}
2583
2584
2585void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2586{
2587 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2588}
2589
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002591{
2592 // FIXME we should only do one push per cycle; confirm this is true
2593 // Start the fast mixer if it's not already running
2594 if (mFastMixer != NULL) {
2595 FastMixerStateQueue *sq = mFastMixer->sq();
2596 FastMixerState *state = sq->begin();
2597 if (state->mCommand != FastMixerState::MIX_WRITE &&
2598 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2599 if (state->mCommand == FastMixerState::COLD_IDLE) {
2600 int32_t old = android_atomic_inc(&mFastMixerFutex);
2601 if (old == -1) {
2602 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2603 }
2604#ifdef AUDIO_WATCHDOG
2605 if (mAudioWatchdog != 0) {
2606 mAudioWatchdog->resume();
2607 }
2608#endif
2609 }
2610 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002611 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2612 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002613 sq->end();
2614 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2615 if (kUseFastMixer == FastMixer_Dynamic) {
2616 mNormalSink = mPipeSink;
2617 }
2618 } else {
2619 sq->end(false /*didModify*/);
2620 }
2621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002622 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002623}
2624
2625void AudioFlinger::MixerThread::threadLoop_standby()
2626{
2627 // Idle the fast mixer if it's currently running
2628 if (mFastMixer != NULL) {
2629 FastMixerStateQueue *sq = mFastMixer->sq();
2630 FastMixerState *state = sq->begin();
2631 if (!(state->mCommand & FastMixerState::IDLE)) {
2632 state->mCommand = FastMixerState::COLD_IDLE;
2633 state->mColdFutexAddr = &mFastMixerFutex;
2634 state->mColdGen++;
2635 mFastMixerFutex = 0;
2636 sq->end();
2637 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2638 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2639 if (kUseFastMixer == FastMixer_Dynamic) {
2640 mNormalSink = mOutputSink;
2641 }
2642#ifdef AUDIO_WATCHDOG
2643 if (mAudioWatchdog != 0) {
2644 mAudioWatchdog->pause();
2645 }
2646#endif
2647 } else {
2648 sq->end(false /*didModify*/);
2649 }
2650 }
2651 PlaybackThread::threadLoop_standby();
2652}
2653
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654// Empty implementation for standard mixer
2655// Overridden for offloaded playback
2656void AudioFlinger::PlaybackThread::flushOutput_l()
2657{
2658}
2659
2660bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2661{
2662 return false;
2663}
2664
2665bool AudioFlinger::PlaybackThread::shouldStandby_l()
2666{
2667 return !mStandby;
2668}
2669
2670bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2671{
2672 Mutex::Autolock _l(mLock);
2673 return waitingAsyncCallback_l();
2674}
2675
Eric Laurent81784c32012-11-19 14:55:58 -08002676// shared by MIXER and DIRECT, overridden by DUPLICATING
2677void AudioFlinger::PlaybackThread::threadLoop_standby()
2678{
2679 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2680 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002682 // discard any pending drain or write ack by incrementing sequence
2683 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2684 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002686 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2687 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 }
Eric Laurent81784c32012-11-19 14:55:58 -08002689}
2690
2691void AudioFlinger::MixerThread::threadLoop_mix()
2692{
2693 // obtain the presentation timestamp of the next output buffer
2694 int64_t pts;
2695 status_t status = INVALID_OPERATION;
2696
2697 if (mNormalSink != 0) {
2698 status = mNormalSink->getNextWriteTimestamp(&pts);
2699 } else {
2700 status = mOutputSink->getNextWriteTimestamp(&pts);
2701 }
2702
2703 if (status != NO_ERROR) {
2704 pts = AudioBufferProvider::kInvalidPTS;
2705 }
2706
2707 // mix buffers...
2708 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002710 // increase sleep time progressively when application underrun condition clears.
2711 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2712 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2713 // such that we would underrun the audio HAL.
2714 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2715 sleepTimeShift--;
2716 }
2717 sleepTime = 0;
2718 standbyTime = systemTime() + standbyDelay;
2719 //TODO: delay standby when effects have a tail
2720}
2721
2722void AudioFlinger::MixerThread::threadLoop_sleepTime()
2723{
2724 // If no tracks are ready, sleep once for the duration of an output
2725 // buffer size, then write 0s to the output
2726 if (sleepTime == 0) {
2727 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2728 sleepTime = activeSleepTime >> sleepTimeShift;
2729 if (sleepTime < kMinThreadSleepTimeUs) {
2730 sleepTime = kMinThreadSleepTimeUs;
2731 }
2732 // reduce sleep time in case of consecutive application underruns to avoid
2733 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2734 // duration we would end up writing less data than needed by the audio HAL if
2735 // the condition persists.
2736 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2737 sleepTimeShift++;
2738 }
2739 } else {
2740 sleepTime = idleSleepTime;
2741 }
2742 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002743 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 sleepTime = 0;
2745 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2746 "anticipated start");
2747 }
2748 // TODO add standby time extension fct of effect tail
2749}
2750
2751// prepareTracks_l() must be called with ThreadBase::mLock held
2752AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2753 Vector< sp<Track> > *tracksToRemove)
2754{
2755
2756 mixer_state mixerStatus = MIXER_IDLE;
2757 // find out which tracks need to be processed
2758 size_t count = mActiveTracks.size();
2759 size_t mixedTracks = 0;
2760 size_t tracksWithEffect = 0;
2761 // counts only _active_ fast tracks
2762 size_t fastTracks = 0;
2763 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2764
2765 float masterVolume = mMasterVolume;
2766 bool masterMute = mMasterMute;
2767
2768 if (masterMute) {
2769 masterVolume = 0;
2770 }
2771 // Delegate master volume control to effect in output mix effect chain if needed
2772 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2773 if (chain != 0) {
2774 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2775 chain->setVolume_l(&v, &v);
2776 masterVolume = (float)((v + (1 << 23)) >> 24);
2777 chain.clear();
2778 }
2779
2780 // prepare a new state to push
2781 FastMixerStateQueue *sq = NULL;
2782 FastMixerState *state = NULL;
2783 bool didModify = false;
2784 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2785 if (mFastMixer != NULL) {
2786 sq = mFastMixer->sq();
2787 state = sq->begin();
2788 }
2789
2790 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002791 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002792 if (t == 0) {
2793 continue;
2794 }
2795
2796 // this const just means the local variable doesn't change
2797 Track* const track = t.get();
2798
2799 // process fast tracks
2800 if (track->isFastTrack()) {
2801
2802 // It's theoretically possible (though unlikely) for a fast track to be created
2803 // and then removed within the same normal mix cycle. This is not a problem, as
2804 // the track never becomes active so it's fast mixer slot is never touched.
2805 // The converse, of removing an (active) track and then creating a new track
2806 // at the identical fast mixer slot within the same normal mix cycle,
2807 // is impossible because the slot isn't marked available until the end of each cycle.
2808 int j = track->mFastIndex;
2809 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2810 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2811 FastTrack *fastTrack = &state->mFastTracks[j];
2812
2813 // Determine whether the track is currently in underrun condition,
2814 // and whether it had a recent underrun.
2815 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2816 FastTrackUnderruns underruns = ftDump->mUnderruns;
2817 uint32_t recentFull = (underruns.mBitFields.mFull -
2818 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2819 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2820 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2821 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2822 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2823 uint32_t recentUnderruns = recentPartial + recentEmpty;
2824 track->mObservedUnderruns = underruns;
2825 // don't count underruns that occur while stopping or pausing
2826 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002827 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2828 recentUnderruns > 0) {
2829 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2830 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002831 }
2832
2833 // This is similar to the state machine for normal tracks,
2834 // with a few modifications for fast tracks.
2835 bool isActive = true;
2836 switch (track->mState) {
2837 case TrackBase::STOPPING_1:
2838 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002840 track->mState = TrackBase::STOPPING_2;
2841 }
2842 break;
2843 case TrackBase::PAUSING:
2844 // ramp down is not yet implemented
2845 track->setPaused();
2846 break;
2847 case TrackBase::RESUMING:
2848 // ramp up is not yet implemented
2849 track->mState = TrackBase::ACTIVE;
2850 break;
2851 case TrackBase::ACTIVE:
2852 if (recentFull > 0 || recentPartial > 0) {
2853 // track has provided at least some frames recently: reset retry count
2854 track->mRetryCount = kMaxTrackRetries;
2855 }
2856 if (recentUnderruns == 0) {
2857 // no recent underruns: stay active
2858 break;
2859 }
2860 // there has recently been an underrun of some kind
2861 if (track->sharedBuffer() == 0) {
2862 // were any of the recent underruns "empty" (no frames available)?
2863 if (recentEmpty == 0) {
2864 // no, then ignore the partial underruns as they are allowed indefinitely
2865 break;
2866 }
2867 // there has recently been an "empty" underrun: decrement the retry counter
2868 if (--(track->mRetryCount) > 0) {
2869 break;
2870 }
2871 // indicate to client process that the track was disabled because of underrun;
2872 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002873 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002874 // remove from active list, but state remains ACTIVE [confusing but true]
2875 isActive = false;
2876 break;
2877 }
2878 // fall through
2879 case TrackBase::STOPPING_2:
2880 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002881 case TrackBase::STOPPED:
2882 case TrackBase::FLUSHED: // flush() while active
2883 // Check for presentation complete if track is inactive
2884 // We have consumed all the buffers of this track.
2885 // This would be incomplete if we auto-paused on underrun
2886 {
2887 size_t audioHALFrames =
2888 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2889 size_t framesWritten = mBytesWritten / mFrameSize;
2890 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2891 // track stays in active list until presentation is complete
2892 break;
2893 }
2894 }
2895 if (track->isStopping_2()) {
2896 track->mState = TrackBase::STOPPED;
2897 }
2898 if (track->isStopped()) {
2899 // Can't reset directly, as fast mixer is still polling this track
2900 // track->reset();
2901 // So instead mark this track as needing to be reset after push with ack
2902 resetMask |= 1 << i;
2903 }
2904 isActive = false;
2905 break;
2906 case TrackBase::IDLE:
2907 default:
2908 LOG_FATAL("unexpected track state %d", track->mState);
2909 }
2910
2911 if (isActive) {
2912 // was it previously inactive?
2913 if (!(state->mTrackMask & (1 << j))) {
2914 ExtendedAudioBufferProvider *eabp = track;
2915 VolumeProvider *vp = track;
2916 fastTrack->mBufferProvider = eabp;
2917 fastTrack->mVolumeProvider = vp;
2918 fastTrack->mSampleRate = track->mSampleRate;
2919 fastTrack->mChannelMask = track->mChannelMask;
2920 fastTrack->mGeneration++;
2921 state->mTrackMask |= 1 << j;
2922 didModify = true;
2923 // no acknowledgement required for newly active tracks
2924 }
2925 // cache the combined master volume and stream type volume for fast mixer; this
2926 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002927 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002928 ++fastTracks;
2929 } else {
2930 // was it previously active?
2931 if (state->mTrackMask & (1 << j)) {
2932 fastTrack->mBufferProvider = NULL;
2933 fastTrack->mGeneration++;
2934 state->mTrackMask &= ~(1 << j);
2935 didModify = true;
2936 // If any fast tracks were removed, we must wait for acknowledgement
2937 // because we're about to decrement the last sp<> on those tracks.
2938 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2939 } else {
2940 LOG_FATAL("fast track %d should have been active", j);
2941 }
2942 tracksToRemove->add(track);
2943 // Avoids a misleading display in dumpsys
2944 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2945 }
2946 continue;
2947 }
2948
2949 { // local variable scope to avoid goto warning
2950
2951 audio_track_cblk_t* cblk = track->cblk();
2952
2953 // The first time a track is added we wait
2954 // for all its buffers to be filled before processing it
2955 int name = track->name();
2956 // make sure that we have enough frames to mix one full buffer.
2957 // enforce this condition only once to enable draining the buffer in case the client
2958 // app does not call stop() and relies on underrun to stop:
2959 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2960 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002961 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002962 uint32_t sr = track->sampleRate();
2963 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002964 desiredFrames = mNormalFrameCount;
2965 } else {
2966 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002967 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002968 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002969 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002970 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2971 // the minimum track buffer size is normally twice the number of frames necessary
2972 // to fill one buffer and the resampler should not leave more than one buffer worth
2973 // of unreleased frames after each pass, but just in case...
2974 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2975 }
Eric Laurent81784c32012-11-19 14:55:58 -08002976 uint32_t minFrames = 1;
2977 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2978 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002979 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002980 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002981 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2982 size_t framesReady;
2983 if (track->sharedBuffer() == 0) {
2984 framesReady = track->framesReady();
2985 } else if (track->isStopped()) {
2986 framesReady = 0;
2987 } else {
2988 framesReady = 1;
2989 }
2990 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002991 !track->isPaused() && !track->isTerminated())
2992 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002993 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002994
2995 mixedTracks++;
2996
2997 // track->mainBuffer() != mMixBuffer means there is an effect chain
2998 // connected to the track
2999 chain.clear();
3000 if (track->mainBuffer() != mMixBuffer) {
3001 chain = getEffectChain_l(track->sessionId());
3002 // Delegate volume control to effect in track effect chain if needed
3003 if (chain != 0) {
3004 tracksWithEffect++;
3005 } else {
3006 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3007 "session %d",
3008 name, track->sessionId());
3009 }
3010 }
3011
3012
3013 int param = AudioMixer::VOLUME;
3014 if (track->mFillingUpStatus == Track::FS_FILLED) {
3015 // no ramp for the first volume setting
3016 track->mFillingUpStatus = Track::FS_ACTIVE;
3017 if (track->mState == TrackBase::RESUMING) {
3018 track->mState = TrackBase::ACTIVE;
3019 param = AudioMixer::RAMP_VOLUME;
3020 }
3021 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003022 // FIXME should not make a decision based on mServer
3023 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003024 // If the track is stopped before the first frame was mixed,
3025 // do not apply ramp
3026 param = AudioMixer::RAMP_VOLUME;
3027 }
3028
3029 // compute volume for this track
3030 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003031 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003032 vl = vr = va = 0;
3033 if (track->isPausing()) {
3034 track->setPaused();
3035 }
3036 } else {
3037
3038 // read original volumes with volume control
3039 float typeVolume = mStreamTypes[track->streamType()].volume;
3040 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003041 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003042 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003043 vl = vlr & 0xFFFF;
3044 vr = vlr >> 16;
3045 // track volumes come from shared memory, so can't be trusted and must be clamped
3046 if (vl > MAX_GAIN_INT) {
3047 ALOGV("Track left volume out of range: %04X", vl);
3048 vl = MAX_GAIN_INT;
3049 }
3050 if (vr > MAX_GAIN_INT) {
3051 ALOGV("Track right volume out of range: %04X", vr);
3052 vr = MAX_GAIN_INT;
3053 }
3054 // now apply the master volume and stream type volume
3055 vl = (uint32_t)(v * vl) << 12;
3056 vr = (uint32_t)(v * vr) << 12;
3057 // assuming master volume and stream type volume each go up to 1.0,
3058 // vl and vr are now in 8.24 format
3059
Glenn Kastene3aa6592012-12-04 12:22:46 -08003060 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // send level comes from shared memory and so may be corrupt
3062 if (sendLevel > MAX_GAIN_INT) {
3063 ALOGV("Track send level out of range: %04X", sendLevel);
3064 sendLevel = MAX_GAIN_INT;
3065 }
3066 va = (uint32_t)(v * sendLevel);
3067 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068
Eric Laurent81784c32012-11-19 14:55:58 -08003069 // Delegate volume control to effect in track effect chain if needed
3070 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3071 // Do not ramp volume if volume is controlled by effect
3072 param = AudioMixer::VOLUME;
3073 track->mHasVolumeController = true;
3074 } else {
3075 // force no volume ramp when volume controller was just disabled or removed
3076 // from effect chain to avoid volume spike
3077 if (track->mHasVolumeController) {
3078 param = AudioMixer::VOLUME;
3079 }
3080 track->mHasVolumeController = false;
3081 }
3082
3083 // Convert volumes from 8.24 to 4.12 format
3084 // This additional clamping is needed in case chain->setVolume_l() overshot
3085 vl = (vl + (1 << 11)) >> 12;
3086 if (vl > MAX_GAIN_INT) {
3087 vl = MAX_GAIN_INT;
3088 }
3089 vr = (vr + (1 << 11)) >> 12;
3090 if (vr > MAX_GAIN_INT) {
3091 vr = MAX_GAIN_INT;
3092 }
3093
3094 if (va > MAX_GAIN_INT) {
3095 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3096 }
3097
3098 // XXX: these things DON'T need to be done each time
3099 mAudioMixer->setBufferProvider(name, track);
3100 mAudioMixer->enable(name);
3101
3102 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3103 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3104 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3105 mAudioMixer->setParameter(
3106 name,
3107 AudioMixer::TRACK,
3108 AudioMixer::FORMAT, (void *)track->format());
3109 mAudioMixer->setParameter(
3110 name,
3111 AudioMixer::TRACK,
3112 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003113 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3114 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003115 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003116 if (reqSampleRate == 0) {
3117 reqSampleRate = mSampleRate;
3118 } else if (reqSampleRate > maxSampleRate) {
3119 reqSampleRate = maxSampleRate;
3120 }
Eric Laurent81784c32012-11-19 14:55:58 -08003121 mAudioMixer->setParameter(
3122 name,
3123 AudioMixer::RESAMPLE,
3124 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003125 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003126 mAudioMixer->setParameter(
3127 name,
3128 AudioMixer::TRACK,
3129 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3130 mAudioMixer->setParameter(
3131 name,
3132 AudioMixer::TRACK,
3133 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3134
3135 // reset retry count
3136 track->mRetryCount = kMaxTrackRetries;
3137
3138 // If one track is ready, set the mixer ready if:
3139 // - the mixer was not ready during previous round OR
3140 // - no other track is not ready
3141 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3142 mixerStatus != MIXER_TRACKS_ENABLED) {
3143 mixerStatus = MIXER_TRACKS_READY;
3144 }
3145 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003146 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003147 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003148 }
Eric Laurent81784c32012-11-19 14:55:58 -08003149 // clear effect chain input buffer if an active track underruns to avoid sending
3150 // previous audio buffer again to effects
3151 chain = getEffectChain_l(track->sessionId());
3152 if (chain != 0) {
3153 chain->clearInputBuffer();
3154 }
3155
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003156 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003157 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3158 track->isStopped() || track->isPaused()) {
3159 // We have consumed all the buffers of this track.
3160 // Remove it from the list of active tracks.
3161 // TODO: use actual buffer filling status instead of latency when available from
3162 // audio HAL
3163 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3164 size_t framesWritten = mBytesWritten / mFrameSize;
3165 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3166 if (track->isStopped()) {
3167 track->reset();
3168 }
3169 tracksToRemove->add(track);
3170 }
3171 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003172 // No buffers for this track. Give it a few chances to
3173 // fill a buffer, then remove it from active list.
3174 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003175 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003176 tracksToRemove->add(track);
3177 // indicate to client process that the track was disabled because of underrun;
3178 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003179 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003180 // If one track is not ready, mark the mixer also not ready if:
3181 // - the mixer was ready during previous round OR
3182 // - no other track is ready
3183 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3184 mixerStatus != MIXER_TRACKS_READY) {
3185 mixerStatus = MIXER_TRACKS_ENABLED;
3186 }
3187 }
3188 mAudioMixer->disable(name);
3189 }
3190
3191 } // local variable scope to avoid goto warning
3192track_is_ready: ;
3193
3194 }
3195
3196 // Push the new FastMixer state if necessary
3197 bool pauseAudioWatchdog = false;
3198 if (didModify) {
3199 state->mFastTracksGen++;
3200 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3201 if (kUseFastMixer == FastMixer_Dynamic &&
3202 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3203 state->mCommand = FastMixerState::COLD_IDLE;
3204 state->mColdFutexAddr = &mFastMixerFutex;
3205 state->mColdGen++;
3206 mFastMixerFutex = 0;
3207 if (kUseFastMixer == FastMixer_Dynamic) {
3208 mNormalSink = mOutputSink;
3209 }
3210 // If we go into cold idle, need to wait for acknowledgement
3211 // so that fast mixer stops doing I/O.
3212 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3213 pauseAudioWatchdog = true;
3214 }
Eric Laurent81784c32012-11-19 14:55:58 -08003215 }
3216 if (sq != NULL) {
3217 sq->end(didModify);
3218 sq->push(block);
3219 }
3220#ifdef AUDIO_WATCHDOG
3221 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3222 mAudioWatchdog->pause();
3223 }
3224#endif
3225
3226 // Now perform the deferred reset on fast tracks that have stopped
3227 while (resetMask != 0) {
3228 size_t i = __builtin_ctz(resetMask);
3229 ALOG_ASSERT(i < count);
3230 resetMask &= ~(1 << i);
3231 sp<Track> t = mActiveTracks[i].promote();
3232 if (t == 0) {
3233 continue;
3234 }
3235 Track* track = t.get();
3236 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3237 track->reset();
3238 }
3239
3240 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003242
3243 // mix buffer must be cleared if all tracks are connected to an
3244 // effect chain as in this case the mixer will not write to
3245 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3247 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003248 // FIXME as a performance optimization, should remember previous zero status
3249 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3250 }
3251
3252 // if any fast tracks, then status is ready
3253 mMixerStatusIgnoringFastTracks = mixerStatus;
3254 if (fastTracks > 0) {
3255 mixerStatus = MIXER_TRACKS_READY;
3256 }
3257 return mixerStatus;
3258}
3259
3260// getTrackName_l() must be called with ThreadBase::mLock held
3261int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3262{
3263 return mAudioMixer->getTrackName(channelMask, sessionId);
3264}
3265
3266// deleteTrackName_l() must be called with ThreadBase::mLock held
3267void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3268{
3269 ALOGV("remove track (%d) and delete from mixer", name);
3270 mAudioMixer->deleteTrackName(name);
3271}
3272
3273// checkForNewParameters_l() must be called with ThreadBase::mLock held
3274bool AudioFlinger::MixerThread::checkForNewParameters_l()
3275{
3276 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3277 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3278 bool reconfig = false;
3279
3280 while (!mNewParameters.isEmpty()) {
3281
3282 if (mFastMixer != NULL) {
3283 FastMixerStateQueue *sq = mFastMixer->sq();
3284 FastMixerState *state = sq->begin();
3285 if (!(state->mCommand & FastMixerState::IDLE)) {
3286 previousCommand = state->mCommand;
3287 state->mCommand = FastMixerState::HOT_IDLE;
3288 sq->end();
3289 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3290 } else {
3291 sq->end(false /*didModify*/);
3292 }
3293 }
3294
3295 status_t status = NO_ERROR;
3296 String8 keyValuePair = mNewParameters[0];
3297 AudioParameter param = AudioParameter(keyValuePair);
3298 int value;
3299
3300 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3301 reconfig = true;
3302 }
3303 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3304 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3305 status = BAD_VALUE;
3306 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003307 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003308 reconfig = true;
3309 }
3310 }
3311 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003312 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003313 status = BAD_VALUE;
3314 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003315 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003316 reconfig = true;
3317 }
3318 }
3319 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3320 // do not accept frame count changes if tracks are open as the track buffer
3321 // size depends on frame count and correct behavior would not be guaranteed
3322 // if frame count is changed after track creation
3323 if (!mTracks.isEmpty()) {
3324 status = INVALID_OPERATION;
3325 } else {
3326 reconfig = true;
3327 }
3328 }
3329 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3330#ifdef ADD_BATTERY_DATA
3331 // when changing the audio output device, call addBatteryData to notify
3332 // the change
3333 if (mOutDevice != value) {
3334 uint32_t params = 0;
3335 // check whether speaker is on
3336 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3337 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3338 }
3339
3340 audio_devices_t deviceWithoutSpeaker
3341 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3342 // check if any other device (except speaker) is on
3343 if (value & deviceWithoutSpeaker ) {
3344 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3345 }
3346
3347 if (params != 0) {
3348 addBatteryData(params);
3349 }
3350 }
3351#endif
3352
3353 // forward device change to effects that have requested to be
3354 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003355 if (value != AUDIO_DEVICE_NONE) {
3356 mOutDevice = value;
3357 for (size_t i = 0; i < mEffectChains.size(); i++) {
3358 mEffectChains[i]->setDevice_l(mOutDevice);
3359 }
Eric Laurent81784c32012-11-19 14:55:58 -08003360 }
3361 }
3362
3363 if (status == NO_ERROR) {
3364 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3365 keyValuePair.string());
3366 if (!mStandby && status == INVALID_OPERATION) {
3367 mOutput->stream->common.standby(&mOutput->stream->common);
3368 mStandby = true;
3369 mBytesWritten = 0;
3370 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3371 keyValuePair.string());
3372 }
3373 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003374 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003375 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003376 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3377 for (size_t i = 0; i < mTracks.size() ; i++) {
3378 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3379 if (name < 0) {
3380 break;
3381 }
3382 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003383 }
3384 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3385 }
3386 }
3387
3388 mNewParameters.removeAt(0);
3389
3390 mParamStatus = status;
3391 mParamCond.signal();
3392 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3393 // already timed out waiting for the status and will never signal the condition.
3394 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3395 }
3396
3397 if (!(previousCommand & FastMixerState::IDLE)) {
3398 ALOG_ASSERT(mFastMixer != NULL);
3399 FastMixerStateQueue *sq = mFastMixer->sq();
3400 FastMixerState *state = sq->begin();
3401 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3402 state->mCommand = previousCommand;
3403 sq->end();
3404 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3405 }
3406
3407 return reconfig;
3408}
3409
3410
3411void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3412{
3413 const size_t SIZE = 256;
3414 char buffer[SIZE];
3415 String8 result;
3416
3417 PlaybackThread::dumpInternals(fd, args);
3418
3419 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3420 result.append(buffer);
3421 write(fd, result.string(), result.size());
3422
3423 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003424 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003425 copy.dump(fd);
3426
3427#ifdef STATE_QUEUE_DUMP
3428 // Similar for state queue
3429 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3430 observerCopy.dump(fd);
3431 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3432 mutatorCopy.dump(fd);
3433#endif
3434
Glenn Kasten46909e72013-02-26 09:20:22 -08003435#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003436 // Write the tee output to a .wav file
3437 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003438#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003439
3440#ifdef AUDIO_WATCHDOG
3441 if (mAudioWatchdog != 0) {
3442 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3443 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3444 wdCopy.dump(fd);
3445 }
3446#endif
3447}
3448
3449uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3450{
3451 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3452}
3453
3454uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3455{
3456 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3457}
3458
3459void AudioFlinger::MixerThread::cacheParameters_l()
3460{
3461 PlaybackThread::cacheParameters_l();
3462
3463 // FIXME: Relaxed timing because of a certain device that can't meet latency
3464 // Should be reduced to 2x after the vendor fixes the driver issue
3465 // increase threshold again due to low power audio mode. The way this warning
3466 // threshold is calculated and its usefulness should be reconsidered anyway.
3467 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3468}
3469
3470// ----------------------------------------------------------------------------
3471
3472AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3473 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3474 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3475 // mLeftVolFloat, mRightVolFloat
3476{
3477}
3478
Eric Laurentbfb1b832013-01-07 09:53:42 -08003479AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3480 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3481 ThreadBase::type_t type)
3482 : PlaybackThread(audioFlinger, output, id, device, type)
3483 // mLeftVolFloat, mRightVolFloat
3484{
3485}
3486
Eric Laurent81784c32012-11-19 14:55:58 -08003487AudioFlinger::DirectOutputThread::~DirectOutputThread()
3488{
3489}
3490
Eric Laurentbfb1b832013-01-07 09:53:42 -08003491void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3492{
3493 audio_track_cblk_t* cblk = track->cblk();
3494 float left, right;
3495
3496 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3497 left = right = 0;
3498 } else {
3499 float typeVolume = mStreamTypes[track->streamType()].volume;
3500 float v = mMasterVolume * typeVolume;
3501 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3502 uint32_t vlr = proxy->getVolumeLR();
3503 float v_clamped = v * (vlr & 0xFFFF);
3504 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3505 left = v_clamped/MAX_GAIN;
3506 v_clamped = v * (vlr >> 16);
3507 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3508 right = v_clamped/MAX_GAIN;
3509 }
3510
3511 if (lastTrack) {
3512 if (left != mLeftVolFloat || right != mRightVolFloat) {
3513 mLeftVolFloat = left;
3514 mRightVolFloat = right;
3515
3516 // Convert volumes from float to 8.24
3517 uint32_t vl = (uint32_t)(left * (1 << 24));
3518 uint32_t vr = (uint32_t)(right * (1 << 24));
3519
3520 // Delegate volume control to effect in track effect chain if needed
3521 // only one effect chain can be present on DirectOutputThread, so if
3522 // there is one, the track is connected to it
3523 if (!mEffectChains.isEmpty()) {
3524 mEffectChains[0]->setVolume_l(&vl, &vr);
3525 left = (float)vl / (1 << 24);
3526 right = (float)vr / (1 << 24);
3527 }
3528 if (mOutput->stream->set_volume) {
3529 mOutput->stream->set_volume(mOutput->stream, left, right);
3530 }
3531 }
3532 }
3533}
3534
3535
Eric Laurent81784c32012-11-19 14:55:58 -08003536AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3537 Vector< sp<Track> > *tracksToRemove
3538)
3539{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003540 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003541 mixer_state mixerStatus = MIXER_IDLE;
3542
3543 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003544 for (size_t i = 0; i < count; i++) {
3545 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003546 // The track died recently
3547 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003548 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003549 }
3550
3551 Track* const track = t.get();
3552 audio_track_cblk_t* cblk = track->cblk();
3553
3554 // The first time a track is added we wait
3555 // for all its buffers to be filled before processing it
3556 uint32_t minFrames;
3557 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3558 minFrames = mNormalFrameCount;
3559 } else {
3560 minFrames = 1;
3561 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562 // Only consider last track started for volume and mixer state control.
3563 // This is the last entry in mActiveTracks unless a track underruns.
3564 // As we only care about the transition phase between two tracks on a
3565 // direct output, it is not a problem to ignore the underrun case.
3566 bool last = (i == (count - 1));
3567
Eric Laurent81784c32012-11-19 14:55:58 -08003568 if ((track->framesReady() >= minFrames) && track->isReady() &&
3569 !track->isPaused() && !track->isTerminated())
3570 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003571 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003572
3573 if (track->mFillingUpStatus == Track::FS_FILLED) {
3574 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003575 // make sure processVolume_l() will apply new volume even if 0
3576 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003577 if (track->mState == TrackBase::RESUMING) {
3578 track->mState = TrackBase::ACTIVE;
3579 }
3580 }
3581
3582 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003583 processVolume_l(track, last);
3584 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003585 // reset retry count
3586 track->mRetryCount = kMaxTrackRetriesDirect;
3587 mActiveTrack = t;
3588 mixerStatus = MIXER_TRACKS_READY;
3589 }
Eric Laurent81784c32012-11-19 14:55:58 -08003590 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003591 // clear effect chain input buffer if the last active track started underruns
3592 // to avoid sending previous audio buffer again to effects
3593 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003594 mEffectChains[0]->clearInputBuffer();
3595 }
3596
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003597 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003598 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3599 track->isStopped() || track->isPaused()) {
3600 // We have consumed all the buffers of this track.
3601 // Remove it from the list of active tracks.
3602 // TODO: implement behavior for compressed audio
3603 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3604 size_t framesWritten = mBytesWritten / mFrameSize;
3605 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3606 if (track->isStopped()) {
3607 track->reset();
3608 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003609 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003610 }
3611 } else {
3612 // No buffers for this track. Give it a few chances to
3613 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003614 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003615 if (--(track->mRetryCount) <= 0) {
3616 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003617 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003619 mixerStatus = MIXER_TRACKS_ENABLED;
3620 }
3621 }
3622 }
3623 }
3624
Eric Laurent81784c32012-11-19 14:55:58 -08003625 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003627
3628 return mixerStatus;
3629}
3630
3631void AudioFlinger::DirectOutputThread::threadLoop_mix()
3632{
Eric Laurent81784c32012-11-19 14:55:58 -08003633 size_t frameCount = mFrameCount;
3634 int8_t *curBuf = (int8_t *)mMixBuffer;
3635 // output audio to hardware
3636 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003637 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003638 buffer.frameCount = frameCount;
3639 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003640 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003641 memset(curBuf, 0, frameCount * mFrameSize);
3642 break;
3643 }
3644 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3645 frameCount -= buffer.frameCount;
3646 curBuf += buffer.frameCount * mFrameSize;
3647 mActiveTrack->releaseBuffer(&buffer);
3648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003650 sleepTime = 0;
3651 standbyTime = systemTime() + standbyDelay;
3652 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003653}
3654
3655void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3656{
3657 if (sleepTime == 0) {
3658 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3659 sleepTime = activeSleepTime;
3660 } else {
3661 sleepTime = idleSleepTime;
3662 }
3663 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3664 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3665 sleepTime = 0;
3666 }
3667}
3668
3669// getTrackName_l() must be called with ThreadBase::mLock held
3670int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3671 int sessionId)
3672{
3673 return 0;
3674}
3675
3676// deleteTrackName_l() must be called with ThreadBase::mLock held
3677void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3678{
3679}
3680
3681// checkForNewParameters_l() must be called with ThreadBase::mLock held
3682bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3683{
3684 bool reconfig = false;
3685
3686 while (!mNewParameters.isEmpty()) {
3687 status_t status = NO_ERROR;
3688 String8 keyValuePair = mNewParameters[0];
3689 AudioParameter param = AudioParameter(keyValuePair);
3690 int value;
3691
3692 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3693 // do not accept frame count changes if tracks are open as the track buffer
3694 // size depends on frame count and correct behavior would not be garantied
3695 // if frame count is changed after track creation
3696 if (!mTracks.isEmpty()) {
3697 status = INVALID_OPERATION;
3698 } else {
3699 reconfig = true;
3700 }
3701 }
3702 if (status == NO_ERROR) {
3703 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3704 keyValuePair.string());
3705 if (!mStandby && status == INVALID_OPERATION) {
3706 mOutput->stream->common.standby(&mOutput->stream->common);
3707 mStandby = true;
3708 mBytesWritten = 0;
3709 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3710 keyValuePair.string());
3711 }
3712 if (status == NO_ERROR && reconfig) {
3713 readOutputParameters();
3714 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3715 }
3716 }
3717
3718 mNewParameters.removeAt(0);
3719
3720 mParamStatus = status;
3721 mParamCond.signal();
3722 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3723 // already timed out waiting for the status and will never signal the condition.
3724 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3725 }
3726 return reconfig;
3727}
3728
3729uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3730{
3731 uint32_t time;
3732 if (audio_is_linear_pcm(mFormat)) {
3733 time = PlaybackThread::activeSleepTimeUs();
3734 } else {
3735 time = 10000;
3736 }
3737 return time;
3738}
3739
3740uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3741{
3742 uint32_t time;
3743 if (audio_is_linear_pcm(mFormat)) {
3744 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3745 } else {
3746 time = 10000;
3747 }
3748 return time;
3749}
3750
3751uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3752{
3753 uint32_t time;
3754 if (audio_is_linear_pcm(mFormat)) {
3755 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3756 } else {
3757 time = 10000;
3758 }
3759 return time;
3760}
3761
3762void AudioFlinger::DirectOutputThread::cacheParameters_l()
3763{
3764 PlaybackThread::cacheParameters_l();
3765
3766 // use shorter standby delay as on normal output to release
3767 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003768 if (audio_is_linear_pcm(mFormat)) {
3769 standbyDelay = microseconds(activeSleepTime*2);
3770 } else {
3771 standbyDelay = kOffloadStandbyDelayNs;
3772 }
Eric Laurent81784c32012-11-19 14:55:58 -08003773}
3774
3775// ----------------------------------------------------------------------------
3776
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003778 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003779 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003780 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003781 mWriteAckSequence(0),
3782 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003783{
3784}
3785
3786AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3787{
3788}
3789
3790void AudioFlinger::AsyncCallbackThread::onFirstRef()
3791{
3792 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3793}
3794
3795bool AudioFlinger::AsyncCallbackThread::threadLoop()
3796{
3797 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003798 uint32_t writeAckSequence;
3799 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800
3801 {
3802 Mutex::Autolock _l(mLock);
3803 mWaitWorkCV.wait(mLock);
3804 if (exitPending()) {
3805 break;
3806 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003807 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3808 mWriteAckSequence, mDrainSequence);
3809 writeAckSequence = mWriteAckSequence;
3810 mWriteAckSequence &= ~1;
3811 drainSequence = mDrainSequence;
3812 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813 }
3814 {
Eric Laurent4de95592013-09-26 15:28:21 -07003815 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3816 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003817 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003818 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003820 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003821 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003822 }
3823 }
3824 }
3825 }
3826 return false;
3827}
3828
3829void AudioFlinger::AsyncCallbackThread::exit()
3830{
3831 ALOGV("AsyncCallbackThread::exit");
3832 Mutex::Autolock _l(mLock);
3833 requestExit();
3834 mWaitWorkCV.broadcast();
3835}
3836
Eric Laurent3b4529e2013-09-05 18:09:19 -07003837void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838{
3839 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003840 // bit 0 is cleared
3841 mWriteAckSequence = sequence << 1;
3842}
3843
3844void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3845{
3846 Mutex::Autolock _l(mLock);
3847 // ignore unexpected callbacks
3848 if (mWriteAckSequence & 2) {
3849 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003850 mWaitWorkCV.signal();
3851 }
3852}
3853
Eric Laurent3b4529e2013-09-05 18:09:19 -07003854void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003855{
3856 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003857 // bit 0 is cleared
3858 mDrainSequence = sequence << 1;
3859}
3860
3861void AudioFlinger::AsyncCallbackThread::resetDraining()
3862{
3863 Mutex::Autolock _l(mLock);
3864 // ignore unexpected callbacks
3865 if (mDrainSequence & 2) {
3866 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867 mWaitWorkCV.signal();
3868 }
3869}
3870
3871
3872// ----------------------------------------------------------------------------
3873AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3874 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3875 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3876 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003877 mFlushPending(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 mPausedBytesRemaining(0)
3879{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880}
3881
3882AudioFlinger::OffloadThread::~OffloadThread()
3883{
3884 mPreviousTrack.clear();
3885}
3886
3887void AudioFlinger::OffloadThread::threadLoop_exit()
3888{
3889 if (mFlushPending || mHwPaused) {
3890 // If a flush is pending or track was paused, just discard buffered data
3891 flushHw_l();
3892 } else {
3893 mMixerStatus = MIXER_DRAIN_ALL;
3894 threadLoop_drain();
3895 }
3896 mCallbackThread->exit();
3897 PlaybackThread::threadLoop_exit();
3898}
3899
3900AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3901 Vector< sp<Track> > *tracksToRemove
3902)
3903{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 size_t count = mActiveTracks.size();
3905
3906 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003907 bool doHwPause = false;
3908 bool doHwResume = false;
3909
Eric Laurentede6c3b2013-09-19 14:37:46 -07003910 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3911
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 // find out which tracks need to be processed
3913 for (size_t i = 0; i < count; i++) {
3914 sp<Track> t = mActiveTracks[i].promote();
3915 // The track died recently
3916 if (t == 0) {
3917 continue;
3918 }
3919 Track* const track = t.get();
3920 audio_track_cblk_t* cblk = track->cblk();
3921 if (mPreviousTrack != NULL) {
3922 if (t != mPreviousTrack) {
3923 // Flush any data still being written from last track
3924 mBytesRemaining = 0;
3925 if (mPausedBytesRemaining) {
3926 // Last track was paused so we also need to flush saved
3927 // mixbuffer state and invalidate track so that it will
3928 // re-submit that unwritten data when it is next resumed
3929 mPausedBytesRemaining = 0;
3930 // Invalidate is a bit drastic - would be more efficient
3931 // to have a flag to tell client that some of the
3932 // previously written data was lost
3933 mPreviousTrack->invalidate();
3934 }
3935 }
3936 }
3937 mPreviousTrack = t;
3938 bool last = (i == (count - 1));
3939 if (track->isPausing()) {
3940 track->setPaused();
3941 if (last) {
3942 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003943 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003944 mHwPaused = true;
3945 }
3946 // If we were part way through writing the mixbuffer to
3947 // the HAL we must save this until we resume
3948 // BUG - this will be wrong if a different track is made active,
3949 // in that case we want to discard the pending data in the
3950 // mixbuffer and tell the client to present it again when the
3951 // track is resumed
3952 mPausedWriteLength = mCurrentWriteLength;
3953 mPausedBytesRemaining = mBytesRemaining;
3954 mBytesRemaining = 0; // stop writing
3955 }
3956 tracksToRemove->add(track);
3957 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003958 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003959 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960 if (track->mFillingUpStatus == Track::FS_FILLED) {
3961 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003962 // make sure processVolume_l() will apply new volume even if 0
3963 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003966 if (last) {
3967 if (mPausedBytesRemaining) {
3968 // Need to continue write that was interrupted
3969 mCurrentWriteLength = mPausedWriteLength;
3970 mBytesRemaining = mPausedBytesRemaining;
3971 mPausedBytesRemaining = 0;
3972 }
3973 if (mHwPaused) {
3974 doHwResume = true;
3975 mHwPaused = false;
3976 // threadLoop_mix() will handle the case that we need to
3977 // resume an interrupted write
3978 }
3979 // enable write to audio HAL
3980 sleepTime = 0;
3981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003982 }
3983 }
3984
3985 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003986 // reset retry count
3987 track->mRetryCount = kMaxTrackRetriesOffload;
3988 mActiveTrack = t;
3989 mixerStatus = MIXER_TRACKS_READY;
3990 }
3991 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003992 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003993 if (track->isStopping_1()) {
3994 // Hardware buffer can hold a large amount of audio so we must
3995 // wait for all current track's data to drain before we say
3996 // that the track is stopped.
3997 if (mBytesRemaining == 0) {
3998 // Only start draining when all data in mixbuffer
3999 // has been written
4000 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4001 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurentbfb1b832013-01-07 09:53:42 -08004002 if (last) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07004003 sleepTime = 0;
4004 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07004006 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 if (mHwPaused) {
4008 // It is possible to move from PAUSED to STOPPING_1 without
4009 // a resume so we must ensure hardware is running
4010 mOutput->stream->resume(mOutput->stream);
4011 mHwPaused = false;
4012 }
4013 }
4014 }
4015 } else if (track->isStopping_2()) {
4016 // Drain has completed, signal presentation complete
Eric Laurent3b4529e2013-09-05 18:09:19 -07004017 if (!(mDrainSequence & 1) || !last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004018 track->mState = TrackBase::STOPPED;
4019 size_t audioHALFrames =
4020 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4021 size_t framesWritten =
4022 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4023 track->presentationComplete(framesWritten, audioHALFrames);
4024 track->reset();
4025 tracksToRemove->add(track);
4026 }
4027 } else {
4028 // No buffers for this track. Give it a few chances to
4029 // fill a buffer, then remove it from active list.
4030 if (--(track->mRetryCount) <= 0) {
4031 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4032 track->name());
4033 tracksToRemove->add(track);
4034 } else if (last){
4035 mixerStatus = MIXER_TRACKS_ENABLED;
4036 }
4037 }
4038 }
4039 // compute volume for this track
4040 processVolume_l(track, last);
4041 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004042
Eric Laurentea0fade2013-10-04 16:23:48 -07004043 // make sure the pause/flush/resume sequence is executed in the right order.
4044 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4045 // before flush and then resume HW. This can happen in case of pause/flush/resume
4046 // if resume is received before pause is executed.
4047 if (doHwPause || (mFlushPending && !mHwPaused && (count != 0))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004048 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004049 if (!doHwPause) {
4050 doHwResume = true;
4051 }
Eric Laurent972a1732013-09-04 09:42:59 -07004052 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004053 if (mFlushPending) {
4054 flushHw_l();
4055 mFlushPending = false;
4056 }
Eric Laurent972a1732013-09-04 09:42:59 -07004057 if (doHwResume) {
4058 mOutput->stream->resume(mOutput->stream);
4059 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004060
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061 // remove all the tracks that need to be...
4062 removeTracks_l(*tracksToRemove);
4063
4064 return mixerStatus;
4065}
4066
4067void AudioFlinger::OffloadThread::flushOutput_l()
4068{
4069 mFlushPending = true;
4070}
4071
4072// must be called with thread mutex locked
4073bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4074{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004075 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4076 mWriteAckSequence, mDrainSequence);
4077 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 return true;
4079 }
4080 return false;
4081}
4082
4083// must be called with thread mutex locked
4084bool AudioFlinger::OffloadThread::shouldStandby_l()
4085{
4086 bool TrackPaused = false;
4087
4088 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4089 // after a timeout and we will enter standby then.
4090 if (mTracks.size() > 0) {
4091 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4092 }
4093
4094 return !mStandby && !TrackPaused;
4095}
4096
4097
4098bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4099{
4100 Mutex::Autolock _l(mLock);
4101 return waitingAsyncCallback_l();
4102}
4103
4104void AudioFlinger::OffloadThread::flushHw_l()
4105{
4106 mOutput->stream->flush(mOutput->stream);
4107 // Flush anything still waiting in the mixbuffer
4108 mCurrentWriteLength = 0;
4109 mBytesRemaining = 0;
4110 mPausedWriteLength = 0;
4111 mPausedBytesRemaining = 0;
4112 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004113 // discard any pending drain or write ack by incrementing sequence
4114 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4115 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004116 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004117 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4118 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119 }
4120}
4121
4122// ----------------------------------------------------------------------------
4123
Eric Laurent81784c32012-11-19 14:55:58 -08004124AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4125 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4126 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4127 DUPLICATING),
4128 mWaitTimeMs(UINT_MAX)
4129{
4130 addOutputTrack(mainThread);
4131}
4132
4133AudioFlinger::DuplicatingThread::~DuplicatingThread()
4134{
4135 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4136 mOutputTracks[i]->destroy();
4137 }
4138}
4139
4140void AudioFlinger::DuplicatingThread::threadLoop_mix()
4141{
4142 // mix buffers...
4143 if (outputsReady(outputTracks)) {
4144 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4145 } else {
4146 memset(mMixBuffer, 0, mixBufferSize);
4147 }
4148 sleepTime = 0;
4149 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004151 standbyTime = systemTime() + standbyDelay;
4152}
4153
4154void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4155{
4156 if (sleepTime == 0) {
4157 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4158 sleepTime = activeSleepTime;
4159 } else {
4160 sleepTime = idleSleepTime;
4161 }
4162 } else if (mBytesWritten != 0) {
4163 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4164 writeFrames = mNormalFrameCount;
4165 memset(mMixBuffer, 0, mixBufferSize);
4166 } else {
4167 // flush remaining overflow buffers in output tracks
4168 writeFrames = 0;
4169 }
4170 sleepTime = 0;
4171 }
4172}
4173
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004175{
4176 for (size_t i = 0; i < outputTracks.size(); i++) {
4177 outputTracks[i]->write(mMixBuffer, writeFrames);
4178 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004179 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004180}
4181
4182void AudioFlinger::DuplicatingThread::threadLoop_standby()
4183{
4184 // DuplicatingThread implements standby by stopping all tracks
4185 for (size_t i = 0; i < outputTracks.size(); i++) {
4186 outputTracks[i]->stop();
4187 }
4188}
4189
4190void AudioFlinger::DuplicatingThread::saveOutputTracks()
4191{
4192 outputTracks = mOutputTracks;
4193}
4194
4195void AudioFlinger::DuplicatingThread::clearOutputTracks()
4196{
4197 outputTracks.clear();
4198}
4199
4200void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4201{
4202 Mutex::Autolock _l(mLock);
4203 // FIXME explain this formula
4204 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4205 OutputTrack *outputTrack = new OutputTrack(thread,
4206 this,
4207 mSampleRate,
4208 mFormat,
4209 mChannelMask,
4210 frameCount);
4211 if (outputTrack->cblk() != NULL) {
4212 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4213 mOutputTracks.add(outputTrack);
4214 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4215 updateWaitTime_l();
4216 }
4217}
4218
4219void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4220{
4221 Mutex::Autolock _l(mLock);
4222 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4223 if (mOutputTracks[i]->thread() == thread) {
4224 mOutputTracks[i]->destroy();
4225 mOutputTracks.removeAt(i);
4226 updateWaitTime_l();
4227 return;
4228 }
4229 }
4230 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4231}
4232
4233// caller must hold mLock
4234void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4235{
4236 mWaitTimeMs = UINT_MAX;
4237 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4238 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4239 if (strong != 0) {
4240 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4241 if (waitTimeMs < mWaitTimeMs) {
4242 mWaitTimeMs = waitTimeMs;
4243 }
4244 }
4245 }
4246}
4247
4248
4249bool AudioFlinger::DuplicatingThread::outputsReady(
4250 const SortedVector< sp<OutputTrack> > &outputTracks)
4251{
4252 for (size_t i = 0; i < outputTracks.size(); i++) {
4253 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4254 if (thread == 0) {
4255 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4256 outputTracks[i].get());
4257 return false;
4258 }
4259 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4260 // see note at standby() declaration
4261 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4262 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4263 thread.get());
4264 return false;
4265 }
4266 }
4267 return true;
4268}
4269
4270uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4271{
4272 return (mWaitTimeMs * 1000) / 2;
4273}
4274
4275void AudioFlinger::DuplicatingThread::cacheParameters_l()
4276{
4277 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4278 updateWaitTime_l();
4279
4280 MixerThread::cacheParameters_l();
4281}
4282
4283// ----------------------------------------------------------------------------
4284// Record
4285// ----------------------------------------------------------------------------
4286
4287AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4288 AudioStreamIn *input,
4289 uint32_t sampleRate,
4290 audio_channel_mask_t channelMask,
4291 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004292 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004293 audio_devices_t inDevice
4294#ifdef TEE_SINK
4295 , const sp<NBAIO_Sink>& teeSink
4296#endif
4297 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004298 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004299 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004300 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004301 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004302 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004303 // mBytesRead is only meaningful while active, and so is cleared in start()
4304 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004305#ifdef TEE_SINK
4306 , mTeeSink(teeSink)
4307#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004308{
4309 snprintf(mName, kNameLength, "AudioIn_%X", id);
4310
4311 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004312 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004313}
4314
4315
4316AudioFlinger::RecordThread::~RecordThread()
4317{
4318 delete[] mRsmpInBuffer;
4319 delete mResampler;
4320 delete[] mRsmpOutBuffer;
4321}
4322
4323void AudioFlinger::RecordThread::onFirstRef()
4324{
4325 run(mName, PRIORITY_URGENT_AUDIO);
4326}
4327
Eric Laurent81784c32012-11-19 14:55:58 -08004328bool AudioFlinger::RecordThread::threadLoop()
4329{
4330 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004331
4332 nsecs_t lastWarning = 0;
4333
4334 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004335 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004336
4337 // used to verify we've read at least once before evaluating how many bytes were read
4338 bool readOnce = false;
4339
Glenn Kasten5edadd42013-08-14 16:30:49 -07004340 // used to request a deferred sleep, to be executed later while mutex is unlocked
4341 bool doSleep = false;
4342
Eric Laurent81784c32012-11-19 14:55:58 -08004343 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004344 for (;;) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004345 sp<RecordTrack> activeTrack;
Glenn Kastenb86432b2013-08-14 15:08:12 -07004346 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004347 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004348
Glenn Kasten5edadd42013-08-14 16:30:49 -07004349 // sleep with mutex unlocked
4350 if (doSleep) {
4351 doSleep = false;
4352 usleep(kRecordThreadSleepUs);
4353 }
4354
Eric Laurent81784c32012-11-19 14:55:58 -08004355 { // scope for mLock
4356 Mutex::Autolock _l(mLock);
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004357 if (exitPending()) {
4358 break;
4359 }
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004360 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004361 // return value 'reconfig' is currently unused
4362 bool reconfig = checkForNewParameters_l();
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004363 // make a stable copy of mActiveTrack
4364 activeTrack = mActiveTrack;
4365 if (activeTrack == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004366 standby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004367 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004368 releaseWakeLock_l();
4369 ALOGV("RecordThread: loop stopping");
4370 // go to sleep
4371 mWaitWorkCV.wait(mLock);
4372 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004373 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004374 continue;
4375 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004376
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004377 if (activeTrack->isTerminated()) {
4378 removeTrack_l(activeTrack);
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004379 mActiveTrack.clear();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004380 continue;
4381 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004382
Glenn Kastenb86432b2013-08-14 15:08:12 -07004383 activeTrackState = activeTrack->mState;
4384 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004385 case TrackBase::PAUSING:
4386 standby();
4387 mActiveTrack.clear();
4388 mStartStopCond.broadcast();
4389 doSleep = true;
4390 continue;
4391
4392 case TrackBase::RESUMING:
4393 mStandby = false;
4394 if (mReqChannelCount != activeTrack->channelCount()) {
4395 mActiveTrack.clear();
4396 mStartStopCond.broadcast();
4397 continue;
4398 }
4399 if (readOnce) {
4400 mStartStopCond.broadcast();
4401 // record start succeeds only if first read from audio input succeeds
4402 if (mBytesRead < 0) {
4403 mActiveTrack.clear();
4404 continue;
4405 }
4406 activeTrack->mState = TrackBase::ACTIVE;
4407 }
4408 break;
4409
4410 case TrackBase::ACTIVE:
4411 break;
4412
4413 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004414 doSleep = true;
4415 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004416
4417 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004418 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004419 }
4420
Eric Laurent81784c32012-11-19 14:55:58 -08004421 lockEffectChains_l(effectChains);
4422 }
4423
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004424 // thread mutex is now unlocked, mActiveTrack unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004425 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4426
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004427 for (size_t i = 0; i < effectChains.size(); i ++) {
4428 // thread mutex is not locked, but effect chain is locked
4429 effectChains[i]->process_l();
4430 }
4431
4432 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004433 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004434 if (status == NO_ERROR) {
4435 readOnce = true;
4436 size_t framesOut = buffer.frameCount;
4437 if (mResampler == NULL) {
4438 // no resampling
4439 while (framesOut) {
4440 size_t framesIn = mFrameCount - mRsmpInIndex;
4441 if (framesIn > 0) {
4442 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4443 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004444 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004445 if (framesIn > framesOut) {
4446 framesIn = framesOut;
4447 }
4448 mRsmpInIndex += framesIn;
4449 framesOut -= framesIn;
4450 if (mChannelCount == mReqChannelCount) {
4451 memcpy(dst, src, framesIn * mFrameSize);
4452 } else {
4453 if (mChannelCount == 1) {
4454 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4455 (int16_t *)src, framesIn);
4456 } else {
4457 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4458 (int16_t *)src, framesIn);
4459 }
4460 }
4461 }
4462 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4463 void *readInto;
4464 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4465 readInto = buffer.raw;
4466 framesOut = 0;
4467 } else {
4468 readInto = mRsmpInBuffer;
4469 mRsmpInIndex = 0;
4470 }
4471 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4472 mBufferSize);
4473 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004474 // TODO: verify that it's benign to use a stale track state
4475 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004476 {
4477 ALOGE("Error reading audio input");
4478 // Force input into standby so that it tries to
4479 // recover at next read attempt
4480 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004481 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004482 }
4483 mRsmpInIndex = mFrameCount;
4484 framesOut = 0;
4485 buffer.frameCount = 0;
4486 }
4487#ifdef TEE_SINK
4488 else if (mTeeSink != 0) {
4489 (void) mTeeSink->write(readInto,
4490 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4491 }
4492#endif
4493 }
4494 }
4495 } else {
4496 // resampling
4497
4498 // resampler accumulates, but we only have one source track
4499 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4500 // alter output frame count as if we were expecting stereo samples
4501 if (mChannelCount == 1 && mReqChannelCount == 1) {
4502 framesOut >>= 1;
4503 }
4504 mResampler->resample(mRsmpOutBuffer, framesOut,
4505 this /* AudioBufferProvider* */);
4506 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004507 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004508 if (mChannelCount == 2 && mReqChannelCount == 1) {
4509 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4510 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4511 // the resampler always outputs stereo samples:
4512 // do post stereo to mono conversion
4513 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4514 framesOut);
4515 } else {
4516 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4517 }
4518 // now done with mRsmpOutBuffer
4519
4520 }
4521 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004522 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004523 } else {
4524 if (mFramestoDrop > 0) {
4525 mFramestoDrop -= buffer.frameCount;
4526 if (mFramestoDrop <= 0) {
4527 clearSyncStartEvent();
4528 }
4529 } else {
4530 mFramestoDrop += buffer.frameCount;
4531 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4532 mSyncStartEvent->isCancelled()) {
4533 ALOGW("Synced record %s, session %d, trigger session %d",
4534 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004535 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004536 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4537 clearSyncStartEvent();
4538 }
4539 }
4540 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004541 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004542 }
4543 // client isn't retrieving buffers fast enough
4544 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004545 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004546 nsecs_t now = systemTime();
4547 if ((now - lastWarning) > kWarningThrottleNs) {
4548 ALOGW("RecordThread: buffer overflow");
4549 lastWarning = now;
4550 }
4551 }
4552 // Release the processor for a while before asking for a new buffer.
4553 // This will give the application more chance to read from the buffer and
4554 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004555 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004556 }
4557
Eric Laurent81784c32012-11-19 14:55:58 -08004558 // enable changes in effect chain
4559 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004560 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004561 }
4562
4563 standby();
4564
4565 {
4566 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004567 for (size_t i = 0; i < mTracks.size(); i++) {
4568 sp<RecordTrack> track = mTracks[i];
4569 track->invalidate();
4570 }
Eric Laurent81784c32012-11-19 14:55:58 -08004571 mActiveTrack.clear();
4572 mStartStopCond.broadcast();
4573 }
4574
4575 releaseWakeLock();
4576
4577 ALOGV("RecordThread %p exiting", this);
4578 return false;
4579}
4580
4581void AudioFlinger::RecordThread::standby()
4582{
4583 if (!mStandby) {
4584 inputStandBy();
4585 mStandby = true;
4586 }
4587}
4588
4589void AudioFlinger::RecordThread::inputStandBy()
4590{
4591 mInput->stream->common.standby(&mInput->stream->common);
4592}
4593
Glenn Kastene198c362013-08-13 09:13:36 -07004594sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004595 const sp<AudioFlinger::Client>& client,
4596 uint32_t sampleRate,
4597 audio_format_t format,
4598 audio_channel_mask_t channelMask,
4599 size_t frameCount,
4600 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004601 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004602 pid_t tid,
4603 status_t *status)
4604{
4605 sp<RecordTrack> track;
4606 status_t lStatus;
4607
4608 lStatus = initCheck();
4609 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004610 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004611 goto Exit;
4612 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004613 // client expresses a preference for FAST, but we get the final say
4614 if (*flags & IAudioFlinger::TRACK_FAST) {
4615 if (
4616 // use case: callback handler and frame count is default or at least as large as HAL
4617 (
4618 (tid != -1) &&
4619 ((frameCount == 0) ||
4620 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4621 ) &&
4622 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4623 // mono or stereo
4624 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4625 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4626 // hardware sample rate
4627 (sampleRate == mSampleRate) &&
4628 // record thread has an associated fast recorder
4629 hasFastRecorder()
4630 // FIXME test that RecordThread for this fast track has a capable output HAL
4631 // FIXME add a permission test also?
4632 ) {
4633 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4634 if (frameCount == 0) {
4635 frameCount = mFrameCount * kFastTrackMultiplier;
4636 }
4637 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4638 frameCount, mFrameCount);
4639 } else {
4640 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4641 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4642 "hasFastRecorder=%d tid=%d",
4643 frameCount, mFrameCount, format,
4644 audio_is_linear_pcm(format),
4645 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4646 *flags &= ~IAudioFlinger::TRACK_FAST;
4647 // For compatibility with AudioRecord calculation, buffer depth is forced
4648 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4649 // This is probably too conservative, but legacy application code may depend on it.
4650 // If you change this calculation, also review the start threshold which is related.
4651 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4652 size_t mNormalFrameCount = 2048; // FIXME
4653 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4654 if (minBufCount < 2) {
4655 minBufCount = 2;
4656 }
4657 size_t minFrameCount = mNormalFrameCount * minBufCount;
4658 if (frameCount < minFrameCount) {
4659 frameCount = minFrameCount;
4660 }
4661 }
4662 }
4663
Eric Laurent81784c32012-11-19 14:55:58 -08004664 // FIXME use flags and tid similar to createTrack_l()
4665
4666 { // scope for mLock
4667 Mutex::Autolock _l(mLock);
4668
4669 track = new RecordTrack(this, client, sampleRate,
4670 format, channelMask, frameCount, sessionId);
4671
Glenn Kasten03003332013-08-06 15:40:54 -07004672 lStatus = track->initCheck();
4673 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004674 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07004675 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004676 goto Exit;
4677 }
4678 mTracks.add(track);
4679
4680 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4681 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4682 mAudioFlinger->btNrecIsOff();
4683 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4684 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004685
4686 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4687 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4688 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4689 // so ask activity manager to do this on our behalf
4690 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4691 }
Eric Laurent81784c32012-11-19 14:55:58 -08004692 }
4693 lStatus = NO_ERROR;
4694
4695Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004696 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004697 return track;
4698}
4699
4700status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4701 AudioSystem::sync_event_t event,
4702 int triggerSession)
4703{
4704 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4705 sp<ThreadBase> strongMe = this;
4706 status_t status = NO_ERROR;
4707
4708 if (event == AudioSystem::SYNC_EVENT_NONE) {
4709 clearSyncStartEvent();
4710 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4711 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4712 triggerSession,
4713 recordTrack->sessionId(),
4714 syncStartEventCallback,
4715 this);
4716 // Sync event can be cancelled by the trigger session if the track is not in a
4717 // compatible state in which case we start record immediately
4718 if (mSyncStartEvent->isCancelled()) {
4719 clearSyncStartEvent();
4720 } else {
4721 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4722 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4723 }
4724 }
4725
4726 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004727 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004728 AutoMutex lock(mLock);
4729 if (mActiveTrack != 0) {
4730 if (recordTrack != mActiveTrack.get()) {
4731 status = -EBUSY;
4732 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4733 mActiveTrack->mState = TrackBase::ACTIVE;
4734 }
4735 return status;
4736 }
4737
Glenn Kasten47c20702013-08-13 15:37:35 -07004738 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004739 recordTrack->mState = TrackBase::IDLE;
4740 mActiveTrack = recordTrack;
4741 mLock.unlock();
4742 status_t status = AudioSystem::startInput(mId);
4743 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004744 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004745 if (status != NO_ERROR) {
4746 mActiveTrack.clear();
4747 clearSyncStartEvent();
4748 return status;
4749 }
4750 mRsmpInIndex = mFrameCount;
4751 mBytesRead = 0;
4752 if (mResampler != NULL) {
4753 mResampler->reset();
4754 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004755 // FIXME hijacking a playback track state name which was intended for start after pause;
4756 // here 'STARTING_2' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004757 mActiveTrack->mState = TrackBase::RESUMING;
4758 // signal thread to start
4759 ALOGV("Signal record thread");
4760 mWaitWorkCV.broadcast();
4761 // do not wait for mStartStopCond if exiting
4762 if (exitPending()) {
4763 mActiveTrack.clear();
4764 status = INVALID_OPERATION;
4765 goto startError;
4766 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004767 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004768 mStartStopCond.wait(mLock);
4769 if (mActiveTrack == 0) {
4770 ALOGV("Record failed to start");
4771 status = BAD_VALUE;
4772 goto startError;
4773 }
4774 ALOGV("Record started OK");
4775 return status;
4776 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004777
Eric Laurent81784c32012-11-19 14:55:58 -08004778startError:
4779 AudioSystem::stopInput(mId);
4780 clearSyncStartEvent();
4781 return status;
4782}
4783
4784void AudioFlinger::RecordThread::clearSyncStartEvent()
4785{
4786 if (mSyncStartEvent != 0) {
4787 mSyncStartEvent->cancel();
4788 }
4789 mSyncStartEvent.clear();
4790 mFramestoDrop = 0;
4791}
4792
4793void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4794{
4795 sp<SyncEvent> strongEvent = event.promote();
4796
4797 if (strongEvent != 0) {
4798 RecordThread *me = (RecordThread *)strongEvent->cookie();
4799 me->handleSyncStartEvent(strongEvent);
4800 }
4801}
4802
4803void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4804{
4805 if (event == mSyncStartEvent) {
4806 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4807 // from audio HAL
4808 mFramestoDrop = mFrameCount * 2;
4809 }
4810}
4811
Glenn Kastena8356f62013-07-25 14:37:52 -07004812bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004813 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004814 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004815 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4816 return false;
4817 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004818 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08004819 recordTrack->mState = TrackBase::PAUSING;
4820 // do not wait for mStartStopCond if exiting
4821 if (exitPending()) {
4822 return true;
4823 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004824 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004825 mStartStopCond.wait(mLock);
4826 // if we have been restarted, recordTrack == mActiveTrack.get() here
4827 if (exitPending() || recordTrack != mActiveTrack.get()) {
4828 ALOGV("Record stopped OK");
4829 return true;
4830 }
4831 return false;
4832}
4833
4834bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4835{
4836 return false;
4837}
4838
4839status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4840{
4841#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4842 if (!isValidSyncEvent(event)) {
4843 return BAD_VALUE;
4844 }
4845
4846 int eventSession = event->triggerSession();
4847 status_t ret = NAME_NOT_FOUND;
4848
4849 Mutex::Autolock _l(mLock);
4850
4851 for (size_t i = 0; i < mTracks.size(); i++) {
4852 sp<RecordTrack> track = mTracks[i];
4853 if (eventSession == track->sessionId()) {
4854 (void) track->setSyncEvent(event);
4855 ret = NO_ERROR;
4856 }
4857 }
4858 return ret;
4859#else
4860 return BAD_VALUE;
4861#endif
4862}
4863
4864// destroyTrack_l() must be called with ThreadBase::mLock held
4865void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4866{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 track->terminate();
4868 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004869 // active tracks are removed by threadLoop()
4870 if (mActiveTrack != track) {
4871 removeTrack_l(track);
4872 }
4873}
4874
4875void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4876{
4877 mTracks.remove(track);
4878 // need anything related to effects here?
4879}
4880
4881void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4882{
4883 dumpInternals(fd, args);
4884 dumpTracks(fd, args);
4885 dumpEffectChains(fd, args);
4886}
4887
4888void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4889{
4890 const size_t SIZE = 256;
4891 char buffer[SIZE];
4892 String8 result;
4893
4894 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4895 result.append(buffer);
4896
4897 if (mActiveTrack != 0) {
4898 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4899 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004900 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004901 result.append(buffer);
4902 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4903 result.append(buffer);
4904 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4905 result.append(buffer);
4906 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4907 result.append(buffer);
4908 } else {
4909 result.append("No active record client\n");
4910 }
4911
4912 write(fd, result.string(), result.size());
4913
4914 dumpBase(fd, args);
4915}
4916
4917void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4918{
4919 const size_t SIZE = 256;
4920 char buffer[SIZE];
4921 String8 result;
4922
4923 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4924 result.append(buffer);
4925 RecordTrack::appendDumpHeader(result);
4926 for (size_t i = 0; i < mTracks.size(); ++i) {
4927 sp<RecordTrack> track = mTracks[i];
4928 if (track != 0) {
4929 track->dump(buffer, SIZE);
4930 result.append(buffer);
4931 }
4932 }
4933
4934 if (mActiveTrack != 0) {
4935 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4936 result.append(buffer);
4937 RecordTrack::appendDumpHeader(result);
4938 mActiveTrack->dump(buffer, SIZE);
4939 result.append(buffer);
4940
4941 }
4942 write(fd, result.string(), result.size());
4943}
4944
4945// AudioBufferProvider interface
4946status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4947{
4948 size_t framesReq = buffer->frameCount;
4949 size_t framesReady = mFrameCount - mRsmpInIndex;
4950 int channelCount;
4951
4952 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004953 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004954 if (mBytesRead <= 0) {
4955 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4956 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4957 // Force input into standby so that it tries to
4958 // recover at next read attempt
4959 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004960 // FIXME an awkward place to sleep, consider using doSleep when this is pulled up
Eric Laurent81784c32012-11-19 14:55:58 -08004961 usleep(kRecordThreadSleepUs);
4962 }
4963 buffer->raw = NULL;
4964 buffer->frameCount = 0;
4965 return NOT_ENOUGH_DATA;
4966 }
4967 mRsmpInIndex = 0;
4968 framesReady = mFrameCount;
4969 }
4970
4971 if (framesReq > framesReady) {
4972 framesReq = framesReady;
4973 }
4974
4975 if (mChannelCount == 1 && mReqChannelCount == 2) {
4976 channelCount = 1;
4977 } else {
4978 channelCount = 2;
4979 }
4980 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4981 buffer->frameCount = framesReq;
4982 return NO_ERROR;
4983}
4984
4985// AudioBufferProvider interface
4986void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4987{
4988 mRsmpInIndex += buffer->frameCount;
4989 buffer->frameCount = 0;
4990}
4991
4992bool AudioFlinger::RecordThread::checkForNewParameters_l()
4993{
4994 bool reconfig = false;
4995
4996 while (!mNewParameters.isEmpty()) {
4997 status_t status = NO_ERROR;
4998 String8 keyValuePair = mNewParameters[0];
4999 AudioParameter param = AudioParameter(keyValuePair);
5000 int value;
5001 audio_format_t reqFormat = mFormat;
5002 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005003 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005004
5005 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5006 reqSamplingRate = value;
5007 reconfig = true;
5008 }
5009 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005010 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5011 status = BAD_VALUE;
5012 } else {
5013 reqFormat = (audio_format_t) value;
5014 reconfig = true;
5015 }
Eric Laurent81784c32012-11-19 14:55:58 -08005016 }
5017 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005018 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5019 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5020 status = BAD_VALUE;
5021 } else {
5022 reqChannelMask = mask;
5023 reconfig = true;
5024 }
Eric Laurent81784c32012-11-19 14:55:58 -08005025 }
5026 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5027 // do not accept frame count changes if tracks are open as the track buffer
5028 // size depends on frame count and correct behavior would not be guaranteed
5029 // if frame count is changed after track creation
5030 if (mActiveTrack != 0) {
5031 status = INVALID_OPERATION;
5032 } else {
5033 reconfig = true;
5034 }
5035 }
5036 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5037 // forward device change to effects that have requested to be
5038 // aware of attached audio device.
5039 for (size_t i = 0; i < mEffectChains.size(); i++) {
5040 mEffectChains[i]->setDevice_l(value);
5041 }
5042
5043 // store input device and output device but do not forward output device to audio HAL.
5044 // Note that status is ignored by the caller for output device
5045 // (see AudioFlinger::setParameters()
5046 if (audio_is_output_devices(value)) {
5047 mOutDevice = value;
5048 status = BAD_VALUE;
5049 } else {
5050 mInDevice = value;
5051 // disable AEC and NS if the device is a BT SCO headset supporting those
5052 // pre processings
5053 if (mTracks.size() > 0) {
5054 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5055 mAudioFlinger->btNrecIsOff();
5056 for (size_t i = 0; i < mTracks.size(); i++) {
5057 sp<RecordTrack> track = mTracks[i];
5058 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5059 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5060 }
5061 }
5062 }
5063 }
5064 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5065 mAudioSource != (audio_source_t)value) {
5066 // forward device change to effects that have requested to be
5067 // aware of attached audio device.
5068 for (size_t i = 0; i < mEffectChains.size(); i++) {
5069 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5070 }
5071 mAudioSource = (audio_source_t)value;
5072 }
Glenn Kastene198c362013-08-13 09:13:36 -07005073
Eric Laurent81784c32012-11-19 14:55:58 -08005074 if (status == NO_ERROR) {
5075 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5076 keyValuePair.string());
5077 if (status == INVALID_OPERATION) {
5078 inputStandBy();
5079 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5080 keyValuePair.string());
5081 }
5082 if (reconfig) {
5083 if (status == BAD_VALUE &&
5084 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5085 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005086 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005087 <= (2 * reqSamplingRate)) &&
5088 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5089 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005090 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5091 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005092 status = NO_ERROR;
5093 }
5094 if (status == NO_ERROR) {
5095 readInputParameters();
5096 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5097 }
5098 }
5099 }
5100
5101 mNewParameters.removeAt(0);
5102
5103 mParamStatus = status;
5104 mParamCond.signal();
5105 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5106 // already timed out waiting for the status and will never signal the condition.
5107 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5108 }
5109 return reconfig;
5110}
5111
5112String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5113{
Eric Laurent81784c32012-11-19 14:55:58 -08005114 Mutex::Autolock _l(mLock);
5115 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005116 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005117 }
5118
Glenn Kastend8ea6992013-07-16 14:17:15 -07005119 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5120 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005121 free(s);
5122 return out_s8;
5123}
5124
5125void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5126 AudioSystem::OutputDescriptor desc;
5127 void *param2 = NULL;
5128
5129 switch (event) {
5130 case AudioSystem::INPUT_OPENED:
5131 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005132 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 desc.samplingRate = mSampleRate;
5134 desc.format = mFormat;
5135 desc.frameCount = mFrameCount;
5136 desc.latency = 0;
5137 param2 = &desc;
5138 break;
5139
5140 case AudioSystem::INPUT_CLOSED:
5141 default:
5142 break;
5143 }
5144 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5145}
5146
5147void AudioFlinger::RecordThread::readInputParameters()
5148{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005149 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005150 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005151 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005152 mRsmpOutBuffer = NULL;
5153 delete mResampler;
5154 mResampler = NULL;
5155
5156 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5157 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005158 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005159 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005160 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5161 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5162 }
Eric Laurent81784c32012-11-19 14:55:58 -08005163 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005164 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5165 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005166 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5167
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005168 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005169 int channelCount;
5170 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5171 // stereo to mono post process as the resampler always outputs stereo.
5172 if (mChannelCount == 1 && mReqChannelCount == 2) {
5173 channelCount = 1;
5174 } else {
5175 channelCount = 2;
5176 }
5177 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5178 mResampler->setSampleRate(mSampleRate);
5179 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005180 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005181
5182 // optmization: if mono to mono, alter input frame count as if we were inputing
5183 // stereo samples
5184 if (mChannelCount == 1 && mReqChannelCount == 1) {
5185 mFrameCount >>= 1;
5186 }
5187
5188 }
5189 mRsmpInIndex = mFrameCount;
5190}
5191
5192unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5193{
5194 Mutex::Autolock _l(mLock);
5195 if (initCheck() != NO_ERROR) {
5196 return 0;
5197 }
5198
5199 return mInput->stream->get_input_frames_lost(mInput->stream);
5200}
5201
5202uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5203{
5204 Mutex::Autolock _l(mLock);
5205 uint32_t result = 0;
5206 if (getEffectChain_l(sessionId) != 0) {
5207 result = EFFECT_SESSION;
5208 }
5209
5210 for (size_t i = 0; i < mTracks.size(); ++i) {
5211 if (sessionId == mTracks[i]->sessionId()) {
5212 result |= TRACK_SESSION;
5213 break;
5214 }
5215 }
5216
5217 return result;
5218}
5219
5220KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5221{
5222 KeyedVector<int, bool> ids;
5223 Mutex::Autolock _l(mLock);
5224 for (size_t j = 0; j < mTracks.size(); ++j) {
5225 sp<RecordThread::RecordTrack> track = mTracks[j];
5226 int sessionId = track->sessionId();
5227 if (ids.indexOfKey(sessionId) < 0) {
5228 ids.add(sessionId, true);
5229 }
5230 }
5231 return ids;
5232}
5233
5234AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5235{
5236 Mutex::Autolock _l(mLock);
5237 AudioStreamIn *input = mInput;
5238 mInput = NULL;
5239 return input;
5240}
5241
5242// this method must always be called either with ThreadBase mLock held or inside the thread loop
5243audio_stream_t* AudioFlinger::RecordThread::stream() const
5244{
5245 if (mInput == NULL) {
5246 return NULL;
5247 }
5248 return &mInput->stream->common;
5249}
5250
5251status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5252{
5253 // only one chain per input thread
5254 if (mEffectChains.size() != 0) {
5255 return INVALID_OPERATION;
5256 }
5257 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5258
5259 chain->setInBuffer(NULL);
5260 chain->setOutBuffer(NULL);
5261
5262 checkSuspendOnAddEffectChain_l(chain);
5263
5264 mEffectChains.add(chain);
5265
5266 return NO_ERROR;
5267}
5268
5269size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5270{
5271 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5272 ALOGW_IF(mEffectChains.size() != 1,
5273 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5274 chain.get(), mEffectChains.size(), this);
5275 if (mEffectChains.size() == 1) {
5276 mEffectChains.removeAt(0);
5277 }
5278 return 0;
5279}
5280
5281}; // namespace android