blob: 6b2bc5e96c780a6ffdc73aafa210675e733c5e5b [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 Kastend812fc02013-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 Kastend812fc02013-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,
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800742 status_t *status,
743 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -0800744{
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
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800812 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -0800813 if (lStatus != NO_ERROR) {
814 goto Exit;
815 }
816 effectCreated = true;
817
818 effect->setDevice(mOutDevice);
819 effect->setDevice(mInDevice);
820 effect->setMode(mAudioFlinger->getMode());
821 effect->setAudioSource(mAudioSource);
822 }
823 // create effect handle and connect it to effect module
824 handle = new EffectHandle(effect, client, effectClient, priority);
825 lStatus = effect->addHandle(handle.get());
826 if (enabled != NULL) {
827 *enabled = (int)effect->isEnabled();
828 }
829 }
830
831Exit:
832 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
833 Mutex::Autolock _l(mLock);
834 if (effectCreated) {
835 chain->removeEffect_l(effect);
836 }
837 if (effectRegistered) {
838 AudioSystem::unregisterEffect(effect->id());
839 }
840 if (chainCreated) {
841 removeEffectChain_l(chain);
842 }
843 handle.clear();
844 }
845
846 if (status != NULL) {
847 *status = lStatus;
848 }
849 return handle;
850}
851
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800852void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
853 bool unpinIfLast)
854{
855 bool remove = false;
856 sp<EffectModule> effect;
857 {
858 Mutex::Autolock _l(mLock);
859
860 effect = handle->effect().promote();
861 if (effect == 0) {
862 return;
863 }
864 // restore suspended effects if the disconnected handle was enabled and the last one.
865 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
866 if (remove) {
867 removeEffect_l(effect, true);
868 }
869 }
870 if (remove) {
871 AudioSystem::unregisterEffect(effect->id());
872 if (handle->enabled()) {
873 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
874 }
875 }
876}
877
Eric Laurent81784c32012-11-19 14:55:58 -0800878sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
879{
880 Mutex::Autolock _l(mLock);
881 return getEffect_l(sessionId, effectId);
882}
883
884sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
885{
886 sp<EffectChain> chain = getEffectChain_l(sessionId);
887 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
888}
889
890// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
891// PlaybackThread::mLock held
892status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
893{
894 // check for existing effect chain with the requested audio session
895 int sessionId = effect->sessionId();
896 sp<EffectChain> chain = getEffectChain_l(sessionId);
897 bool chainCreated = false;
898
Eric Laurent5baf2af2013-09-12 17:37:00 -0700899 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
900 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
901 this, effect->desc().name, effect->desc().flags);
902
Eric Laurent81784c32012-11-19 14:55:58 -0800903 if (chain == 0) {
904 // create a new chain for this session
905 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
906 chain = new EffectChain(this, sessionId);
907 addEffectChain_l(chain);
908 chain->setStrategy(getStrategyForSession_l(sessionId));
909 chainCreated = true;
910 }
911 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
912
913 if (chain->getEffectFromId_l(effect->id()) != 0) {
914 ALOGW("addEffect_l() %p effect %s already present in chain %p",
915 this, effect->desc().name, chain.get());
916 return BAD_VALUE;
917 }
918
Eric Laurent5baf2af2013-09-12 17:37:00 -0700919 effect->setOffloaded(mType == OFFLOAD, mId);
920
Eric Laurent81784c32012-11-19 14:55:58 -0800921 status_t status = chain->addEffect_l(effect);
922 if (status != NO_ERROR) {
923 if (chainCreated) {
924 removeEffectChain_l(chain);
925 }
926 return status;
927 }
928
929 effect->setDevice(mOutDevice);
930 effect->setDevice(mInDevice);
931 effect->setMode(mAudioFlinger->getMode());
932 effect->setAudioSource(mAudioSource);
933 return NO_ERROR;
934}
935
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800936void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800938 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -0800939 effect_descriptor_t desc = effect->desc();
940 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
941 detachAuxEffect_l(effect->id());
942 }
943
944 sp<EffectChain> chain = effect->chain().promote();
945 if (chain != 0) {
946 // remove effect chain if removing last effect
Eric Laurentb47a5ab2016-12-01 15:28:29 -0800947 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800948 removeEffectChain_l(chain);
949 }
950 } else {
951 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
952 }
953}
954
955void AudioFlinger::ThreadBase::lockEffectChains_l(
956 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
957{
958 effectChains = mEffectChains;
959 for (size_t i = 0; i < mEffectChains.size(); i++) {
960 mEffectChains[i]->lock();
961 }
962}
963
964void AudioFlinger::ThreadBase::unlockEffectChains(
965 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
966{
967 for (size_t i = 0; i < effectChains.size(); i++) {
968 effectChains[i]->unlock();
969 }
970}
971
972sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
973{
974 Mutex::Autolock _l(mLock);
975 return getEffectChain_l(sessionId);
976}
977
978sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
979{
980 size_t size = mEffectChains.size();
981 for (size_t i = 0; i < size; i++) {
982 if (mEffectChains[i]->sessionId() == sessionId) {
983 return mEffectChains[i];
984 }
985 }
986 return 0;
987}
988
989void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
990{
991 Mutex::Autolock _l(mLock);
992 size_t size = mEffectChains.size();
993 for (size_t i = 0; i < size; i++) {
994 mEffectChains[i]->setMode_l(mode);
995 }
996}
997
998void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
999 EffectHandle *handle,
1000 bool unpinIfLast) {
1001
1002 Mutex::Autolock _l(mLock);
1003 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1004 // delete the effect module if removing last handle on it
1005 if (effect->removeHandle(handle) == 0) {
1006 if (!effect->isPinned() || unpinIfLast) {
1007 removeEffect_l(effect);
1008 AudioSystem::unregisterEffect(effect->id());
1009 }
1010 }
1011}
1012
1013// ----------------------------------------------------------------------------
1014// Playback
1015// ----------------------------------------------------------------------------
1016
1017AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1018 AudioStreamOut* output,
1019 audio_io_handle_t id,
1020 audio_devices_t device,
1021 type_t type)
1022 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001023 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001024 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Marco Nelissen9cae2172013-01-14 14:12:05 -08001025 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001026 // mStreamTypes[] initialized in constructor body
1027 mOutput(output),
1028 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1029 mMixerStatus(MIXER_IDLE),
1030 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1031 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001032 mBytesRemaining(0),
1033 mCurrentWriteLength(0),
1034 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001035 mWriteAckSequence(0),
1036 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001037 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001038 mScreenState(AudioFlinger::mScreenState),
1039 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001040 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1041 // mLatchD, mLatchQ,
1042 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001043{
1044 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001045 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001046
1047 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1048 // it would be safer to explicitly pass initial masterVolume/masterMute as
1049 // parameter.
1050 //
1051 // If the HAL we are using has support for master volume or master mute,
1052 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1053 // and the mute set to false).
1054 mMasterVolume = audioFlinger->masterVolume_l();
1055 mMasterMute = audioFlinger->masterMute_l();
1056 if (mOutput && mOutput->audioHwDev) {
1057 if (mOutput->audioHwDev->canSetMasterVolume()) {
1058 mMasterVolume = 1.0;
1059 }
1060
1061 if (mOutput->audioHwDev->canSetMasterMute()) {
1062 mMasterMute = false;
1063 }
1064 }
1065
1066 readOutputParameters();
1067
1068 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1069 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1070 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1071 stream = (audio_stream_type_t) (stream + 1)) {
1072 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1073 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1074 }
1075 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1076 // because mAudioFlinger doesn't have one to copy from
1077}
1078
1079AudioFlinger::PlaybackThread::~PlaybackThread()
1080{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001081 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001082 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001083}
1084
1085void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1086{
1087 dumpInternals(fd, args);
1088 dumpTracks(fd, args);
1089 dumpEffectChains(fd, args);
1090}
1091
1092void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1093{
1094 const size_t SIZE = 256;
1095 char buffer[SIZE];
1096 String8 result;
1097
1098 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1099 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1100 const stream_type_t *st = &mStreamTypes[i];
1101 if (i > 0) {
1102 result.appendFormat(", ");
1103 }
1104 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1105 if (st->mute) {
1106 result.append("M");
1107 }
1108 }
1109 result.append("\n");
1110 write(fd, result.string(), result.length());
1111 result.clear();
1112
1113 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1114 result.append(buffer);
1115 Track::appendDumpHeader(result);
1116 for (size_t i = 0; i < mTracks.size(); ++i) {
1117 sp<Track> track = mTracks[i];
1118 if (track != 0) {
1119 track->dump(buffer, SIZE);
1120 result.append(buffer);
1121 }
1122 }
1123
1124 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1125 result.append(buffer);
1126 Track::appendDumpHeader(result);
1127 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1128 sp<Track> track = mActiveTracks[i].promote();
1129 if (track != 0) {
1130 track->dump(buffer, SIZE);
1131 result.append(buffer);
1132 }
1133 }
1134 write(fd, result.string(), result.size());
1135
1136 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1137 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1138 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1139 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1140}
1141
1142void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1143{
1144 const size_t SIZE = 256;
1145 char buffer[SIZE];
1146 String8 result;
1147
1148 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1149 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001150 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1151 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001152 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1153 ns2ms(systemTime() - mLastWriteTime));
1154 result.append(buffer);
1155 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1156 result.append(buffer);
1157 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1158 result.append(buffer);
1159 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1160 result.append(buffer);
1161 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1162 result.append(buffer);
1163 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1164 result.append(buffer);
1165 write(fd, result.string(), result.size());
1166 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1167
1168 dumpBase(fd, args);
1169}
1170
1171// Thread virtuals
1172status_t AudioFlinger::PlaybackThread::readyToRun()
1173{
1174 status_t status = initCheck();
1175 if (status == NO_ERROR) {
1176 ALOGI("AudioFlinger's thread %p ready to run", this);
1177 } else {
1178 ALOGE("No working audio driver found.");
1179 }
1180 return status;
1181}
1182
1183void AudioFlinger::PlaybackThread::onFirstRef()
1184{
1185 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1186}
1187
1188// ThreadBase virtuals
1189void AudioFlinger::PlaybackThread::preExit()
1190{
1191 ALOGV(" preExit()");
1192 // FIXME this is using hard-coded strings but in the future, this functionality will be
1193 // converted to use audio HAL extensions required to support tunneling
1194 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1195}
1196
1197// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1198sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1199 const sp<AudioFlinger::Client>& client,
1200 audio_stream_type_t streamType,
1201 uint32_t sampleRate,
1202 audio_format_t format,
1203 audio_channel_mask_t channelMask,
1204 size_t frameCount,
1205 const sp<IMemory>& sharedBuffer,
1206 int sessionId,
1207 IAudioFlinger::track_flags_t *flags,
1208 pid_t tid,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001209 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001210 status_t *status)
1211{
1212 sp<Track> track;
1213 status_t lStatus;
1214
1215 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1216
1217 // client expresses a preference for FAST, but we get the final say
1218 if (*flags & IAudioFlinger::TRACK_FAST) {
1219 if (
1220 // not timed
1221 (!isTimed) &&
1222 // either of these use cases:
1223 (
1224 // use case 1: shared buffer with any frame count
1225 (
1226 (sharedBuffer != 0)
1227 ) ||
1228 // use case 2: callback handler and frame count is default or at least as large as HAL
1229 (
1230 (tid != -1) &&
1231 ((frameCount == 0) ||
Glenn Kastend812fc02013-12-03 09:06:43 -08001232 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001233 )
1234 ) &&
1235 // PCM data
1236 audio_is_linear_pcm(format) &&
1237 // mono or stereo
1238 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1239 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1240#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1241 // hardware sample rate
1242 (sampleRate == mSampleRate) &&
1243#endif
1244 // normal mixer has an associated fast mixer
1245 hasFastMixer() &&
1246 // there are sufficient fast track slots available
1247 (mFastTrackAvailMask != 0)
1248 // FIXME test that MixerThread for this fast track has a capable output HAL
1249 // FIXME add a permission test also?
1250 ) {
1251 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1252 if (frameCount == 0) {
1253 frameCount = mFrameCount * kFastTrackMultiplier;
1254 }
1255 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1256 frameCount, mFrameCount);
1257 } else {
1258 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1259 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1260 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1261 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1262 audio_is_linear_pcm(format),
1263 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1264 *flags &= ~IAudioFlinger::TRACK_FAST;
1265 // For compatibility with AudioTrack calculation, buffer depth is forced
1266 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1267 // This is probably too conservative, but legacy application code may depend on it.
1268 // If you change this calculation, also review the start threshold which is related.
1269 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1270 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1271 if (minBufCount < 2) {
1272 minBufCount = 2;
1273 }
1274 size_t minFrameCount = mNormalFrameCount * minBufCount;
1275 if (frameCount < minFrameCount) {
1276 frameCount = minFrameCount;
1277 }
1278 }
1279 }
1280
1281 if (mType == DIRECT) {
1282 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1283 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1284 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1285 "for output %p with format %d",
1286 sampleRate, format, channelMask, mOutput, mFormat);
1287 lStatus = BAD_VALUE;
1288 goto Exit;
1289 }
1290 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001291 } else if (mType == OFFLOAD) {
1292 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1293 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1294 "for output %p with format %d",
1295 sampleRate, format, channelMask, mOutput, mFormat);
1296 lStatus = BAD_VALUE;
1297 goto Exit;
1298 }
Eric Laurent81784c32012-11-19 14:55:58 -08001299 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001300 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1301 ALOGE("createTrack_l() Bad parameter: format %d \""
1302 "for output %p with format %d",
1303 format, mOutput, mFormat);
1304 lStatus = BAD_VALUE;
1305 goto Exit;
1306 }
Eric Laurent81784c32012-11-19 14:55:58 -08001307 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1308 if (sampleRate > mSampleRate*2) {
1309 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1310 lStatus = BAD_VALUE;
1311 goto Exit;
1312 }
1313 }
1314
1315 lStatus = initCheck();
1316 if (lStatus != NO_ERROR) {
1317 ALOGE("Audio driver not initialized.");
1318 goto Exit;
1319 }
1320
1321 { // scope for mLock
1322 Mutex::Autolock _l(mLock);
1323
1324 // all tracks in same audio session must share the same routing strategy otherwise
1325 // conflicts will happen when tracks are moved from one output to another by audio policy
1326 // manager
1327 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1328 for (size_t i = 0; i < mTracks.size(); ++i) {
1329 sp<Track> t = mTracks[i];
1330 if (t != 0 && !t->isOutputTrack()) {
1331 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1332 if (sessionId == t->sessionId() && strategy != actual) {
1333 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1334 strategy, actual);
1335 lStatus = BAD_VALUE;
1336 goto Exit;
1337 }
1338 }
1339 }
1340
1341 if (!isTimed) {
1342 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001343 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001344 } else {
1345 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001346 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001347 }
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08001348
Eric Laurent81784c32012-11-19 14:55:58 -08001349 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1350 lStatus = NO_MEMORY;
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08001351 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001352 goto Exit;
1353 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001354
Eric Laurent81784c32012-11-19 14:55:58 -08001355 mTracks.add(track);
1356
1357 sp<EffectChain> chain = getEffectChain_l(sessionId);
1358 if (chain != 0) {
1359 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1360 track->setMainBuffer(chain->inBuffer());
1361 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1362 chain->incTrackCnt();
1363 }
1364
1365 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1366 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1367 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1368 // so ask activity manager to do this on our behalf
1369 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1370 }
1371 }
1372
1373 lStatus = NO_ERROR;
1374
1375Exit:
1376 if (status) {
1377 *status = lStatus;
1378 }
1379 return track;
1380}
1381
1382uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1383{
1384 return latency;
1385}
1386
1387uint32_t AudioFlinger::PlaybackThread::latency() const
1388{
1389 Mutex::Autolock _l(mLock);
1390 return latency_l();
1391}
1392uint32_t AudioFlinger::PlaybackThread::latency_l() const
1393{
1394 if (initCheck() == NO_ERROR) {
1395 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1396 } else {
1397 return 0;
1398 }
1399}
1400
1401void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1402{
1403 Mutex::Autolock _l(mLock);
1404 // Don't apply master volume in SW if our HAL can do it for us.
1405 if (mOutput && mOutput->audioHwDev &&
1406 mOutput->audioHwDev->canSetMasterVolume()) {
1407 mMasterVolume = 1.0;
1408 } else {
1409 mMasterVolume = value;
1410 }
1411}
1412
1413void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1414{
1415 Mutex::Autolock _l(mLock);
1416 // Don't apply master mute in SW if our HAL can do it for us.
1417 if (mOutput && mOutput->audioHwDev &&
1418 mOutput->audioHwDev->canSetMasterMute()) {
1419 mMasterMute = false;
1420 } else {
1421 mMasterMute = muted;
1422 }
1423}
1424
1425void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1426{
1427 Mutex::Autolock _l(mLock);
1428 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001429 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001430}
1431
1432void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1433{
1434 Mutex::Autolock _l(mLock);
1435 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001436 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001437}
1438
1439float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1440{
1441 Mutex::Autolock _l(mLock);
1442 return mStreamTypes[stream].volume;
1443}
1444
1445// addTrack_l() must be called with ThreadBase::mLock held
1446status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1447{
1448 status_t status = ALREADY_EXISTS;
1449
1450 // set retry count for buffer fill
1451 track->mRetryCount = kMaxTrackStartupRetries;
1452 if (mActiveTracks.indexOf(track) < 0) {
1453 // the track is newly added, make sure it fills up all its
1454 // buffers before playing. This is to ensure the client will
1455 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001456 if (!track->isOutputTrack()) {
1457 TrackBase::track_state state = track->mState;
1458 mLock.unlock();
1459 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1460 mLock.lock();
1461 // abort track was stopped/paused while we released the lock
1462 if (state != track->mState) {
1463 if (status == NO_ERROR) {
1464 mLock.unlock();
1465 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1466 mLock.lock();
1467 }
1468 return INVALID_OPERATION;
1469 }
1470 // abort if start is rejected by audio policy manager
1471 if (status != NO_ERROR) {
1472 return PERMISSION_DENIED;
1473 }
1474#ifdef ADD_BATTERY_DATA
1475 // to track the speaker usage
1476 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1477#endif
1478 }
1479
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001480 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001481 track->mResetDone = false;
1482 track->mPresentationCompleteFrames = 0;
1483 mActiveTracks.add(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08001484 mWakeLockUids.add(track->uid());
1485 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001486 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001487 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1488 if (chain != 0) {
1489 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1490 track->sessionId());
1491 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001492 }
1493
1494 status = NO_ERROR;
1495 }
1496
Eric Laurentede6c3b2013-09-19 14:37:46 -07001497 ALOGV("signal playback thread");
1498 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001499
1500 return status;
1501}
1502
Eric Laurentbfb1b832013-01-07 09:53:42 -08001503bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001504{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001505 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001506 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001507 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1508 track->mState = TrackBase::STOPPED;
1509 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001510 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001511 } else if (track->isFastTrack() || track->isOffloaded()) {
1512 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001513 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001514
1515 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001516}
1517
1518void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1519{
1520 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1521 mTracks.remove(track);
1522 deleteTrackName_l(track->name());
1523 // redundant as track is about to be destroyed, for dumpsys only
1524 track->mName = -1;
1525 if (track->isFastTrack()) {
1526 int index = track->mFastIndex;
1527 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1528 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1529 mFastTrackAvailMask |= 1 << index;
1530 // redundant as track is about to be destroyed, for dumpsys only
1531 track->mFastIndex = -1;
1532 }
1533 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1534 if (chain != 0) {
1535 chain->decTrackCnt();
1536 }
1537}
1538
Eric Laurentede6c3b2013-09-19 14:37:46 -07001539void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001540{
1541 // Thread could be blocked waiting for async
1542 // so signal it to handle state changes immediately
1543 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1544 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1545 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001546 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001547}
1548
Eric Laurent81784c32012-11-19 14:55:58 -08001549String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1550{
Eric Laurent81784c32012-11-19 14:55:58 -08001551 Mutex::Autolock _l(mLock);
1552 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001553 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001554 }
1555
Glenn Kastend8ea6992013-07-16 14:17:15 -07001556 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1557 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001558 free(s);
1559 return out_s8;
1560}
1561
1562// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1563void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1564 AudioSystem::OutputDescriptor desc;
1565 void *param2 = NULL;
1566
1567 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1568 param);
1569
1570 switch (event) {
1571 case AudioSystem::OUTPUT_OPENED:
1572 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001573 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001574 desc.samplingRate = mSampleRate;
1575 desc.format = mFormat;
1576 desc.frameCount = mNormalFrameCount; // FIXME see
1577 // AudioFlinger::frameCount(audio_io_handle_t)
1578 desc.latency = latency();
1579 param2 = &desc;
1580 break;
1581
1582 case AudioSystem::STREAM_CONFIG_CHANGED:
1583 param2 = &param;
1584 case AudioSystem::OUTPUT_CLOSED:
1585 default:
1586 break;
1587 }
1588 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1589}
1590
Eric Laurentbfb1b832013-01-07 09:53:42 -08001591void AudioFlinger::PlaybackThread::writeCallback()
1592{
1593 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001594 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001595}
1596
1597void AudioFlinger::PlaybackThread::drainCallback()
1598{
1599 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001600 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001601}
1602
Eric Laurent3b4529e2013-09-05 18:09:19 -07001603void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001604{
1605 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001606 // reject out of sequence requests
1607 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1608 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001609 mWaitWorkCV.signal();
1610 }
1611}
1612
Eric Laurent3b4529e2013-09-05 18:09:19 -07001613void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001614{
1615 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001616 // reject out of sequence requests
1617 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1618 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619 mWaitWorkCV.signal();
1620 }
1621}
1622
1623// static
1624int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1625 void *param,
1626 void *cookie)
1627{
1628 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1629 ALOGV("asyncCallback() event %d", event);
1630 switch (event) {
1631 case STREAM_CBK_EVENT_WRITE_READY:
1632 me->writeCallback();
1633 break;
1634 case STREAM_CBK_EVENT_DRAIN_READY:
1635 me->drainCallback();
1636 break;
1637 default:
1638 ALOGW("asyncCallback() unknown event %d", event);
1639 break;
1640 }
1641 return 0;
1642}
1643
Eric Laurent81784c32012-11-19 14:55:58 -08001644void AudioFlinger::PlaybackThread::readOutputParameters()
1645{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001646 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001647 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1648 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001649 if (!audio_is_output_channel(mChannelMask)) {
1650 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1651 }
1652 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1653 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1654 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1655 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001656 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001657 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001658 if (!audio_is_valid_format(mFormat)) {
1659 LOG_FATAL("HAL format %d not valid for output", mFormat);
1660 }
1661 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1662 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1663 mFormat);
1664 }
Eric Laurent81784c32012-11-19 14:55:58 -08001665 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1666 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1667 if (mFrameCount & 15) {
1668 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1669 mFrameCount);
1670 }
1671
Eric Laurentbfb1b832013-01-07 09:53:42 -08001672 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1673 (mOutput->stream->set_callback != NULL)) {
1674 if (mOutput->stream->set_callback(mOutput->stream,
1675 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1676 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001677 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678 }
1679 }
1680
Eric Laurent81784c32012-11-19 14:55:58 -08001681 // Calculate size of normal mix buffer relative to the HAL output buffer size
1682 double multiplier = 1.0;
1683 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1684 kUseFastMixer == FastMixer_Dynamic)) {
1685 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1686 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1687 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1688 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1689 maxNormalFrameCount = maxNormalFrameCount & ~15;
1690 if (maxNormalFrameCount < minNormalFrameCount) {
1691 maxNormalFrameCount = minNormalFrameCount;
1692 }
1693 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1694 if (multiplier <= 1.0) {
1695 multiplier = 1.0;
1696 } else if (multiplier <= 2.0) {
1697 if (2 * mFrameCount <= maxNormalFrameCount) {
1698 multiplier = 2.0;
1699 } else {
1700 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1701 }
1702 } else {
1703 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1704 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1705 // track, but we sometimes have to do this to satisfy the maximum frame count
1706 // constraint)
1707 // FIXME this rounding up should not be done if no HAL SRC
1708 uint32_t truncMult = (uint32_t) multiplier;
1709 if ((truncMult & 1)) {
1710 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1711 ++truncMult;
1712 }
1713 }
1714 multiplier = (double) truncMult;
1715 }
1716 }
1717 mNormalFrameCount = multiplier * mFrameCount;
1718 // round up to nearest 16 frames to satisfy AudioMixer
1719 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1720 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1721 mNormalFrameCount);
1722
Eric Laurentbfb1b832013-01-07 09:53:42 -08001723 delete[] mAllocMixBuffer;
1724 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1725 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1726 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1727 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001728
1729 // force reconfiguration of effect chains and engines to take new buffer size and audio
1730 // parameters into account
1731 // Note that mLock is not held when readOutputParameters() is called from the constructor
1732 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1733 // matter.
1734 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1735 Vector< sp<EffectChain> > effectChains = mEffectChains;
1736 for (size_t i = 0; i < effectChains.size(); i ++) {
1737 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1738 }
1739}
1740
1741
1742status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1743{
1744 if (halFrames == NULL || dspFrames == NULL) {
1745 return BAD_VALUE;
1746 }
1747 Mutex::Autolock _l(mLock);
1748 if (initCheck() != NO_ERROR) {
1749 return INVALID_OPERATION;
1750 }
1751 size_t framesWritten = mBytesWritten / mFrameSize;
1752 *halFrames = framesWritten;
1753
1754 if (isSuspended()) {
1755 // return an estimation of rendered frames when the output is suspended
1756 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1757 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1758 return NO_ERROR;
1759 } else {
1760 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1761 }
1762}
1763
1764uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1765{
1766 Mutex::Autolock _l(mLock);
1767 uint32_t result = 0;
1768 if (getEffectChain_l(sessionId) != 0) {
1769 result = EFFECT_SESSION;
1770 }
1771
1772 for (size_t i = 0; i < mTracks.size(); ++i) {
1773 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001774 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001775 result |= TRACK_SESSION;
1776 break;
1777 }
1778 }
1779
1780 return result;
1781}
1782
1783uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1784{
1785 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1786 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1787 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1788 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1789 }
1790 for (size_t i = 0; i < mTracks.size(); i++) {
1791 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001792 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001793 return AudioSystem::getStrategyForStream(track->streamType());
1794 }
1795 }
1796 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1797}
1798
1799
1800AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1801{
1802 Mutex::Autolock _l(mLock);
1803 return mOutput;
1804}
1805
1806AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1807{
1808 Mutex::Autolock _l(mLock);
1809 AudioStreamOut *output = mOutput;
1810 mOutput = NULL;
1811 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1812 // must push a NULL and wait for ack
1813 mOutputSink.clear();
1814 mPipeSink.clear();
1815 mNormalSink.clear();
1816 return output;
1817}
1818
1819// this method must always be called either with ThreadBase mLock held or inside the thread loop
1820audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1821{
1822 if (mOutput == NULL) {
1823 return NULL;
1824 }
1825 return &mOutput->stream->common;
1826}
1827
1828uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1829{
1830 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1831}
1832
1833status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1834{
1835 if (!isValidSyncEvent(event)) {
1836 return BAD_VALUE;
1837 }
1838
1839 Mutex::Autolock _l(mLock);
1840
1841 for (size_t i = 0; i < mTracks.size(); ++i) {
1842 sp<Track> track = mTracks[i];
1843 if (event->triggerSession() == track->sessionId()) {
1844 (void) track->setSyncEvent(event);
1845 return NO_ERROR;
1846 }
1847 }
1848
1849 return NAME_NOT_FOUND;
1850}
1851
1852bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1853{
1854 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1855}
1856
1857void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1858 const Vector< sp<Track> >& tracksToRemove)
1859{
1860 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001861 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001862 for (size_t i = 0 ; i < count ; i++) {
1863 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001864 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001865 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001866#ifdef ADD_BATTERY_DATA
1867 // to track the speaker usage
1868 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1869#endif
1870 if (track->isTerminated()) {
1871 AudioSystem::releaseOutput(mId);
1872 }
Eric Laurent81784c32012-11-19 14:55:58 -08001873 }
1874 }
1875 }
Eric Laurent81784c32012-11-19 14:55:58 -08001876}
1877
1878void AudioFlinger::PlaybackThread::checkSilentMode_l()
1879{
1880 if (!mMasterMute) {
1881 char value[PROPERTY_VALUE_MAX];
1882 if (property_get("ro.audio.silent", value, "0") > 0) {
1883 char *endptr;
1884 unsigned long ul = strtoul(value, &endptr, 0);
1885 if (*endptr == '\0' && ul != 0) {
1886 ALOGD("Silence is golden");
1887 // The setprop command will not allow a property to be changed after
1888 // the first time it is set, so we don't have to worry about un-muting.
1889 setMasterMute_l(true);
1890 }
1891 }
1892 }
1893}
1894
1895// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001897{
1898 // FIXME rewrite to reduce number of system calls
1899 mLastWriteTime = systemTime();
1900 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001901 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001902
1903 // If an NBAIO sink is present, use it to write the normal mixer's submix
1904 if (mNormalSink != 0) {
1905#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001906 size_t count = mBytesRemaining >> mBitShift;
1907 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001908 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001909 // update the setpoint when AudioFlinger::mScreenState changes
1910 uint32_t screenState = AudioFlinger::mScreenState;
1911 if (screenState != mScreenState) {
1912 mScreenState = screenState;
1913 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1914 if (pipe != NULL) {
1915 pipe->setAvgFrames((mScreenState & 1) ?
1916 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1917 }
1918 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001920 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001921 if (framesWritten > 0) {
1922 bytesWritten = framesWritten << mBitShift;
1923 } else {
1924 bytesWritten = framesWritten;
1925 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001926 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001927 if (status == NO_ERROR) {
1928 size_t totalFramesWritten = mNormalSink->framesWritten();
1929 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1930 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1931 mLatchDValid = true;
1932 }
1933 }
Eric Laurent81784c32012-11-19 14:55:58 -08001934 // otherwise use the HAL / AudioStreamOut directly
1935 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001936 // Direct output and offload threads
Eric Laurent7e92abe2013-11-22 09:29:56 -08001937 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001939 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1940 mWriteAckSequence += 2;
1941 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001943 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001945 // FIXME We should have an implementation of timestamps for direct output threads.
1946 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent7e92abe2013-11-22 09:29:56 -08001948 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001949 if (mUseAsyncWrite &&
1950 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1951 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001952 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001954 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001955 }
Eric Laurent81784c32012-11-19 14:55:58 -08001956 }
1957
Eric Laurent81784c32012-11-19 14:55:58 -08001958 mNumWrites++;
1959 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001960 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001961 return bytesWritten;
1962}
1963
1964void AudioFlinger::PlaybackThread::threadLoop_drain()
1965{
1966 if (mOutput->stream->drain) {
1967 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1968 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001969 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1970 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001972 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 }
1974 mOutput->stream->drain(mOutput->stream,
1975 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1976 : AUDIO_DRAIN_ALL);
1977 }
1978}
1979
1980void AudioFlinger::PlaybackThread::threadLoop_exit()
1981{
1982 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001983}
1984
1985/*
1986The derived values that are cached:
1987 - mixBufferSize from frame count * frame size
1988 - activeSleepTime from activeSleepTimeUs()
1989 - idleSleepTime from idleSleepTimeUs()
1990 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1991 - maxPeriod from frame count and sample rate (MIXER only)
1992
1993The parameters that affect these derived values are:
1994 - frame count
1995 - frame size
1996 - sample rate
1997 - device type: A2DP or not
1998 - device latency
1999 - format: PCM or not
2000 - active sleep time
2001 - idle sleep time
2002*/
2003
2004void AudioFlinger::PlaybackThread::cacheParameters_l()
2005{
2006 mixBufferSize = mNormalFrameCount * mFrameSize;
2007 activeSleepTime = activeSleepTimeUs();
2008 idleSleepTime = idleSleepTimeUs();
2009}
2010
2011void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2012{
Glenn Kasten7c027242012-12-26 14:43:16 -08002013 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002014 this, streamType, mTracks.size());
2015 Mutex::Autolock _l(mLock);
2016
2017 size_t size = mTracks.size();
2018 for (size_t i = 0; i < size; i++) {
2019 sp<Track> t = mTracks[i];
2020 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002021 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023 }
2024}
2025
2026status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2027{
2028 int session = chain->sessionId();
2029 int16_t *buffer = mMixBuffer;
2030 bool ownsBuffer = false;
2031
2032 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2033 if (session > 0) {
2034 // Only one effect chain can be present in direct output thread and it uses
2035 // the mix buffer as input
2036 if (mType != DIRECT) {
2037 size_t numSamples = mNormalFrameCount * mChannelCount;
2038 buffer = new int16_t[numSamples];
2039 memset(buffer, 0, numSamples * sizeof(int16_t));
2040 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2041 ownsBuffer = true;
2042 }
2043
2044 // Attach all tracks with same session ID to this chain.
2045 for (size_t i = 0; i < mTracks.size(); ++i) {
2046 sp<Track> track = mTracks[i];
2047 if (session == track->sessionId()) {
2048 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2049 buffer);
2050 track->setMainBuffer(buffer);
2051 chain->incTrackCnt();
2052 }
2053 }
2054
2055 // indicate all active tracks in the chain
2056 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2057 sp<Track> track = mActiveTracks[i].promote();
2058 if (track == 0) {
2059 continue;
2060 }
2061 if (session == track->sessionId()) {
2062 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2063 chain->incActiveTrackCnt();
2064 }
2065 }
2066 }
2067
2068 chain->setInBuffer(buffer, ownsBuffer);
2069 chain->setOutBuffer(mMixBuffer);
2070 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2071 // chains list in order to be processed last as it contains output stage effects
2072 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2073 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2074 // after track specific effects and before output stage
2075 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2076 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2077 // Effect chain for other sessions are inserted at beginning of effect
2078 // chains list to be processed before output mix effects. Relative order between other
2079 // sessions is not important
2080 size_t size = mEffectChains.size();
2081 size_t i = 0;
2082 for (i = 0; i < size; i++) {
2083 if (mEffectChains[i]->sessionId() < session) {
2084 break;
2085 }
2086 }
2087 mEffectChains.insertAt(chain, i);
2088 checkSuspendOnAddEffectChain_l(chain);
2089
2090 return NO_ERROR;
2091}
2092
2093size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2094{
2095 int session = chain->sessionId();
2096
2097 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2098
2099 for (size_t i = 0; i < mEffectChains.size(); i++) {
2100 if (chain == mEffectChains[i]) {
2101 mEffectChains.removeAt(i);
2102 // detach all active tracks from the chain
2103 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2104 sp<Track> track = mActiveTracks[i].promote();
2105 if (track == 0) {
2106 continue;
2107 }
2108 if (session == track->sessionId()) {
2109 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2110 chain.get(), session);
2111 chain->decActiveTrackCnt();
2112 }
2113 }
2114
2115 // detach all tracks with same session ID from this chain
2116 for (size_t i = 0; i < mTracks.size(); ++i) {
2117 sp<Track> track = mTracks[i];
2118 if (session == track->sessionId()) {
2119 track->setMainBuffer(mMixBuffer);
2120 chain->decTrackCnt();
2121 }
2122 }
2123 break;
2124 }
2125 }
2126 return mEffectChains.size();
2127}
2128
2129status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2130 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2131{
2132 Mutex::Autolock _l(mLock);
2133 return attachAuxEffect_l(track, EffectId);
2134}
2135
2136status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2137 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2138{
2139 status_t status = NO_ERROR;
2140
2141 if (EffectId == 0) {
2142 track->setAuxBuffer(0, NULL);
2143 } else {
2144 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2145 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2146 if (effect != 0) {
2147 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2148 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2149 } else {
2150 status = INVALID_OPERATION;
2151 }
2152 } else {
2153 status = BAD_VALUE;
2154 }
2155 }
2156 return status;
2157}
2158
2159void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2160{
2161 for (size_t i = 0; i < mTracks.size(); ++i) {
2162 sp<Track> track = mTracks[i];
2163 if (track->auxEffectId() == effectId) {
2164 attachAuxEffect_l(track, 0);
2165 }
2166 }
2167}
2168
2169bool AudioFlinger::PlaybackThread::threadLoop()
2170{
2171 Vector< sp<Track> > tracksToRemove;
2172
2173 standbyTime = systemTime();
2174
2175 // MIXER
2176 nsecs_t lastWarning = 0;
2177
2178 // DUPLICATING
2179 // FIXME could this be made local to while loop?
2180 writeFrames = 0;
2181
Marco Nelissen9cae2172013-01-14 14:12:05 -08002182 int lastGeneration = 0;
2183
Eric Laurent81784c32012-11-19 14:55:58 -08002184 cacheParameters_l();
2185 sleepTime = idleSleepTime;
2186
2187 if (mType == MIXER) {
2188 sleepTimeShift = 0;
2189 }
2190
2191 CpuStats cpuStats;
2192 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2193
2194 acquireWakeLock();
2195
Glenn Kasten9e58b552013-01-18 15:09:48 -08002196 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2197 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2198 // and then that string will be logged at the next convenient opportunity.
2199 const char *logString = NULL;
2200
Eric Laurent664539d2013-09-23 18:24:31 -07002201 checkSilentMode_l();
2202
Eric Laurent81784c32012-11-19 14:55:58 -08002203 while (!exitPending())
2204 {
2205 cpuStats.sample(myName);
2206
2207 Vector< sp<EffectChain> > effectChains;
2208
2209 processConfigEvents();
2210
2211 { // scope for mLock
2212
2213 Mutex::Autolock _l(mLock);
2214
Glenn Kasten9e58b552013-01-18 15:09:48 -08002215 if (logString != NULL) {
2216 mNBLogWriter->logTimestamp();
2217 mNBLogWriter->log(logString);
2218 logString = NULL;
2219 }
2220
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002221 if (mLatchDValid) {
2222 mLatchQ = mLatchD;
2223 mLatchDValid = false;
2224 mLatchQValid = true;
2225 }
2226
Eric Laurent81784c32012-11-19 14:55:58 -08002227 if (checkForNewParameters_l()) {
2228 cacheParameters_l();
2229 }
2230
2231 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002232 if (mSignalPending) {
2233 // A signal was raised while we were unlocked
2234 mSignalPending = false;
2235 } else if (waitingAsyncCallback_l()) {
2236 if (exitPending()) {
2237 break;
2238 }
2239 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002240 mWakeLockUids.clear();
2241 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242 ALOGV("wait async completion");
2243 mWaitWorkCV.wait(mLock);
2244 ALOGV("async completion/wake");
2245 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002246 standbyTime = systemTime() + standbyDelay;
2247 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002248
2249 continue;
2250 }
2251 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252 isSuspended()) {
2253 // put audio hardware into standby after short delay
2254 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002255
2256 threadLoop_standby();
2257
2258 mStandby = true;
2259 }
2260
2261 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2262 // we're about to wait, flush the binder command buffer
2263 IPCThreadState::self()->flushCommands();
2264
2265 clearOutputTracks();
2266
2267 if (exitPending()) {
2268 break;
2269 }
2270
2271 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002272 mWakeLockUids.clear();
2273 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002274 // wait until we have something to do...
2275 ALOGV("%s going to sleep", myName.string());
2276 mWaitWorkCV.wait(mLock);
2277 ALOGV("%s waking up", myName.string());
2278 acquireWakeLock_l();
2279
2280 mMixerStatus = MIXER_IDLE;
2281 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2282 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002284 checkSilentMode_l();
2285
2286 standbyTime = systemTime() + standbyDelay;
2287 sleepTime = idleSleepTime;
2288 if (mType == MIXER) {
2289 sleepTimeShift = 0;
2290 }
2291
2292 continue;
2293 }
2294 }
Eric Laurent81784c32012-11-19 14:55:58 -08002295 // mMixerStatusIgnoringFastTracks is also updated internally
2296 mMixerStatus = prepareTracks_l(&tracksToRemove);
2297
Marco Nelissen9cae2172013-01-14 14:12:05 -08002298 // compare with previously applied list
2299 if (lastGeneration != mActiveTracksGeneration) {
2300 // update wakelock
2301 updateWakeLockUids_l(mWakeLockUids);
2302 lastGeneration = mActiveTracksGeneration;
2303 }
2304
Eric Laurent81784c32012-11-19 14:55:58 -08002305 // prevent any changes in effect chain list and in each effect chain
2306 // during mixing and effect process as the audio buffers could be deleted
2307 // or modified if an effect is created or deleted
2308 lockEffectChains_l(effectChains);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002309 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002310
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311 if (mBytesRemaining == 0) {
2312 mCurrentWriteLength = 0;
2313 if (mMixerStatus == MIXER_TRACKS_READY) {
2314 // threadLoop_mix() sets mCurrentWriteLength
2315 threadLoop_mix();
2316 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2317 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2318 // threadLoop_sleepTime sets sleepTime to 0 if data
2319 // must be written to HAL
2320 threadLoop_sleepTime();
2321 if (sleepTime == 0) {
2322 mCurrentWriteLength = mixBufferSize;
2323 }
2324 }
2325 mBytesRemaining = mCurrentWriteLength;
2326 if (isSuspended()) {
2327 sleepTime = suspendSleepTimeUs();
2328 // simulate write to HAL when suspended
2329 mBytesWritten += mixBufferSize;
2330 mBytesRemaining = 0;
2331 }
Eric Laurent81784c32012-11-19 14:55:58 -08002332
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002334 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 for (size_t i = 0; i < effectChains.size(); i ++) {
2336 effectChains[i]->process_l();
2337 }
Eric Laurent81784c32012-11-19 14:55:58 -08002338 }
2339 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002340 // Process effect chains for offloaded thread even if no audio
2341 // was read from audio track: process only updates effect state
2342 // and thus does have to be synchronized with audio writes but may have
2343 // to be called while waiting for async write callback
2344 if (mType == OFFLOAD) {
2345 for (size_t i = 0; i < effectChains.size(); i ++) {
2346 effectChains[i]->process_l();
2347 }
2348 }
Eric Laurent81784c32012-11-19 14:55:58 -08002349
2350 // enable changes in effect chain
2351 unlockEffectChains(effectChains);
2352
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 if (!waitingAsyncCallback()) {
2354 // sleepTime == 0 means we must write to audio hardware
2355 if (sleepTime == 0) {
2356 if (mBytesRemaining) {
2357 ssize_t ret = threadLoop_write();
2358 if (ret < 0) {
2359 mBytesRemaining = 0;
2360 } else {
2361 mBytesWritten += ret;
2362 mBytesRemaining -= ret;
2363 }
2364 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2365 (mMixerStatus == MIXER_DRAIN_ALL)) {
2366 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002367 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368if (mType == MIXER) {
2369 // write blocked detection
2370 nsecs_t now = systemTime();
2371 nsecs_t delta = now - mLastWriteTime;
2372 if (!mStandby && delta > maxPeriod) {
2373 mNumDelayedWrites++;
2374 if ((now - lastWarning) > kWarningThrottleNs) {
2375 ATRACE_NAME("underrun");
2376 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2377 ns2ms(delta), mNumDelayedWrites, this);
2378 lastWarning = now;
2379 }
2380 }
Eric Laurent81784c32012-11-19 14:55:58 -08002381}
2382
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 } else {
2384 usleep(sleepTime);
2385 }
Eric Laurent81784c32012-11-19 14:55:58 -08002386 }
2387
2388 // Finally let go of removed track(s), without the lock held
2389 // since we can't guarantee the destructors won't acquire that
2390 // same lock. This will also mutate and push a new fast mixer state.
2391 threadLoop_removeTracks(tracksToRemove);
2392 tracksToRemove.clear();
2393
2394 // FIXME I don't understand the need for this here;
2395 // it was in the original code but maybe the
2396 // assignment in saveOutputTracks() makes this unnecessary?
2397 clearOutputTracks();
2398
2399 // Effect chains will be actually deleted here if they were removed from
2400 // mEffectChains list during mixing or effects processing
2401 effectChains.clear();
2402
2403 // FIXME Note that the above .clear() is no longer necessary since effectChains
2404 // is now local to this block, but will keep it for now (at least until merge done).
2405 }
2406
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 threadLoop_exit();
2408
Eric Laurent81784c32012-11-19 14:55:58 -08002409 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002411 // put output stream into standby mode
2412 if (!mStandby) {
2413 mOutput->stream->common.standby(&mOutput->stream->common);
2414 }
2415 }
2416
2417 releaseWakeLock();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002418 mWakeLockUids.clear();
2419 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002420
2421 ALOGV("Thread %p type %d exiting", this, mType);
2422 return false;
2423}
2424
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425// removeTracks_l() must be called with ThreadBase::mLock held
2426void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2427{
2428 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002429 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002430 for (size_t i=0 ; i<count ; i++) {
2431 const sp<Track>& track = tracksToRemove.itemAt(i);
2432 mActiveTracks.remove(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002433 mWakeLockUids.remove(track->uid());
2434 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002435 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2436 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2437 if (chain != 0) {
2438 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2439 track->sessionId());
2440 chain->decActiveTrackCnt();
2441 }
2442 if (track->isTerminated()) {
2443 removeTrack_l(track);
2444 }
2445 }
2446 }
2447
2448}
Eric Laurent81784c32012-11-19 14:55:58 -08002449
Eric Laurentaccc1472013-09-20 09:36:34 -07002450status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2451{
2452 if (mNormalSink != 0) {
2453 return mNormalSink->getTimestamp(timestamp);
2454 }
2455 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2456 uint64_t position64;
2457 int ret = mOutput->stream->get_presentation_position(
2458 mOutput->stream, &position64, &timestamp.mTime);
2459 if (ret == 0) {
2460 timestamp.mPosition = (uint32_t)position64;
2461 return NO_ERROR;
2462 }
2463 }
2464 return INVALID_OPERATION;
2465}
Eric Laurent81784c32012-11-19 14:55:58 -08002466// ----------------------------------------------------------------------------
2467
2468AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2469 audio_io_handle_t id, audio_devices_t device, type_t type)
2470 : PlaybackThread(audioFlinger, output, id, device, type),
2471 // mAudioMixer below
2472 // mFastMixer below
2473 mFastMixerFutex(0)
2474 // mOutputSink below
2475 // mPipeSink below
2476 // mNormalSink below
2477{
2478 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002479 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002480 "mFrameCount=%d, mNormalFrameCount=%d",
2481 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2482 mNormalFrameCount);
2483 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2484
2485 // FIXME - Current mixer implementation only supports stereo output
2486 if (mChannelCount != FCC_2) {
2487 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2488 }
2489
2490 // create an NBAIO sink for the HAL output stream, and negotiate
2491 mOutputSink = new AudioStreamOutSink(output->stream);
2492 size_t numCounterOffers = 0;
2493 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2494 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2495 ALOG_ASSERT(index == 0);
2496
2497 // initialize fast mixer depending on configuration
2498 bool initFastMixer;
2499 switch (kUseFastMixer) {
2500 case FastMixer_Never:
2501 initFastMixer = false;
2502 break;
2503 case FastMixer_Always:
2504 initFastMixer = true;
2505 break;
2506 case FastMixer_Static:
2507 case FastMixer_Dynamic:
2508 initFastMixer = mFrameCount < mNormalFrameCount;
2509 break;
2510 }
2511 if (initFastMixer) {
2512
2513 // create a MonoPipe to connect our submix to FastMixer
2514 NBAIO_Format format = mOutputSink->format();
2515 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2516 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2517 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2518 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2519 const NBAIO_Format offers[1] = {format};
2520 size_t numCounterOffers = 0;
2521 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2522 ALOG_ASSERT(index == 0);
2523 monoPipe->setAvgFrames((mScreenState & 1) ?
2524 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2525 mPipeSink = monoPipe;
2526
Glenn Kasten46909e72013-02-26 09:20:22 -08002527#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002528 if (mTeeSinkOutputEnabled) {
2529 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2530 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2531 numCounterOffers = 0;
2532 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2533 ALOG_ASSERT(index == 0);
2534 mTeeSink = teeSink;
2535 PipeReader *teeSource = new PipeReader(*teeSink);
2536 numCounterOffers = 0;
2537 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2538 ALOG_ASSERT(index == 0);
2539 mTeeSource = teeSource;
2540 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002541#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002542
2543 // create fast mixer and configure it initially with just one fast track for our submix
2544 mFastMixer = new FastMixer();
2545 FastMixerStateQueue *sq = mFastMixer->sq();
2546#ifdef STATE_QUEUE_DUMP
2547 sq->setObserverDump(&mStateQueueObserverDump);
2548 sq->setMutatorDump(&mStateQueueMutatorDump);
2549#endif
2550 FastMixerState *state = sq->begin();
2551 FastTrack *fastTrack = &state->mFastTracks[0];
2552 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2553 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2554 fastTrack->mVolumeProvider = NULL;
2555 fastTrack->mGeneration++;
2556 state->mFastTracksGen++;
2557 state->mTrackMask = 1;
2558 // fast mixer will use the HAL output sink
2559 state->mOutputSink = mOutputSink.get();
2560 state->mOutputSinkGen++;
2561 state->mFrameCount = mFrameCount;
2562 state->mCommand = FastMixerState::COLD_IDLE;
2563 // already done in constructor initialization list
2564 //mFastMixerFutex = 0;
2565 state->mColdFutexAddr = &mFastMixerFutex;
2566 state->mColdGen++;
2567 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002568#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002569 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002570#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002571 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2572 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002573 sq->end();
2574 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2575
2576 // start the fast mixer
2577 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2578 pid_t tid = mFastMixer->getTid();
2579 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2580 if (err != 0) {
2581 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2582 kPriorityFastMixer, getpid_cached, tid, err);
2583 }
2584
2585#ifdef AUDIO_WATCHDOG
2586 // create and start the watchdog
2587 mAudioWatchdog = new AudioWatchdog();
2588 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2589 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2590 tid = mAudioWatchdog->getTid();
2591 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2592 if (err != 0) {
2593 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2594 kPriorityFastMixer, getpid_cached, tid, err);
2595 }
2596#endif
2597
2598 } else {
2599 mFastMixer = NULL;
2600 }
2601
2602 switch (kUseFastMixer) {
2603 case FastMixer_Never:
2604 case FastMixer_Dynamic:
2605 mNormalSink = mOutputSink;
2606 break;
2607 case FastMixer_Always:
2608 mNormalSink = mPipeSink;
2609 break;
2610 case FastMixer_Static:
2611 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2612 break;
2613 }
2614}
2615
2616AudioFlinger::MixerThread::~MixerThread()
2617{
2618 if (mFastMixer != NULL) {
2619 FastMixerStateQueue *sq = mFastMixer->sq();
2620 FastMixerState *state = sq->begin();
2621 if (state->mCommand == FastMixerState::COLD_IDLE) {
2622 int32_t old = android_atomic_inc(&mFastMixerFutex);
2623 if (old == -1) {
2624 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2625 }
2626 }
2627 state->mCommand = FastMixerState::EXIT;
2628 sq->end();
2629 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2630 mFastMixer->join();
2631 // Though the fast mixer thread has exited, it's state queue is still valid.
2632 // We'll use that extract the final state which contains one remaining fast track
2633 // corresponding to our sub-mix.
2634 state = sq->begin();
2635 ALOG_ASSERT(state->mTrackMask == 1);
2636 FastTrack *fastTrack = &state->mFastTracks[0];
2637 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2638 delete fastTrack->mBufferProvider;
2639 sq->end(false /*didModify*/);
2640 delete mFastMixer;
2641#ifdef AUDIO_WATCHDOG
2642 if (mAudioWatchdog != 0) {
2643 mAudioWatchdog->requestExit();
2644 mAudioWatchdog->requestExitAndWait();
2645 mAudioWatchdog.clear();
2646 }
2647#endif
2648 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002649 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002650 delete mAudioMixer;
2651}
2652
2653
2654uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2655{
2656 if (mFastMixer != NULL) {
2657 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2658 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2659 }
2660 return latency;
2661}
2662
2663
2664void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2665{
2666 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2667}
2668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002670{
2671 // FIXME we should only do one push per cycle; confirm this is true
2672 // Start the fast mixer if it's not already running
2673 if (mFastMixer != NULL) {
2674 FastMixerStateQueue *sq = mFastMixer->sq();
2675 FastMixerState *state = sq->begin();
2676 if (state->mCommand != FastMixerState::MIX_WRITE &&
2677 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2678 if (state->mCommand == FastMixerState::COLD_IDLE) {
2679 int32_t old = android_atomic_inc(&mFastMixerFutex);
2680 if (old == -1) {
2681 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2682 }
2683#ifdef AUDIO_WATCHDOG
2684 if (mAudioWatchdog != 0) {
2685 mAudioWatchdog->resume();
2686 }
2687#endif
2688 }
2689 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002690 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2691 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002692 sq->end();
2693 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2694 if (kUseFastMixer == FastMixer_Dynamic) {
2695 mNormalSink = mPipeSink;
2696 }
2697 } else {
2698 sq->end(false /*didModify*/);
2699 }
2700 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002701 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002702}
2703
2704void AudioFlinger::MixerThread::threadLoop_standby()
2705{
2706 // Idle the fast mixer if it's currently running
2707 if (mFastMixer != NULL) {
2708 FastMixerStateQueue *sq = mFastMixer->sq();
2709 FastMixerState *state = sq->begin();
2710 if (!(state->mCommand & FastMixerState::IDLE)) {
2711 state->mCommand = FastMixerState::COLD_IDLE;
2712 state->mColdFutexAddr = &mFastMixerFutex;
2713 state->mColdGen++;
2714 mFastMixerFutex = 0;
2715 sq->end();
2716 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2717 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2718 if (kUseFastMixer == FastMixer_Dynamic) {
2719 mNormalSink = mOutputSink;
2720 }
2721#ifdef AUDIO_WATCHDOG
2722 if (mAudioWatchdog != 0) {
2723 mAudioWatchdog->pause();
2724 }
2725#endif
2726 } else {
2727 sq->end(false /*didModify*/);
2728 }
2729 }
2730 PlaybackThread::threadLoop_standby();
2731}
2732
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733// Empty implementation for standard mixer
2734// Overridden for offloaded playback
2735void AudioFlinger::PlaybackThread::flushOutput_l()
2736{
2737}
2738
2739bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2740{
2741 return false;
2742}
2743
2744bool AudioFlinger::PlaybackThread::shouldStandby_l()
2745{
2746 return !mStandby;
2747}
2748
2749bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2750{
2751 Mutex::Autolock _l(mLock);
2752 return waitingAsyncCallback_l();
2753}
2754
Eric Laurent81784c32012-11-19 14:55:58 -08002755// shared by MIXER and DIRECT, overridden by DUPLICATING
2756void AudioFlinger::PlaybackThread::threadLoop_standby()
2757{
2758 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2759 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002761 // discard any pending drain or write ack by incrementing sequence
2762 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2763 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002764 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002765 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2766 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 }
Eric Laurent81784c32012-11-19 14:55:58 -08002768}
2769
2770void AudioFlinger::MixerThread::threadLoop_mix()
2771{
2772 // obtain the presentation timestamp of the next output buffer
2773 int64_t pts;
2774 status_t status = INVALID_OPERATION;
2775
2776 if (mNormalSink != 0) {
2777 status = mNormalSink->getNextWriteTimestamp(&pts);
2778 } else {
2779 status = mOutputSink->getNextWriteTimestamp(&pts);
2780 }
2781
2782 if (status != NO_ERROR) {
2783 pts = AudioBufferProvider::kInvalidPTS;
2784 }
2785
2786 // mix buffers...
2787 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002789 // increase sleep time progressively when application underrun condition clears.
2790 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2791 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2792 // such that we would underrun the audio HAL.
2793 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2794 sleepTimeShift--;
2795 }
2796 sleepTime = 0;
2797 standbyTime = systemTime() + standbyDelay;
2798 //TODO: delay standby when effects have a tail
2799}
2800
2801void AudioFlinger::MixerThread::threadLoop_sleepTime()
2802{
2803 // If no tracks are ready, sleep once for the duration of an output
2804 // buffer size, then write 0s to the output
2805 if (sleepTime == 0) {
2806 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2807 sleepTime = activeSleepTime >> sleepTimeShift;
2808 if (sleepTime < kMinThreadSleepTimeUs) {
2809 sleepTime = kMinThreadSleepTimeUs;
2810 }
2811 // reduce sleep time in case of consecutive application underruns to avoid
2812 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2813 // duration we would end up writing less data than needed by the audio HAL if
2814 // the condition persists.
2815 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2816 sleepTimeShift++;
2817 }
2818 } else {
2819 sleepTime = idleSleepTime;
2820 }
2821 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2822 memset (mMixBuffer, 0, mixBufferSize);
2823 sleepTime = 0;
2824 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2825 "anticipated start");
2826 }
2827 // TODO add standby time extension fct of effect tail
2828}
2829
2830// prepareTracks_l() must be called with ThreadBase::mLock held
2831AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2832 Vector< sp<Track> > *tracksToRemove)
2833{
2834
2835 mixer_state mixerStatus = MIXER_IDLE;
2836 // find out which tracks need to be processed
2837 size_t count = mActiveTracks.size();
2838 size_t mixedTracks = 0;
2839 size_t tracksWithEffect = 0;
2840 // counts only _active_ fast tracks
2841 size_t fastTracks = 0;
2842 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2843
2844 float masterVolume = mMasterVolume;
2845 bool masterMute = mMasterMute;
2846
2847 if (masterMute) {
2848 masterVolume = 0;
2849 }
2850 // Delegate master volume control to effect in output mix effect chain if needed
2851 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2852 if (chain != 0) {
2853 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2854 chain->setVolume_l(&v, &v);
2855 masterVolume = (float)((v + (1 << 23)) >> 24);
2856 chain.clear();
2857 }
2858
2859 // prepare a new state to push
2860 FastMixerStateQueue *sq = NULL;
2861 FastMixerState *state = NULL;
2862 bool didModify = false;
2863 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2864 if (mFastMixer != NULL) {
2865 sq = mFastMixer->sq();
2866 state = sq->begin();
2867 }
2868
2869 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002870 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002871 if (t == 0) {
2872 continue;
2873 }
2874
2875 // this const just means the local variable doesn't change
2876 Track* const track = t.get();
2877
2878 // process fast tracks
2879 if (track->isFastTrack()) {
2880
2881 // It's theoretically possible (though unlikely) for a fast track to be created
2882 // and then removed within the same normal mix cycle. This is not a problem, as
2883 // the track never becomes active so it's fast mixer slot is never touched.
2884 // The converse, of removing an (active) track and then creating a new track
2885 // at the identical fast mixer slot within the same normal mix cycle,
2886 // is impossible because the slot isn't marked available until the end of each cycle.
2887 int j = track->mFastIndex;
2888 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2889 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2890 FastTrack *fastTrack = &state->mFastTracks[j];
2891
2892 // Determine whether the track is currently in underrun condition,
2893 // and whether it had a recent underrun.
2894 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2895 FastTrackUnderruns underruns = ftDump->mUnderruns;
2896 uint32_t recentFull = (underruns.mBitFields.mFull -
2897 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2898 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2899 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2900 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2901 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2902 uint32_t recentUnderruns = recentPartial + recentEmpty;
2903 track->mObservedUnderruns = underruns;
2904 // don't count underruns that occur while stopping or pausing
2905 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002906 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2907 recentUnderruns > 0) {
2908 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2909 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002910 }
2911
2912 // This is similar to the state machine for normal tracks,
2913 // with a few modifications for fast tracks.
2914 bool isActive = true;
2915 switch (track->mState) {
2916 case TrackBase::STOPPING_1:
2917 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002919 track->mState = TrackBase::STOPPING_2;
2920 }
2921 break;
2922 case TrackBase::PAUSING:
2923 // ramp down is not yet implemented
2924 track->setPaused();
2925 break;
2926 case TrackBase::RESUMING:
2927 // ramp up is not yet implemented
2928 track->mState = TrackBase::ACTIVE;
2929 break;
2930 case TrackBase::ACTIVE:
2931 if (recentFull > 0 || recentPartial > 0) {
2932 // track has provided at least some frames recently: reset retry count
2933 track->mRetryCount = kMaxTrackRetries;
2934 }
2935 if (recentUnderruns == 0) {
2936 // no recent underruns: stay active
2937 break;
2938 }
2939 // there has recently been an underrun of some kind
2940 if (track->sharedBuffer() == 0) {
2941 // were any of the recent underruns "empty" (no frames available)?
2942 if (recentEmpty == 0) {
2943 // no, then ignore the partial underruns as they are allowed indefinitely
2944 break;
2945 }
2946 // there has recently been an "empty" underrun: decrement the retry counter
2947 if (--(track->mRetryCount) > 0) {
2948 break;
2949 }
2950 // indicate to client process that the track was disabled because of underrun;
2951 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002952 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002953 // remove from active list, but state remains ACTIVE [confusing but true]
2954 isActive = false;
2955 break;
2956 }
2957 // fall through
2958 case TrackBase::STOPPING_2:
2959 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002960 case TrackBase::STOPPED:
2961 case TrackBase::FLUSHED: // flush() while active
2962 // Check for presentation complete if track is inactive
2963 // We have consumed all the buffers of this track.
2964 // This would be incomplete if we auto-paused on underrun
2965 {
2966 size_t audioHALFrames =
2967 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2968 size_t framesWritten = mBytesWritten / mFrameSize;
2969 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2970 // track stays in active list until presentation is complete
2971 break;
2972 }
2973 }
2974 if (track->isStopping_2()) {
2975 track->mState = TrackBase::STOPPED;
2976 }
2977 if (track->isStopped()) {
2978 // Can't reset directly, as fast mixer is still polling this track
2979 // track->reset();
2980 // So instead mark this track as needing to be reset after push with ack
2981 resetMask |= 1 << i;
2982 }
2983 isActive = false;
2984 break;
2985 case TrackBase::IDLE:
2986 default:
2987 LOG_FATAL("unexpected track state %d", track->mState);
2988 }
2989
2990 if (isActive) {
2991 // was it previously inactive?
2992 if (!(state->mTrackMask & (1 << j))) {
2993 ExtendedAudioBufferProvider *eabp = track;
2994 VolumeProvider *vp = track;
2995 fastTrack->mBufferProvider = eabp;
2996 fastTrack->mVolumeProvider = vp;
2997 fastTrack->mSampleRate = track->mSampleRate;
2998 fastTrack->mChannelMask = track->mChannelMask;
2999 fastTrack->mGeneration++;
3000 state->mTrackMask |= 1 << j;
3001 didModify = true;
3002 // no acknowledgement required for newly active tracks
3003 }
3004 // cache the combined master volume and stream type volume for fast mixer; this
3005 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003006 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003007 ++fastTracks;
3008 } else {
3009 // was it previously active?
3010 if (state->mTrackMask & (1 << j)) {
3011 fastTrack->mBufferProvider = NULL;
3012 fastTrack->mGeneration++;
3013 state->mTrackMask &= ~(1 << j);
3014 didModify = true;
3015 // If any fast tracks were removed, we must wait for acknowledgement
3016 // because we're about to decrement the last sp<> on those tracks.
3017 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3018 } else {
3019 LOG_FATAL("fast track %d should have been active", j);
3020 }
3021 tracksToRemove->add(track);
3022 // Avoids a misleading display in dumpsys
3023 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3024 }
3025 continue;
3026 }
3027
3028 { // local variable scope to avoid goto warning
3029
3030 audio_track_cblk_t* cblk = track->cblk();
3031
3032 // The first time a track is added we wait
3033 // for all its buffers to be filled before processing it
3034 int name = track->name();
3035 // make sure that we have enough frames to mix one full buffer.
3036 // enforce this condition only once to enable draining the buffer in case the client
3037 // app does not call stop() and relies on underrun to stop:
3038 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3039 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003040 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003041 uint32_t sr = track->sampleRate();
3042 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003043 desiredFrames = mNormalFrameCount;
3044 } else {
3045 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003046 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003047 // add frames already consumed but not yet released by the resampler
3048 // because cblk->framesReady() will include these frames
3049 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3050 // the minimum track buffer size is normally twice the number of frames necessary
3051 // to fill one buffer and the resampler should not leave more than one buffer worth
3052 // of unreleased frames after each pass, but just in case...
3053 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3054 }
Eric Laurent81784c32012-11-19 14:55:58 -08003055 uint32_t minFrames = 1;
3056 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3057 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003058 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003059 }
Eric Laurent281dd4e2013-12-20 17:36:01 -08003060
3061 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003062 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003063 !track->isPaused() && !track->isTerminated())
3064 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003065 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003066
3067 mixedTracks++;
3068
3069 // track->mainBuffer() != mMixBuffer means there is an effect chain
3070 // connected to the track
3071 chain.clear();
3072 if (track->mainBuffer() != mMixBuffer) {
3073 chain = getEffectChain_l(track->sessionId());
3074 // Delegate volume control to effect in track effect chain if needed
3075 if (chain != 0) {
3076 tracksWithEffect++;
3077 } else {
3078 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3079 "session %d",
3080 name, track->sessionId());
3081 }
3082 }
3083
3084
3085 int param = AudioMixer::VOLUME;
3086 if (track->mFillingUpStatus == Track::FS_FILLED) {
3087 // no ramp for the first volume setting
3088 track->mFillingUpStatus = Track::FS_ACTIVE;
3089 if (track->mState == TrackBase::RESUMING) {
3090 track->mState = TrackBase::ACTIVE;
3091 param = AudioMixer::RAMP_VOLUME;
3092 }
3093 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003094 // FIXME should not make a decision based on mServer
3095 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003096 // If the track is stopped before the first frame was mixed,
3097 // do not apply ramp
3098 param = AudioMixer::RAMP_VOLUME;
3099 }
3100
3101 // compute volume for this track
3102 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003103 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003104 vl = vr = va = 0;
3105 if (track->isPausing()) {
3106 track->setPaused();
3107 }
3108 } else {
3109
3110 // read original volumes with volume control
3111 float typeVolume = mStreamTypes[track->streamType()].volume;
3112 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003113 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003114 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003115 vl = vlr & 0xFFFF;
3116 vr = vlr >> 16;
3117 // track volumes come from shared memory, so can't be trusted and must be clamped
3118 if (vl > MAX_GAIN_INT) {
3119 ALOGV("Track left volume out of range: %04X", vl);
3120 vl = MAX_GAIN_INT;
3121 }
3122 if (vr > MAX_GAIN_INT) {
3123 ALOGV("Track right volume out of range: %04X", vr);
3124 vr = MAX_GAIN_INT;
3125 }
3126 // now apply the master volume and stream type volume
3127 vl = (uint32_t)(v * vl) << 12;
3128 vr = (uint32_t)(v * vr) << 12;
3129 // assuming master volume and stream type volume each go up to 1.0,
3130 // vl and vr are now in 8.24 format
3131
Glenn Kastene3aa6592012-12-04 12:22:46 -08003132 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003133 // send level comes from shared memory and so may be corrupt
3134 if (sendLevel > MAX_GAIN_INT) {
3135 ALOGV("Track send level out of range: %04X", sendLevel);
3136 sendLevel = MAX_GAIN_INT;
3137 }
3138 va = (uint32_t)(v * sendLevel);
3139 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003140
Eric Laurent81784c32012-11-19 14:55:58 -08003141 // Delegate volume control to effect in track effect chain if needed
3142 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3143 // Do not ramp volume if volume is controlled by effect
3144 param = AudioMixer::VOLUME;
3145 track->mHasVolumeController = true;
3146 } else {
3147 // force no volume ramp when volume controller was just disabled or removed
3148 // from effect chain to avoid volume spike
3149 if (track->mHasVolumeController) {
3150 param = AudioMixer::VOLUME;
3151 }
3152 track->mHasVolumeController = false;
3153 }
3154
3155 // Convert volumes from 8.24 to 4.12 format
3156 // This additional clamping is needed in case chain->setVolume_l() overshot
3157 vl = (vl + (1 << 11)) >> 12;
3158 if (vl > MAX_GAIN_INT) {
3159 vl = MAX_GAIN_INT;
3160 }
3161 vr = (vr + (1 << 11)) >> 12;
3162 if (vr > MAX_GAIN_INT) {
3163 vr = MAX_GAIN_INT;
3164 }
3165
3166 if (va > MAX_GAIN_INT) {
3167 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3168 }
3169
3170 // XXX: these things DON'T need to be done each time
3171 mAudioMixer->setBufferProvider(name, track);
3172 mAudioMixer->enable(name);
3173
3174 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3175 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3176 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3177 mAudioMixer->setParameter(
3178 name,
3179 AudioMixer::TRACK,
3180 AudioMixer::FORMAT, (void *)track->format());
3181 mAudioMixer->setParameter(
3182 name,
3183 AudioMixer::TRACK,
3184 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003185 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3186 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003187 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003188 if (reqSampleRate == 0) {
3189 reqSampleRate = mSampleRate;
3190 } else if (reqSampleRate > maxSampleRate) {
3191 reqSampleRate = maxSampleRate;
3192 }
Eric Laurent81784c32012-11-19 14:55:58 -08003193 mAudioMixer->setParameter(
3194 name,
3195 AudioMixer::RESAMPLE,
3196 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003197 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003198 mAudioMixer->setParameter(
3199 name,
3200 AudioMixer::TRACK,
3201 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3202 mAudioMixer->setParameter(
3203 name,
3204 AudioMixer::TRACK,
3205 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3206
3207 // reset retry count
3208 track->mRetryCount = kMaxTrackRetries;
3209
3210 // If one track is ready, set the mixer ready if:
3211 // - the mixer was not ready during previous round OR
3212 // - no other track is not ready
3213 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3214 mixerStatus != MIXER_TRACKS_ENABLED) {
3215 mixerStatus = MIXER_TRACKS_READY;
3216 }
3217 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003218 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003219 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003220 }
Eric Laurent81784c32012-11-19 14:55:58 -08003221 // clear effect chain input buffer if an active track underruns to avoid sending
3222 // previous audio buffer again to effects
3223 chain = getEffectChain_l(track->sessionId());
3224 if (chain != 0) {
3225 chain->clearInputBuffer();
3226 }
3227
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003228 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003229 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3230 track->isStopped() || track->isPaused()) {
3231 // We have consumed all the buffers of this track.
3232 // Remove it from the list of active tracks.
3233 // TODO: use actual buffer filling status instead of latency when available from
3234 // audio HAL
3235 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3236 size_t framesWritten = mBytesWritten / mFrameSize;
3237 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3238 if (track->isStopped()) {
3239 track->reset();
3240 }
3241 tracksToRemove->add(track);
3242 }
3243 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003244 // No buffers for this track. Give it a few chances to
3245 // fill a buffer, then remove it from active list.
3246 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003247 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003248 tracksToRemove->add(track);
3249 // indicate to client process that the track was disabled because of underrun;
3250 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003251 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003252 // If one track is not ready, mark the mixer also not ready if:
3253 // - the mixer was ready during previous round OR
3254 // - no other track is ready
3255 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3256 mixerStatus != MIXER_TRACKS_READY) {
3257 mixerStatus = MIXER_TRACKS_ENABLED;
3258 }
3259 }
3260 mAudioMixer->disable(name);
3261 }
3262
3263 } // local variable scope to avoid goto warning
3264track_is_ready: ;
3265
3266 }
3267
3268 // Push the new FastMixer state if necessary
3269 bool pauseAudioWatchdog = false;
3270 if (didModify) {
3271 state->mFastTracksGen++;
3272 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3273 if (kUseFastMixer == FastMixer_Dynamic &&
3274 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3275 state->mCommand = FastMixerState::COLD_IDLE;
3276 state->mColdFutexAddr = &mFastMixerFutex;
3277 state->mColdGen++;
3278 mFastMixerFutex = 0;
3279 if (kUseFastMixer == FastMixer_Dynamic) {
3280 mNormalSink = mOutputSink;
3281 }
3282 // If we go into cold idle, need to wait for acknowledgement
3283 // so that fast mixer stops doing I/O.
3284 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3285 pauseAudioWatchdog = true;
3286 }
Eric Laurent81784c32012-11-19 14:55:58 -08003287 }
3288 if (sq != NULL) {
3289 sq->end(didModify);
3290 sq->push(block);
3291 }
3292#ifdef AUDIO_WATCHDOG
3293 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3294 mAudioWatchdog->pause();
3295 }
3296#endif
3297
3298 // Now perform the deferred reset on fast tracks that have stopped
3299 while (resetMask != 0) {
3300 size_t i = __builtin_ctz(resetMask);
3301 ALOG_ASSERT(i < count);
3302 resetMask &= ~(1 << i);
3303 sp<Track> t = mActiveTracks[i].promote();
3304 if (t == 0) {
3305 continue;
3306 }
3307 Track* track = t.get();
3308 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3309 track->reset();
3310 }
3311
3312 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003313 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003314
3315 // mix buffer must be cleared if all tracks are connected to an
3316 // effect chain as in this case the mixer will not write to
3317 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003318 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3319 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003320 // FIXME as a performance optimization, should remember previous zero status
3321 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3322 }
3323
3324 // if any fast tracks, then status is ready
3325 mMixerStatusIgnoringFastTracks = mixerStatus;
3326 if (fastTracks > 0) {
3327 mixerStatus = MIXER_TRACKS_READY;
3328 }
3329 return mixerStatus;
3330}
3331
3332// getTrackName_l() must be called with ThreadBase::mLock held
3333int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3334{
3335 return mAudioMixer->getTrackName(channelMask, sessionId);
3336}
3337
3338// deleteTrackName_l() must be called with ThreadBase::mLock held
3339void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3340{
3341 ALOGV("remove track (%d) and delete from mixer", name);
3342 mAudioMixer->deleteTrackName(name);
3343}
3344
3345// checkForNewParameters_l() must be called with ThreadBase::mLock held
3346bool AudioFlinger::MixerThread::checkForNewParameters_l()
3347{
3348 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3349 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3350 bool reconfig = false;
3351
3352 while (!mNewParameters.isEmpty()) {
3353
3354 if (mFastMixer != NULL) {
3355 FastMixerStateQueue *sq = mFastMixer->sq();
3356 FastMixerState *state = sq->begin();
3357 if (!(state->mCommand & FastMixerState::IDLE)) {
3358 previousCommand = state->mCommand;
3359 state->mCommand = FastMixerState::HOT_IDLE;
3360 sq->end();
3361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3362 } else {
3363 sq->end(false /*didModify*/);
3364 }
3365 }
3366
3367 status_t status = NO_ERROR;
3368 String8 keyValuePair = mNewParameters[0];
3369 AudioParameter param = AudioParameter(keyValuePair);
3370 int value;
3371
3372 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3373 reconfig = true;
3374 }
3375 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3376 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3377 status = BAD_VALUE;
3378 } else {
3379 reconfig = true;
3380 }
3381 }
3382 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003383 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003384 status = BAD_VALUE;
3385 } else {
3386 reconfig = true;
3387 }
3388 }
3389 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3390 // do not accept frame count changes if tracks are open as the track buffer
3391 // size depends on frame count and correct behavior would not be guaranteed
3392 // if frame count is changed after track creation
3393 if (!mTracks.isEmpty()) {
3394 status = INVALID_OPERATION;
3395 } else {
3396 reconfig = true;
3397 }
3398 }
3399 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3400#ifdef ADD_BATTERY_DATA
3401 // when changing the audio output device, call addBatteryData to notify
3402 // the change
3403 if (mOutDevice != value) {
3404 uint32_t params = 0;
3405 // check whether speaker is on
3406 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3407 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3408 }
3409
3410 audio_devices_t deviceWithoutSpeaker
3411 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3412 // check if any other device (except speaker) is on
3413 if (value & deviceWithoutSpeaker ) {
3414 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3415 }
3416
3417 if (params != 0) {
3418 addBatteryData(params);
3419 }
3420 }
3421#endif
3422
3423 // forward device change to effects that have requested to be
3424 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003425 if (value != AUDIO_DEVICE_NONE) {
3426 mOutDevice = value;
3427 for (size_t i = 0; i < mEffectChains.size(); i++) {
3428 mEffectChains[i]->setDevice_l(mOutDevice);
3429 }
Eric Laurent81784c32012-11-19 14:55:58 -08003430 }
3431 }
3432
3433 if (status == NO_ERROR) {
3434 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3435 keyValuePair.string());
3436 if (!mStandby && status == INVALID_OPERATION) {
3437 mOutput->stream->common.standby(&mOutput->stream->common);
3438 mStandby = true;
3439 mBytesWritten = 0;
3440 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3441 keyValuePair.string());
3442 }
3443 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003444 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003445 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003446 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3447 for (size_t i = 0; i < mTracks.size() ; i++) {
3448 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3449 if (name < 0) {
3450 break;
3451 }
3452 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003453 }
3454 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3455 }
3456 }
3457
3458 mNewParameters.removeAt(0);
3459
3460 mParamStatus = status;
3461 mParamCond.signal();
3462 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3463 // already timed out waiting for the status and will never signal the condition.
3464 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3465 }
3466
3467 if (!(previousCommand & FastMixerState::IDLE)) {
3468 ALOG_ASSERT(mFastMixer != NULL);
3469 FastMixerStateQueue *sq = mFastMixer->sq();
3470 FastMixerState *state = sq->begin();
3471 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3472 state->mCommand = previousCommand;
3473 sq->end();
3474 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3475 }
3476
3477 return reconfig;
3478}
3479
3480
3481void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3482{
3483 const size_t SIZE = 256;
3484 char buffer[SIZE];
3485 String8 result;
3486
3487 PlaybackThread::dumpInternals(fd, args);
3488
3489 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3490 result.append(buffer);
3491 write(fd, result.string(), result.size());
3492
3493 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003494 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003495 copy.dump(fd);
3496
3497#ifdef STATE_QUEUE_DUMP
3498 // Similar for state queue
3499 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3500 observerCopy.dump(fd);
3501 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3502 mutatorCopy.dump(fd);
3503#endif
3504
Glenn Kasten46909e72013-02-26 09:20:22 -08003505#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // Write the tee output to a .wav file
3507 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003508#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003509
3510#ifdef AUDIO_WATCHDOG
3511 if (mAudioWatchdog != 0) {
3512 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3513 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3514 wdCopy.dump(fd);
3515 }
3516#endif
3517}
3518
3519uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3520{
3521 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3522}
3523
3524uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3525{
3526 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3527}
3528
3529void AudioFlinger::MixerThread::cacheParameters_l()
3530{
3531 PlaybackThread::cacheParameters_l();
3532
3533 // FIXME: Relaxed timing because of a certain device that can't meet latency
3534 // Should be reduced to 2x after the vendor fixes the driver issue
3535 // increase threshold again due to low power audio mode. The way this warning
3536 // threshold is calculated and its usefulness should be reconsidered anyway.
3537 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3538}
3539
3540// ----------------------------------------------------------------------------
3541
3542AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3543 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3544 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3545 // mLeftVolFloat, mRightVolFloat
3546{
3547}
3548
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3550 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3551 ThreadBase::type_t type)
3552 : PlaybackThread(audioFlinger, output, id, device, type)
3553 // mLeftVolFloat, mRightVolFloat
3554{
3555}
3556
Eric Laurent81784c32012-11-19 14:55:58 -08003557AudioFlinger::DirectOutputThread::~DirectOutputThread()
3558{
3559}
3560
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3562{
3563 audio_track_cblk_t* cblk = track->cblk();
3564 float left, right;
3565
3566 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3567 left = right = 0;
3568 } else {
3569 float typeVolume = mStreamTypes[track->streamType()].volume;
3570 float v = mMasterVolume * typeVolume;
3571 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3572 uint32_t vlr = proxy->getVolumeLR();
3573 float v_clamped = v * (vlr & 0xFFFF);
3574 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3575 left = v_clamped/MAX_GAIN;
3576 v_clamped = v * (vlr >> 16);
3577 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3578 right = v_clamped/MAX_GAIN;
3579 }
3580
3581 if (lastTrack) {
3582 if (left != mLeftVolFloat || right != mRightVolFloat) {
3583 mLeftVolFloat = left;
3584 mRightVolFloat = right;
3585
3586 // Convert volumes from float to 8.24
3587 uint32_t vl = (uint32_t)(left * (1 << 24));
3588 uint32_t vr = (uint32_t)(right * (1 << 24));
3589
3590 // Delegate volume control to effect in track effect chain if needed
3591 // only one effect chain can be present on DirectOutputThread, so if
3592 // there is one, the track is connected to it
3593 if (!mEffectChains.isEmpty()) {
3594 mEffectChains[0]->setVolume_l(&vl, &vr);
3595 left = (float)vl / (1 << 24);
3596 right = (float)vr / (1 << 24);
3597 }
3598 if (mOutput->stream->set_volume) {
3599 mOutput->stream->set_volume(mOutput->stream, left, right);
3600 }
3601 }
3602 }
3603}
3604
3605
Eric Laurent81784c32012-11-19 14:55:58 -08003606AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3607 Vector< sp<Track> > *tracksToRemove
3608)
3609{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003610 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003611 mixer_state mixerStatus = MIXER_IDLE;
3612
3613 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003614 for (size_t i = 0; i < count; i++) {
3615 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003616 // The track died recently
3617 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003618 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003619 }
3620
3621 Track* const track = t.get();
3622 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003623 // Only consider last track started for volume and mixer state control.
3624 // In theory an older track could underrun and restart after the new one starts
3625 // but as we only care about the transition phase between two tracks on a
3626 // direct output, it is not a problem to ignore the underrun case.
3627 sp<Track> l = mLatestActiveTrack.promote();
3628 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003629
3630 // The first time a track is added we wait
3631 // for all its buffers to be filled before processing it
3632 uint32_t minFrames;
3633 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3634 minFrames = mNormalFrameCount;
3635 } else {
3636 minFrames = 1;
3637 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003638
Eric Laurent81784c32012-11-19 14:55:58 -08003639 if ((track->framesReady() >= minFrames) && track->isReady() &&
3640 !track->isPaused() && !track->isTerminated())
3641 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003642 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003643
3644 if (track->mFillingUpStatus == Track::FS_FILLED) {
3645 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003646 // make sure processVolume_l() will apply new volume even if 0
3647 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 if (track->mState == TrackBase::RESUMING) {
3649 track->mState = TrackBase::ACTIVE;
3650 }
3651 }
3652
3653 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003654 processVolume_l(track, last);
3655 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003656 // reset retry count
3657 track->mRetryCount = kMaxTrackRetriesDirect;
3658 mActiveTrack = t;
3659 mixerStatus = MIXER_TRACKS_READY;
3660 }
Eric Laurent81784c32012-11-19 14:55:58 -08003661 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003662 // clear effect chain input buffer if the last active track started underruns
3663 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003664 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003665 mEffectChains[0]->clearInputBuffer();
3666 }
3667
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003668 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003669 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3670 track->isStopped() || track->isPaused()) {
3671 // We have consumed all the buffers of this track.
3672 // Remove it from the list of active tracks.
3673 // TODO: implement behavior for compressed audio
3674 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3675 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003676 if (mStandby || !last ||
3677 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003678 if (track->isStopped()) {
3679 track->reset();
3680 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003681 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003682 }
3683 } else {
3684 // No buffers for this track. Give it a few chances to
3685 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003686 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003687 if (--(track->mRetryCount) <= 0) {
3688 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003689 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003690 // indicate to client process that the track was disabled because of underrun;
3691 // it will then automatically call start() when data is available
3692 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003693 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003694 mixerStatus = MIXER_TRACKS_ENABLED;
3695 }
3696 }
3697 }
3698 }
3699
Eric Laurent81784c32012-11-19 14:55:58 -08003700 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003701 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003702
3703 return mixerStatus;
3704}
3705
3706void AudioFlinger::DirectOutputThread::threadLoop_mix()
3707{
Eric Laurent81784c32012-11-19 14:55:58 -08003708 size_t frameCount = mFrameCount;
3709 int8_t *curBuf = (int8_t *)mMixBuffer;
3710 // output audio to hardware
3711 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003712 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003713 buffer.frameCount = frameCount;
3714 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003715 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003716 memset(curBuf, 0, frameCount * mFrameSize);
3717 break;
3718 }
3719 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3720 frameCount -= buffer.frameCount;
3721 curBuf += buffer.frameCount * mFrameSize;
3722 mActiveTrack->releaseBuffer(&buffer);
3723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003724 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003725 sleepTime = 0;
3726 standbyTime = systemTime() + standbyDelay;
3727 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003728}
3729
3730void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3731{
3732 if (sleepTime == 0) {
3733 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3734 sleepTime = activeSleepTime;
3735 } else {
3736 sleepTime = idleSleepTime;
3737 }
3738 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3739 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3740 sleepTime = 0;
3741 }
3742}
3743
3744// getTrackName_l() must be called with ThreadBase::mLock held
3745int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3746 int sessionId)
3747{
3748 return 0;
3749}
3750
3751// deleteTrackName_l() must be called with ThreadBase::mLock held
3752void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3753{
3754}
3755
3756// checkForNewParameters_l() must be called with ThreadBase::mLock held
3757bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3758{
3759 bool reconfig = false;
3760
3761 while (!mNewParameters.isEmpty()) {
3762 status_t status = NO_ERROR;
3763 String8 keyValuePair = mNewParameters[0];
3764 AudioParameter param = AudioParameter(keyValuePair);
3765 int value;
3766
3767 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3768 // do not accept frame count changes if tracks are open as the track buffer
3769 // size depends on frame count and correct behavior would not be garantied
3770 // if frame count is changed after track creation
3771 if (!mTracks.isEmpty()) {
3772 status = INVALID_OPERATION;
3773 } else {
3774 reconfig = true;
3775 }
3776 }
3777 if (status == NO_ERROR) {
3778 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3779 keyValuePair.string());
3780 if (!mStandby && status == INVALID_OPERATION) {
3781 mOutput->stream->common.standby(&mOutput->stream->common);
3782 mStandby = true;
3783 mBytesWritten = 0;
3784 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3785 keyValuePair.string());
3786 }
3787 if (status == NO_ERROR && reconfig) {
3788 readOutputParameters();
3789 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3790 }
3791 }
3792
3793 mNewParameters.removeAt(0);
3794
3795 mParamStatus = status;
3796 mParamCond.signal();
3797 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3798 // already timed out waiting for the status and will never signal the condition.
3799 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3800 }
3801 return reconfig;
3802}
3803
3804uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3805{
3806 uint32_t time;
3807 if (audio_is_linear_pcm(mFormat)) {
3808 time = PlaybackThread::activeSleepTimeUs();
3809 } else {
3810 time = 10000;
3811 }
3812 return time;
3813}
3814
3815uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3816{
3817 uint32_t time;
3818 if (audio_is_linear_pcm(mFormat)) {
3819 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3820 } else {
3821 time = 10000;
3822 }
3823 return time;
3824}
3825
3826uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3827{
3828 uint32_t time;
3829 if (audio_is_linear_pcm(mFormat)) {
3830 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3831 } else {
3832 time = 10000;
3833 }
3834 return time;
3835}
3836
3837void AudioFlinger::DirectOutputThread::cacheParameters_l()
3838{
3839 PlaybackThread::cacheParameters_l();
3840
3841 // use shorter standby delay as on normal output to release
3842 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003843 if (audio_is_linear_pcm(mFormat)) {
3844 standbyDelay = microseconds(activeSleepTime*2);
3845 } else {
3846 standbyDelay = kOffloadStandbyDelayNs;
3847 }
Eric Laurent81784c32012-11-19 14:55:58 -08003848}
3849
3850// ----------------------------------------------------------------------------
3851
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003853 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003854 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003855 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003856 mWriteAckSequence(0),
3857 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003858{
3859}
3860
3861AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3862{
3863}
3864
3865void AudioFlinger::AsyncCallbackThread::onFirstRef()
3866{
3867 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3868}
3869
3870bool AudioFlinger::AsyncCallbackThread::threadLoop()
3871{
3872 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003873 uint32_t writeAckSequence;
3874 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003875
3876 {
3877 Mutex::Autolock _l(mLock);
Haynes Mathew George50c31572013-12-03 21:26:02 -08003878 while (!((mWriteAckSequence & 1) ||
3879 (mDrainSequence & 1) ||
3880 exitPending())) {
3881 mWaitWorkCV.wait(mLock);
3882 }
3883
Eric Laurentbfb1b832013-01-07 09:53:42 -08003884 if (exitPending()) {
3885 break;
3886 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003887 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3888 mWriteAckSequence, mDrainSequence);
3889 writeAckSequence = mWriteAckSequence;
3890 mWriteAckSequence &= ~1;
3891 drainSequence = mDrainSequence;
3892 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003893 }
3894 {
Eric Laurent4de95592013-09-26 15:28:21 -07003895 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3896 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003897 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003898 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003900 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003901 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902 }
3903 }
3904 }
3905 }
3906 return false;
3907}
3908
3909void AudioFlinger::AsyncCallbackThread::exit()
3910{
3911 ALOGV("AsyncCallbackThread::exit");
3912 Mutex::Autolock _l(mLock);
3913 requestExit();
3914 mWaitWorkCV.broadcast();
3915}
3916
Eric Laurent3b4529e2013-09-05 18:09:19 -07003917void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918{
3919 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003920 // bit 0 is cleared
3921 mWriteAckSequence = sequence << 1;
3922}
3923
3924void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3925{
3926 Mutex::Autolock _l(mLock);
3927 // ignore unexpected callbacks
3928 if (mWriteAckSequence & 2) {
3929 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 mWaitWorkCV.signal();
3931 }
3932}
3933
Eric Laurent3b4529e2013-09-05 18:09:19 -07003934void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003935{
3936 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003937 // bit 0 is cleared
3938 mDrainSequence = sequence << 1;
3939}
3940
3941void AudioFlinger::AsyncCallbackThread::resetDraining()
3942{
3943 Mutex::Autolock _l(mLock);
3944 // ignore unexpected callbacks
3945 if (mDrainSequence & 2) {
3946 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003947 mWaitWorkCV.signal();
3948 }
3949}
3950
3951
3952// ----------------------------------------------------------------------------
3953AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3954 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3955 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3956 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003957 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003958 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959{
Eric Laurentfd477972013-10-25 18:10:40 -07003960 //FIXME: mStandby should be set to true by ThreadBase constructor
3961 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962}
3963
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964void AudioFlinger::OffloadThread::threadLoop_exit()
3965{
3966 if (mFlushPending || mHwPaused) {
3967 // If a flush is pending or track was paused, just discard buffered data
3968 flushHw_l();
3969 } else {
3970 mMixerStatus = MIXER_DRAIN_ALL;
3971 threadLoop_drain();
3972 }
3973 mCallbackThread->exit();
3974 PlaybackThread::threadLoop_exit();
3975}
3976
3977AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3978 Vector< sp<Track> > *tracksToRemove
3979)
3980{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003981 size_t count = mActiveTracks.size();
3982
3983 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003984 bool doHwPause = false;
3985 bool doHwResume = false;
3986
Eric Laurentede6c3b2013-09-19 14:37:46 -07003987 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3988
Eric Laurentbfb1b832013-01-07 09:53:42 -08003989 // find out which tracks need to be processed
3990 for (size_t i = 0; i < count; i++) {
3991 sp<Track> t = mActiveTracks[i].promote();
3992 // The track died recently
3993 if (t == 0) {
3994 continue;
3995 }
3996 Track* const track = t.get();
3997 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003998 // Only consider last track started for volume and mixer state control.
3999 // In theory an older track could underrun and restart after the new one starts
4000 // but as we only care about the transition phase between two tracks on a
4001 // direct output, it is not a problem to ignore the underrun case.
4002 sp<Track> l = mLatestActiveTrack.promote();
4003 bool last = l.get() == track;
4004
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 if (track->isPausing()) {
4006 track->setPaused();
4007 if (last) {
4008 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004009 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010 mHwPaused = true;
4011 }
4012 // If we were part way through writing the mixbuffer to
4013 // the HAL we must save this until we resume
4014 // BUG - this will be wrong if a different track is made active,
4015 // in that case we want to discard the pending data in the
4016 // mixbuffer and tell the client to present it again when the
4017 // track is resumed
4018 mPausedWriteLength = mCurrentWriteLength;
4019 mPausedBytesRemaining = mBytesRemaining;
4020 mBytesRemaining = 0; // stop writing
4021 }
4022 tracksToRemove->add(track);
4023 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004024 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004025 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004026 if (track->mFillingUpStatus == Track::FS_FILLED) {
4027 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004028 // make sure processVolume_l() will apply new volume even if 0
4029 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004030 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004032 if (last) {
4033 if (mPausedBytesRemaining) {
4034 // Need to continue write that was interrupted
4035 mCurrentWriteLength = mPausedWriteLength;
4036 mBytesRemaining = mPausedBytesRemaining;
4037 mPausedBytesRemaining = 0;
4038 }
4039 if (mHwPaused) {
4040 doHwResume = true;
4041 mHwPaused = false;
4042 // threadLoop_mix() will handle the case that we need to
4043 // resume an interrupted write
4044 }
4045 // enable write to audio HAL
4046 sleepTime = 0;
4047 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048 }
4049 }
4050
4051 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004052 sp<Track> previousTrack = mPreviousTrack.promote();
4053 if (previousTrack != 0) {
4054 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004055 // Flush any data still being written from last track
4056 mBytesRemaining = 0;
4057 if (mPausedBytesRemaining) {
4058 // Last track was paused so we also need to flush saved
4059 // mixbuffer state and invalidate track so that it will
4060 // re-submit that unwritten data when it is next resumed
4061 mPausedBytesRemaining = 0;
4062 // Invalidate is a bit drastic - would be more efficient
4063 // to have a flag to tell client that some of the
4064 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004065 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004066 }
4067 // flush data already sent to the DSP if changing audio session as audio
4068 // comes from a different source. Also invalidate previous track to force a
4069 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004070 if (previousTrack->sessionId() != track->sessionId()) {
4071 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004072 mFlushPending = true;
4073 }
4074 }
4075 }
4076 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 // reset retry count
4078 track->mRetryCount = kMaxTrackRetriesOffload;
4079 mActiveTrack = t;
4080 mixerStatus = MIXER_TRACKS_READY;
4081 }
4082 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004083 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 if (track->isStopping_1()) {
4085 // Hardware buffer can hold a large amount of audio so we must
4086 // wait for all current track's data to drain before we say
4087 // that the track is stopped.
4088 if (mBytesRemaining == 0) {
4089 // Only start draining when all data in mixbuffer
4090 // has been written
4091 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4092 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004093 // do not drain if no data was ever sent to HAL (mStandby == true)
4094 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004095 // do not modify drain sequence if we are already draining. This happens
4096 // when resuming from pause after drain.
4097 if ((mDrainSequence & 1) == 0) {
4098 sleepTime = 0;
4099 standbyTime = systemTime() + standbyDelay;
4100 mixerStatus = MIXER_DRAIN_TRACK;
4101 mDrainSequence += 2;
4102 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004103 if (mHwPaused) {
4104 // It is possible to move from PAUSED to STOPPING_1 without
4105 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004106 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 mHwPaused = false;
4108 }
4109 }
4110 }
4111 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004112 // Drain has completed or we are in standby, signal presentation complete
4113 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004114 track->mState = TrackBase::STOPPED;
4115 size_t audioHALFrames =
4116 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4117 size_t framesWritten =
4118 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4119 track->presentationComplete(framesWritten, audioHALFrames);
4120 track->reset();
4121 tracksToRemove->add(track);
4122 }
4123 } else {
4124 // No buffers for this track. Give it a few chances to
4125 // fill a buffer, then remove it from active list.
4126 if (--(track->mRetryCount) <= 0) {
4127 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4128 track->name());
4129 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004130 // indicate to client process that the track was disabled because of underrun;
4131 // it will then automatically call start() when data is available
4132 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 } else if (last){
4134 mixerStatus = MIXER_TRACKS_ENABLED;
4135 }
4136 }
4137 }
4138 // compute volume for this track
4139 processVolume_l(track, last);
4140 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004141
Eric Laurentea0fade2013-10-04 16:23:48 -07004142 // make sure the pause/flush/resume sequence is executed in the right order.
4143 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4144 // before flush and then resume HW. This can happen in case of pause/flush/resume
4145 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004146 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004147 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004148 if (!doHwPause) {
4149 doHwResume = true;
4150 }
Eric Laurent972a1732013-09-04 09:42:59 -07004151 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004152 if (mFlushPending) {
4153 flushHw_l();
4154 mFlushPending = false;
4155 }
Eric Laurentfd477972013-10-25 18:10:40 -07004156 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004157 mOutput->stream->resume(mOutput->stream);
4158 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004159
Eric Laurentbfb1b832013-01-07 09:53:42 -08004160 // remove all the tracks that need to be...
4161 removeTracks_l(*tracksToRemove);
4162
4163 return mixerStatus;
4164}
4165
4166void AudioFlinger::OffloadThread::flushOutput_l()
4167{
4168 mFlushPending = true;
4169}
4170
4171// must be called with thread mutex locked
4172bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4173{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004174 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4175 mWriteAckSequence, mDrainSequence);
4176 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 return true;
4178 }
4179 return false;
4180}
4181
4182// must be called with thread mutex locked
4183bool AudioFlinger::OffloadThread::shouldStandby_l()
4184{
4185 bool TrackPaused = false;
4186
4187 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4188 // after a timeout and we will enter standby then.
4189 if (mTracks.size() > 0) {
4190 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4191 }
4192
4193 return !mStandby && !TrackPaused;
4194}
4195
4196
4197bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4198{
4199 Mutex::Autolock _l(mLock);
4200 return waitingAsyncCallback_l();
4201}
4202
4203void AudioFlinger::OffloadThread::flushHw_l()
4204{
4205 mOutput->stream->flush(mOutput->stream);
4206 // Flush anything still waiting in the mixbuffer
4207 mCurrentWriteLength = 0;
4208 mBytesRemaining = 0;
4209 mPausedWriteLength = 0;
4210 mPausedBytesRemaining = 0;
4211 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004212 // discard any pending drain or write ack by incrementing sequence
4213 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4214 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004216 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4217 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218 }
4219}
4220
4221// ----------------------------------------------------------------------------
4222
Eric Laurent81784c32012-11-19 14:55:58 -08004223AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4224 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4225 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4226 DUPLICATING),
4227 mWaitTimeMs(UINT_MAX)
4228{
4229 addOutputTrack(mainThread);
4230}
4231
4232AudioFlinger::DuplicatingThread::~DuplicatingThread()
4233{
4234 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4235 mOutputTracks[i]->destroy();
4236 }
4237}
4238
4239void AudioFlinger::DuplicatingThread::threadLoop_mix()
4240{
4241 // mix buffers...
4242 if (outputsReady(outputTracks)) {
4243 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4244 } else {
4245 memset(mMixBuffer, 0, mixBufferSize);
4246 }
4247 sleepTime = 0;
4248 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004250 standbyTime = systemTime() + standbyDelay;
4251}
4252
4253void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4254{
4255 if (sleepTime == 0) {
4256 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4257 sleepTime = activeSleepTime;
4258 } else {
4259 sleepTime = idleSleepTime;
4260 }
4261 } else if (mBytesWritten != 0) {
4262 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4263 writeFrames = mNormalFrameCount;
4264 memset(mMixBuffer, 0, mixBufferSize);
4265 } else {
4266 // flush remaining overflow buffers in output tracks
4267 writeFrames = 0;
4268 }
4269 sleepTime = 0;
4270 }
4271}
4272
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004274{
4275 for (size_t i = 0; i < outputTracks.size(); i++) {
4276 outputTracks[i]->write(mMixBuffer, writeFrames);
4277 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004278 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004279 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004280}
4281
4282void AudioFlinger::DuplicatingThread::threadLoop_standby()
4283{
4284 // DuplicatingThread implements standby by stopping all tracks
4285 for (size_t i = 0; i < outputTracks.size(); i++) {
4286 outputTracks[i]->stop();
4287 }
4288}
4289
4290void AudioFlinger::DuplicatingThread::saveOutputTracks()
4291{
4292 outputTracks = mOutputTracks;
4293}
4294
4295void AudioFlinger::DuplicatingThread::clearOutputTracks()
4296{
4297 outputTracks.clear();
4298}
4299
4300void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4301{
4302 Mutex::Autolock _l(mLock);
4303 // FIXME explain this formula
4304 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4305 OutputTrack *outputTrack = new OutputTrack(thread,
4306 this,
4307 mSampleRate,
4308 mFormat,
4309 mChannelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004310 frameCount,
4311 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004312 if (outputTrack->cblk() != NULL) {
4313 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4314 mOutputTracks.add(outputTrack);
4315 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4316 updateWaitTime_l();
4317 }
4318}
4319
4320void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4321{
4322 Mutex::Autolock _l(mLock);
4323 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4324 if (mOutputTracks[i]->thread() == thread) {
4325 mOutputTracks[i]->destroy();
4326 mOutputTracks.removeAt(i);
4327 updateWaitTime_l();
Eric Laurent22ac20e2015-05-08 10:50:03 -07004328 if (thread->getOutput() == mOutput) {
4329 mOutput = NULL;
4330 }
Eric Laurent81784c32012-11-19 14:55:58 -08004331 return;
4332 }
4333 }
Eric Laurent22ac20e2015-05-08 10:50:03 -07004334 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004335}
4336
4337// caller must hold mLock
4338void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4339{
4340 mWaitTimeMs = UINT_MAX;
4341 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4342 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4343 if (strong != 0) {
4344 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4345 if (waitTimeMs < mWaitTimeMs) {
4346 mWaitTimeMs = waitTimeMs;
4347 }
4348 }
4349 }
4350}
4351
4352
4353bool AudioFlinger::DuplicatingThread::outputsReady(
4354 const SortedVector< sp<OutputTrack> > &outputTracks)
4355{
4356 for (size_t i = 0; i < outputTracks.size(); i++) {
4357 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4358 if (thread == 0) {
4359 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4360 outputTracks[i].get());
4361 return false;
4362 }
4363 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4364 // see note at standby() declaration
4365 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4366 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4367 thread.get());
4368 return false;
4369 }
4370 }
4371 return true;
4372}
4373
4374uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4375{
4376 return (mWaitTimeMs * 1000) / 2;
4377}
4378
4379void AudioFlinger::DuplicatingThread::cacheParameters_l()
4380{
4381 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4382 updateWaitTime_l();
4383
4384 MixerThread::cacheParameters_l();
4385}
4386
4387// ----------------------------------------------------------------------------
4388// Record
4389// ----------------------------------------------------------------------------
4390
4391AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4392 AudioStreamIn *input,
4393 uint32_t sampleRate,
4394 audio_channel_mask_t channelMask,
4395 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004396 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004397 audio_devices_t inDevice
4398#ifdef TEE_SINK
4399 , const sp<NBAIO_Sink>& teeSink
4400#endif
4401 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004402 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004403 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004404 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004405 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004406 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004407 // mBytesRead is only meaningful while active, and so is cleared in start()
4408 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004409#ifdef TEE_SINK
4410 , mTeeSink(teeSink)
4411#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004412{
4413 snprintf(mName, kNameLength, "AudioIn_%X", id);
4414
4415 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004416}
4417
4418
4419AudioFlinger::RecordThread::~RecordThread()
4420{
4421 delete[] mRsmpInBuffer;
4422 delete mResampler;
4423 delete[] mRsmpOutBuffer;
4424}
4425
4426void AudioFlinger::RecordThread::onFirstRef()
4427{
4428 run(mName, PRIORITY_URGENT_AUDIO);
4429}
4430
4431status_t AudioFlinger::RecordThread::readyToRun()
4432{
4433 status_t status = initCheck();
4434 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4435 return status;
4436}
4437
4438bool AudioFlinger::RecordThread::threadLoop()
4439{
4440 AudioBufferProvider::Buffer buffer;
4441 sp<RecordTrack> activeTrack;
4442 Vector< sp<EffectChain> > effectChains;
4443
4444 nsecs_t lastWarning = 0;
4445
4446 inputStandBy();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004447 {
4448 Mutex::Autolock _l(mLock);
4449 activeTrack = mActiveTrack;
4450 acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
4451 }
Eric Laurent81784c32012-11-19 14:55:58 -08004452
4453 // used to verify we've read at least once before evaluating how many bytes were read
4454 bool readOnce = false;
4455
4456 // start recording
4457 while (!exitPending()) {
4458
4459 processConfigEvents();
4460
4461 { // scope for mLock
4462 Mutex::Autolock _l(mLock);
4463 checkForNewParameters_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004464 if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
4465 SortedVector<int> tmp;
4466 tmp.add(mActiveTrack->uid());
4467 updateWakeLockUids_l(tmp);
4468 }
4469 activeTrack = mActiveTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004470 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4471 standby();
4472
4473 if (exitPending()) {
4474 break;
4475 }
4476
4477 releaseWakeLock_l();
4478 ALOGV("RecordThread: loop stopping");
4479 // go to sleep
4480 mWaitWorkCV.wait(mLock);
4481 ALOGV("RecordThread: loop starting");
Marco Nelissen9cae2172013-01-14 14:12:05 -08004482 acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08004483 continue;
4484 }
4485 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004486 if (mActiveTrack->isTerminated()) {
4487 removeTrack_l(mActiveTrack);
4488 mActiveTrack.clear();
4489 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004490 standby();
4491 mActiveTrack.clear();
4492 mStartStopCond.broadcast();
4493 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4494 if (mReqChannelCount != mActiveTrack->channelCount()) {
4495 mActiveTrack.clear();
4496 mStartStopCond.broadcast();
4497 } else if (readOnce) {
4498 // record start succeeds only if first read from audio input
4499 // succeeds
4500 if (mBytesRead >= 0) {
4501 mActiveTrack->mState = TrackBase::ACTIVE;
4502 } else {
4503 mActiveTrack.clear();
4504 }
4505 mStartStopCond.broadcast();
4506 }
4507 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 }
4509 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004510
Eric Laurent81784c32012-11-19 14:55:58 -08004511 lockEffectChains_l(effectChains);
4512 }
4513
4514 if (mActiveTrack != 0) {
4515 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4516 mActiveTrack->mState != TrackBase::RESUMING) {
4517 unlockEffectChains(effectChains);
4518 usleep(kRecordThreadSleepUs);
4519 continue;
4520 }
4521 for (size_t i = 0; i < effectChains.size(); i ++) {
4522 effectChains[i]->process_l();
4523 }
4524
4525 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004526 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004527 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004528 readOnce = true;
4529 size_t framesOut = buffer.frameCount;
4530 if (mResampler == NULL) {
4531 // no resampling
4532 while (framesOut) {
4533 size_t framesIn = mFrameCount - mRsmpInIndex;
4534 if (framesIn) {
4535 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4536 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4537 mActiveTrack->mFrameSize;
4538 if (framesIn > framesOut)
4539 framesIn = framesOut;
4540 mRsmpInIndex += framesIn;
4541 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004542 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004543 memcpy(dst, src, framesIn * mFrameSize);
4544 } else {
4545 if (mChannelCount == 1) {
4546 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4547 (int16_t *)src, framesIn);
4548 } else {
4549 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4550 (int16_t *)src, framesIn);
4551 }
4552 }
4553 }
4554 if (framesOut && mFrameCount == mRsmpInIndex) {
4555 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004556 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004557 readInto = buffer.raw;
4558 framesOut = 0;
4559 } else {
4560 readInto = mRsmpInBuffer;
4561 mRsmpInIndex = 0;
4562 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004563 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004564 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 if (mBytesRead <= 0) {
4566 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4567 {
4568 ALOGE("Error reading audio input");
4569 // Force input into standby so that it tries to
4570 // recover at next read attempt
4571 inputStandBy();
4572 usleep(kRecordThreadSleepUs);
4573 }
4574 mRsmpInIndex = mFrameCount;
4575 framesOut = 0;
4576 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004577 }
4578#ifdef TEE_SINK
4579 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004580 (void) mTeeSink->write(readInto,
4581 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4582 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004583#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004584 }
4585 }
4586 } else {
4587 // resampling
4588
Glenn Kasten34af0262013-07-30 11:52:39 -07004589 // resampler accumulates, but we only have one source track
4590 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004591 // alter output frame count as if we were expecting stereo samples
4592 if (mChannelCount == 1 && mReqChannelCount == 1) {
4593 framesOut >>= 1;
4594 }
4595 mResampler->resample(mRsmpOutBuffer, framesOut,
4596 this /* AudioBufferProvider* */);
4597 // ditherAndClamp() works as long as all buffers returned by
4598 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4599 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004600 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004601 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4602 // the resampler always outputs stereo samples:
4603 // do post stereo to mono conversion
4604 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4605 framesOut);
4606 } else {
4607 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4608 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004609 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004610
4611 }
4612 if (mFramestoDrop == 0) {
4613 mActiveTrack->releaseBuffer(&buffer);
4614 } else {
4615 if (mFramestoDrop > 0) {
4616 mFramestoDrop -= buffer.frameCount;
4617 if (mFramestoDrop <= 0) {
4618 clearSyncStartEvent();
4619 }
4620 } else {
4621 mFramestoDrop += buffer.frameCount;
4622 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4623 mSyncStartEvent->isCancelled()) {
4624 ALOGW("Synced record %s, session %d, trigger session %d",
4625 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4626 mActiveTrack->sessionId(),
4627 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4628 clearSyncStartEvent();
4629 }
4630 }
4631 }
4632 mActiveTrack->clearOverflow();
4633 }
4634 // client isn't retrieving buffers fast enough
4635 else {
4636 if (!mActiveTrack->setOverflow()) {
4637 nsecs_t now = systemTime();
4638 if ((now - lastWarning) > kWarningThrottleNs) {
4639 ALOGW("RecordThread: buffer overflow");
4640 lastWarning = now;
4641 }
4642 }
4643 // Release the processor for a while before asking for a new buffer.
4644 // This will give the application more chance to read from the buffer and
4645 // clear the overflow.
4646 usleep(kRecordThreadSleepUs);
4647 }
4648 }
4649 // enable changes in effect chain
4650 unlockEffectChains(effectChains);
4651 effectChains.clear();
4652 }
4653
4654 standby();
4655
4656 {
4657 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004658 for (size_t i = 0; i < mTracks.size(); i++) {
4659 sp<RecordTrack> track = mTracks[i];
4660 track->invalidate();
4661 }
Eric Laurent81784c32012-11-19 14:55:58 -08004662 mActiveTrack.clear();
4663 mStartStopCond.broadcast();
4664 }
4665
4666 releaseWakeLock();
4667
4668 ALOGV("RecordThread %p exiting", this);
4669 return false;
4670}
4671
4672void AudioFlinger::RecordThread::standby()
4673{
4674 if (!mStandby) {
4675 inputStandBy();
4676 mStandby = true;
4677 }
4678}
4679
4680void AudioFlinger::RecordThread::inputStandBy()
4681{
4682 mInput->stream->common.standby(&mInput->stream->common);
4683}
4684
4685sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4686 const sp<AudioFlinger::Client>& client,
4687 uint32_t sampleRate,
4688 audio_format_t format,
4689 audio_channel_mask_t channelMask,
4690 size_t frameCount,
4691 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004692 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004693 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004694 pid_t tid,
4695 status_t *status)
4696{
4697 sp<RecordTrack> track;
4698 status_t lStatus;
4699
4700 lStatus = initCheck();
4701 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004702 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004703 goto Exit;
4704 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004705 // client expresses a preference for FAST, but we get the final say
4706 if (*flags & IAudioFlinger::TRACK_FAST) {
4707 if (
4708 // use case: callback handler and frame count is default or at least as large as HAL
4709 (
4710 (tid != -1) &&
4711 ((frameCount == 0) ||
Glenn Kastend812fc02013-12-03 09:06:43 -08004712 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004713 ) &&
4714 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4715 // mono or stereo
4716 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4717 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4718 // hardware sample rate
4719 (sampleRate == mSampleRate) &&
4720 // record thread has an associated fast recorder
4721 hasFastRecorder()
4722 // FIXME test that RecordThread for this fast track has a capable output HAL
4723 // FIXME add a permission test also?
4724 ) {
4725 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4726 if (frameCount == 0) {
4727 frameCount = mFrameCount * kFastTrackMultiplier;
4728 }
4729 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4730 frameCount, mFrameCount);
4731 } else {
4732 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4733 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4734 "hasFastRecorder=%d tid=%d",
4735 frameCount, mFrameCount, format,
4736 audio_is_linear_pcm(format),
4737 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4738 *flags &= ~IAudioFlinger::TRACK_FAST;
4739 // For compatibility with AudioRecord calculation, buffer depth is forced
4740 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4741 // This is probably too conservative, but legacy application code may depend on it.
4742 // If you change this calculation, also review the start threshold which is related.
4743 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4744 size_t mNormalFrameCount = 2048; // FIXME
4745 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4746 if (minBufCount < 2) {
4747 minBufCount = 2;
4748 }
4749 size_t minFrameCount = mNormalFrameCount * minBufCount;
4750 if (frameCount < minFrameCount) {
4751 frameCount = minFrameCount;
4752 }
4753 }
4754 }
4755
Eric Laurent81784c32012-11-19 14:55:58 -08004756 // FIXME use flags and tid similar to createTrack_l()
4757
4758 { // scope for mLock
4759 Mutex::Autolock _l(mLock);
4760
4761 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004762 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004763
4764 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004765 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004766 lStatus = NO_MEMORY;
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08004767 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004768 goto Exit;
4769 }
4770 mTracks.add(track);
4771
4772 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4773 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4774 mAudioFlinger->btNrecIsOff();
4775 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4776 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004777
4778 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4779 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4780 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4781 // so ask activity manager to do this on our behalf
4782 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4783 }
Eric Laurent81784c32012-11-19 14:55:58 -08004784 }
4785 lStatus = NO_ERROR;
4786
4787Exit:
4788 if (status) {
4789 *status = lStatus;
4790 }
4791 return track;
4792}
4793
4794status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4795 AudioSystem::sync_event_t event,
4796 int triggerSession)
4797{
4798 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4799 sp<ThreadBase> strongMe = this;
4800 status_t status = NO_ERROR;
4801
4802 if (event == AudioSystem::SYNC_EVENT_NONE) {
4803 clearSyncStartEvent();
4804 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4805 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4806 triggerSession,
4807 recordTrack->sessionId(),
4808 syncStartEventCallback,
4809 this);
4810 // Sync event can be cancelled by the trigger session if the track is not in a
4811 // compatible state in which case we start record immediately
4812 if (mSyncStartEvent->isCancelled()) {
4813 clearSyncStartEvent();
4814 } else {
4815 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4816 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4817 }
4818 }
4819
4820 {
4821 AutoMutex lock(mLock);
4822 if (mActiveTrack != 0) {
4823 if (recordTrack != mActiveTrack.get()) {
4824 status = -EBUSY;
4825 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4826 mActiveTrack->mState = TrackBase::ACTIVE;
4827 }
4828 return status;
4829 }
4830
4831 recordTrack->mState = TrackBase::IDLE;
4832 mActiveTrack = recordTrack;
4833 mLock.unlock();
4834 status_t status = AudioSystem::startInput(mId);
4835 mLock.lock();
4836 if (status != NO_ERROR) {
4837 mActiveTrack.clear();
4838 clearSyncStartEvent();
4839 return status;
4840 }
4841 mRsmpInIndex = mFrameCount;
4842 mBytesRead = 0;
4843 if (mResampler != NULL) {
4844 mResampler->reset();
4845 }
4846 mActiveTrack->mState = TrackBase::RESUMING;
4847 // signal thread to start
4848 ALOGV("Signal record thread");
4849 mWaitWorkCV.broadcast();
4850 // do not wait for mStartStopCond if exiting
4851 if (exitPending()) {
4852 mActiveTrack.clear();
4853 status = INVALID_OPERATION;
4854 goto startError;
4855 }
4856 mStartStopCond.wait(mLock);
4857 if (mActiveTrack == 0) {
4858 ALOGV("Record failed to start");
4859 status = BAD_VALUE;
4860 goto startError;
4861 }
4862 ALOGV("Record started OK");
4863 return status;
4864 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004865
Eric Laurent81784c32012-11-19 14:55:58 -08004866startError:
4867 AudioSystem::stopInput(mId);
4868 clearSyncStartEvent();
4869 return status;
4870}
4871
4872void AudioFlinger::RecordThread::clearSyncStartEvent()
4873{
4874 if (mSyncStartEvent != 0) {
4875 mSyncStartEvent->cancel();
4876 }
4877 mSyncStartEvent.clear();
4878 mFramestoDrop = 0;
4879}
4880
4881void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4882{
4883 sp<SyncEvent> strongEvent = event.promote();
4884
4885 if (strongEvent != 0) {
4886 RecordThread *me = (RecordThread *)strongEvent->cookie();
4887 me->handleSyncStartEvent(strongEvent);
4888 }
4889}
4890
4891void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4892{
4893 if (event == mSyncStartEvent) {
4894 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4895 // from audio HAL
4896 mFramestoDrop = mFrameCount * 2;
4897 }
4898}
4899
Glenn Kastena8356f62013-07-25 14:37:52 -07004900bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004901 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004902 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004903 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4904 return false;
4905 }
4906 recordTrack->mState = TrackBase::PAUSING;
4907 // do not wait for mStartStopCond if exiting
4908 if (exitPending()) {
4909 return true;
4910 }
4911 mStartStopCond.wait(mLock);
4912 // if we have been restarted, recordTrack == mActiveTrack.get() here
4913 if (exitPending() || recordTrack != mActiveTrack.get()) {
4914 ALOGV("Record stopped OK");
4915 return true;
4916 }
4917 return false;
4918}
4919
4920bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4921{
4922 return false;
4923}
4924
4925status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4926{
4927#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4928 if (!isValidSyncEvent(event)) {
4929 return BAD_VALUE;
4930 }
4931
4932 int eventSession = event->triggerSession();
4933 status_t ret = NAME_NOT_FOUND;
4934
4935 Mutex::Autolock _l(mLock);
4936
4937 for (size_t i = 0; i < mTracks.size(); i++) {
4938 sp<RecordTrack> track = mTracks[i];
4939 if (eventSession == track->sessionId()) {
4940 (void) track->setSyncEvent(event);
4941 ret = NO_ERROR;
4942 }
4943 }
4944 return ret;
4945#else
4946 return BAD_VALUE;
4947#endif
4948}
4949
4950// destroyTrack_l() must be called with ThreadBase::mLock held
4951void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4952{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004953 track->terminate();
4954 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004955 // active tracks are removed by threadLoop()
4956 if (mActiveTrack != track) {
4957 removeTrack_l(track);
4958 }
4959}
4960
4961void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4962{
4963 mTracks.remove(track);
4964 // need anything related to effects here?
4965}
4966
4967void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4968{
4969 dumpInternals(fd, args);
4970 dumpTracks(fd, args);
4971 dumpEffectChains(fd, args);
4972}
4973
4974void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4975{
4976 const size_t SIZE = 256;
4977 char buffer[SIZE];
4978 String8 result;
4979
4980 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4981 result.append(buffer);
4982
4983 if (mActiveTrack != 0) {
4984 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4985 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004986 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004987 result.append(buffer);
4988 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4989 result.append(buffer);
4990 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4991 result.append(buffer);
4992 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4993 result.append(buffer);
4994 } else {
4995 result.append("No active record client\n");
4996 }
4997
4998 write(fd, result.string(), result.size());
4999
5000 dumpBase(fd, args);
5001}
5002
5003void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
5004{
5005 const size_t SIZE = 256;
5006 char buffer[SIZE];
5007 String8 result;
5008
5009 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5010 result.append(buffer);
5011 RecordTrack::appendDumpHeader(result);
5012 for (size_t i = 0; i < mTracks.size(); ++i) {
5013 sp<RecordTrack> track = mTracks[i];
5014 if (track != 0) {
5015 track->dump(buffer, SIZE);
5016 result.append(buffer);
5017 }
5018 }
5019
5020 if (mActiveTrack != 0) {
5021 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5022 result.append(buffer);
5023 RecordTrack::appendDumpHeader(result);
5024 mActiveTrack->dump(buffer, SIZE);
5025 result.append(buffer);
5026
5027 }
5028 write(fd, result.string(), result.size());
5029}
5030
5031// AudioBufferProvider interface
5032status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5033{
5034 size_t framesReq = buffer->frameCount;
5035 size_t framesReady = mFrameCount - mRsmpInIndex;
5036 int channelCount;
5037
5038 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005039 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005040 if (mBytesRead <= 0) {
5041 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5042 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5043 // Force input into standby so that it tries to
5044 // recover at next read attempt
5045 inputStandBy();
5046 usleep(kRecordThreadSleepUs);
5047 }
5048 buffer->raw = NULL;
5049 buffer->frameCount = 0;
5050 return NOT_ENOUGH_DATA;
5051 }
5052 mRsmpInIndex = 0;
5053 framesReady = mFrameCount;
5054 }
5055
5056 if (framesReq > framesReady) {
5057 framesReq = framesReady;
5058 }
5059
5060 if (mChannelCount == 1 && mReqChannelCount == 2) {
5061 channelCount = 1;
5062 } else {
5063 channelCount = 2;
5064 }
5065 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5066 buffer->frameCount = framesReq;
5067 return NO_ERROR;
5068}
5069
5070// AudioBufferProvider interface
5071void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5072{
5073 mRsmpInIndex += buffer->frameCount;
5074 buffer->frameCount = 0;
5075}
5076
5077bool AudioFlinger::RecordThread::checkForNewParameters_l()
5078{
5079 bool reconfig = false;
5080
5081 while (!mNewParameters.isEmpty()) {
5082 status_t status = NO_ERROR;
5083 String8 keyValuePair = mNewParameters[0];
5084 AudioParameter param = AudioParameter(keyValuePair);
5085 int value;
5086 audio_format_t reqFormat = mFormat;
5087 uint32_t reqSamplingRate = mReqSampleRate;
5088 uint32_t reqChannelCount = mReqChannelCount;
5089
5090 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5091 reqSamplingRate = value;
5092 reconfig = true;
5093 }
5094 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005095 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5096 status = BAD_VALUE;
5097 } else {
5098 reqFormat = (audio_format_t) value;
5099 reconfig = true;
5100 }
Eric Laurent81784c32012-11-19 14:55:58 -08005101 }
5102 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5103 reqChannelCount = popcount(value);
5104 reconfig = true;
5105 }
5106 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5107 // do not accept frame count changes if tracks are open as the track buffer
5108 // size depends on frame count and correct behavior would not be guaranteed
5109 // if frame count is changed after track creation
5110 if (mActiveTrack != 0) {
5111 status = INVALID_OPERATION;
5112 } else {
5113 reconfig = true;
5114 }
5115 }
5116 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5117 // forward device change to effects that have requested to be
5118 // aware of attached audio device.
5119 for (size_t i = 0; i < mEffectChains.size(); i++) {
5120 mEffectChains[i]->setDevice_l(value);
5121 }
5122
5123 // store input device and output device but do not forward output device to audio HAL.
5124 // Note that status is ignored by the caller for output device
5125 // (see AudioFlinger::setParameters()
5126 if (audio_is_output_devices(value)) {
5127 mOutDevice = value;
5128 status = BAD_VALUE;
5129 } else {
5130 mInDevice = value;
5131 // disable AEC and NS if the device is a BT SCO headset supporting those
5132 // pre processings
5133 if (mTracks.size() > 0) {
5134 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5135 mAudioFlinger->btNrecIsOff();
5136 for (size_t i = 0; i < mTracks.size(); i++) {
5137 sp<RecordTrack> track = mTracks[i];
5138 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5139 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5140 }
5141 }
5142 }
5143 }
5144 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5145 mAudioSource != (audio_source_t)value) {
5146 // forward device change to effects that have requested to be
5147 // aware of attached audio device.
5148 for (size_t i = 0; i < mEffectChains.size(); i++) {
5149 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5150 }
5151 mAudioSource = (audio_source_t)value;
5152 }
5153 if (status == NO_ERROR) {
5154 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5155 keyValuePair.string());
5156 if (status == INVALID_OPERATION) {
5157 inputStandBy();
5158 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5159 keyValuePair.string());
5160 }
5161 if (reconfig) {
5162 if (status == BAD_VALUE &&
5163 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5164 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005165 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005166 <= (2 * reqSamplingRate)) &&
5167 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5168 <= FCC_2 &&
5169 (reqChannelCount <= FCC_2)) {
5170 status = NO_ERROR;
5171 }
5172 if (status == NO_ERROR) {
5173 readInputParameters();
5174 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5175 }
5176 }
5177 }
5178
5179 mNewParameters.removeAt(0);
5180
5181 mParamStatus = status;
5182 mParamCond.signal();
5183 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5184 // already timed out waiting for the status and will never signal the condition.
5185 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5186 }
5187 return reconfig;
5188}
5189
5190String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5191{
Eric Laurent81784c32012-11-19 14:55:58 -08005192 Mutex::Autolock _l(mLock);
5193 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005194 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005195 }
5196
Glenn Kastend8ea6992013-07-16 14:17:15 -07005197 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5198 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005199 free(s);
5200 return out_s8;
5201}
5202
5203void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5204 AudioSystem::OutputDescriptor desc;
5205 void *param2 = NULL;
5206
5207 switch (event) {
5208 case AudioSystem::INPUT_OPENED:
5209 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005210 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005211 desc.samplingRate = mSampleRate;
5212 desc.format = mFormat;
5213 desc.frameCount = mFrameCount;
5214 desc.latency = 0;
5215 param2 = &desc;
5216 break;
5217
5218 case AudioSystem::INPUT_CLOSED:
5219 default:
5220 break;
5221 }
5222 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5223}
5224
5225void AudioFlinger::RecordThread::readInputParameters()
5226{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005227 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005228 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005229 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005230 mRsmpOutBuffer = NULL;
5231 delete mResampler;
5232 mResampler = NULL;
5233
5234 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5235 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005236 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005237 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005238 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5239 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5240 }
Eric Laurent81784c32012-11-19 14:55:58 -08005241 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005242 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5243 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
Andy Hungab0ea0f2015-09-24 15:08:13 -07005245 memset(mRsmpInBuffer, 0, mFrameCount * mChannelCount * sizeof(mRsmpInBuffer[0]));
Eric Laurent81784c32012-11-19 14:55:58 -08005246
5247 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5248 {
5249 int channelCount;
5250 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5251 // stereo to mono post process as the resampler always outputs stereo.
5252 if (mChannelCount == 1 && mReqChannelCount == 2) {
5253 channelCount = 1;
5254 } else {
5255 channelCount = 2;
5256 }
5257 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5258 mResampler->setSampleRate(mSampleRate);
5259 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005260 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005261
5262 // optmization: if mono to mono, alter input frame count as if we were inputing
5263 // stereo samples
5264 if (mChannelCount == 1 && mReqChannelCount == 1) {
5265 mFrameCount >>= 1;
5266 }
5267
5268 }
5269 mRsmpInIndex = mFrameCount;
5270}
5271
5272unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5273{
5274 Mutex::Autolock _l(mLock);
5275 if (initCheck() != NO_ERROR) {
5276 return 0;
5277 }
5278
5279 return mInput->stream->get_input_frames_lost(mInput->stream);
5280}
5281
5282uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5283{
5284 Mutex::Autolock _l(mLock);
5285 uint32_t result = 0;
5286 if (getEffectChain_l(sessionId) != 0) {
5287 result = EFFECT_SESSION;
5288 }
5289
5290 for (size_t i = 0; i < mTracks.size(); ++i) {
5291 if (sessionId == mTracks[i]->sessionId()) {
5292 result |= TRACK_SESSION;
5293 break;
5294 }
5295 }
5296
5297 return result;
5298}
5299
5300KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5301{
5302 KeyedVector<int, bool> ids;
5303 Mutex::Autolock _l(mLock);
5304 for (size_t j = 0; j < mTracks.size(); ++j) {
5305 sp<RecordThread::RecordTrack> track = mTracks[j];
5306 int sessionId = track->sessionId();
5307 if (ids.indexOfKey(sessionId) < 0) {
5308 ids.add(sessionId, true);
5309 }
5310 }
5311 return ids;
5312}
5313
5314AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5315{
5316 Mutex::Autolock _l(mLock);
5317 AudioStreamIn *input = mInput;
5318 mInput = NULL;
5319 return input;
5320}
5321
5322// this method must always be called either with ThreadBase mLock held or inside the thread loop
5323audio_stream_t* AudioFlinger::RecordThread::stream() const
5324{
5325 if (mInput == NULL) {
5326 return NULL;
5327 }
5328 return &mInput->stream->common;
5329}
5330
5331status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5332{
5333 // only one chain per input thread
5334 if (mEffectChains.size() != 0) {
5335 return INVALID_OPERATION;
5336 }
5337 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5338
5339 chain->setInBuffer(NULL);
5340 chain->setOutBuffer(NULL);
5341
5342 checkSuspendOnAddEffectChain_l(chain);
5343
5344 mEffectChains.add(chain);
5345
5346 return NO_ERROR;
5347}
5348
5349size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5350{
5351 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5352 ALOGW_IF(mEffectChains.size() != 1,
5353 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5354 chain.get(), mEffectChains.size(), this);
5355 if (mEffectChains.size() == 1) {
5356 mEffectChains.removeAt(0);
5357 }
5358 return 0;
5359}
5360
5361}; // namespace android