blob: 73429ec083641600de4559a6bfb5ff77dda5bd9b [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.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
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),
272 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, and mFormat are
273 // set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800274 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700275 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800276 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
277 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
278 // mName will be set by concrete (non-virtual) subclass
279 mDeathRecipient(new PMDeathRecipient(this))
280{
281}
282
283AudioFlinger::ThreadBase::~ThreadBase()
284{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700285 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
286 for (size_t i = 0; i < mConfigEvents.size(); i++) {
287 delete mConfigEvents[i];
288 }
289 mConfigEvents.clear();
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291 mParamCond.broadcast();
292 // do not lock the mutex in destructor
293 releaseWakeLock_l();
294 if (mPowerManager != 0) {
295 sp<IBinder> binder = mPowerManager->asBinder();
296 binder->unlinkToDeath(mDeathRecipient);
297 }
298}
299
300void AudioFlinger::ThreadBase::exit()
301{
302 ALOGV("ThreadBase::exit");
303 // do any cleanup required for exit to succeed
304 preExit();
305 {
306 // This lock prevents the following race in thread (uniprocessor for illustration):
307 // if (!exitPending()) {
308 // // context switch from here to exit()
309 // // exit() calls requestExit(), what exitPending() observes
310 // // exit() calls signal(), which is dropped since no waiters
311 // // context switch back from exit() to here
312 // mWaitWorkCV.wait(...);
313 // // now thread is hung
314 // }
315 AutoMutex lock(mLock);
316 requestExit();
317 mWaitWorkCV.broadcast();
318 }
319 // When Thread::requestExitAndWait is made virtual and this method is renamed to
320 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
321 requestExitAndWait();
322}
323
324status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
325{
326 status_t status;
327
328 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
329 Mutex::Autolock _l(mLock);
330
331 mNewParameters.add(keyValuePairs);
332 mWaitWorkCV.signal();
333 // wait condition with timeout in case the thread loop has exited
334 // before the request could be processed
335 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
336 status = mParamStatus;
337 mWaitWorkCV.signal();
338 } else {
339 status = TIMED_OUT;
340 }
341 return status;
342}
343
344void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
345{
346 Mutex::Autolock _l(mLock);
347 sendIoConfigEvent_l(event, param);
348}
349
350// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
351void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
352{
353 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
354 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
355 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
356 param);
357 mWaitWorkCV.signal();
358}
359
360// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
361void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
362{
363 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
364 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
365 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
366 mConfigEvents.size(), pid, tid, prio);
367 mWaitWorkCV.signal();
368}
369
370void AudioFlinger::ThreadBase::processConfigEvents()
371{
372 mLock.lock();
373 while (!mConfigEvents.isEmpty()) {
374 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
375 ConfigEvent *event = mConfigEvents[0];
376 mConfigEvents.removeAt(0);
377 // release mLock before locking AudioFlinger mLock: lock order is always
378 // AudioFlinger then ThreadBase to avoid cross deadlock
379 mLock.unlock();
380 switch(event->type()) {
381 case CFG_EVENT_PRIO: {
382 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700383 // FIXME Need to understand why this has be done asynchronously
384 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
385 true /*asynchronous*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800386 if (err != 0) {
387 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
388 "error %d",
389 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
390 }
391 } break;
392 case CFG_EVENT_IO: {
393 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
394 mAudioFlinger->mLock.lock();
395 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
396 mAudioFlinger->mLock.unlock();
397 } break;
398 default:
399 ALOGE("processConfigEvents() unknown event type %d", event->type());
400 break;
401 }
402 delete event;
403 mLock.lock();
404 }
405 mLock.unlock();
406}
407
408void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413
414 bool locked = AudioFlinger::dumpTryLock(mLock);
415 if (!locked) {
416 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
417 write(fd, buffer, strlen(buffer));
418 }
419
420 snprintf(buffer, SIZE, "io handle: %d\n", mId);
421 result.append(buffer);
422 snprintf(buffer, SIZE, "TID: %d\n", getTid());
423 result.append(buffer);
424 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
425 result.append(buffer);
426 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
427 result.append(buffer);
428 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
429 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700430 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800431 result.append(buffer);
432 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
433 result.append(buffer);
434 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
435 result.append(buffer);
436 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
437 result.append(buffer);
438
439 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
440 result.append(buffer);
441 result.append(" Index Command");
442 for (size_t i = 0; i < mNewParameters.size(); ++i) {
443 snprintf(buffer, SIZE, "\n %02d ", i);
444 result.append(buffer);
445 result.append(mNewParameters[i]);
446 }
447
448 snprintf(buffer, SIZE, "\n\nPending config events: \n");
449 result.append(buffer);
450 for (size_t i = 0; i < mConfigEvents.size(); i++) {
451 mConfigEvents[i]->dump(buffer, SIZE);
452 result.append(buffer);
453 }
454 result.append("\n");
455
456 write(fd, result.string(), result.size());
457
458 if (locked) {
459 mLock.unlock();
460 }
461}
462
463void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
464{
465 const size_t SIZE = 256;
466 char buffer[SIZE];
467 String8 result;
468
469 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
470 write(fd, buffer, strlen(buffer));
471
472 for (size_t i = 0; i < mEffectChains.size(); ++i) {
473 sp<EffectChain> chain = mEffectChains[i];
474 if (chain != 0) {
475 chain->dump(fd, args);
476 }
477 }
478}
479
Marco Nelissene14a5d62013-10-03 08:51:24 -0700480void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800481{
482 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700483 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800484}
485
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100486String16 AudioFlinger::ThreadBase::getWakeLockTag()
487{
488 switch (mType) {
489 case MIXER:
490 return String16("AudioMix");
491 case DIRECT:
492 return String16("AudioDirectOut");
493 case DUPLICATING:
494 return String16("AudioDup");
495 case RECORD:
496 return String16("AudioIn");
497 case OFFLOAD:
498 return String16("AudioOffload");
499 default:
500 ALOG_ASSERT(false);
501 return String16("AudioUnknown");
502 }
503}
504
Marco Nelissene14a5d62013-10-03 08:51:24 -0700505void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800506{
Marco Nelissen9cae2172013-01-14 14:12:05 -0800507 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800508 if (mPowerManager != 0) {
509 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700510 status_t status;
511 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700512 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700513 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100514 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700515 String16("media"),
516 uid);
517 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700518 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700519 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100520 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700521 String16("media"));
522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523 if (status == NO_ERROR) {
524 mWakeLockToken = binder;
525 }
526 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
527 }
528}
529
530void AudioFlinger::ThreadBase::releaseWakeLock()
531{
532 Mutex::Autolock _l(mLock);
533 releaseWakeLock_l();
534}
535
536void AudioFlinger::ThreadBase::releaseWakeLock_l()
537{
538 if (mWakeLockToken != 0) {
539 ALOGV("releaseWakeLock_l() %s", mName);
540 if (mPowerManager != 0) {
541 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
542 }
543 mWakeLockToken.clear();
544 }
545}
546
Marco Nelissen9cae2172013-01-14 14:12:05 -0800547void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
548 Mutex::Autolock _l(mLock);
549 updateWakeLockUids_l(uids);
550}
551
552void AudioFlinger::ThreadBase::getPowerManager_l() {
553
554 if (mPowerManager == 0) {
555 // use checkService() to avoid blocking if power service is not up yet
556 sp<IBinder> binder =
557 defaultServiceManager()->checkService(String16("power"));
558 if (binder == 0) {
559 ALOGW("Thread %s cannot connect to the power manager service", mName);
560 } else {
561 mPowerManager = interface_cast<IPowerManager>(binder);
562 binder->linkToDeath(mDeathRecipient);
563 }
564 }
565}
566
567void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
568
569 getPowerManager_l();
570 if (mWakeLockToken == NULL) {
571 ALOGE("no wake lock to update!");
572 return;
573 }
574 if (mPowerManager != 0) {
575 sp<IBinder> binder = new BBinder();
576 status_t status;
577 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
578 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
579 }
580}
581
Eric Laurent81784c32012-11-19 14:55:58 -0800582void AudioFlinger::ThreadBase::clearPowerManager()
583{
584 Mutex::Autolock _l(mLock);
585 releaseWakeLock_l();
586 mPowerManager.clear();
587}
588
589void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
590{
591 sp<ThreadBase> thread = mThread.promote();
592 if (thread != 0) {
593 thread->clearPowerManager();
594 }
595 ALOGW("power manager service died !!!");
596}
597
598void AudioFlinger::ThreadBase::setEffectSuspended(
599 const effect_uuid_t *type, bool suspend, int sessionId)
600{
601 Mutex::Autolock _l(mLock);
602 setEffectSuspended_l(type, suspend, sessionId);
603}
604
605void AudioFlinger::ThreadBase::setEffectSuspended_l(
606 const effect_uuid_t *type, bool suspend, int sessionId)
607{
608 sp<EffectChain> chain = getEffectChain_l(sessionId);
609 if (chain != 0) {
610 if (type != NULL) {
611 chain->setEffectSuspended_l(type, suspend);
612 } else {
613 chain->setEffectSuspendedAll_l(suspend);
614 }
615 }
616
617 updateSuspendedSessions_l(type, suspend, sessionId);
618}
619
620void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
621{
622 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
623 if (index < 0) {
624 return;
625 }
626
627 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
628 mSuspendedSessions.valueAt(index);
629
630 for (size_t i = 0; i < sessionEffects.size(); i++) {
631 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
632 for (int j = 0; j < desc->mRefCount; j++) {
633 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
634 chain->setEffectSuspendedAll_l(true);
635 } else {
636 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
637 desc->mType.timeLow);
638 chain->setEffectSuspended_l(&desc->mType, true);
639 }
640 }
641 }
642}
643
644void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
645 bool suspend,
646 int sessionId)
647{
648 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
649
650 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
651
652 if (suspend) {
653 if (index >= 0) {
654 sessionEffects = mSuspendedSessions.valueAt(index);
655 } else {
656 mSuspendedSessions.add(sessionId, sessionEffects);
657 }
658 } else {
659 if (index < 0) {
660 return;
661 }
662 sessionEffects = mSuspendedSessions.valueAt(index);
663 }
664
665
666 int key = EffectChain::kKeyForSuspendAll;
667 if (type != NULL) {
668 key = type->timeLow;
669 }
670 index = sessionEffects.indexOfKey(key);
671
672 sp<SuspendedSessionDesc> desc;
673 if (suspend) {
674 if (index >= 0) {
675 desc = sessionEffects.valueAt(index);
676 } else {
677 desc = new SuspendedSessionDesc();
678 if (type != NULL) {
679 desc->mType = *type;
680 }
681 sessionEffects.add(key, desc);
682 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
683 }
684 desc->mRefCount++;
685 } else {
686 if (index < 0) {
687 return;
688 }
689 desc = sessionEffects.valueAt(index);
690 if (--desc->mRefCount == 0) {
691 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
692 sessionEffects.removeItemsAt(index);
693 if (sessionEffects.isEmpty()) {
694 ALOGV("updateSuspendedSessions_l() restore removing session %d",
695 sessionId);
696 mSuspendedSessions.removeItem(sessionId);
697 }
698 }
699 }
700 if (!sessionEffects.isEmpty()) {
701 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
702 }
703}
704
705void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
706 bool enabled,
707 int sessionId)
708{
709 Mutex::Autolock _l(mLock);
710 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
711}
712
713void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
714 bool enabled,
715 int sessionId)
716{
717 if (mType != RECORD) {
718 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
719 // another session. This gives the priority to well behaved effect control panels
720 // and applications not using global effects.
721 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
722 // global effects
723 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
724 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
725 }
726 }
727
728 sp<EffectChain> chain = getEffectChain_l(sessionId);
729 if (chain != 0) {
730 chain->checkSuspendOnEffectEnabled(effect, enabled);
731 }
732}
733
734// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
735sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
736 const sp<AudioFlinger::Client>& client,
737 const sp<IEffectClient>& effectClient,
738 int32_t priority,
739 int sessionId,
740 effect_descriptor_t *desc,
741 int *enabled,
742 status_t *status
743 )
744{
745 sp<EffectModule> effect;
746 sp<EffectHandle> handle;
747 status_t lStatus;
748 sp<EffectChain> chain;
749 bool chainCreated = false;
750 bool effectCreated = false;
751 bool effectRegistered = false;
752
753 lStatus = initCheck();
754 if (lStatus != NO_ERROR) {
755 ALOGW("createEffect_l() Audio driver not initialized.");
756 goto Exit;
757 }
758
Eric Laurent5baf2af2013-09-12 17:37:00 -0700759 // Allow global effects only on offloaded and mixer threads
760 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
761 switch (mType) {
762 case MIXER:
763 case OFFLOAD:
764 break;
765 case DIRECT:
766 case DUPLICATING:
767 case RECORD:
768 default:
769 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
770 lStatus = BAD_VALUE;
771 goto Exit;
772 }
Eric Laurent81784c32012-11-19 14:55:58 -0800773 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700774
Eric Laurent81784c32012-11-19 14:55:58 -0800775 // Only Pre processor effects are allowed on input threads and only on input threads
776 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
777 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
778 desc->name, desc->flags, mType);
779 lStatus = BAD_VALUE;
780 goto Exit;
781 }
782
783 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
784
785 { // scope for mLock
786 Mutex::Autolock _l(mLock);
787
788 // check for existing effect chain with the requested audio session
789 chain = getEffectChain_l(sessionId);
790 if (chain == 0) {
791 // create a new chain for this session
792 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
793 chain = new EffectChain(this, sessionId);
794 addEffectChain_l(chain);
795 chain->setStrategy(getStrategyForSession_l(sessionId));
796 chainCreated = true;
797 } else {
798 effect = chain->getEffectFromDesc_l(desc);
799 }
800
801 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
802
803 if (effect == 0) {
804 int id = mAudioFlinger->nextUniqueId();
805 // Check CPU and memory usage
806 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
807 if (lStatus != NO_ERROR) {
808 goto Exit;
809 }
810 effectRegistered = true;
811 // create a new effect module if none present in the chain
812 effect = new EffectModule(this, chain, desc, id, sessionId);
813 lStatus = effect->status();
814 if (lStatus != NO_ERROR) {
815 goto Exit;
816 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700817 effect->setOffloaded(mType == OFFLOAD, mId);
818
Eric Laurent81784c32012-11-19 14:55:58 -0800819 lStatus = chain->addEffect_l(effect);
820 if (lStatus != NO_ERROR) {
821 goto Exit;
822 }
823 effectCreated = true;
824
825 effect->setDevice(mOutDevice);
826 effect->setDevice(mInDevice);
827 effect->setMode(mAudioFlinger->getMode());
828 effect->setAudioSource(mAudioSource);
829 }
830 // create effect handle and connect it to effect module
831 handle = new EffectHandle(effect, client, effectClient, priority);
832 lStatus = effect->addHandle(handle.get());
833 if (enabled != NULL) {
834 *enabled = (int)effect->isEnabled();
835 }
836 }
837
838Exit:
839 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
840 Mutex::Autolock _l(mLock);
841 if (effectCreated) {
842 chain->removeEffect_l(effect);
843 }
844 if (effectRegistered) {
845 AudioSystem::unregisterEffect(effect->id());
846 }
847 if (chainCreated) {
848 removeEffectChain_l(chain);
849 }
850 handle.clear();
851 }
852
853 if (status != NULL) {
854 *status = lStatus;
855 }
856 return handle;
857}
858
859sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
860{
861 Mutex::Autolock _l(mLock);
862 return getEffect_l(sessionId, effectId);
863}
864
865sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
866{
867 sp<EffectChain> chain = getEffectChain_l(sessionId);
868 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
869}
870
871// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
872// PlaybackThread::mLock held
873status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
874{
875 // check for existing effect chain with the requested audio session
876 int sessionId = effect->sessionId();
877 sp<EffectChain> chain = getEffectChain_l(sessionId);
878 bool chainCreated = false;
879
Eric Laurent5baf2af2013-09-12 17:37:00 -0700880 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
881 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
882 this, effect->desc().name, effect->desc().flags);
883
Eric Laurent81784c32012-11-19 14:55:58 -0800884 if (chain == 0) {
885 // create a new chain for this session
886 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
887 chain = new EffectChain(this, sessionId);
888 addEffectChain_l(chain);
889 chain->setStrategy(getStrategyForSession_l(sessionId));
890 chainCreated = true;
891 }
892 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
893
894 if (chain->getEffectFromId_l(effect->id()) != 0) {
895 ALOGW("addEffect_l() %p effect %s already present in chain %p",
896 this, effect->desc().name, chain.get());
897 return BAD_VALUE;
898 }
899
Eric Laurent5baf2af2013-09-12 17:37:00 -0700900 effect->setOffloaded(mType == OFFLOAD, mId);
901
Eric Laurent81784c32012-11-19 14:55:58 -0800902 status_t status = chain->addEffect_l(effect);
903 if (status != NO_ERROR) {
904 if (chainCreated) {
905 removeEffectChain_l(chain);
906 }
907 return status;
908 }
909
910 effect->setDevice(mOutDevice);
911 effect->setDevice(mInDevice);
912 effect->setMode(mAudioFlinger->getMode());
913 effect->setAudioSource(mAudioSource);
914 return NO_ERROR;
915}
916
917void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
918
919 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
920 effect_descriptor_t desc = effect->desc();
921 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
922 detachAuxEffect_l(effect->id());
923 }
924
925 sp<EffectChain> chain = effect->chain().promote();
926 if (chain != 0) {
927 // remove effect chain if removing last effect
928 if (chain->removeEffect_l(effect) == 0) {
929 removeEffectChain_l(chain);
930 }
931 } else {
932 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
933 }
934}
935
936void AudioFlinger::ThreadBase::lockEffectChains_l(
937 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
938{
939 effectChains = mEffectChains;
940 for (size_t i = 0; i < mEffectChains.size(); i++) {
941 mEffectChains[i]->lock();
942 }
943}
944
945void AudioFlinger::ThreadBase::unlockEffectChains(
946 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
947{
948 for (size_t i = 0; i < effectChains.size(); i++) {
949 effectChains[i]->unlock();
950 }
951}
952
953sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
954{
955 Mutex::Autolock _l(mLock);
956 return getEffectChain_l(sessionId);
957}
958
959sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
960{
961 size_t size = mEffectChains.size();
962 for (size_t i = 0; i < size; i++) {
963 if (mEffectChains[i]->sessionId() == sessionId) {
964 return mEffectChains[i];
965 }
966 }
967 return 0;
968}
969
970void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
971{
972 Mutex::Autolock _l(mLock);
973 size_t size = mEffectChains.size();
974 for (size_t i = 0; i < size; i++) {
975 mEffectChains[i]->setMode_l(mode);
976 }
977}
978
979void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
980 EffectHandle *handle,
981 bool unpinIfLast) {
982
983 Mutex::Autolock _l(mLock);
984 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
985 // delete the effect module if removing last handle on it
986 if (effect->removeHandle(handle) == 0) {
987 if (!effect->isPinned() || unpinIfLast) {
988 removeEffect_l(effect);
989 AudioSystem::unregisterEffect(effect->id());
990 }
991 }
992}
993
994// ----------------------------------------------------------------------------
995// Playback
996// ----------------------------------------------------------------------------
997
998AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
999 AudioStreamOut* output,
1000 audio_io_handle_t id,
1001 audio_devices_t device,
1002 type_t type)
1003 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001004 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001005 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Marco Nelissen9cae2172013-01-14 14:12:05 -08001006 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001007 // mStreamTypes[] initialized in constructor body
1008 mOutput(output),
1009 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1010 mMixerStatus(MIXER_IDLE),
1011 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1012 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001013 mBytesRemaining(0),
1014 mCurrentWriteLength(0),
1015 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001016 mWriteAckSequence(0),
1017 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001018 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001019 mScreenState(AudioFlinger::mScreenState),
1020 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001021 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1022 // mLatchD, mLatchQ,
1023 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
1025 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001026 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001027
1028 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1029 // it would be safer to explicitly pass initial masterVolume/masterMute as
1030 // parameter.
1031 //
1032 // If the HAL we are using has support for master volume or master mute,
1033 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1034 // and the mute set to false).
1035 mMasterVolume = audioFlinger->masterVolume_l();
1036 mMasterMute = audioFlinger->masterMute_l();
1037 if (mOutput && mOutput->audioHwDev) {
1038 if (mOutput->audioHwDev->canSetMasterVolume()) {
1039 mMasterVolume = 1.0;
1040 }
1041
1042 if (mOutput->audioHwDev->canSetMasterMute()) {
1043 mMasterMute = false;
1044 }
1045 }
1046
1047 readOutputParameters();
1048
1049 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1050 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1051 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1052 stream = (audio_stream_type_t) (stream + 1)) {
1053 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1054 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1055 }
1056 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1057 // because mAudioFlinger doesn't have one to copy from
1058}
1059
1060AudioFlinger::PlaybackThread::~PlaybackThread()
1061{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001062 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001063 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001064}
1065
1066void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1067{
1068 dumpInternals(fd, args);
1069 dumpTracks(fd, args);
1070 dumpEffectChains(fd, args);
1071}
1072
1073void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1074{
1075 const size_t SIZE = 256;
1076 char buffer[SIZE];
1077 String8 result;
1078
1079 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1080 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1081 const stream_type_t *st = &mStreamTypes[i];
1082 if (i > 0) {
1083 result.appendFormat(", ");
1084 }
1085 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1086 if (st->mute) {
1087 result.append("M");
1088 }
1089 }
1090 result.append("\n");
1091 write(fd, result.string(), result.length());
1092 result.clear();
1093
1094 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1095 result.append(buffer);
1096 Track::appendDumpHeader(result);
1097 for (size_t i = 0; i < mTracks.size(); ++i) {
1098 sp<Track> track = mTracks[i];
1099 if (track != 0) {
1100 track->dump(buffer, SIZE);
1101 result.append(buffer);
1102 }
1103 }
1104
1105 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1106 result.append(buffer);
1107 Track::appendDumpHeader(result);
1108 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1109 sp<Track> track = mActiveTracks[i].promote();
1110 if (track != 0) {
1111 track->dump(buffer, SIZE);
1112 result.append(buffer);
1113 }
1114 }
1115 write(fd, result.string(), result.size());
1116
1117 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1118 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1119 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1120 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1121}
1122
1123void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1124{
1125 const size_t SIZE = 256;
1126 char buffer[SIZE];
1127 String8 result;
1128
1129 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1130 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001131 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1132 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001133 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1134 ns2ms(systemTime() - mLastWriteTime));
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1137 result.append(buffer);
1138 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1139 result.append(buffer);
1140 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1143 result.append(buffer);
1144 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1145 result.append(buffer);
1146 write(fd, result.string(), result.size());
1147 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1148
1149 dumpBase(fd, args);
1150}
1151
1152// Thread virtuals
1153status_t AudioFlinger::PlaybackThread::readyToRun()
1154{
1155 status_t status = initCheck();
1156 if (status == NO_ERROR) {
1157 ALOGI("AudioFlinger's thread %p ready to run", this);
1158 } else {
1159 ALOGE("No working audio driver found.");
1160 }
1161 return status;
1162}
1163
1164void AudioFlinger::PlaybackThread::onFirstRef()
1165{
1166 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1167}
1168
1169// ThreadBase virtuals
1170void AudioFlinger::PlaybackThread::preExit()
1171{
1172 ALOGV(" preExit()");
1173 // FIXME this is using hard-coded strings but in the future, this functionality will be
1174 // converted to use audio HAL extensions required to support tunneling
1175 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1176}
1177
1178// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1179sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1180 const sp<AudioFlinger::Client>& client,
1181 audio_stream_type_t streamType,
1182 uint32_t sampleRate,
1183 audio_format_t format,
1184 audio_channel_mask_t channelMask,
1185 size_t frameCount,
1186 const sp<IMemory>& sharedBuffer,
1187 int sessionId,
1188 IAudioFlinger::track_flags_t *flags,
1189 pid_t tid,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001190 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001191 status_t *status)
1192{
1193 sp<Track> track;
1194 status_t lStatus;
1195
1196 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1197
1198 // client expresses a preference for FAST, but we get the final say
1199 if (*flags & IAudioFlinger::TRACK_FAST) {
1200 if (
1201 // not timed
1202 (!isTimed) &&
1203 // either of these use cases:
1204 (
1205 // use case 1: shared buffer with any frame count
1206 (
1207 (sharedBuffer != 0)
1208 ) ||
1209 // use case 2: callback handler and frame count is default or at least as large as HAL
1210 (
1211 (tid != -1) &&
1212 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001213 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001214 )
1215 ) &&
1216 // PCM data
1217 audio_is_linear_pcm(format) &&
1218 // mono or stereo
1219 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1220 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1221#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1222 // hardware sample rate
1223 (sampleRate == mSampleRate) &&
1224#endif
1225 // normal mixer has an associated fast mixer
1226 hasFastMixer() &&
1227 // there are sufficient fast track slots available
1228 (mFastTrackAvailMask != 0)
1229 // FIXME test that MixerThread for this fast track has a capable output HAL
1230 // FIXME add a permission test also?
1231 ) {
1232 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1233 if (frameCount == 0) {
1234 frameCount = mFrameCount * kFastTrackMultiplier;
1235 }
1236 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1237 frameCount, mFrameCount);
1238 } else {
1239 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1240 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1241 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1242 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1243 audio_is_linear_pcm(format),
1244 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1245 *flags &= ~IAudioFlinger::TRACK_FAST;
1246 // For compatibility with AudioTrack calculation, buffer depth is forced
1247 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1248 // This is probably too conservative, but legacy application code may depend on it.
1249 // If you change this calculation, also review the start threshold which is related.
1250 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1251 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1252 if (minBufCount < 2) {
1253 minBufCount = 2;
1254 }
1255 size_t minFrameCount = mNormalFrameCount * minBufCount;
1256 if (frameCount < minFrameCount) {
1257 frameCount = minFrameCount;
1258 }
1259 }
1260 }
1261
1262 if (mType == DIRECT) {
1263 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1264 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1265 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1266 "for output %p with format %d",
1267 sampleRate, format, channelMask, mOutput, mFormat);
1268 lStatus = BAD_VALUE;
1269 goto Exit;
1270 }
1271 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001272 } else if (mType == OFFLOAD) {
1273 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1274 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1275 "for output %p with format %d",
1276 sampleRate, format, channelMask, mOutput, mFormat);
1277 lStatus = BAD_VALUE;
1278 goto Exit;
1279 }
Eric Laurent81784c32012-11-19 14:55:58 -08001280 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001281 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1282 ALOGE("createTrack_l() Bad parameter: format %d \""
1283 "for output %p with format %d",
1284 format, mOutput, mFormat);
1285 lStatus = BAD_VALUE;
1286 goto Exit;
1287 }
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1289 if (sampleRate > mSampleRate*2) {
1290 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1291 lStatus = BAD_VALUE;
1292 goto Exit;
1293 }
1294 }
1295
1296 lStatus = initCheck();
1297 if (lStatus != NO_ERROR) {
1298 ALOGE("Audio driver not initialized.");
1299 goto Exit;
1300 }
1301
1302 { // scope for mLock
1303 Mutex::Autolock _l(mLock);
1304
1305 // all tracks in same audio session must share the same routing strategy otherwise
1306 // conflicts will happen when tracks are moved from one output to another by audio policy
1307 // manager
1308 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1309 for (size_t i = 0; i < mTracks.size(); ++i) {
1310 sp<Track> t = mTracks[i];
1311 if (t != 0 && !t->isOutputTrack()) {
1312 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1313 if (sessionId == t->sessionId() && strategy != actual) {
1314 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1315 strategy, actual);
1316 lStatus = BAD_VALUE;
1317 goto Exit;
1318 }
1319 }
1320 }
1321
1322 if (!isTimed) {
1323 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001324 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 } else {
1326 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001327 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 }
1329 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1330 lStatus = NO_MEMORY;
1331 goto Exit;
1332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001333
Eric Laurent81784c32012-11-19 14:55:58 -08001334 mTracks.add(track);
1335
1336 sp<EffectChain> chain = getEffectChain_l(sessionId);
1337 if (chain != 0) {
1338 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1339 track->setMainBuffer(chain->inBuffer());
1340 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1341 chain->incTrackCnt();
1342 }
1343
1344 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1345 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1346 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1347 // so ask activity manager to do this on our behalf
1348 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1349 }
1350 }
1351
1352 lStatus = NO_ERROR;
1353
1354Exit:
1355 if (status) {
1356 *status = lStatus;
1357 }
1358 return track;
1359}
1360
1361uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1362{
1363 return latency;
1364}
1365
1366uint32_t AudioFlinger::PlaybackThread::latency() const
1367{
1368 Mutex::Autolock _l(mLock);
1369 return latency_l();
1370}
1371uint32_t AudioFlinger::PlaybackThread::latency_l() const
1372{
1373 if (initCheck() == NO_ERROR) {
1374 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1375 } else {
1376 return 0;
1377 }
1378}
1379
1380void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1381{
1382 Mutex::Autolock _l(mLock);
1383 // Don't apply master volume in SW if our HAL can do it for us.
1384 if (mOutput && mOutput->audioHwDev &&
1385 mOutput->audioHwDev->canSetMasterVolume()) {
1386 mMasterVolume = 1.0;
1387 } else {
1388 mMasterVolume = value;
1389 }
1390}
1391
1392void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1393{
1394 Mutex::Autolock _l(mLock);
1395 // Don't apply master mute in SW if our HAL can do it for us.
1396 if (mOutput && mOutput->audioHwDev &&
1397 mOutput->audioHwDev->canSetMasterMute()) {
1398 mMasterMute = false;
1399 } else {
1400 mMasterMute = muted;
1401 }
1402}
1403
1404void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1405{
1406 Mutex::Autolock _l(mLock);
1407 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001408 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001409}
1410
1411void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1412{
1413 Mutex::Autolock _l(mLock);
1414 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001415 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001416}
1417
1418float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1419{
1420 Mutex::Autolock _l(mLock);
1421 return mStreamTypes[stream].volume;
1422}
1423
1424// addTrack_l() must be called with ThreadBase::mLock held
1425status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1426{
1427 status_t status = ALREADY_EXISTS;
1428
1429 // set retry count for buffer fill
1430 track->mRetryCount = kMaxTrackStartupRetries;
1431 if (mActiveTracks.indexOf(track) < 0) {
1432 // the track is newly added, make sure it fills up all its
1433 // buffers before playing. This is to ensure the client will
1434 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001435 if (!track->isOutputTrack()) {
1436 TrackBase::track_state state = track->mState;
1437 mLock.unlock();
1438 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1439 mLock.lock();
1440 // abort track was stopped/paused while we released the lock
1441 if (state != track->mState) {
1442 if (status == NO_ERROR) {
1443 mLock.unlock();
1444 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1445 mLock.lock();
1446 }
1447 return INVALID_OPERATION;
1448 }
1449 // abort if start is rejected by audio policy manager
1450 if (status != NO_ERROR) {
1451 return PERMISSION_DENIED;
1452 }
1453#ifdef ADD_BATTERY_DATA
1454 // to track the speaker usage
1455 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1456#endif
1457 }
1458
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001459 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001460 track->mResetDone = false;
1461 track->mPresentationCompleteFrames = 0;
1462 mActiveTracks.add(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08001463 mWakeLockUids.add(track->uid());
1464 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001465 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001466 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1467 if (chain != 0) {
1468 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1469 track->sessionId());
1470 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001471 }
1472
1473 status = NO_ERROR;
1474 }
1475
Eric Laurentede6c3b2013-09-19 14:37:46 -07001476 ALOGV("signal playback thread");
1477 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001478
1479 return status;
1480}
1481
Eric Laurentbfb1b832013-01-07 09:53:42 -08001482bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001483{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001484 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001485 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001486 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1487 track->mState = TrackBase::STOPPED;
1488 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001489 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001490 } else if (track->isFastTrack() || track->isOffloaded()) {
1491 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001493
1494 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001495}
1496
1497void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1498{
1499 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1500 mTracks.remove(track);
1501 deleteTrackName_l(track->name());
1502 // redundant as track is about to be destroyed, for dumpsys only
1503 track->mName = -1;
1504 if (track->isFastTrack()) {
1505 int index = track->mFastIndex;
1506 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1507 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1508 mFastTrackAvailMask |= 1 << index;
1509 // redundant as track is about to be destroyed, for dumpsys only
1510 track->mFastIndex = -1;
1511 }
1512 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1513 if (chain != 0) {
1514 chain->decTrackCnt();
1515 }
1516}
1517
Eric Laurentede6c3b2013-09-19 14:37:46 -07001518void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001519{
1520 // Thread could be blocked waiting for async
1521 // so signal it to handle state changes immediately
1522 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1523 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1524 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001525 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001526}
1527
Eric Laurent81784c32012-11-19 14:55:58 -08001528String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1529{
Eric Laurent81784c32012-11-19 14:55:58 -08001530 Mutex::Autolock _l(mLock);
1531 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001532 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001533 }
1534
Glenn Kastend8ea6992013-07-16 14:17:15 -07001535 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1536 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001537 free(s);
1538 return out_s8;
1539}
1540
1541// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1542void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1543 AudioSystem::OutputDescriptor desc;
1544 void *param2 = NULL;
1545
1546 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1547 param);
1548
1549 switch (event) {
1550 case AudioSystem::OUTPUT_OPENED:
1551 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001552 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001553 desc.samplingRate = mSampleRate;
1554 desc.format = mFormat;
1555 desc.frameCount = mNormalFrameCount; // FIXME see
1556 // AudioFlinger::frameCount(audio_io_handle_t)
1557 desc.latency = latency();
1558 param2 = &desc;
1559 break;
1560
1561 case AudioSystem::STREAM_CONFIG_CHANGED:
1562 param2 = &param;
1563 case AudioSystem::OUTPUT_CLOSED:
1564 default:
1565 break;
1566 }
1567 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1568}
1569
Eric Laurentbfb1b832013-01-07 09:53:42 -08001570void AudioFlinger::PlaybackThread::writeCallback()
1571{
1572 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001573 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001574}
1575
1576void AudioFlinger::PlaybackThread::drainCallback()
1577{
1578 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001579 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001580}
1581
Eric Laurent3b4529e2013-09-05 18:09:19 -07001582void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001583{
1584 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001585 // reject out of sequence requests
1586 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1587 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001588 mWaitWorkCV.signal();
1589 }
1590}
1591
Eric Laurent3b4529e2013-09-05 18:09:19 -07001592void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001593{
1594 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001595 // reject out of sequence requests
1596 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1597 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001598 mWaitWorkCV.signal();
1599 }
1600}
1601
1602// static
1603int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1604 void *param,
1605 void *cookie)
1606{
1607 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1608 ALOGV("asyncCallback() event %d", event);
1609 switch (event) {
1610 case STREAM_CBK_EVENT_WRITE_READY:
1611 me->writeCallback();
1612 break;
1613 case STREAM_CBK_EVENT_DRAIN_READY:
1614 me->drainCallback();
1615 break;
1616 default:
1617 ALOGW("asyncCallback() unknown event %d", event);
1618 break;
1619 }
1620 return 0;
1621}
1622
Eric Laurent81784c32012-11-19 14:55:58 -08001623void AudioFlinger::PlaybackThread::readOutputParameters()
1624{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001625 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001626 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1627 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001628 if (!audio_is_output_channel(mChannelMask)) {
1629 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1630 }
1631 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1632 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1633 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1634 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001635 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001636 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001637 if (!audio_is_valid_format(mFormat)) {
1638 LOG_FATAL("HAL format %d not valid for output", mFormat);
1639 }
1640 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1641 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1642 mFormat);
1643 }
Eric Laurent81784c32012-11-19 14:55:58 -08001644 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1645 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1646 if (mFrameCount & 15) {
1647 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1648 mFrameCount);
1649 }
1650
Eric Laurentbfb1b832013-01-07 09:53:42 -08001651 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1652 (mOutput->stream->set_callback != NULL)) {
1653 if (mOutput->stream->set_callback(mOutput->stream,
1654 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1655 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001656 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001657 }
1658 }
1659
Eric Laurent81784c32012-11-19 14:55:58 -08001660 // Calculate size of normal mix buffer relative to the HAL output buffer size
1661 double multiplier = 1.0;
1662 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1663 kUseFastMixer == FastMixer_Dynamic)) {
1664 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1665 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1666 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1667 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1668 maxNormalFrameCount = maxNormalFrameCount & ~15;
1669 if (maxNormalFrameCount < minNormalFrameCount) {
1670 maxNormalFrameCount = minNormalFrameCount;
1671 }
1672 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1673 if (multiplier <= 1.0) {
1674 multiplier = 1.0;
1675 } else if (multiplier <= 2.0) {
1676 if (2 * mFrameCount <= maxNormalFrameCount) {
1677 multiplier = 2.0;
1678 } else {
1679 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1680 }
1681 } else {
1682 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1683 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1684 // track, but we sometimes have to do this to satisfy the maximum frame count
1685 // constraint)
1686 // FIXME this rounding up should not be done if no HAL SRC
1687 uint32_t truncMult = (uint32_t) multiplier;
1688 if ((truncMult & 1)) {
1689 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1690 ++truncMult;
1691 }
1692 }
1693 multiplier = (double) truncMult;
1694 }
1695 }
1696 mNormalFrameCount = multiplier * mFrameCount;
1697 // round up to nearest 16 frames to satisfy AudioMixer
1698 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1699 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1700 mNormalFrameCount);
1701
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702 delete[] mAllocMixBuffer;
1703 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1704 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1705 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1706 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001707
1708 // force reconfiguration of effect chains and engines to take new buffer size and audio
1709 // parameters into account
1710 // Note that mLock is not held when readOutputParameters() is called from the constructor
1711 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1712 // matter.
1713 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1714 Vector< sp<EffectChain> > effectChains = mEffectChains;
1715 for (size_t i = 0; i < effectChains.size(); i ++) {
1716 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1717 }
1718}
1719
1720
1721status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1722{
1723 if (halFrames == NULL || dspFrames == NULL) {
1724 return BAD_VALUE;
1725 }
1726 Mutex::Autolock _l(mLock);
1727 if (initCheck() != NO_ERROR) {
1728 return INVALID_OPERATION;
1729 }
1730 size_t framesWritten = mBytesWritten / mFrameSize;
1731 *halFrames = framesWritten;
1732
1733 if (isSuspended()) {
1734 // return an estimation of rendered frames when the output is suspended
1735 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1736 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1737 return NO_ERROR;
1738 } else {
1739 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1740 }
1741}
1742
1743uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1744{
1745 Mutex::Autolock _l(mLock);
1746 uint32_t result = 0;
1747 if (getEffectChain_l(sessionId) != 0) {
1748 result = EFFECT_SESSION;
1749 }
1750
1751 for (size_t i = 0; i < mTracks.size(); ++i) {
1752 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001753 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001754 result |= TRACK_SESSION;
1755 break;
1756 }
1757 }
1758
1759 return result;
1760}
1761
1762uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1763{
1764 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1765 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1766 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1767 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1768 }
1769 for (size_t i = 0; i < mTracks.size(); i++) {
1770 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001771 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001772 return AudioSystem::getStrategyForStream(track->streamType());
1773 }
1774 }
1775 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1776}
1777
1778
1779AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1780{
1781 Mutex::Autolock _l(mLock);
1782 return mOutput;
1783}
1784
1785AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1786{
1787 Mutex::Autolock _l(mLock);
1788 AudioStreamOut *output = mOutput;
1789 mOutput = NULL;
1790 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1791 // must push a NULL and wait for ack
1792 mOutputSink.clear();
1793 mPipeSink.clear();
1794 mNormalSink.clear();
1795 return output;
1796}
1797
1798// this method must always be called either with ThreadBase mLock held or inside the thread loop
1799audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1800{
1801 if (mOutput == NULL) {
1802 return NULL;
1803 }
1804 return &mOutput->stream->common;
1805}
1806
1807uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1808{
1809 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1810}
1811
1812status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1813{
1814 if (!isValidSyncEvent(event)) {
1815 return BAD_VALUE;
1816 }
1817
1818 Mutex::Autolock _l(mLock);
1819
1820 for (size_t i = 0; i < mTracks.size(); ++i) {
1821 sp<Track> track = mTracks[i];
1822 if (event->triggerSession() == track->sessionId()) {
1823 (void) track->setSyncEvent(event);
1824 return NO_ERROR;
1825 }
1826 }
1827
1828 return NAME_NOT_FOUND;
1829}
1830
1831bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1832{
1833 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1834}
1835
1836void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1837 const Vector< sp<Track> >& tracksToRemove)
1838{
1839 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001840 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001841 for (size_t i = 0 ; i < count ; i++) {
1842 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001844 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845#ifdef ADD_BATTERY_DATA
1846 // to track the speaker usage
1847 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1848#endif
1849 if (track->isTerminated()) {
1850 AudioSystem::releaseOutput(mId);
1851 }
Eric Laurent81784c32012-11-19 14:55:58 -08001852 }
1853 }
1854 }
Eric Laurent81784c32012-11-19 14:55:58 -08001855}
1856
1857void AudioFlinger::PlaybackThread::checkSilentMode_l()
1858{
1859 if (!mMasterMute) {
1860 char value[PROPERTY_VALUE_MAX];
1861 if (property_get("ro.audio.silent", value, "0") > 0) {
1862 char *endptr;
1863 unsigned long ul = strtoul(value, &endptr, 0);
1864 if (*endptr == '\0' && ul != 0) {
1865 ALOGD("Silence is golden");
1866 // The setprop command will not allow a property to be changed after
1867 // the first time it is set, so we don't have to worry about un-muting.
1868 setMasterMute_l(true);
1869 }
1870 }
1871 }
1872}
1873
1874// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001875ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
1877 // FIXME rewrite to reduce number of system calls
1878 mLastWriteTime = systemTime();
1879 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001881
1882 // If an NBAIO sink is present, use it to write the normal mixer's submix
1883 if (mNormalSink != 0) {
1884#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885 size_t count = mBytesRemaining >> mBitShift;
1886 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001887 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001888 // update the setpoint when AudioFlinger::mScreenState changes
1889 uint32_t screenState = AudioFlinger::mScreenState;
1890 if (screenState != mScreenState) {
1891 mScreenState = screenState;
1892 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1893 if (pipe != NULL) {
1894 pipe->setAvgFrames((mScreenState & 1) ?
1895 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1896 }
1897 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001899 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001900 if (framesWritten > 0) {
1901 bytesWritten = framesWritten << mBitShift;
1902 } else {
1903 bytesWritten = framesWritten;
1904 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001905 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001906 if (status == NO_ERROR) {
1907 size_t totalFramesWritten = mNormalSink->framesWritten();
1908 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1909 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1910 mLatchDValid = true;
1911 }
1912 }
Eric Laurent81784c32012-11-19 14:55:58 -08001913 // otherwise use the HAL / AudioStreamOut directly
1914 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001915 // Direct output and offload threads
1916 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1917 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001918 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1919 mWriteAckSequence += 2;
1920 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001921 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001922 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001923 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001924 // FIXME We should have an implementation of timestamps for direct output threads.
1925 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001926 bytesWritten = mOutput->stream->write(mOutput->stream,
1927 mMixBuffer + offset, mBytesRemaining);
1928 if (mUseAsyncWrite &&
1929 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1930 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001931 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001933 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001934 }
Eric Laurent81784c32012-11-19 14:55:58 -08001935 }
1936
Eric Laurent81784c32012-11-19 14:55:58 -08001937 mNumWrites++;
1938 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001939 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940 return bytesWritten;
1941}
1942
1943void AudioFlinger::PlaybackThread::threadLoop_drain()
1944{
1945 if (mOutput->stream->drain) {
1946 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1947 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001948 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1949 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001951 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 }
1953 mOutput->stream->drain(mOutput->stream,
1954 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1955 : AUDIO_DRAIN_ALL);
1956 }
1957}
1958
1959void AudioFlinger::PlaybackThread::threadLoop_exit()
1960{
1961 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001962}
1963
1964/*
1965The derived values that are cached:
1966 - mixBufferSize from frame count * frame size
1967 - activeSleepTime from activeSleepTimeUs()
1968 - idleSleepTime from idleSleepTimeUs()
1969 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1970 - maxPeriod from frame count and sample rate (MIXER only)
1971
1972The parameters that affect these derived values are:
1973 - frame count
1974 - frame size
1975 - sample rate
1976 - device type: A2DP or not
1977 - device latency
1978 - format: PCM or not
1979 - active sleep time
1980 - idle sleep time
1981*/
1982
1983void AudioFlinger::PlaybackThread::cacheParameters_l()
1984{
1985 mixBufferSize = mNormalFrameCount * mFrameSize;
1986 activeSleepTime = activeSleepTimeUs();
1987 idleSleepTime = idleSleepTimeUs();
1988}
1989
1990void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1991{
Glenn Kasten7c027242012-12-26 14:43:16 -08001992 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001993 this, streamType, mTracks.size());
1994 Mutex::Autolock _l(mLock);
1995
1996 size_t size = mTracks.size();
1997 for (size_t i = 0; i < size; i++) {
1998 sp<Track> t = mTracks[i];
1999 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002000 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002001 }
2002 }
2003}
2004
2005status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2006{
2007 int session = chain->sessionId();
2008 int16_t *buffer = mMixBuffer;
2009 bool ownsBuffer = false;
2010
2011 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2012 if (session > 0) {
2013 // Only one effect chain can be present in direct output thread and it uses
2014 // the mix buffer as input
2015 if (mType != DIRECT) {
2016 size_t numSamples = mNormalFrameCount * mChannelCount;
2017 buffer = new int16_t[numSamples];
2018 memset(buffer, 0, numSamples * sizeof(int16_t));
2019 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2020 ownsBuffer = true;
2021 }
2022
2023 // Attach all tracks with same session ID to this chain.
2024 for (size_t i = 0; i < mTracks.size(); ++i) {
2025 sp<Track> track = mTracks[i];
2026 if (session == track->sessionId()) {
2027 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2028 buffer);
2029 track->setMainBuffer(buffer);
2030 chain->incTrackCnt();
2031 }
2032 }
2033
2034 // indicate all active tracks in the chain
2035 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2036 sp<Track> track = mActiveTracks[i].promote();
2037 if (track == 0) {
2038 continue;
2039 }
2040 if (session == track->sessionId()) {
2041 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2042 chain->incActiveTrackCnt();
2043 }
2044 }
2045 }
2046
2047 chain->setInBuffer(buffer, ownsBuffer);
2048 chain->setOutBuffer(mMixBuffer);
2049 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2050 // chains list in order to be processed last as it contains output stage effects
2051 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2052 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2053 // after track specific effects and before output stage
2054 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2055 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2056 // Effect chain for other sessions are inserted at beginning of effect
2057 // chains list to be processed before output mix effects. Relative order between other
2058 // sessions is not important
2059 size_t size = mEffectChains.size();
2060 size_t i = 0;
2061 for (i = 0; i < size; i++) {
2062 if (mEffectChains[i]->sessionId() < session) {
2063 break;
2064 }
2065 }
2066 mEffectChains.insertAt(chain, i);
2067 checkSuspendOnAddEffectChain_l(chain);
2068
2069 return NO_ERROR;
2070}
2071
2072size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2073{
2074 int session = chain->sessionId();
2075
2076 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2077
2078 for (size_t i = 0; i < mEffectChains.size(); i++) {
2079 if (chain == mEffectChains[i]) {
2080 mEffectChains.removeAt(i);
2081 // detach all active tracks from the chain
2082 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2083 sp<Track> track = mActiveTracks[i].promote();
2084 if (track == 0) {
2085 continue;
2086 }
2087 if (session == track->sessionId()) {
2088 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2089 chain.get(), session);
2090 chain->decActiveTrackCnt();
2091 }
2092 }
2093
2094 // detach all tracks with same session ID from this chain
2095 for (size_t i = 0; i < mTracks.size(); ++i) {
2096 sp<Track> track = mTracks[i];
2097 if (session == track->sessionId()) {
2098 track->setMainBuffer(mMixBuffer);
2099 chain->decTrackCnt();
2100 }
2101 }
2102 break;
2103 }
2104 }
2105 return mEffectChains.size();
2106}
2107
2108status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2109 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2110{
2111 Mutex::Autolock _l(mLock);
2112 return attachAuxEffect_l(track, EffectId);
2113}
2114
2115status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2116 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2117{
2118 status_t status = NO_ERROR;
2119
2120 if (EffectId == 0) {
2121 track->setAuxBuffer(0, NULL);
2122 } else {
2123 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2124 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2125 if (effect != 0) {
2126 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2127 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2128 } else {
2129 status = INVALID_OPERATION;
2130 }
2131 } else {
2132 status = BAD_VALUE;
2133 }
2134 }
2135 return status;
2136}
2137
2138void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2139{
2140 for (size_t i = 0; i < mTracks.size(); ++i) {
2141 sp<Track> track = mTracks[i];
2142 if (track->auxEffectId() == effectId) {
2143 attachAuxEffect_l(track, 0);
2144 }
2145 }
2146}
2147
2148bool AudioFlinger::PlaybackThread::threadLoop()
2149{
2150 Vector< sp<Track> > tracksToRemove;
2151
2152 standbyTime = systemTime();
2153
2154 // MIXER
2155 nsecs_t lastWarning = 0;
2156
2157 // DUPLICATING
2158 // FIXME could this be made local to while loop?
2159 writeFrames = 0;
2160
Marco Nelissen9cae2172013-01-14 14:12:05 -08002161 int lastGeneration = 0;
2162
Eric Laurent81784c32012-11-19 14:55:58 -08002163 cacheParameters_l();
2164 sleepTime = idleSleepTime;
2165
2166 if (mType == MIXER) {
2167 sleepTimeShift = 0;
2168 }
2169
2170 CpuStats cpuStats;
2171 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2172
2173 acquireWakeLock();
2174
Glenn Kasten9e58b552013-01-18 15:09:48 -08002175 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2176 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2177 // and then that string will be logged at the next convenient opportunity.
2178 const char *logString = NULL;
2179
Eric Laurent664539d2013-09-23 18:24:31 -07002180 checkSilentMode_l();
2181
Eric Laurent81784c32012-11-19 14:55:58 -08002182 while (!exitPending())
2183 {
2184 cpuStats.sample(myName);
2185
2186 Vector< sp<EffectChain> > effectChains;
2187
2188 processConfigEvents();
2189
2190 { // scope for mLock
2191
2192 Mutex::Autolock _l(mLock);
2193
Glenn Kasten9e58b552013-01-18 15:09:48 -08002194 if (logString != NULL) {
2195 mNBLogWriter->logTimestamp();
2196 mNBLogWriter->log(logString);
2197 logString = NULL;
2198 }
2199
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002200 if (mLatchDValid) {
2201 mLatchQ = mLatchD;
2202 mLatchDValid = false;
2203 mLatchQValid = true;
2204 }
2205
Eric Laurent81784c32012-11-19 14:55:58 -08002206 if (checkForNewParameters_l()) {
2207 cacheParameters_l();
2208 }
2209
2210 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 if (mSignalPending) {
2212 // A signal was raised while we were unlocked
2213 mSignalPending = false;
2214 } else if (waitingAsyncCallback_l()) {
2215 if (exitPending()) {
2216 break;
2217 }
2218 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002219 mWakeLockUids.clear();
2220 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002221 ALOGV("wait async completion");
2222 mWaitWorkCV.wait(mLock);
2223 ALOGV("async completion/wake");
2224 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002225 standbyTime = systemTime() + standbyDelay;
2226 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002227
2228 continue;
2229 }
2230 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002231 isSuspended()) {
2232 // put audio hardware into standby after short delay
2233 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002234
2235 threadLoop_standby();
2236
2237 mStandby = true;
2238 }
2239
2240 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2241 // we're about to wait, flush the binder command buffer
2242 IPCThreadState::self()->flushCommands();
2243
2244 clearOutputTracks();
2245
2246 if (exitPending()) {
2247 break;
2248 }
2249
2250 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002251 mWakeLockUids.clear();
2252 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002253 // wait until we have something to do...
2254 ALOGV("%s going to sleep", myName.string());
2255 mWaitWorkCV.wait(mLock);
2256 ALOGV("%s waking up", myName.string());
2257 acquireWakeLock_l();
2258
2259 mMixerStatus = MIXER_IDLE;
2260 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2261 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002263 checkSilentMode_l();
2264
2265 standbyTime = systemTime() + standbyDelay;
2266 sleepTime = idleSleepTime;
2267 if (mType == MIXER) {
2268 sleepTimeShift = 0;
2269 }
2270
2271 continue;
2272 }
2273 }
Eric Laurent81784c32012-11-19 14:55:58 -08002274 // mMixerStatusIgnoringFastTracks is also updated internally
2275 mMixerStatus = prepareTracks_l(&tracksToRemove);
2276
Marco Nelissen9cae2172013-01-14 14:12:05 -08002277 // compare with previously applied list
2278 if (lastGeneration != mActiveTracksGeneration) {
2279 // update wakelock
2280 updateWakeLockUids_l(mWakeLockUids);
2281 lastGeneration = mActiveTracksGeneration;
2282 }
2283
Eric Laurent81784c32012-11-19 14:55:58 -08002284 // prevent any changes in effect chain list and in each effect chain
2285 // during mixing and effect process as the audio buffers could be deleted
2286 // or modified if an effect is created or deleted
2287 lockEffectChains_l(effectChains);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002288 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002289
Eric Laurentbfb1b832013-01-07 09:53:42 -08002290 if (mBytesRemaining == 0) {
2291 mCurrentWriteLength = 0;
2292 if (mMixerStatus == MIXER_TRACKS_READY) {
2293 // threadLoop_mix() sets mCurrentWriteLength
2294 threadLoop_mix();
2295 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2296 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2297 // threadLoop_sleepTime sets sleepTime to 0 if data
2298 // must be written to HAL
2299 threadLoop_sleepTime();
2300 if (sleepTime == 0) {
2301 mCurrentWriteLength = mixBufferSize;
2302 }
2303 }
2304 mBytesRemaining = mCurrentWriteLength;
2305 if (isSuspended()) {
2306 sleepTime = suspendSleepTimeUs();
2307 // simulate write to HAL when suspended
2308 mBytesWritten += mixBufferSize;
2309 mBytesRemaining = 0;
2310 }
Eric Laurent81784c32012-11-19 14:55:58 -08002311
Eric Laurentbfb1b832013-01-07 09:53:42 -08002312 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002313 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 for (size_t i = 0; i < effectChains.size(); i ++) {
2315 effectChains[i]->process_l();
2316 }
Eric Laurent81784c32012-11-19 14:55:58 -08002317 }
2318 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002319 // Process effect chains for offloaded thread even if no audio
2320 // was read from audio track: process only updates effect state
2321 // and thus does have to be synchronized with audio writes but may have
2322 // to be called while waiting for async write callback
2323 if (mType == OFFLOAD) {
2324 for (size_t i = 0; i < effectChains.size(); i ++) {
2325 effectChains[i]->process_l();
2326 }
2327 }
Eric Laurent81784c32012-11-19 14:55:58 -08002328
2329 // enable changes in effect chain
2330 unlockEffectChains(effectChains);
2331
Eric Laurentbfb1b832013-01-07 09:53:42 -08002332 if (!waitingAsyncCallback()) {
2333 // sleepTime == 0 means we must write to audio hardware
2334 if (sleepTime == 0) {
2335 if (mBytesRemaining) {
2336 ssize_t ret = threadLoop_write();
2337 if (ret < 0) {
2338 mBytesRemaining = 0;
2339 } else {
2340 mBytesWritten += ret;
2341 mBytesRemaining -= ret;
2342 }
2343 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2344 (mMixerStatus == MIXER_DRAIN_ALL)) {
2345 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002346 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002347if (mType == MIXER) {
2348 // write blocked detection
2349 nsecs_t now = systemTime();
2350 nsecs_t delta = now - mLastWriteTime;
2351 if (!mStandby && delta > maxPeriod) {
2352 mNumDelayedWrites++;
2353 if ((now - lastWarning) > kWarningThrottleNs) {
2354 ATRACE_NAME("underrun");
2355 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2356 ns2ms(delta), mNumDelayedWrites, this);
2357 lastWarning = now;
2358 }
2359 }
Eric Laurent81784c32012-11-19 14:55:58 -08002360}
2361
Eric Laurentbfb1b832013-01-07 09:53:42 -08002362 } else {
2363 usleep(sleepTime);
2364 }
Eric Laurent81784c32012-11-19 14:55:58 -08002365 }
2366
2367 // Finally let go of removed track(s), without the lock held
2368 // since we can't guarantee the destructors won't acquire that
2369 // same lock. This will also mutate and push a new fast mixer state.
2370 threadLoop_removeTracks(tracksToRemove);
2371 tracksToRemove.clear();
2372
2373 // FIXME I don't understand the need for this here;
2374 // it was in the original code but maybe the
2375 // assignment in saveOutputTracks() makes this unnecessary?
2376 clearOutputTracks();
2377
2378 // Effect chains will be actually deleted here if they were removed from
2379 // mEffectChains list during mixing or effects processing
2380 effectChains.clear();
2381
2382 // FIXME Note that the above .clear() is no longer necessary since effectChains
2383 // is now local to this block, but will keep it for now (at least until merge done).
2384 }
2385
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 threadLoop_exit();
2387
Eric Laurent81784c32012-11-19 14:55:58 -08002388 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // put output stream into standby mode
2391 if (!mStandby) {
2392 mOutput->stream->common.standby(&mOutput->stream->common);
2393 }
2394 }
2395
2396 releaseWakeLock();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002397 mWakeLockUids.clear();
2398 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002399
2400 ALOGV("Thread %p type %d exiting", this, mType);
2401 return false;
2402}
2403
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404// removeTracks_l() must be called with ThreadBase::mLock held
2405void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2406{
2407 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002408 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002409 for (size_t i=0 ; i<count ; i++) {
2410 const sp<Track>& track = tracksToRemove.itemAt(i);
2411 mActiveTracks.remove(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002412 mWakeLockUids.remove(track->uid());
2413 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2415 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2416 if (chain != 0) {
2417 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2418 track->sessionId());
2419 chain->decActiveTrackCnt();
2420 }
2421 if (track->isTerminated()) {
2422 removeTrack_l(track);
2423 }
2424 }
2425 }
2426
2427}
Eric Laurent81784c32012-11-19 14:55:58 -08002428
Eric Laurentaccc1472013-09-20 09:36:34 -07002429status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2430{
2431 if (mNormalSink != 0) {
2432 return mNormalSink->getTimestamp(timestamp);
2433 }
2434 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2435 uint64_t position64;
2436 int ret = mOutput->stream->get_presentation_position(
2437 mOutput->stream, &position64, &timestamp.mTime);
2438 if (ret == 0) {
2439 timestamp.mPosition = (uint32_t)position64;
2440 return NO_ERROR;
2441 }
2442 }
2443 return INVALID_OPERATION;
2444}
Eric Laurent81784c32012-11-19 14:55:58 -08002445// ----------------------------------------------------------------------------
2446
2447AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2448 audio_io_handle_t id, audio_devices_t device, type_t type)
2449 : PlaybackThread(audioFlinger, output, id, device, type),
2450 // mAudioMixer below
2451 // mFastMixer below
2452 mFastMixerFutex(0)
2453 // mOutputSink below
2454 // mPipeSink below
2455 // mNormalSink below
2456{
2457 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002458 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002459 "mFrameCount=%d, mNormalFrameCount=%d",
2460 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2461 mNormalFrameCount);
2462 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2463
2464 // FIXME - Current mixer implementation only supports stereo output
2465 if (mChannelCount != FCC_2) {
2466 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2467 }
2468
2469 // create an NBAIO sink for the HAL output stream, and negotiate
2470 mOutputSink = new AudioStreamOutSink(output->stream);
2471 size_t numCounterOffers = 0;
2472 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2473 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2474 ALOG_ASSERT(index == 0);
2475
2476 // initialize fast mixer depending on configuration
2477 bool initFastMixer;
2478 switch (kUseFastMixer) {
2479 case FastMixer_Never:
2480 initFastMixer = false;
2481 break;
2482 case FastMixer_Always:
2483 initFastMixer = true;
2484 break;
2485 case FastMixer_Static:
2486 case FastMixer_Dynamic:
2487 initFastMixer = mFrameCount < mNormalFrameCount;
2488 break;
2489 }
2490 if (initFastMixer) {
2491
2492 // create a MonoPipe to connect our submix to FastMixer
2493 NBAIO_Format format = mOutputSink->format();
2494 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2495 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2496 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2497 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2498 const NBAIO_Format offers[1] = {format};
2499 size_t numCounterOffers = 0;
2500 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2501 ALOG_ASSERT(index == 0);
2502 monoPipe->setAvgFrames((mScreenState & 1) ?
2503 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2504 mPipeSink = monoPipe;
2505
Glenn Kasten46909e72013-02-26 09:20:22 -08002506#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002507 if (mTeeSinkOutputEnabled) {
2508 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2509 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2510 numCounterOffers = 0;
2511 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2512 ALOG_ASSERT(index == 0);
2513 mTeeSink = teeSink;
2514 PipeReader *teeSource = new PipeReader(*teeSink);
2515 numCounterOffers = 0;
2516 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2517 ALOG_ASSERT(index == 0);
2518 mTeeSource = teeSource;
2519 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002520#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002521
2522 // create fast mixer and configure it initially with just one fast track for our submix
2523 mFastMixer = new FastMixer();
2524 FastMixerStateQueue *sq = mFastMixer->sq();
2525#ifdef STATE_QUEUE_DUMP
2526 sq->setObserverDump(&mStateQueueObserverDump);
2527 sq->setMutatorDump(&mStateQueueMutatorDump);
2528#endif
2529 FastMixerState *state = sq->begin();
2530 FastTrack *fastTrack = &state->mFastTracks[0];
2531 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2532 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2533 fastTrack->mVolumeProvider = NULL;
2534 fastTrack->mGeneration++;
2535 state->mFastTracksGen++;
2536 state->mTrackMask = 1;
2537 // fast mixer will use the HAL output sink
2538 state->mOutputSink = mOutputSink.get();
2539 state->mOutputSinkGen++;
2540 state->mFrameCount = mFrameCount;
2541 state->mCommand = FastMixerState::COLD_IDLE;
2542 // already done in constructor initialization list
2543 //mFastMixerFutex = 0;
2544 state->mColdFutexAddr = &mFastMixerFutex;
2545 state->mColdGen++;
2546 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002547#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002548 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002549#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002550 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2551 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002552 sq->end();
2553 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2554
2555 // start the fast mixer
2556 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2557 pid_t tid = mFastMixer->getTid();
2558 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2559 if (err != 0) {
2560 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2561 kPriorityFastMixer, getpid_cached, tid, err);
2562 }
2563
2564#ifdef AUDIO_WATCHDOG
2565 // create and start the watchdog
2566 mAudioWatchdog = new AudioWatchdog();
2567 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2568 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2569 tid = mAudioWatchdog->getTid();
2570 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2571 if (err != 0) {
2572 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2573 kPriorityFastMixer, getpid_cached, tid, err);
2574 }
2575#endif
2576
2577 } else {
2578 mFastMixer = NULL;
2579 }
2580
2581 switch (kUseFastMixer) {
2582 case FastMixer_Never:
2583 case FastMixer_Dynamic:
2584 mNormalSink = mOutputSink;
2585 break;
2586 case FastMixer_Always:
2587 mNormalSink = mPipeSink;
2588 break;
2589 case FastMixer_Static:
2590 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2591 break;
2592 }
2593}
2594
2595AudioFlinger::MixerThread::~MixerThread()
2596{
2597 if (mFastMixer != NULL) {
2598 FastMixerStateQueue *sq = mFastMixer->sq();
2599 FastMixerState *state = sq->begin();
2600 if (state->mCommand == FastMixerState::COLD_IDLE) {
2601 int32_t old = android_atomic_inc(&mFastMixerFutex);
2602 if (old == -1) {
2603 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2604 }
2605 }
2606 state->mCommand = FastMixerState::EXIT;
2607 sq->end();
2608 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2609 mFastMixer->join();
2610 // Though the fast mixer thread has exited, it's state queue is still valid.
2611 // We'll use that extract the final state which contains one remaining fast track
2612 // corresponding to our sub-mix.
2613 state = sq->begin();
2614 ALOG_ASSERT(state->mTrackMask == 1);
2615 FastTrack *fastTrack = &state->mFastTracks[0];
2616 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2617 delete fastTrack->mBufferProvider;
2618 sq->end(false /*didModify*/);
2619 delete mFastMixer;
2620#ifdef AUDIO_WATCHDOG
2621 if (mAudioWatchdog != 0) {
2622 mAudioWatchdog->requestExit();
2623 mAudioWatchdog->requestExitAndWait();
2624 mAudioWatchdog.clear();
2625 }
2626#endif
2627 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002628 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002629 delete mAudioMixer;
2630}
2631
2632
2633uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2634{
2635 if (mFastMixer != NULL) {
2636 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2637 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2638 }
2639 return latency;
2640}
2641
2642
2643void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2644{
2645 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2646}
2647
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002649{
2650 // FIXME we should only do one push per cycle; confirm this is true
2651 // Start the fast mixer if it's not already running
2652 if (mFastMixer != NULL) {
2653 FastMixerStateQueue *sq = mFastMixer->sq();
2654 FastMixerState *state = sq->begin();
2655 if (state->mCommand != FastMixerState::MIX_WRITE &&
2656 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2657 if (state->mCommand == FastMixerState::COLD_IDLE) {
2658 int32_t old = android_atomic_inc(&mFastMixerFutex);
2659 if (old == -1) {
2660 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2661 }
2662#ifdef AUDIO_WATCHDOG
2663 if (mAudioWatchdog != 0) {
2664 mAudioWatchdog->resume();
2665 }
2666#endif
2667 }
2668 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002669 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2670 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002671 sq->end();
2672 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2673 if (kUseFastMixer == FastMixer_Dynamic) {
2674 mNormalSink = mPipeSink;
2675 }
2676 } else {
2677 sq->end(false /*didModify*/);
2678 }
2679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002681}
2682
2683void AudioFlinger::MixerThread::threadLoop_standby()
2684{
2685 // Idle the fast mixer if it's currently running
2686 if (mFastMixer != NULL) {
2687 FastMixerStateQueue *sq = mFastMixer->sq();
2688 FastMixerState *state = sq->begin();
2689 if (!(state->mCommand & FastMixerState::IDLE)) {
2690 state->mCommand = FastMixerState::COLD_IDLE;
2691 state->mColdFutexAddr = &mFastMixerFutex;
2692 state->mColdGen++;
2693 mFastMixerFutex = 0;
2694 sq->end();
2695 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2696 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2697 if (kUseFastMixer == FastMixer_Dynamic) {
2698 mNormalSink = mOutputSink;
2699 }
2700#ifdef AUDIO_WATCHDOG
2701 if (mAudioWatchdog != 0) {
2702 mAudioWatchdog->pause();
2703 }
2704#endif
2705 } else {
2706 sq->end(false /*didModify*/);
2707 }
2708 }
2709 PlaybackThread::threadLoop_standby();
2710}
2711
Eric Laurentbfb1b832013-01-07 09:53:42 -08002712// Empty implementation for standard mixer
2713// Overridden for offloaded playback
2714void AudioFlinger::PlaybackThread::flushOutput_l()
2715{
2716}
2717
2718bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2719{
2720 return false;
2721}
2722
2723bool AudioFlinger::PlaybackThread::shouldStandby_l()
2724{
2725 return !mStandby;
2726}
2727
2728bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2729{
2730 Mutex::Autolock _l(mLock);
2731 return waitingAsyncCallback_l();
2732}
2733
Eric Laurent81784c32012-11-19 14:55:58 -08002734// shared by MIXER and DIRECT, overridden by DUPLICATING
2735void AudioFlinger::PlaybackThread::threadLoop_standby()
2736{
2737 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2738 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002740 // discard any pending drain or write ack by incrementing sequence
2741 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2742 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002743 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002744 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2745 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 }
Eric Laurent81784c32012-11-19 14:55:58 -08002747}
2748
2749void AudioFlinger::MixerThread::threadLoop_mix()
2750{
2751 // obtain the presentation timestamp of the next output buffer
2752 int64_t pts;
2753 status_t status = INVALID_OPERATION;
2754
2755 if (mNormalSink != 0) {
2756 status = mNormalSink->getNextWriteTimestamp(&pts);
2757 } else {
2758 status = mOutputSink->getNextWriteTimestamp(&pts);
2759 }
2760
2761 if (status != NO_ERROR) {
2762 pts = AudioBufferProvider::kInvalidPTS;
2763 }
2764
2765 // mix buffers...
2766 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002768 // increase sleep time progressively when application underrun condition clears.
2769 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2770 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2771 // such that we would underrun the audio HAL.
2772 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2773 sleepTimeShift--;
2774 }
2775 sleepTime = 0;
2776 standbyTime = systemTime() + standbyDelay;
2777 //TODO: delay standby when effects have a tail
2778}
2779
2780void AudioFlinger::MixerThread::threadLoop_sleepTime()
2781{
2782 // If no tracks are ready, sleep once for the duration of an output
2783 // buffer size, then write 0s to the output
2784 if (sleepTime == 0) {
2785 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2786 sleepTime = activeSleepTime >> sleepTimeShift;
2787 if (sleepTime < kMinThreadSleepTimeUs) {
2788 sleepTime = kMinThreadSleepTimeUs;
2789 }
2790 // reduce sleep time in case of consecutive application underruns to avoid
2791 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2792 // duration we would end up writing less data than needed by the audio HAL if
2793 // the condition persists.
2794 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2795 sleepTimeShift++;
2796 }
2797 } else {
2798 sleepTime = idleSleepTime;
2799 }
2800 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2801 memset (mMixBuffer, 0, mixBufferSize);
2802 sleepTime = 0;
2803 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2804 "anticipated start");
2805 }
2806 // TODO add standby time extension fct of effect tail
2807}
2808
2809// prepareTracks_l() must be called with ThreadBase::mLock held
2810AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2811 Vector< sp<Track> > *tracksToRemove)
2812{
2813
2814 mixer_state mixerStatus = MIXER_IDLE;
2815 // find out which tracks need to be processed
2816 size_t count = mActiveTracks.size();
2817 size_t mixedTracks = 0;
2818 size_t tracksWithEffect = 0;
2819 // counts only _active_ fast tracks
2820 size_t fastTracks = 0;
2821 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2822
2823 float masterVolume = mMasterVolume;
2824 bool masterMute = mMasterMute;
2825
2826 if (masterMute) {
2827 masterVolume = 0;
2828 }
2829 // Delegate master volume control to effect in output mix effect chain if needed
2830 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2831 if (chain != 0) {
2832 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2833 chain->setVolume_l(&v, &v);
2834 masterVolume = (float)((v + (1 << 23)) >> 24);
2835 chain.clear();
2836 }
2837
2838 // prepare a new state to push
2839 FastMixerStateQueue *sq = NULL;
2840 FastMixerState *state = NULL;
2841 bool didModify = false;
2842 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2843 if (mFastMixer != NULL) {
2844 sq = mFastMixer->sq();
2845 state = sq->begin();
2846 }
2847
2848 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002849 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002850 if (t == 0) {
2851 continue;
2852 }
2853
2854 // this const just means the local variable doesn't change
2855 Track* const track = t.get();
2856
2857 // process fast tracks
2858 if (track->isFastTrack()) {
2859
2860 // It's theoretically possible (though unlikely) for a fast track to be created
2861 // and then removed within the same normal mix cycle. This is not a problem, as
2862 // the track never becomes active so it's fast mixer slot is never touched.
2863 // The converse, of removing an (active) track and then creating a new track
2864 // at the identical fast mixer slot within the same normal mix cycle,
2865 // is impossible because the slot isn't marked available until the end of each cycle.
2866 int j = track->mFastIndex;
2867 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2868 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2869 FastTrack *fastTrack = &state->mFastTracks[j];
2870
2871 // Determine whether the track is currently in underrun condition,
2872 // and whether it had a recent underrun.
2873 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2874 FastTrackUnderruns underruns = ftDump->mUnderruns;
2875 uint32_t recentFull = (underruns.mBitFields.mFull -
2876 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2877 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2878 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2879 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2880 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2881 uint32_t recentUnderruns = recentPartial + recentEmpty;
2882 track->mObservedUnderruns = underruns;
2883 // don't count underruns that occur while stopping or pausing
2884 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002885 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2886 recentUnderruns > 0) {
2887 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2888 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002889 }
2890
2891 // This is similar to the state machine for normal tracks,
2892 // with a few modifications for fast tracks.
2893 bool isActive = true;
2894 switch (track->mState) {
2895 case TrackBase::STOPPING_1:
2896 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002898 track->mState = TrackBase::STOPPING_2;
2899 }
2900 break;
2901 case TrackBase::PAUSING:
2902 // ramp down is not yet implemented
2903 track->setPaused();
2904 break;
2905 case TrackBase::RESUMING:
2906 // ramp up is not yet implemented
2907 track->mState = TrackBase::ACTIVE;
2908 break;
2909 case TrackBase::ACTIVE:
2910 if (recentFull > 0 || recentPartial > 0) {
2911 // track has provided at least some frames recently: reset retry count
2912 track->mRetryCount = kMaxTrackRetries;
2913 }
2914 if (recentUnderruns == 0) {
2915 // no recent underruns: stay active
2916 break;
2917 }
2918 // there has recently been an underrun of some kind
2919 if (track->sharedBuffer() == 0) {
2920 // were any of the recent underruns "empty" (no frames available)?
2921 if (recentEmpty == 0) {
2922 // no, then ignore the partial underruns as they are allowed indefinitely
2923 break;
2924 }
2925 // there has recently been an "empty" underrun: decrement the retry counter
2926 if (--(track->mRetryCount) > 0) {
2927 break;
2928 }
2929 // indicate to client process that the track was disabled because of underrun;
2930 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002931 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002932 // remove from active list, but state remains ACTIVE [confusing but true]
2933 isActive = false;
2934 break;
2935 }
2936 // fall through
2937 case TrackBase::STOPPING_2:
2938 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002939 case TrackBase::STOPPED:
2940 case TrackBase::FLUSHED: // flush() while active
2941 // Check for presentation complete if track is inactive
2942 // We have consumed all the buffers of this track.
2943 // This would be incomplete if we auto-paused on underrun
2944 {
2945 size_t audioHALFrames =
2946 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2947 size_t framesWritten = mBytesWritten / mFrameSize;
2948 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2949 // track stays in active list until presentation is complete
2950 break;
2951 }
2952 }
2953 if (track->isStopping_2()) {
2954 track->mState = TrackBase::STOPPED;
2955 }
2956 if (track->isStopped()) {
2957 // Can't reset directly, as fast mixer is still polling this track
2958 // track->reset();
2959 // So instead mark this track as needing to be reset after push with ack
2960 resetMask |= 1 << i;
2961 }
2962 isActive = false;
2963 break;
2964 case TrackBase::IDLE:
2965 default:
2966 LOG_FATAL("unexpected track state %d", track->mState);
2967 }
2968
2969 if (isActive) {
2970 // was it previously inactive?
2971 if (!(state->mTrackMask & (1 << j))) {
2972 ExtendedAudioBufferProvider *eabp = track;
2973 VolumeProvider *vp = track;
2974 fastTrack->mBufferProvider = eabp;
2975 fastTrack->mVolumeProvider = vp;
2976 fastTrack->mSampleRate = track->mSampleRate;
2977 fastTrack->mChannelMask = track->mChannelMask;
2978 fastTrack->mGeneration++;
2979 state->mTrackMask |= 1 << j;
2980 didModify = true;
2981 // no acknowledgement required for newly active tracks
2982 }
2983 // cache the combined master volume and stream type volume for fast mixer; this
2984 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002985 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002986 ++fastTracks;
2987 } else {
2988 // was it previously active?
2989 if (state->mTrackMask & (1 << j)) {
2990 fastTrack->mBufferProvider = NULL;
2991 fastTrack->mGeneration++;
2992 state->mTrackMask &= ~(1 << j);
2993 didModify = true;
2994 // If any fast tracks were removed, we must wait for acknowledgement
2995 // because we're about to decrement the last sp<> on those tracks.
2996 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2997 } else {
2998 LOG_FATAL("fast track %d should have been active", j);
2999 }
3000 tracksToRemove->add(track);
3001 // Avoids a misleading display in dumpsys
3002 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3003 }
3004 continue;
3005 }
3006
3007 { // local variable scope to avoid goto warning
3008
3009 audio_track_cblk_t* cblk = track->cblk();
3010
3011 // The first time a track is added we wait
3012 // for all its buffers to be filled before processing it
3013 int name = track->name();
3014 // make sure that we have enough frames to mix one full buffer.
3015 // enforce this condition only once to enable draining the buffer in case the client
3016 // app does not call stop() and relies on underrun to stop:
3017 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3018 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003019 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003020 uint32_t sr = track->sampleRate();
3021 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003022 desiredFrames = mNormalFrameCount;
3023 } else {
3024 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003025 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003026 // add frames already consumed but not yet released by the resampler
3027 // because cblk->framesReady() will include these frames
3028 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3029 // the minimum track buffer size is normally twice the number of frames necessary
3030 // to fill one buffer and the resampler should not leave more than one buffer worth
3031 // of unreleased frames after each pass, but just in case...
3032 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3033 }
Eric Laurent81784c32012-11-19 14:55:58 -08003034 uint32_t minFrames = 1;
3035 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3036 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003037 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003038 }
Eric Laurent745e9a82013-12-20 17:36:01 -08003039
3040 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003041 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003042 !track->isPaused() && !track->isTerminated())
3043 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003044 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003045
3046 mixedTracks++;
3047
3048 // track->mainBuffer() != mMixBuffer means there is an effect chain
3049 // connected to the track
3050 chain.clear();
3051 if (track->mainBuffer() != mMixBuffer) {
3052 chain = getEffectChain_l(track->sessionId());
3053 // Delegate volume control to effect in track effect chain if needed
3054 if (chain != 0) {
3055 tracksWithEffect++;
3056 } else {
3057 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3058 "session %d",
3059 name, track->sessionId());
3060 }
3061 }
3062
3063
3064 int param = AudioMixer::VOLUME;
3065 if (track->mFillingUpStatus == Track::FS_FILLED) {
3066 // no ramp for the first volume setting
3067 track->mFillingUpStatus = Track::FS_ACTIVE;
3068 if (track->mState == TrackBase::RESUMING) {
3069 track->mState = TrackBase::ACTIVE;
3070 param = AudioMixer::RAMP_VOLUME;
3071 }
3072 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003073 // FIXME should not make a decision based on mServer
3074 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003075 // If the track is stopped before the first frame was mixed,
3076 // do not apply ramp
3077 param = AudioMixer::RAMP_VOLUME;
3078 }
3079
3080 // compute volume for this track
3081 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003082 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003083 vl = vr = va = 0;
3084 if (track->isPausing()) {
3085 track->setPaused();
3086 }
3087 } else {
3088
3089 // read original volumes with volume control
3090 float typeVolume = mStreamTypes[track->streamType()].volume;
3091 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003092 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003093 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003094 vl = vlr & 0xFFFF;
3095 vr = vlr >> 16;
3096 // track volumes come from shared memory, so can't be trusted and must be clamped
3097 if (vl > MAX_GAIN_INT) {
3098 ALOGV("Track left volume out of range: %04X", vl);
3099 vl = MAX_GAIN_INT;
3100 }
3101 if (vr > MAX_GAIN_INT) {
3102 ALOGV("Track right volume out of range: %04X", vr);
3103 vr = MAX_GAIN_INT;
3104 }
3105 // now apply the master volume and stream type volume
3106 vl = (uint32_t)(v * vl) << 12;
3107 vr = (uint32_t)(v * vr) << 12;
3108 // assuming master volume and stream type volume each go up to 1.0,
3109 // vl and vr are now in 8.24 format
3110
Glenn Kastene3aa6592012-12-04 12:22:46 -08003111 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003112 // send level comes from shared memory and so may be corrupt
3113 if (sendLevel > MAX_GAIN_INT) {
3114 ALOGV("Track send level out of range: %04X", sendLevel);
3115 sendLevel = MAX_GAIN_INT;
3116 }
3117 va = (uint32_t)(v * sendLevel);
3118 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119
Eric Laurent81784c32012-11-19 14:55:58 -08003120 // Delegate volume control to effect in track effect chain if needed
3121 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3122 // Do not ramp volume if volume is controlled by effect
3123 param = AudioMixer::VOLUME;
3124 track->mHasVolumeController = true;
3125 } else {
3126 // force no volume ramp when volume controller was just disabled or removed
3127 // from effect chain to avoid volume spike
3128 if (track->mHasVolumeController) {
3129 param = AudioMixer::VOLUME;
3130 }
3131 track->mHasVolumeController = false;
3132 }
3133
3134 // Convert volumes from 8.24 to 4.12 format
3135 // This additional clamping is needed in case chain->setVolume_l() overshot
3136 vl = (vl + (1 << 11)) >> 12;
3137 if (vl > MAX_GAIN_INT) {
3138 vl = MAX_GAIN_INT;
3139 }
3140 vr = (vr + (1 << 11)) >> 12;
3141 if (vr > MAX_GAIN_INT) {
3142 vr = MAX_GAIN_INT;
3143 }
3144
3145 if (va > MAX_GAIN_INT) {
3146 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3147 }
3148
3149 // XXX: these things DON'T need to be done each time
3150 mAudioMixer->setBufferProvider(name, track);
3151 mAudioMixer->enable(name);
3152
3153 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3154 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3155 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3156 mAudioMixer->setParameter(
3157 name,
3158 AudioMixer::TRACK,
3159 AudioMixer::FORMAT, (void *)track->format());
3160 mAudioMixer->setParameter(
3161 name,
3162 AudioMixer::TRACK,
3163 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003164 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3165 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003166 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003167 if (reqSampleRate == 0) {
3168 reqSampleRate = mSampleRate;
3169 } else if (reqSampleRate > maxSampleRate) {
3170 reqSampleRate = maxSampleRate;
3171 }
Eric Laurent81784c32012-11-19 14:55:58 -08003172 mAudioMixer->setParameter(
3173 name,
3174 AudioMixer::RESAMPLE,
3175 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003176 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003177 mAudioMixer->setParameter(
3178 name,
3179 AudioMixer::TRACK,
3180 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3181 mAudioMixer->setParameter(
3182 name,
3183 AudioMixer::TRACK,
3184 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3185
3186 // reset retry count
3187 track->mRetryCount = kMaxTrackRetries;
3188
3189 // If one track is ready, set the mixer ready if:
3190 // - the mixer was not ready during previous round OR
3191 // - no other track is not ready
3192 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3193 mixerStatus != MIXER_TRACKS_ENABLED) {
3194 mixerStatus = MIXER_TRACKS_READY;
3195 }
3196 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003197 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003198 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003199 }
Eric Laurent81784c32012-11-19 14:55:58 -08003200 // clear effect chain input buffer if an active track underruns to avoid sending
3201 // previous audio buffer again to effects
3202 chain = getEffectChain_l(track->sessionId());
3203 if (chain != 0) {
3204 chain->clearInputBuffer();
3205 }
3206
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003207 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003208 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3209 track->isStopped() || track->isPaused()) {
3210 // We have consumed all the buffers of this track.
3211 // Remove it from the list of active tracks.
3212 // TODO: use actual buffer filling status instead of latency when available from
3213 // audio HAL
3214 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3215 size_t framesWritten = mBytesWritten / mFrameSize;
3216 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3217 if (track->isStopped()) {
3218 track->reset();
3219 }
3220 tracksToRemove->add(track);
3221 }
3222 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003223 // No buffers for this track. Give it a few chances to
3224 // fill a buffer, then remove it from active list.
3225 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003226 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003227 tracksToRemove->add(track);
3228 // indicate to client process that the track was disabled because of underrun;
3229 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003230 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003231 // If one track is not ready, mark the mixer also not ready if:
3232 // - the mixer was ready during previous round OR
3233 // - no other track is ready
3234 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3235 mixerStatus != MIXER_TRACKS_READY) {
3236 mixerStatus = MIXER_TRACKS_ENABLED;
3237 }
3238 }
3239 mAudioMixer->disable(name);
3240 }
3241
3242 } // local variable scope to avoid goto warning
3243track_is_ready: ;
3244
3245 }
3246
3247 // Push the new FastMixer state if necessary
3248 bool pauseAudioWatchdog = false;
3249 if (didModify) {
3250 state->mFastTracksGen++;
3251 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3252 if (kUseFastMixer == FastMixer_Dynamic &&
3253 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3254 state->mCommand = FastMixerState::COLD_IDLE;
3255 state->mColdFutexAddr = &mFastMixerFutex;
3256 state->mColdGen++;
3257 mFastMixerFutex = 0;
3258 if (kUseFastMixer == FastMixer_Dynamic) {
3259 mNormalSink = mOutputSink;
3260 }
3261 // If we go into cold idle, need to wait for acknowledgement
3262 // so that fast mixer stops doing I/O.
3263 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3264 pauseAudioWatchdog = true;
3265 }
Eric Laurent81784c32012-11-19 14:55:58 -08003266 }
3267 if (sq != NULL) {
3268 sq->end(didModify);
3269 sq->push(block);
3270 }
3271#ifdef AUDIO_WATCHDOG
3272 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3273 mAudioWatchdog->pause();
3274 }
3275#endif
3276
3277 // Now perform the deferred reset on fast tracks that have stopped
3278 while (resetMask != 0) {
3279 size_t i = __builtin_ctz(resetMask);
3280 ALOG_ASSERT(i < count);
3281 resetMask &= ~(1 << i);
3282 sp<Track> t = mActiveTracks[i].promote();
3283 if (t == 0) {
3284 continue;
3285 }
3286 Track* track = t.get();
3287 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3288 track->reset();
3289 }
3290
3291 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003292 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003293
3294 // mix buffer must be cleared if all tracks are connected to an
3295 // effect chain as in this case the mixer will not write to
3296 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3298 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003299 // FIXME as a performance optimization, should remember previous zero status
3300 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3301 }
3302
3303 // if any fast tracks, then status is ready
3304 mMixerStatusIgnoringFastTracks = mixerStatus;
3305 if (fastTracks > 0) {
3306 mixerStatus = MIXER_TRACKS_READY;
3307 }
3308 return mixerStatus;
3309}
3310
3311// getTrackName_l() must be called with ThreadBase::mLock held
3312int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3313{
3314 return mAudioMixer->getTrackName(channelMask, sessionId);
3315}
3316
3317// deleteTrackName_l() must be called with ThreadBase::mLock held
3318void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3319{
3320 ALOGV("remove track (%d) and delete from mixer", name);
3321 mAudioMixer->deleteTrackName(name);
3322}
3323
3324// checkForNewParameters_l() must be called with ThreadBase::mLock held
3325bool AudioFlinger::MixerThread::checkForNewParameters_l()
3326{
3327 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3328 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3329 bool reconfig = false;
3330
3331 while (!mNewParameters.isEmpty()) {
3332
3333 if (mFastMixer != NULL) {
3334 FastMixerStateQueue *sq = mFastMixer->sq();
3335 FastMixerState *state = sq->begin();
3336 if (!(state->mCommand & FastMixerState::IDLE)) {
3337 previousCommand = state->mCommand;
3338 state->mCommand = FastMixerState::HOT_IDLE;
3339 sq->end();
3340 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3341 } else {
3342 sq->end(false /*didModify*/);
3343 }
3344 }
3345
3346 status_t status = NO_ERROR;
3347 String8 keyValuePair = mNewParameters[0];
3348 AudioParameter param = AudioParameter(keyValuePair);
3349 int value;
3350
3351 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3352 reconfig = true;
3353 }
3354 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3355 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3356 status = BAD_VALUE;
3357 } else {
3358 reconfig = true;
3359 }
3360 }
3361 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003362 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003363 status = BAD_VALUE;
3364 } else {
3365 reconfig = true;
3366 }
3367 }
3368 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3369 // do not accept frame count changes if tracks are open as the track buffer
3370 // size depends on frame count and correct behavior would not be guaranteed
3371 // if frame count is changed after track creation
3372 if (!mTracks.isEmpty()) {
3373 status = INVALID_OPERATION;
3374 } else {
3375 reconfig = true;
3376 }
3377 }
3378 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3379#ifdef ADD_BATTERY_DATA
3380 // when changing the audio output device, call addBatteryData to notify
3381 // the change
3382 if (mOutDevice != value) {
3383 uint32_t params = 0;
3384 // check whether speaker is on
3385 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3386 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3387 }
3388
3389 audio_devices_t deviceWithoutSpeaker
3390 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3391 // check if any other device (except speaker) is on
3392 if (value & deviceWithoutSpeaker ) {
3393 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3394 }
3395
3396 if (params != 0) {
3397 addBatteryData(params);
3398 }
3399 }
3400#endif
3401
3402 // forward device change to effects that have requested to be
3403 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003404 if (value != AUDIO_DEVICE_NONE) {
3405 mOutDevice = value;
3406 for (size_t i = 0; i < mEffectChains.size(); i++) {
3407 mEffectChains[i]->setDevice_l(mOutDevice);
3408 }
Eric Laurent81784c32012-11-19 14:55:58 -08003409 }
3410 }
3411
3412 if (status == NO_ERROR) {
3413 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3414 keyValuePair.string());
3415 if (!mStandby && status == INVALID_OPERATION) {
3416 mOutput->stream->common.standby(&mOutput->stream->common);
3417 mStandby = true;
3418 mBytesWritten = 0;
3419 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3420 keyValuePair.string());
3421 }
3422 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003423 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003424 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003425 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3426 for (size_t i = 0; i < mTracks.size() ; i++) {
3427 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3428 if (name < 0) {
3429 break;
3430 }
3431 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003432 }
3433 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3434 }
3435 }
3436
3437 mNewParameters.removeAt(0);
3438
3439 mParamStatus = status;
3440 mParamCond.signal();
3441 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3442 // already timed out waiting for the status and will never signal the condition.
3443 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3444 }
3445
3446 if (!(previousCommand & FastMixerState::IDLE)) {
3447 ALOG_ASSERT(mFastMixer != NULL);
3448 FastMixerStateQueue *sq = mFastMixer->sq();
3449 FastMixerState *state = sq->begin();
3450 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3451 state->mCommand = previousCommand;
3452 sq->end();
3453 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3454 }
3455
3456 return reconfig;
3457}
3458
3459
3460void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3461{
3462 const size_t SIZE = 256;
3463 char buffer[SIZE];
3464 String8 result;
3465
3466 PlaybackThread::dumpInternals(fd, args);
3467
3468 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3469 result.append(buffer);
3470 write(fd, result.string(), result.size());
3471
3472 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003473 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003474 copy.dump(fd);
3475
3476#ifdef STATE_QUEUE_DUMP
3477 // Similar for state queue
3478 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3479 observerCopy.dump(fd);
3480 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3481 mutatorCopy.dump(fd);
3482#endif
3483
Glenn Kasten46909e72013-02-26 09:20:22 -08003484#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003485 // Write the tee output to a .wav file
3486 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003487#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003488
3489#ifdef AUDIO_WATCHDOG
3490 if (mAudioWatchdog != 0) {
3491 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3492 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3493 wdCopy.dump(fd);
3494 }
3495#endif
3496}
3497
3498uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3499{
3500 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3501}
3502
3503uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3504{
3505 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3506}
3507
3508void AudioFlinger::MixerThread::cacheParameters_l()
3509{
3510 PlaybackThread::cacheParameters_l();
3511
3512 // FIXME: Relaxed timing because of a certain device that can't meet latency
3513 // Should be reduced to 2x after the vendor fixes the driver issue
3514 // increase threshold again due to low power audio mode. The way this warning
3515 // threshold is calculated and its usefulness should be reconsidered anyway.
3516 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3517}
3518
3519// ----------------------------------------------------------------------------
3520
3521AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3522 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3523 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3524 // mLeftVolFloat, mRightVolFloat
3525{
3526}
3527
Eric Laurentbfb1b832013-01-07 09:53:42 -08003528AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3529 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3530 ThreadBase::type_t type)
3531 : PlaybackThread(audioFlinger, output, id, device, type)
3532 // mLeftVolFloat, mRightVolFloat
3533{
3534}
3535
Eric Laurent81784c32012-11-19 14:55:58 -08003536AudioFlinger::DirectOutputThread::~DirectOutputThread()
3537{
3538}
3539
Eric Laurentbfb1b832013-01-07 09:53:42 -08003540void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3541{
3542 audio_track_cblk_t* cblk = track->cblk();
3543 float left, right;
3544
3545 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3546 left = right = 0;
3547 } else {
3548 float typeVolume = mStreamTypes[track->streamType()].volume;
3549 float v = mMasterVolume * typeVolume;
3550 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3551 uint32_t vlr = proxy->getVolumeLR();
3552 float v_clamped = v * (vlr & 0xFFFF);
3553 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3554 left = v_clamped/MAX_GAIN;
3555 v_clamped = v * (vlr >> 16);
3556 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3557 right = v_clamped/MAX_GAIN;
3558 }
3559
3560 if (lastTrack) {
3561 if (left != mLeftVolFloat || right != mRightVolFloat) {
3562 mLeftVolFloat = left;
3563 mRightVolFloat = right;
3564
3565 // Convert volumes from float to 8.24
3566 uint32_t vl = (uint32_t)(left * (1 << 24));
3567 uint32_t vr = (uint32_t)(right * (1 << 24));
3568
3569 // Delegate volume control to effect in track effect chain if needed
3570 // only one effect chain can be present on DirectOutputThread, so if
3571 // there is one, the track is connected to it
3572 if (!mEffectChains.isEmpty()) {
3573 mEffectChains[0]->setVolume_l(&vl, &vr);
3574 left = (float)vl / (1 << 24);
3575 right = (float)vr / (1 << 24);
3576 }
3577 if (mOutput->stream->set_volume) {
3578 mOutput->stream->set_volume(mOutput->stream, left, right);
3579 }
3580 }
3581 }
3582}
3583
3584
Eric Laurent81784c32012-11-19 14:55:58 -08003585AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3586 Vector< sp<Track> > *tracksToRemove
3587)
3588{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003589 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003590 mixer_state mixerStatus = MIXER_IDLE;
3591
3592 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003593 for (size_t i = 0; i < count; i++) {
3594 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003595 // The track died recently
3596 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003597 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003598 }
3599
3600 Track* const track = t.get();
3601 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003602 // Only consider last track started for volume and mixer state control.
3603 // In theory an older track could underrun and restart after the new one starts
3604 // but as we only care about the transition phase between two tracks on a
3605 // direct output, it is not a problem to ignore the underrun case.
3606 sp<Track> l = mLatestActiveTrack.promote();
3607 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003608
3609 // The first time a track is added we wait
3610 // for all its buffers to be filled before processing it
3611 uint32_t minFrames;
3612 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3613 minFrames = mNormalFrameCount;
3614 } else {
3615 minFrames = 1;
3616 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617
Eric Laurent81784c32012-11-19 14:55:58 -08003618 if ((track->framesReady() >= minFrames) && track->isReady() &&
3619 !track->isPaused() && !track->isTerminated())
3620 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003621 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003622
3623 if (track->mFillingUpStatus == Track::FS_FILLED) {
3624 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003625 // make sure processVolume_l() will apply new volume even if 0
3626 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003627 if (track->mState == TrackBase::RESUMING) {
3628 track->mState = TrackBase::ACTIVE;
3629 }
3630 }
3631
3632 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633 processVolume_l(track, last);
3634 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003635 // reset retry count
3636 track->mRetryCount = kMaxTrackRetriesDirect;
3637 mActiveTrack = t;
3638 mixerStatus = MIXER_TRACKS_READY;
3639 }
Eric Laurent81784c32012-11-19 14:55:58 -08003640 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003641 // clear effect chain input buffer if the last active track started underruns
3642 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003643 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003644 mEffectChains[0]->clearInputBuffer();
3645 }
3646
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003647 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003648 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3649 track->isStopped() || track->isPaused()) {
3650 // We have consumed all the buffers of this track.
3651 // Remove it from the list of active tracks.
3652 // TODO: implement behavior for compressed audio
3653 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3654 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003655 if (mStandby || !last ||
3656 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003657 if (track->isStopped()) {
3658 track->reset();
3659 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003660 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003661 }
3662 } else {
3663 // No buffers for this track. Give it a few chances to
3664 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003665 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003666 if (--(track->mRetryCount) <= 0) {
3667 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003668 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003669 // indicate to client process that the track was disabled because of underrun;
3670 // it will then automatically call start() when data is available
3671 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003673 mixerStatus = MIXER_TRACKS_ENABLED;
3674 }
3675 }
3676 }
3677 }
3678
Eric Laurent81784c32012-11-19 14:55:58 -08003679 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003681
3682 return mixerStatus;
3683}
3684
3685void AudioFlinger::DirectOutputThread::threadLoop_mix()
3686{
Eric Laurent81784c32012-11-19 14:55:58 -08003687 size_t frameCount = mFrameCount;
3688 int8_t *curBuf = (int8_t *)mMixBuffer;
3689 // output audio to hardware
3690 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003691 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003692 buffer.frameCount = frameCount;
3693 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003694 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003695 memset(curBuf, 0, frameCount * mFrameSize);
3696 break;
3697 }
3698 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3699 frameCount -= buffer.frameCount;
3700 curBuf += buffer.frameCount * mFrameSize;
3701 mActiveTrack->releaseBuffer(&buffer);
3702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003703 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003704 sleepTime = 0;
3705 standbyTime = systemTime() + standbyDelay;
3706 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003707}
3708
3709void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3710{
3711 if (sleepTime == 0) {
3712 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3713 sleepTime = activeSleepTime;
3714 } else {
3715 sleepTime = idleSleepTime;
3716 }
3717 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3718 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3719 sleepTime = 0;
3720 }
3721}
3722
3723// getTrackName_l() must be called with ThreadBase::mLock held
3724int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3725 int sessionId)
3726{
3727 return 0;
3728}
3729
3730// deleteTrackName_l() must be called with ThreadBase::mLock held
3731void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3732{
3733}
3734
3735// checkForNewParameters_l() must be called with ThreadBase::mLock held
3736bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3737{
3738 bool reconfig = false;
3739
3740 while (!mNewParameters.isEmpty()) {
3741 status_t status = NO_ERROR;
3742 String8 keyValuePair = mNewParameters[0];
3743 AudioParameter param = AudioParameter(keyValuePair);
3744 int value;
3745
3746 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3747 // do not accept frame count changes if tracks are open as the track buffer
3748 // size depends on frame count and correct behavior would not be garantied
3749 // if frame count is changed after track creation
3750 if (!mTracks.isEmpty()) {
3751 status = INVALID_OPERATION;
3752 } else {
3753 reconfig = true;
3754 }
3755 }
3756 if (status == NO_ERROR) {
3757 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3758 keyValuePair.string());
3759 if (!mStandby && status == INVALID_OPERATION) {
3760 mOutput->stream->common.standby(&mOutput->stream->common);
3761 mStandby = true;
3762 mBytesWritten = 0;
3763 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3764 keyValuePair.string());
3765 }
3766 if (status == NO_ERROR && reconfig) {
3767 readOutputParameters();
3768 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3769 }
3770 }
3771
3772 mNewParameters.removeAt(0);
3773
3774 mParamStatus = status;
3775 mParamCond.signal();
3776 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3777 // already timed out waiting for the status and will never signal the condition.
3778 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3779 }
3780 return reconfig;
3781}
3782
3783uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3784{
3785 uint32_t time;
3786 if (audio_is_linear_pcm(mFormat)) {
3787 time = PlaybackThread::activeSleepTimeUs();
3788 } else {
3789 time = 10000;
3790 }
3791 return time;
3792}
3793
3794uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3795{
3796 uint32_t time;
3797 if (audio_is_linear_pcm(mFormat)) {
3798 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3799 } else {
3800 time = 10000;
3801 }
3802 return time;
3803}
3804
3805uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3806{
3807 uint32_t time;
3808 if (audio_is_linear_pcm(mFormat)) {
3809 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3810 } else {
3811 time = 10000;
3812 }
3813 return time;
3814}
3815
3816void AudioFlinger::DirectOutputThread::cacheParameters_l()
3817{
3818 PlaybackThread::cacheParameters_l();
3819
3820 // use shorter standby delay as on normal output to release
3821 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003822 if (audio_is_linear_pcm(mFormat)) {
3823 standbyDelay = microseconds(activeSleepTime*2);
3824 } else {
3825 standbyDelay = kOffloadStandbyDelayNs;
3826 }
Eric Laurent81784c32012-11-19 14:55:58 -08003827}
3828
3829// ----------------------------------------------------------------------------
3830
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003832 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003833 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003834 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003835 mWriteAckSequence(0),
3836 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003837{
3838}
3839
3840AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3841{
3842}
3843
3844void AudioFlinger::AsyncCallbackThread::onFirstRef()
3845{
3846 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3847}
3848
3849bool AudioFlinger::AsyncCallbackThread::threadLoop()
3850{
3851 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003852 uint32_t writeAckSequence;
3853 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003854
3855 {
3856 Mutex::Autolock _l(mLock);
Haynes Mathew Georgec9561632013-12-03 21:26:02 -08003857 while (!((mWriteAckSequence & 1) ||
3858 (mDrainSequence & 1) ||
3859 exitPending())) {
3860 mWaitWorkCV.wait(mLock);
3861 }
3862
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863 if (exitPending()) {
3864 break;
3865 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003866 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3867 mWriteAckSequence, mDrainSequence);
3868 writeAckSequence = mWriteAckSequence;
3869 mWriteAckSequence &= ~1;
3870 drainSequence = mDrainSequence;
3871 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 }
3873 {
Eric Laurent4de95592013-09-26 15:28:21 -07003874 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3875 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003876 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003877 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003879 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003880 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003881 }
3882 }
3883 }
3884 }
3885 return false;
3886}
3887
3888void AudioFlinger::AsyncCallbackThread::exit()
3889{
3890 ALOGV("AsyncCallbackThread::exit");
3891 Mutex::Autolock _l(mLock);
3892 requestExit();
3893 mWaitWorkCV.broadcast();
3894}
3895
Eric Laurent3b4529e2013-09-05 18:09:19 -07003896void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897{
3898 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003899 // bit 0 is cleared
3900 mWriteAckSequence = sequence << 1;
3901}
3902
3903void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3904{
3905 Mutex::Autolock _l(mLock);
3906 // ignore unexpected callbacks
3907 if (mWriteAckSequence & 2) {
3908 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 mWaitWorkCV.signal();
3910 }
3911}
3912
Eric Laurent3b4529e2013-09-05 18:09:19 -07003913void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003914{
3915 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003916 // bit 0 is cleared
3917 mDrainSequence = sequence << 1;
3918}
3919
3920void AudioFlinger::AsyncCallbackThread::resetDraining()
3921{
3922 Mutex::Autolock _l(mLock);
3923 // ignore unexpected callbacks
3924 if (mDrainSequence & 2) {
3925 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 mWaitWorkCV.signal();
3927 }
3928}
3929
3930
3931// ----------------------------------------------------------------------------
3932AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3933 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3934 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3935 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003936 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003937 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003938{
Eric Laurentfd477972013-10-25 18:10:40 -07003939 //FIXME: mStandby should be set to true by ThreadBase constructor
3940 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941}
3942
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943void AudioFlinger::OffloadThread::threadLoop_exit()
3944{
3945 if (mFlushPending || mHwPaused) {
3946 // If a flush is pending or track was paused, just discard buffered data
3947 flushHw_l();
3948 } else {
3949 mMixerStatus = MIXER_DRAIN_ALL;
3950 threadLoop_drain();
3951 }
3952 mCallbackThread->exit();
3953 PlaybackThread::threadLoop_exit();
3954}
3955
3956AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3957 Vector< sp<Track> > *tracksToRemove
3958)
3959{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960 size_t count = mActiveTracks.size();
3961
3962 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003963 bool doHwPause = false;
3964 bool doHwResume = false;
3965
Eric Laurentede6c3b2013-09-19 14:37:46 -07003966 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3967
Eric Laurentbfb1b832013-01-07 09:53:42 -08003968 // find out which tracks need to be processed
3969 for (size_t i = 0; i < count; i++) {
3970 sp<Track> t = mActiveTracks[i].promote();
3971 // The track died recently
3972 if (t == 0) {
3973 continue;
3974 }
3975 Track* const track = t.get();
3976 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003977 // Only consider last track started for volume and mixer state control.
3978 // In theory an older track could underrun and restart after the new one starts
3979 // but as we only care about the transition phase between two tracks on a
3980 // direct output, it is not a problem to ignore the underrun case.
3981 sp<Track> l = mLatestActiveTrack.promote();
3982 bool last = l.get() == track;
3983
Eric Laurentbfb1b832013-01-07 09:53:42 -08003984 if (track->isPausing()) {
3985 track->setPaused();
3986 if (last) {
3987 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003988 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003989 mHwPaused = true;
3990 }
3991 // If we were part way through writing the mixbuffer to
3992 // the HAL we must save this until we resume
3993 // BUG - this will be wrong if a different track is made active,
3994 // in that case we want to discard the pending data in the
3995 // mixbuffer and tell the client to present it again when the
3996 // track is resumed
3997 mPausedWriteLength = mCurrentWriteLength;
3998 mPausedBytesRemaining = mBytesRemaining;
3999 mBytesRemaining = 0; // stop writing
4000 }
4001 tracksToRemove->add(track);
4002 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004003 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004004 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 if (track->mFillingUpStatus == Track::FS_FILLED) {
4006 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004007 // make sure processVolume_l() will apply new volume even if 0
4008 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004009 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004011 if (last) {
4012 if (mPausedBytesRemaining) {
4013 // Need to continue write that was interrupted
4014 mCurrentWriteLength = mPausedWriteLength;
4015 mBytesRemaining = mPausedBytesRemaining;
4016 mPausedBytesRemaining = 0;
4017 }
4018 if (mHwPaused) {
4019 doHwResume = true;
4020 mHwPaused = false;
4021 // threadLoop_mix() will handle the case that we need to
4022 // resume an interrupted write
4023 }
4024 // enable write to audio HAL
4025 sleepTime = 0;
4026 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 }
4028 }
4029
4030 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004031 sp<Track> previousTrack = mPreviousTrack.promote();
4032 if (previousTrack != 0) {
4033 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004034 // Flush any data still being written from last track
4035 mBytesRemaining = 0;
4036 if (mPausedBytesRemaining) {
4037 // Last track was paused so we also need to flush saved
4038 // mixbuffer state and invalidate track so that it will
4039 // re-submit that unwritten data when it is next resumed
4040 mPausedBytesRemaining = 0;
4041 // Invalidate is a bit drastic - would be more efficient
4042 // to have a flag to tell client that some of the
4043 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004044 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004045 }
4046 // flush data already sent to the DSP if changing audio session as audio
4047 // comes from a different source. Also invalidate previous track to force a
4048 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004049 if (previousTrack->sessionId() != track->sessionId()) {
4050 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004051 mFlushPending = true;
4052 }
4053 }
4054 }
4055 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 // reset retry count
4057 track->mRetryCount = kMaxTrackRetriesOffload;
4058 mActiveTrack = t;
4059 mixerStatus = MIXER_TRACKS_READY;
4060 }
4061 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004062 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004063 if (track->isStopping_1()) {
4064 // Hardware buffer can hold a large amount of audio so we must
4065 // wait for all current track's data to drain before we say
4066 // that the track is stopped.
4067 if (mBytesRemaining == 0) {
4068 // Only start draining when all data in mixbuffer
4069 // has been written
4070 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4071 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004072 // do not drain if no data was ever sent to HAL (mStandby == true)
4073 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004074 // do not modify drain sequence if we are already draining. This happens
4075 // when resuming from pause after drain.
4076 if ((mDrainSequence & 1) == 0) {
4077 sleepTime = 0;
4078 standbyTime = systemTime() + standbyDelay;
4079 mixerStatus = MIXER_DRAIN_TRACK;
4080 mDrainSequence += 2;
4081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 if (mHwPaused) {
4083 // It is possible to move from PAUSED to STOPPING_1 without
4084 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004085 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086 mHwPaused = false;
4087 }
4088 }
4089 }
4090 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004091 // Drain has completed or we are in standby, signal presentation complete
4092 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 track->mState = TrackBase::STOPPED;
4094 size_t audioHALFrames =
4095 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4096 size_t framesWritten =
4097 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4098 track->presentationComplete(framesWritten, audioHALFrames);
4099 track->reset();
4100 tracksToRemove->add(track);
4101 }
4102 } else {
4103 // No buffers for this track. Give it a few chances to
4104 // fill a buffer, then remove it from active list.
4105 if (--(track->mRetryCount) <= 0) {
4106 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4107 track->name());
4108 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004109 // indicate to client process that the track was disabled because of underrun;
4110 // it will then automatically call start() when data is available
4111 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004112 } else if (last){
4113 mixerStatus = MIXER_TRACKS_ENABLED;
4114 }
4115 }
4116 }
4117 // compute volume for this track
4118 processVolume_l(track, last);
4119 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004120
Eric Laurentea0fade2013-10-04 16:23:48 -07004121 // make sure the pause/flush/resume sequence is executed in the right order.
4122 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4123 // before flush and then resume HW. This can happen in case of pause/flush/resume
4124 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004125 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004126 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004127 if (!doHwPause) {
4128 doHwResume = true;
4129 }
Eric Laurent972a1732013-09-04 09:42:59 -07004130 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004131 if (mFlushPending) {
4132 flushHw_l();
4133 mFlushPending = false;
4134 }
Eric Laurentfd477972013-10-25 18:10:40 -07004135 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004136 mOutput->stream->resume(mOutput->stream);
4137 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004138
Eric Laurentbfb1b832013-01-07 09:53:42 -08004139 // remove all the tracks that need to be...
4140 removeTracks_l(*tracksToRemove);
4141
4142 return mixerStatus;
4143}
4144
4145void AudioFlinger::OffloadThread::flushOutput_l()
4146{
4147 mFlushPending = true;
4148}
4149
4150// must be called with thread mutex locked
4151bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4152{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004153 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4154 mWriteAckSequence, mDrainSequence);
4155 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 return true;
4157 }
4158 return false;
4159}
4160
4161// must be called with thread mutex locked
4162bool AudioFlinger::OffloadThread::shouldStandby_l()
4163{
4164 bool TrackPaused = false;
4165
4166 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4167 // after a timeout and we will enter standby then.
4168 if (mTracks.size() > 0) {
4169 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4170 }
4171
4172 return !mStandby && !TrackPaused;
4173}
4174
4175
4176bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4177{
4178 Mutex::Autolock _l(mLock);
4179 return waitingAsyncCallback_l();
4180}
4181
4182void AudioFlinger::OffloadThread::flushHw_l()
4183{
4184 mOutput->stream->flush(mOutput->stream);
4185 // Flush anything still waiting in the mixbuffer
4186 mCurrentWriteLength = 0;
4187 mBytesRemaining = 0;
4188 mPausedWriteLength = 0;
4189 mPausedBytesRemaining = 0;
4190 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004191 // discard any pending drain or write ack by incrementing sequence
4192 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4193 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004194 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004195 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4196 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 }
4198}
4199
4200// ----------------------------------------------------------------------------
4201
Eric Laurent81784c32012-11-19 14:55:58 -08004202AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4203 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4204 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4205 DUPLICATING),
4206 mWaitTimeMs(UINT_MAX)
4207{
4208 addOutputTrack(mainThread);
4209}
4210
4211AudioFlinger::DuplicatingThread::~DuplicatingThread()
4212{
4213 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4214 mOutputTracks[i]->destroy();
4215 }
4216}
4217
4218void AudioFlinger::DuplicatingThread::threadLoop_mix()
4219{
4220 // mix buffers...
4221 if (outputsReady(outputTracks)) {
4222 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4223 } else {
4224 memset(mMixBuffer, 0, mixBufferSize);
4225 }
4226 sleepTime = 0;
4227 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004228 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004229 standbyTime = systemTime() + standbyDelay;
4230}
4231
4232void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4233{
4234 if (sleepTime == 0) {
4235 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4236 sleepTime = activeSleepTime;
4237 } else {
4238 sleepTime = idleSleepTime;
4239 }
4240 } else if (mBytesWritten != 0) {
4241 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4242 writeFrames = mNormalFrameCount;
4243 memset(mMixBuffer, 0, mixBufferSize);
4244 } else {
4245 // flush remaining overflow buffers in output tracks
4246 writeFrames = 0;
4247 }
4248 sleepTime = 0;
4249 }
4250}
4251
Eric Laurentbfb1b832013-01-07 09:53:42 -08004252ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004253{
4254 for (size_t i = 0; i < outputTracks.size(); i++) {
4255 outputTracks[i]->write(mMixBuffer, writeFrames);
4256 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004257 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004259}
4260
4261void AudioFlinger::DuplicatingThread::threadLoop_standby()
4262{
4263 // DuplicatingThread implements standby by stopping all tracks
4264 for (size_t i = 0; i < outputTracks.size(); i++) {
4265 outputTracks[i]->stop();
4266 }
4267}
4268
4269void AudioFlinger::DuplicatingThread::saveOutputTracks()
4270{
4271 outputTracks = mOutputTracks;
4272}
4273
4274void AudioFlinger::DuplicatingThread::clearOutputTracks()
4275{
4276 outputTracks.clear();
4277}
4278
4279void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4280{
4281 Mutex::Autolock _l(mLock);
4282 // FIXME explain this formula
4283 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4284 OutputTrack *outputTrack = new OutputTrack(thread,
4285 this,
4286 mSampleRate,
4287 mFormat,
4288 mChannelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004289 frameCount,
4290 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004291 if (outputTrack->cblk() != NULL) {
4292 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4293 mOutputTracks.add(outputTrack);
4294 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4295 updateWaitTime_l();
4296 }
4297}
4298
4299void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4300{
4301 Mutex::Autolock _l(mLock);
4302 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4303 if (mOutputTracks[i]->thread() == thread) {
4304 mOutputTracks[i]->destroy();
4305 mOutputTracks.removeAt(i);
4306 updateWaitTime_l();
4307 return;
4308 }
4309 }
4310 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4311}
4312
4313// caller must hold mLock
4314void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4315{
4316 mWaitTimeMs = UINT_MAX;
4317 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4318 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4319 if (strong != 0) {
4320 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4321 if (waitTimeMs < mWaitTimeMs) {
4322 mWaitTimeMs = waitTimeMs;
4323 }
4324 }
4325 }
4326}
4327
4328
4329bool AudioFlinger::DuplicatingThread::outputsReady(
4330 const SortedVector< sp<OutputTrack> > &outputTracks)
4331{
4332 for (size_t i = 0; i < outputTracks.size(); i++) {
4333 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4334 if (thread == 0) {
4335 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4336 outputTracks[i].get());
4337 return false;
4338 }
4339 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4340 // see note at standby() declaration
4341 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4342 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4343 thread.get());
4344 return false;
4345 }
4346 }
4347 return true;
4348}
4349
4350uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4351{
4352 return (mWaitTimeMs * 1000) / 2;
4353}
4354
4355void AudioFlinger::DuplicatingThread::cacheParameters_l()
4356{
4357 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4358 updateWaitTime_l();
4359
4360 MixerThread::cacheParameters_l();
4361}
4362
4363// ----------------------------------------------------------------------------
4364// Record
4365// ----------------------------------------------------------------------------
4366
4367AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4368 AudioStreamIn *input,
4369 uint32_t sampleRate,
4370 audio_channel_mask_t channelMask,
4371 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004372 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004373 audio_devices_t inDevice
4374#ifdef TEE_SINK
4375 , const sp<NBAIO_Sink>& teeSink
4376#endif
4377 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004378 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004379 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004380 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004381 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004382 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004383 // mBytesRead is only meaningful while active, and so is cleared in start()
4384 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004385#ifdef TEE_SINK
4386 , mTeeSink(teeSink)
4387#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004388{
4389 snprintf(mName, kNameLength, "AudioIn_%X", id);
4390
4391 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004392}
4393
4394
4395AudioFlinger::RecordThread::~RecordThread()
4396{
4397 delete[] mRsmpInBuffer;
4398 delete mResampler;
4399 delete[] mRsmpOutBuffer;
4400}
4401
4402void AudioFlinger::RecordThread::onFirstRef()
4403{
4404 run(mName, PRIORITY_URGENT_AUDIO);
4405}
4406
4407status_t AudioFlinger::RecordThread::readyToRun()
4408{
4409 status_t status = initCheck();
4410 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4411 return status;
4412}
4413
4414bool AudioFlinger::RecordThread::threadLoop()
4415{
4416 AudioBufferProvider::Buffer buffer;
4417 sp<RecordTrack> activeTrack;
4418 Vector< sp<EffectChain> > effectChains;
4419
4420 nsecs_t lastWarning = 0;
4421
4422 inputStandBy();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004423 {
4424 Mutex::Autolock _l(mLock);
4425 activeTrack = mActiveTrack;
4426 acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
4427 }
Eric Laurent81784c32012-11-19 14:55:58 -08004428
4429 // used to verify we've read at least once before evaluating how many bytes were read
4430 bool readOnce = false;
4431
4432 // start recording
4433 while (!exitPending()) {
4434
4435 processConfigEvents();
4436
4437 { // scope for mLock
4438 Mutex::Autolock _l(mLock);
4439 checkForNewParameters_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004440 if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
4441 SortedVector<int> tmp;
4442 tmp.add(mActiveTrack->uid());
4443 updateWakeLockUids_l(tmp);
4444 }
4445 activeTrack = mActiveTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004446 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4447 standby();
4448
4449 if (exitPending()) {
4450 break;
4451 }
4452
4453 releaseWakeLock_l();
4454 ALOGV("RecordThread: loop stopping");
4455 // go to sleep
4456 mWaitWorkCV.wait(mLock);
4457 ALOGV("RecordThread: loop starting");
Marco Nelissen9cae2172013-01-14 14:12:05 -08004458 acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08004459 continue;
4460 }
4461 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004462 if (mActiveTrack->isTerminated()) {
4463 removeTrack_l(mActiveTrack);
4464 mActiveTrack.clear();
4465 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004466 standby();
4467 mActiveTrack.clear();
4468 mStartStopCond.broadcast();
4469 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4470 if (mReqChannelCount != mActiveTrack->channelCount()) {
4471 mActiveTrack.clear();
4472 mStartStopCond.broadcast();
4473 } else if (readOnce) {
4474 // record start succeeds only if first read from audio input
4475 // succeeds
4476 if (mBytesRead >= 0) {
4477 mActiveTrack->mState = TrackBase::ACTIVE;
4478 } else {
4479 mActiveTrack.clear();
4480 }
4481 mStartStopCond.broadcast();
4482 }
4483 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004484 }
4485 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004486
Eric Laurent81784c32012-11-19 14:55:58 -08004487 lockEffectChains_l(effectChains);
4488 }
4489
4490 if (mActiveTrack != 0) {
4491 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4492 mActiveTrack->mState != TrackBase::RESUMING) {
4493 unlockEffectChains(effectChains);
4494 usleep(kRecordThreadSleepUs);
4495 continue;
4496 }
4497 for (size_t i = 0; i < effectChains.size(); i ++) {
4498 effectChains[i]->process_l();
4499 }
4500
4501 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004502 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004503 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004504 readOnce = true;
4505 size_t framesOut = buffer.frameCount;
4506 if (mResampler == NULL) {
4507 // no resampling
4508 while (framesOut) {
4509 size_t framesIn = mFrameCount - mRsmpInIndex;
4510 if (framesIn) {
4511 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4512 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4513 mActiveTrack->mFrameSize;
4514 if (framesIn > framesOut)
4515 framesIn = framesOut;
4516 mRsmpInIndex += framesIn;
4517 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004518 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004519 memcpy(dst, src, framesIn * mFrameSize);
4520 } else {
4521 if (mChannelCount == 1) {
4522 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4523 (int16_t *)src, framesIn);
4524 } else {
4525 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4526 (int16_t *)src, framesIn);
4527 }
4528 }
4529 }
4530 if (framesOut && mFrameCount == mRsmpInIndex) {
4531 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004532 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004533 readInto = buffer.raw;
4534 framesOut = 0;
4535 } else {
4536 readInto = mRsmpInBuffer;
4537 mRsmpInIndex = 0;
4538 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004539 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004540 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004541 if (mBytesRead <= 0) {
4542 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4543 {
4544 ALOGE("Error reading audio input");
4545 // Force input into standby so that it tries to
4546 // recover at next read attempt
4547 inputStandBy();
4548 usleep(kRecordThreadSleepUs);
4549 }
4550 mRsmpInIndex = mFrameCount;
4551 framesOut = 0;
4552 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004553 }
4554#ifdef TEE_SINK
4555 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004556 (void) mTeeSink->write(readInto,
4557 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4558 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004559#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004560 }
4561 }
4562 } else {
4563 // resampling
4564
Glenn Kasten34af0262013-07-30 11:52:39 -07004565 // resampler accumulates, but we only have one source track
4566 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004567 // alter output frame count as if we were expecting stereo samples
4568 if (mChannelCount == 1 && mReqChannelCount == 1) {
4569 framesOut >>= 1;
4570 }
4571 mResampler->resample(mRsmpOutBuffer, framesOut,
4572 this /* AudioBufferProvider* */);
4573 // ditherAndClamp() works as long as all buffers returned by
4574 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4575 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004576 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004577 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4578 // the resampler always outputs stereo samples:
4579 // do post stereo to mono conversion
4580 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4581 framesOut);
4582 } else {
4583 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4584 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004585 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004586
4587 }
4588 if (mFramestoDrop == 0) {
4589 mActiveTrack->releaseBuffer(&buffer);
4590 } else {
4591 if (mFramestoDrop > 0) {
4592 mFramestoDrop -= buffer.frameCount;
4593 if (mFramestoDrop <= 0) {
4594 clearSyncStartEvent();
4595 }
4596 } else {
4597 mFramestoDrop += buffer.frameCount;
4598 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4599 mSyncStartEvent->isCancelled()) {
4600 ALOGW("Synced record %s, session %d, trigger session %d",
4601 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4602 mActiveTrack->sessionId(),
4603 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4604 clearSyncStartEvent();
4605 }
4606 }
4607 }
4608 mActiveTrack->clearOverflow();
4609 }
4610 // client isn't retrieving buffers fast enough
4611 else {
4612 if (!mActiveTrack->setOverflow()) {
4613 nsecs_t now = systemTime();
4614 if ((now - lastWarning) > kWarningThrottleNs) {
4615 ALOGW("RecordThread: buffer overflow");
4616 lastWarning = now;
4617 }
4618 }
4619 // Release the processor for a while before asking for a new buffer.
4620 // This will give the application more chance to read from the buffer and
4621 // clear the overflow.
4622 usleep(kRecordThreadSleepUs);
4623 }
4624 }
4625 // enable changes in effect chain
4626 unlockEffectChains(effectChains);
4627 effectChains.clear();
4628 }
4629
4630 standby();
4631
4632 {
4633 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004634 for (size_t i = 0; i < mTracks.size(); i++) {
4635 sp<RecordTrack> track = mTracks[i];
4636 track->invalidate();
4637 }
Eric Laurent81784c32012-11-19 14:55:58 -08004638 mActiveTrack.clear();
4639 mStartStopCond.broadcast();
4640 }
4641
4642 releaseWakeLock();
4643
4644 ALOGV("RecordThread %p exiting", this);
4645 return false;
4646}
4647
4648void AudioFlinger::RecordThread::standby()
4649{
4650 if (!mStandby) {
4651 inputStandBy();
4652 mStandby = true;
4653 }
4654}
4655
4656void AudioFlinger::RecordThread::inputStandBy()
4657{
4658 mInput->stream->common.standby(&mInput->stream->common);
4659}
4660
4661sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4662 const sp<AudioFlinger::Client>& client,
4663 uint32_t sampleRate,
4664 audio_format_t format,
4665 audio_channel_mask_t channelMask,
4666 size_t frameCount,
4667 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004668 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004669 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004670 pid_t tid,
4671 status_t *status)
4672{
4673 sp<RecordTrack> track;
4674 status_t lStatus;
4675
4676 lStatus = initCheck();
4677 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004678 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004679 goto Exit;
4680 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004681 // client expresses a preference for FAST, but we get the final say
4682 if (*flags & IAudioFlinger::TRACK_FAST) {
4683 if (
4684 // use case: callback handler and frame count is default or at least as large as HAL
4685 (
4686 (tid != -1) &&
4687 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004688 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004689 ) &&
4690 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4691 // mono or stereo
4692 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4693 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4694 // hardware sample rate
4695 (sampleRate == mSampleRate) &&
4696 // record thread has an associated fast recorder
4697 hasFastRecorder()
4698 // FIXME test that RecordThread for this fast track has a capable output HAL
4699 // FIXME add a permission test also?
4700 ) {
4701 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4702 if (frameCount == 0) {
4703 frameCount = mFrameCount * kFastTrackMultiplier;
4704 }
4705 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4706 frameCount, mFrameCount);
4707 } else {
4708 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4709 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4710 "hasFastRecorder=%d tid=%d",
4711 frameCount, mFrameCount, format,
4712 audio_is_linear_pcm(format),
4713 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4714 *flags &= ~IAudioFlinger::TRACK_FAST;
4715 // For compatibility with AudioRecord calculation, buffer depth is forced
4716 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4717 // This is probably too conservative, but legacy application code may depend on it.
4718 // If you change this calculation, also review the start threshold which is related.
4719 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4720 size_t mNormalFrameCount = 2048; // FIXME
4721 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4722 if (minBufCount < 2) {
4723 minBufCount = 2;
4724 }
4725 size_t minFrameCount = mNormalFrameCount * minBufCount;
4726 if (frameCount < minFrameCount) {
4727 frameCount = minFrameCount;
4728 }
4729 }
4730 }
4731
Eric Laurent81784c32012-11-19 14:55:58 -08004732 // FIXME use flags and tid similar to createTrack_l()
4733
4734 { // scope for mLock
4735 Mutex::Autolock _l(mLock);
4736
4737 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004738 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004739
4740 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004741 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004742 lStatus = NO_MEMORY;
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004743 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004744 goto Exit;
4745 }
4746 mTracks.add(track);
4747
4748 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4749 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4750 mAudioFlinger->btNrecIsOff();
4751 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4752 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004753
4754 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4755 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4756 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4757 // so ask activity manager to do this on our behalf
4758 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4759 }
Eric Laurent81784c32012-11-19 14:55:58 -08004760 }
4761 lStatus = NO_ERROR;
4762
4763Exit:
4764 if (status) {
4765 *status = lStatus;
4766 }
4767 return track;
4768}
4769
4770status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4771 AudioSystem::sync_event_t event,
4772 int triggerSession)
4773{
4774 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4775 sp<ThreadBase> strongMe = this;
4776 status_t status = NO_ERROR;
4777
4778 if (event == AudioSystem::SYNC_EVENT_NONE) {
4779 clearSyncStartEvent();
4780 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4781 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4782 triggerSession,
4783 recordTrack->sessionId(),
4784 syncStartEventCallback,
4785 this);
4786 // Sync event can be cancelled by the trigger session if the track is not in a
4787 // compatible state in which case we start record immediately
4788 if (mSyncStartEvent->isCancelled()) {
4789 clearSyncStartEvent();
4790 } else {
4791 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4792 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4793 }
4794 }
4795
4796 {
4797 AutoMutex lock(mLock);
4798 if (mActiveTrack != 0) {
4799 if (recordTrack != mActiveTrack.get()) {
4800 status = -EBUSY;
4801 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4802 mActiveTrack->mState = TrackBase::ACTIVE;
4803 }
4804 return status;
4805 }
4806
4807 recordTrack->mState = TrackBase::IDLE;
4808 mActiveTrack = recordTrack;
4809 mLock.unlock();
4810 status_t status = AudioSystem::startInput(mId);
4811 mLock.lock();
4812 if (status != NO_ERROR) {
4813 mActiveTrack.clear();
4814 clearSyncStartEvent();
4815 return status;
4816 }
4817 mRsmpInIndex = mFrameCount;
4818 mBytesRead = 0;
4819 if (mResampler != NULL) {
4820 mResampler->reset();
4821 }
4822 mActiveTrack->mState = TrackBase::RESUMING;
4823 // signal thread to start
4824 ALOGV("Signal record thread");
4825 mWaitWorkCV.broadcast();
4826 // do not wait for mStartStopCond if exiting
4827 if (exitPending()) {
4828 mActiveTrack.clear();
4829 status = INVALID_OPERATION;
4830 goto startError;
4831 }
4832 mStartStopCond.wait(mLock);
4833 if (mActiveTrack == 0) {
4834 ALOGV("Record failed to start");
4835 status = BAD_VALUE;
4836 goto startError;
4837 }
4838 ALOGV("Record started OK");
4839 return status;
4840 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004841
Eric Laurent81784c32012-11-19 14:55:58 -08004842startError:
4843 AudioSystem::stopInput(mId);
4844 clearSyncStartEvent();
4845 return status;
4846}
4847
4848void AudioFlinger::RecordThread::clearSyncStartEvent()
4849{
4850 if (mSyncStartEvent != 0) {
4851 mSyncStartEvent->cancel();
4852 }
4853 mSyncStartEvent.clear();
4854 mFramestoDrop = 0;
4855}
4856
4857void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4858{
4859 sp<SyncEvent> strongEvent = event.promote();
4860
4861 if (strongEvent != 0) {
4862 RecordThread *me = (RecordThread *)strongEvent->cookie();
4863 me->handleSyncStartEvent(strongEvent);
4864 }
4865}
4866
4867void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4868{
4869 if (event == mSyncStartEvent) {
4870 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4871 // from audio HAL
4872 mFramestoDrop = mFrameCount * 2;
4873 }
4874}
4875
Glenn Kastena8356f62013-07-25 14:37:52 -07004876bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004877 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004878 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004879 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4880 return false;
4881 }
4882 recordTrack->mState = TrackBase::PAUSING;
4883 // do not wait for mStartStopCond if exiting
4884 if (exitPending()) {
4885 return true;
4886 }
4887 mStartStopCond.wait(mLock);
4888 // if we have been restarted, recordTrack == mActiveTrack.get() here
4889 if (exitPending() || recordTrack != mActiveTrack.get()) {
4890 ALOGV("Record stopped OK");
4891 return true;
4892 }
4893 return false;
4894}
4895
4896bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4897{
4898 return false;
4899}
4900
4901status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4902{
4903#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4904 if (!isValidSyncEvent(event)) {
4905 return BAD_VALUE;
4906 }
4907
4908 int eventSession = event->triggerSession();
4909 status_t ret = NAME_NOT_FOUND;
4910
4911 Mutex::Autolock _l(mLock);
4912
4913 for (size_t i = 0; i < mTracks.size(); i++) {
4914 sp<RecordTrack> track = mTracks[i];
4915 if (eventSession == track->sessionId()) {
4916 (void) track->setSyncEvent(event);
4917 ret = NO_ERROR;
4918 }
4919 }
4920 return ret;
4921#else
4922 return BAD_VALUE;
4923#endif
4924}
4925
4926// destroyTrack_l() must be called with ThreadBase::mLock held
4927void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4928{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004929 track->terminate();
4930 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004931 // active tracks are removed by threadLoop()
4932 if (mActiveTrack != track) {
4933 removeTrack_l(track);
4934 }
4935}
4936
4937void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4938{
4939 mTracks.remove(track);
4940 // need anything related to effects here?
4941}
4942
4943void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4944{
4945 dumpInternals(fd, args);
4946 dumpTracks(fd, args);
4947 dumpEffectChains(fd, args);
4948}
4949
4950void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4951{
4952 const size_t SIZE = 256;
4953 char buffer[SIZE];
4954 String8 result;
4955
4956 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4957 result.append(buffer);
4958
4959 if (mActiveTrack != 0) {
4960 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4961 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004962 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004963 result.append(buffer);
4964 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4965 result.append(buffer);
4966 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4967 result.append(buffer);
4968 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4969 result.append(buffer);
4970 } else {
4971 result.append("No active record client\n");
4972 }
4973
4974 write(fd, result.string(), result.size());
4975
4976 dumpBase(fd, args);
4977}
4978
4979void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4980{
4981 const size_t SIZE = 256;
4982 char buffer[SIZE];
4983 String8 result;
4984
4985 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4986 result.append(buffer);
4987 RecordTrack::appendDumpHeader(result);
4988 for (size_t i = 0; i < mTracks.size(); ++i) {
4989 sp<RecordTrack> track = mTracks[i];
4990 if (track != 0) {
4991 track->dump(buffer, SIZE);
4992 result.append(buffer);
4993 }
4994 }
4995
4996 if (mActiveTrack != 0) {
4997 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4998 result.append(buffer);
4999 RecordTrack::appendDumpHeader(result);
5000 mActiveTrack->dump(buffer, SIZE);
5001 result.append(buffer);
5002
5003 }
5004 write(fd, result.string(), result.size());
5005}
5006
5007// AudioBufferProvider interface
5008status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5009{
5010 size_t framesReq = buffer->frameCount;
5011 size_t framesReady = mFrameCount - mRsmpInIndex;
5012 int channelCount;
5013
5014 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005015 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005016 if (mBytesRead <= 0) {
5017 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5018 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5019 // Force input into standby so that it tries to
5020 // recover at next read attempt
5021 inputStandBy();
5022 usleep(kRecordThreadSleepUs);
5023 }
5024 buffer->raw = NULL;
5025 buffer->frameCount = 0;
5026 return NOT_ENOUGH_DATA;
5027 }
5028 mRsmpInIndex = 0;
5029 framesReady = mFrameCount;
5030 }
5031
5032 if (framesReq > framesReady) {
5033 framesReq = framesReady;
5034 }
5035
5036 if (mChannelCount == 1 && mReqChannelCount == 2) {
5037 channelCount = 1;
5038 } else {
5039 channelCount = 2;
5040 }
5041 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5042 buffer->frameCount = framesReq;
5043 return NO_ERROR;
5044}
5045
5046// AudioBufferProvider interface
5047void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5048{
5049 mRsmpInIndex += buffer->frameCount;
5050 buffer->frameCount = 0;
5051}
5052
5053bool AudioFlinger::RecordThread::checkForNewParameters_l()
5054{
5055 bool reconfig = false;
5056
5057 while (!mNewParameters.isEmpty()) {
5058 status_t status = NO_ERROR;
5059 String8 keyValuePair = mNewParameters[0];
5060 AudioParameter param = AudioParameter(keyValuePair);
5061 int value;
5062 audio_format_t reqFormat = mFormat;
5063 uint32_t reqSamplingRate = mReqSampleRate;
5064 uint32_t reqChannelCount = mReqChannelCount;
5065
5066 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5067 reqSamplingRate = value;
5068 reconfig = true;
5069 }
5070 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005071 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5072 status = BAD_VALUE;
5073 } else {
5074 reqFormat = (audio_format_t) value;
5075 reconfig = true;
5076 }
Eric Laurent81784c32012-11-19 14:55:58 -08005077 }
5078 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5079 reqChannelCount = popcount(value);
5080 reconfig = true;
5081 }
5082 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5083 // do not accept frame count changes if tracks are open as the track buffer
5084 // size depends on frame count and correct behavior would not be guaranteed
5085 // if frame count is changed after track creation
5086 if (mActiveTrack != 0) {
5087 status = INVALID_OPERATION;
5088 } else {
5089 reconfig = true;
5090 }
5091 }
5092 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5093 // forward device change to effects that have requested to be
5094 // aware of attached audio device.
5095 for (size_t i = 0; i < mEffectChains.size(); i++) {
5096 mEffectChains[i]->setDevice_l(value);
5097 }
5098
5099 // store input device and output device but do not forward output device to audio HAL.
5100 // Note that status is ignored by the caller for output device
5101 // (see AudioFlinger::setParameters()
5102 if (audio_is_output_devices(value)) {
5103 mOutDevice = value;
5104 status = BAD_VALUE;
5105 } else {
5106 mInDevice = value;
5107 // disable AEC and NS if the device is a BT SCO headset supporting those
5108 // pre processings
5109 if (mTracks.size() > 0) {
5110 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5111 mAudioFlinger->btNrecIsOff();
5112 for (size_t i = 0; i < mTracks.size(); i++) {
5113 sp<RecordTrack> track = mTracks[i];
5114 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5115 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5116 }
5117 }
5118 }
5119 }
5120 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5121 mAudioSource != (audio_source_t)value) {
5122 // forward device change to effects that have requested to be
5123 // aware of attached audio device.
5124 for (size_t i = 0; i < mEffectChains.size(); i++) {
5125 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5126 }
5127 mAudioSource = (audio_source_t)value;
5128 }
5129 if (status == NO_ERROR) {
5130 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5131 keyValuePair.string());
5132 if (status == INVALID_OPERATION) {
5133 inputStandBy();
5134 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5135 keyValuePair.string());
5136 }
5137 if (reconfig) {
5138 if (status == BAD_VALUE &&
5139 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5140 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005141 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005142 <= (2 * reqSamplingRate)) &&
5143 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5144 <= FCC_2 &&
5145 (reqChannelCount <= FCC_2)) {
5146 status = NO_ERROR;
5147 }
5148 if (status == NO_ERROR) {
5149 readInputParameters();
5150 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5151 }
5152 }
5153 }
5154
5155 mNewParameters.removeAt(0);
5156
5157 mParamStatus = status;
5158 mParamCond.signal();
5159 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5160 // already timed out waiting for the status and will never signal the condition.
5161 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5162 }
5163 return reconfig;
5164}
5165
5166String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5167{
Eric Laurent81784c32012-11-19 14:55:58 -08005168 Mutex::Autolock _l(mLock);
5169 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005170 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005171 }
5172
Glenn Kastend8ea6992013-07-16 14:17:15 -07005173 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5174 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 free(s);
5176 return out_s8;
5177}
5178
5179void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5180 AudioSystem::OutputDescriptor desc;
5181 void *param2 = NULL;
5182
5183 switch (event) {
5184 case AudioSystem::INPUT_OPENED:
5185 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005186 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005187 desc.samplingRate = mSampleRate;
5188 desc.format = mFormat;
5189 desc.frameCount = mFrameCount;
5190 desc.latency = 0;
5191 param2 = &desc;
5192 break;
5193
5194 case AudioSystem::INPUT_CLOSED:
5195 default:
5196 break;
5197 }
5198 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5199}
5200
5201void AudioFlinger::RecordThread::readInputParameters()
5202{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005203 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005204 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005205 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005206 mRsmpOutBuffer = NULL;
5207 delete mResampler;
5208 mResampler = NULL;
5209
5210 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5211 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005212 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005213 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005214 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5215 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5216 }
Eric Laurent81784c32012-11-19 14:55:58 -08005217 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005218 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5219 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005220 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5221
5222 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5223 {
5224 int channelCount;
5225 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5226 // stereo to mono post process as the resampler always outputs stereo.
5227 if (mChannelCount == 1 && mReqChannelCount == 2) {
5228 channelCount = 1;
5229 } else {
5230 channelCount = 2;
5231 }
5232 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5233 mResampler->setSampleRate(mSampleRate);
5234 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005235 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005236
5237 // optmization: if mono to mono, alter input frame count as if we were inputing
5238 // stereo samples
5239 if (mChannelCount == 1 && mReqChannelCount == 1) {
5240 mFrameCount >>= 1;
5241 }
5242
5243 }
5244 mRsmpInIndex = mFrameCount;
5245}
5246
5247unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5248{
5249 Mutex::Autolock _l(mLock);
5250 if (initCheck() != NO_ERROR) {
5251 return 0;
5252 }
5253
5254 return mInput->stream->get_input_frames_lost(mInput->stream);
5255}
5256
5257uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5258{
5259 Mutex::Autolock _l(mLock);
5260 uint32_t result = 0;
5261 if (getEffectChain_l(sessionId) != 0) {
5262 result = EFFECT_SESSION;
5263 }
5264
5265 for (size_t i = 0; i < mTracks.size(); ++i) {
5266 if (sessionId == mTracks[i]->sessionId()) {
5267 result |= TRACK_SESSION;
5268 break;
5269 }
5270 }
5271
5272 return result;
5273}
5274
5275KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5276{
5277 KeyedVector<int, bool> ids;
5278 Mutex::Autolock _l(mLock);
5279 for (size_t j = 0; j < mTracks.size(); ++j) {
5280 sp<RecordThread::RecordTrack> track = mTracks[j];
5281 int sessionId = track->sessionId();
5282 if (ids.indexOfKey(sessionId) < 0) {
5283 ids.add(sessionId, true);
5284 }
5285 }
5286 return ids;
5287}
5288
5289AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5290{
5291 Mutex::Autolock _l(mLock);
5292 AudioStreamIn *input = mInput;
5293 mInput = NULL;
5294 return input;
5295}
5296
5297// this method must always be called either with ThreadBase mLock held or inside the thread loop
5298audio_stream_t* AudioFlinger::RecordThread::stream() const
5299{
5300 if (mInput == NULL) {
5301 return NULL;
5302 }
5303 return &mInput->stream->common;
5304}
5305
5306status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5307{
5308 // only one chain per input thread
5309 if (mEffectChains.size() != 0) {
5310 return INVALID_OPERATION;
5311 }
5312 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5313
5314 chain->setInBuffer(NULL);
5315 chain->setOutBuffer(NULL);
5316
5317 checkSuspendOnAddEffectChain_l(chain);
5318
5319 mEffectChains.add(chain);
5320
5321 return NO_ERROR;
5322}
5323
5324size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5325{
5326 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5327 ALOGW_IF(mEffectChains.size() != 1,
5328 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5329 chain.get(), mEffectChains.size(), this);
5330 if (mEffectChains.size() == 1) {
5331 mEffectChains.removeAt(0);
5332 }
5333 return 0;
5334}
5335
5336}; // namespace android