blob: 1f8052763400809176d60b26c63f703f8b9abe0f [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
Glenn Kasten0f11b512014-01-31 16:18:54 -0800188void CpuStats::sample(const String8 &title
189#ifndef DEBUG_CPU_USAGE
190 __unused
191#endif
192 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef DEBUG_CPU_USAGE
194 // get current thread's delta CPU time in wall clock ns
195 double wcNs;
196 bool valid = mCpuUsage.sampleAndEnable(wcNs);
197
198 // record sample for wall clock statistics
199 if (valid) {
200 mWcStats.sample(wcNs);
201 }
202
203 // get the current CPU number
204 int cpuNum = sched_getcpu();
205
206 // get the current CPU frequency in kHz
207 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
208
209 // check if either CPU number or frequency changed
210 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
211 mCpuNum = cpuNum;
212 mCpukHz = cpukHz;
213 // ignore sample for purposes of cycles
214 valid = false;
215 }
216
217 // if no change in CPU number or frequency, then record sample for cycle statistics
218 if (valid && mCpukHz > 0) {
219 double cycles = wcNs * cpukHz * 0.000001;
220 mHzStats.sample(cycles);
221 }
222
223 unsigned n = mWcStats.n();
224 // mCpuUsage.elapsed() is expensive, so don't call it every loop
225 if ((n & 127) == 1) {
226 long long elapsed = mCpuUsage.elapsed();
227 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
228 double perLoop = elapsed / (double) n;
229 double perLoop100 = perLoop * 0.01;
230 double perLoop1k = perLoop * 0.001;
231 double mean = mWcStats.mean();
232 double stddev = mWcStats.stddev();
233 double minimum = mWcStats.minimum();
234 double maximum = mWcStats.maximum();
235 double meanCycles = mHzStats.mean();
236 double stddevCycles = mHzStats.stddev();
237 double minCycles = mHzStats.minimum();
238 double maxCycles = mHzStats.maximum();
239 mCpuUsage.resetElapsed();
240 mWcStats.reset();
241 mHzStats.reset();
242 ALOGD("CPU usage for %s over past %.1f secs\n"
243 " (%u mixer loops at %.1f mean ms per loop):\n"
244 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
245 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
246 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
247 title.string(),
248 elapsed * .000000001, n, perLoop * .000001,
249 mean * .001,
250 stddev * .001,
251 minimum * .001,
252 maximum * .001,
253 mean / perLoop100,
254 stddev / perLoop100,
255 minimum / perLoop100,
256 maximum / perLoop100,
257 meanCycles / perLoop1k,
258 stddevCycles / perLoop1k,
259 minCycles / perLoop1k,
260 maxCycles / perLoop1k);
261
262 }
263 }
264#endif
265};
266
267// ----------------------------------------------------------------------------
268// ThreadBase
269// ----------------------------------------------------------------------------
270
271AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
272 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
273 : Thread(false /*canCallJava*/),
274 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700275 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700276 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
277 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800278 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700279 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800280 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
281 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
282 // mName will be set by concrete (non-virtual) subclass
283 mDeathRecipient(new PMDeathRecipient(this))
284{
285}
286
287AudioFlinger::ThreadBase::~ThreadBase()
288{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700289 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
290 for (size_t i = 0; i < mConfigEvents.size(); i++) {
291 delete mConfigEvents[i];
292 }
293 mConfigEvents.clear();
294
Eric Laurent81784c32012-11-19 14:55:58 -0800295 mParamCond.broadcast();
296 // do not lock the mutex in destructor
297 releaseWakeLock_l();
298 if (mPowerManager != 0) {
299 sp<IBinder> binder = mPowerManager->asBinder();
300 binder->unlinkToDeath(mDeathRecipient);
301 }
302}
303
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700304status_t AudioFlinger::ThreadBase::readyToRun()
305{
306 status_t status = initCheck();
307 if (status == NO_ERROR) {
308 ALOGI("AudioFlinger's thread %p ready to run", this);
309 } else {
310 ALOGE("No working audio driver found.");
311 }
312 return status;
313}
314
Eric Laurent81784c32012-11-19 14:55:58 -0800315void AudioFlinger::ThreadBase::exit()
316{
317 ALOGV("ThreadBase::exit");
318 // do any cleanup required for exit to succeed
319 preExit();
320 {
321 // This lock prevents the following race in thread (uniprocessor for illustration):
322 // if (!exitPending()) {
323 // // context switch from here to exit()
324 // // exit() calls requestExit(), what exitPending() observes
325 // // exit() calls signal(), which is dropped since no waiters
326 // // context switch back from exit() to here
327 // mWaitWorkCV.wait(...);
328 // // now thread is hung
329 // }
330 AutoMutex lock(mLock);
331 requestExit();
332 mWaitWorkCV.broadcast();
333 }
334 // When Thread::requestExitAndWait is made virtual and this method is renamed to
335 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
336 requestExitAndWait();
337}
338
339status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
340{
341 status_t status;
342
343 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
344 Mutex::Autolock _l(mLock);
345
346 mNewParameters.add(keyValuePairs);
347 mWaitWorkCV.signal();
348 // wait condition with timeout in case the thread loop has exited
349 // before the request could be processed
350 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
351 status = mParamStatus;
352 mWaitWorkCV.signal();
353 } else {
354 status = TIMED_OUT;
355 }
356 return status;
357}
358
359void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
360{
361 Mutex::Autolock _l(mLock);
362 sendIoConfigEvent_l(event, param);
363}
364
365// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
366void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
367{
368 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
369 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
370 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
371 param);
372 mWaitWorkCV.signal();
373}
374
375// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
376void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
377{
378 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
379 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
380 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
381 mConfigEvents.size(), pid, tid, prio);
382 mWaitWorkCV.signal();
383}
384
385void AudioFlinger::ThreadBase::processConfigEvents()
386{
Glenn Kastenf7773312013-08-13 16:00:42 -0700387 Mutex::Autolock _l(mLock);
388 processConfigEvents_l();
389}
390
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700391// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700392void AudioFlinger::ThreadBase::processConfigEvents_l()
393{
Eric Laurent81784c32012-11-19 14:55:58 -0800394 while (!mConfigEvents.isEmpty()) {
395 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
396 ConfigEvent *event = mConfigEvents[0];
397 mConfigEvents.removeAt(0);
398 // release mLock before locking AudioFlinger mLock: lock order is always
399 // AudioFlinger then ThreadBase to avoid cross deadlock
400 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700401 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700402 case CFG_EVENT_PRIO: {
403 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
404 // FIXME Need to understand why this has be done asynchronously
405 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
406 true /*asynchronous*/);
407 if (err != 0) {
408 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
409 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
410 }
411 } break;
412 case CFG_EVENT_IO: {
413 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700414 {
415 Mutex::Autolock _l(mAudioFlinger->mLock);
416 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
417 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700418 } break;
419 default:
420 ALOGE("processConfigEvents() unknown event type %d", event->type());
421 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
423 delete event;
424 mLock.lock();
425 }
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
Glenn Kasten0f11b512014-01-31 16:18:54 -0800428void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800429{
430 const size_t SIZE = 256;
431 char buffer[SIZE];
432 String8 result;
433
434 bool locked = AudioFlinger::dumpTryLock(mLock);
435 if (!locked) {
436 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
437 write(fd, buffer, strlen(buffer));
438 }
439
440 snprintf(buffer, SIZE, "io handle: %d\n", mId);
441 result.append(buffer);
442 snprintf(buffer, SIZE, "TID: %d\n", getTid());
443 result.append(buffer);
444 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
445 result.append(buffer);
446 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
447 result.append(buffer);
448 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
449 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700450 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
451 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700452 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800453 result.append(buffer);
454 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
455 result.append(buffer);
456 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
457 result.append(buffer);
458 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
459 result.append(buffer);
460
461 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
462 result.append(buffer);
463 result.append(" Index Command");
464 for (size_t i = 0; i < mNewParameters.size(); ++i) {
465 snprintf(buffer, SIZE, "\n %02d ", i);
466 result.append(buffer);
467 result.append(mNewParameters[i]);
468 }
469
470 snprintf(buffer, SIZE, "\n\nPending config events: \n");
471 result.append(buffer);
472 for (size_t i = 0; i < mConfigEvents.size(); i++) {
473 mConfigEvents[i]->dump(buffer, SIZE);
474 result.append(buffer);
475 }
476 result.append("\n");
477
478 write(fd, result.string(), result.size());
479
480 if (locked) {
481 mLock.unlock();
482 }
483}
484
485void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
486{
487 const size_t SIZE = 256;
488 char buffer[SIZE];
489 String8 result;
490
491 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
492 write(fd, buffer, strlen(buffer));
493
494 for (size_t i = 0; i < mEffectChains.size(); ++i) {
495 sp<EffectChain> chain = mEffectChains[i];
496 if (chain != 0) {
497 chain->dump(fd, args);
498 }
499 }
500}
501
Marco Nelissene14a5d62013-10-03 08:51:24 -0700502void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800503{
504 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700505 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800506}
507
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100508String16 AudioFlinger::ThreadBase::getWakeLockTag()
509{
510 switch (mType) {
511 case MIXER:
512 return String16("AudioMix");
513 case DIRECT:
514 return String16("AudioDirectOut");
515 case DUPLICATING:
516 return String16("AudioDup");
517 case RECORD:
518 return String16("AudioIn");
519 case OFFLOAD:
520 return String16("AudioOffload");
521 default:
522 ALOG_ASSERT(false);
523 return String16("AudioUnknown");
524 }
525}
526
Marco Nelissene14a5d62013-10-03 08:51:24 -0700527void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800528{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800529 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800530 if (mPowerManager != 0) {
531 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700532 status_t status;
533 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700534 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700535 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100536 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700537 String16("media"),
538 uid);
539 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700540 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700541 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100542 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700543 String16("media"));
544 }
Eric Laurent81784c32012-11-19 14:55:58 -0800545 if (status == NO_ERROR) {
546 mWakeLockToken = binder;
547 }
548 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
549 }
550}
551
552void AudioFlinger::ThreadBase::releaseWakeLock()
553{
554 Mutex::Autolock _l(mLock);
555 releaseWakeLock_l();
556}
557
558void AudioFlinger::ThreadBase::releaseWakeLock_l()
559{
560 if (mWakeLockToken != 0) {
561 ALOGV("releaseWakeLock_l() %s", mName);
562 if (mPowerManager != 0) {
563 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
564 }
565 mWakeLockToken.clear();
566 }
567}
568
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800569void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
570 Mutex::Autolock _l(mLock);
571 updateWakeLockUids_l(uids);
572}
573
574void AudioFlinger::ThreadBase::getPowerManager_l() {
575
576 if (mPowerManager == 0) {
577 // use checkService() to avoid blocking if power service is not up yet
578 sp<IBinder> binder =
579 defaultServiceManager()->checkService(String16("power"));
580 if (binder == 0) {
581 ALOGW("Thread %s cannot connect to the power manager service", mName);
582 } else {
583 mPowerManager = interface_cast<IPowerManager>(binder);
584 binder->linkToDeath(mDeathRecipient);
585 }
586 }
587}
588
589void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
590
591 getPowerManager_l();
592 if (mWakeLockToken == NULL) {
593 ALOGE("no wake lock to update!");
594 return;
595 }
596 if (mPowerManager != 0) {
597 sp<IBinder> binder = new BBinder();
598 status_t status;
599 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
600 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
601 }
602}
603
Eric Laurent81784c32012-11-19 14:55:58 -0800604void AudioFlinger::ThreadBase::clearPowerManager()
605{
606 Mutex::Autolock _l(mLock);
607 releaseWakeLock_l();
608 mPowerManager.clear();
609}
610
Glenn Kasten0f11b512014-01-31 16:18:54 -0800611void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
613 sp<ThreadBase> thread = mThread.promote();
614 if (thread != 0) {
615 thread->clearPowerManager();
616 }
617 ALOGW("power manager service died !!!");
618}
619
620void AudioFlinger::ThreadBase::setEffectSuspended(
621 const effect_uuid_t *type, bool suspend, int sessionId)
622{
623 Mutex::Autolock _l(mLock);
624 setEffectSuspended_l(type, suspend, sessionId);
625}
626
627void AudioFlinger::ThreadBase::setEffectSuspended_l(
628 const effect_uuid_t *type, bool suspend, int sessionId)
629{
630 sp<EffectChain> chain = getEffectChain_l(sessionId);
631 if (chain != 0) {
632 if (type != NULL) {
633 chain->setEffectSuspended_l(type, suspend);
634 } else {
635 chain->setEffectSuspendedAll_l(suspend);
636 }
637 }
638
639 updateSuspendedSessions_l(type, suspend, sessionId);
640}
641
642void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
643{
644 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
645 if (index < 0) {
646 return;
647 }
648
649 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
650 mSuspendedSessions.valueAt(index);
651
652 for (size_t i = 0; i < sessionEffects.size(); i++) {
653 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
654 for (int j = 0; j < desc->mRefCount; j++) {
655 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
656 chain->setEffectSuspendedAll_l(true);
657 } else {
658 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
659 desc->mType.timeLow);
660 chain->setEffectSuspended_l(&desc->mType, true);
661 }
662 }
663 }
664}
665
666void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
667 bool suspend,
668 int sessionId)
669{
670 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
671
672 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
673
674 if (suspend) {
675 if (index >= 0) {
676 sessionEffects = mSuspendedSessions.valueAt(index);
677 } else {
678 mSuspendedSessions.add(sessionId, sessionEffects);
679 }
680 } else {
681 if (index < 0) {
682 return;
683 }
684 sessionEffects = mSuspendedSessions.valueAt(index);
685 }
686
687
688 int key = EffectChain::kKeyForSuspendAll;
689 if (type != NULL) {
690 key = type->timeLow;
691 }
692 index = sessionEffects.indexOfKey(key);
693
694 sp<SuspendedSessionDesc> desc;
695 if (suspend) {
696 if (index >= 0) {
697 desc = sessionEffects.valueAt(index);
698 } else {
699 desc = new SuspendedSessionDesc();
700 if (type != NULL) {
701 desc->mType = *type;
702 }
703 sessionEffects.add(key, desc);
704 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
705 }
706 desc->mRefCount++;
707 } else {
708 if (index < 0) {
709 return;
710 }
711 desc = sessionEffects.valueAt(index);
712 if (--desc->mRefCount == 0) {
713 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
714 sessionEffects.removeItemsAt(index);
715 if (sessionEffects.isEmpty()) {
716 ALOGV("updateSuspendedSessions_l() restore removing session %d",
717 sessionId);
718 mSuspendedSessions.removeItem(sessionId);
719 }
720 }
721 }
722 if (!sessionEffects.isEmpty()) {
723 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
724 }
725}
726
727void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
728 bool enabled,
729 int sessionId)
730{
731 Mutex::Autolock _l(mLock);
732 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
733}
734
735void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
736 bool enabled,
737 int sessionId)
738{
739 if (mType != RECORD) {
740 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
741 // another session. This gives the priority to well behaved effect control panels
742 // and applications not using global effects.
743 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
744 // global effects
745 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
746 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
747 }
748 }
749
750 sp<EffectChain> chain = getEffectChain_l(sessionId);
751 if (chain != 0) {
752 chain->checkSuspendOnEffectEnabled(effect, enabled);
753 }
754}
755
756// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
757sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
758 const sp<AudioFlinger::Client>& client,
759 const sp<IEffectClient>& effectClient,
760 int32_t priority,
761 int sessionId,
762 effect_descriptor_t *desc,
763 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700764 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800765{
766 sp<EffectModule> effect;
767 sp<EffectHandle> handle;
768 status_t lStatus;
769 sp<EffectChain> chain;
770 bool chainCreated = false;
771 bool effectCreated = false;
772 bool effectRegistered = false;
773
774 lStatus = initCheck();
775 if (lStatus != NO_ERROR) {
776 ALOGW("createEffect_l() Audio driver not initialized.");
777 goto Exit;
778 }
779
Eric Laurent5baf2af2013-09-12 17:37:00 -0700780 // Allow global effects only on offloaded and mixer threads
781 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
782 switch (mType) {
783 case MIXER:
784 case OFFLOAD:
785 break;
786 case DIRECT:
787 case DUPLICATING:
788 case RECORD:
789 default:
790 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
791 lStatus = BAD_VALUE;
792 goto Exit;
793 }
Eric Laurent81784c32012-11-19 14:55:58 -0800794 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700795
Eric Laurent81784c32012-11-19 14:55:58 -0800796 // Only Pre processor effects are allowed on input threads and only on input threads
797 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
798 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
799 desc->name, desc->flags, mType);
800 lStatus = BAD_VALUE;
801 goto Exit;
802 }
803
804 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
805
806 { // scope for mLock
807 Mutex::Autolock _l(mLock);
808
809 // check for existing effect chain with the requested audio session
810 chain = getEffectChain_l(sessionId);
811 if (chain == 0) {
812 // create a new chain for this session
813 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
814 chain = new EffectChain(this, sessionId);
815 addEffectChain_l(chain);
816 chain->setStrategy(getStrategyForSession_l(sessionId));
817 chainCreated = true;
818 } else {
819 effect = chain->getEffectFromDesc_l(desc);
820 }
821
822 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
823
824 if (effect == 0) {
825 int id = mAudioFlinger->nextUniqueId();
826 // Check CPU and memory usage
827 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
828 if (lStatus != NO_ERROR) {
829 goto Exit;
830 }
831 effectRegistered = true;
832 // create a new effect module if none present in the chain
833 effect = new EffectModule(this, chain, desc, id, sessionId);
834 lStatus = effect->status();
835 if (lStatus != NO_ERROR) {
836 goto Exit;
837 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700838 effect->setOffloaded(mType == OFFLOAD, mId);
839
Eric Laurent81784c32012-11-19 14:55:58 -0800840 lStatus = chain->addEffect_l(effect);
841 if (lStatus != NO_ERROR) {
842 goto Exit;
843 }
844 effectCreated = true;
845
846 effect->setDevice(mOutDevice);
847 effect->setDevice(mInDevice);
848 effect->setMode(mAudioFlinger->getMode());
849 effect->setAudioSource(mAudioSource);
850 }
851 // create effect handle and connect it to effect module
852 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800853 lStatus = handle->initCheck();
854 if (lStatus == OK) {
855 lStatus = effect->addHandle(handle.get());
856 }
Eric Laurent81784c32012-11-19 14:55:58 -0800857 if (enabled != NULL) {
858 *enabled = (int)effect->isEnabled();
859 }
860 }
861
862Exit:
863 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
864 Mutex::Autolock _l(mLock);
865 if (effectCreated) {
866 chain->removeEffect_l(effect);
867 }
868 if (effectRegistered) {
869 AudioSystem::unregisterEffect(effect->id());
870 }
871 if (chainCreated) {
872 removeEffectChain_l(chain);
873 }
874 handle.clear();
875 }
876
Glenn Kasten9156ef32013-08-06 15:39:08 -0700877 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800878 return handle;
879}
880
881sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
882{
883 Mutex::Autolock _l(mLock);
884 return getEffect_l(sessionId, effectId);
885}
886
887sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
888{
889 sp<EffectChain> chain = getEffectChain_l(sessionId);
890 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
891}
892
893// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
894// PlaybackThread::mLock held
895status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
896{
897 // check for existing effect chain with the requested audio session
898 int sessionId = effect->sessionId();
899 sp<EffectChain> chain = getEffectChain_l(sessionId);
900 bool chainCreated = false;
901
Eric Laurent5baf2af2013-09-12 17:37:00 -0700902 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
903 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
904 this, effect->desc().name, effect->desc().flags);
905
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (chain == 0) {
907 // create a new chain for this session
908 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
909 chain = new EffectChain(this, sessionId);
910 addEffectChain_l(chain);
911 chain->setStrategy(getStrategyForSession_l(sessionId));
912 chainCreated = true;
913 }
914 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
915
916 if (chain->getEffectFromId_l(effect->id()) != 0) {
917 ALOGW("addEffect_l() %p effect %s already present in chain %p",
918 this, effect->desc().name, chain.get());
919 return BAD_VALUE;
920 }
921
Eric Laurent5baf2af2013-09-12 17:37:00 -0700922 effect->setOffloaded(mType == OFFLOAD, mId);
923
Eric Laurent81784c32012-11-19 14:55:58 -0800924 status_t status = chain->addEffect_l(effect);
925 if (status != NO_ERROR) {
926 if (chainCreated) {
927 removeEffectChain_l(chain);
928 }
929 return status;
930 }
931
932 effect->setDevice(mOutDevice);
933 effect->setDevice(mInDevice);
934 effect->setMode(mAudioFlinger->getMode());
935 effect->setAudioSource(mAudioSource);
936 return NO_ERROR;
937}
938
939void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
940
941 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
942 effect_descriptor_t desc = effect->desc();
943 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
944 detachAuxEffect_l(effect->id());
945 }
946
947 sp<EffectChain> chain = effect->chain().promote();
948 if (chain != 0) {
949 // remove effect chain if removing last effect
950 if (chain->removeEffect_l(effect) == 0) {
951 removeEffectChain_l(chain);
952 }
953 } else {
954 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
955 }
956}
957
958void AudioFlinger::ThreadBase::lockEffectChains_l(
959 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
960{
961 effectChains = mEffectChains;
962 for (size_t i = 0; i < mEffectChains.size(); i++) {
963 mEffectChains[i]->lock();
964 }
965}
966
967void AudioFlinger::ThreadBase::unlockEffectChains(
968 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
969{
970 for (size_t i = 0; i < effectChains.size(); i++) {
971 effectChains[i]->unlock();
972 }
973}
974
975sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
976{
977 Mutex::Autolock _l(mLock);
978 return getEffectChain_l(sessionId);
979}
980
981sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
982{
983 size_t size = mEffectChains.size();
984 for (size_t i = 0; i < size; i++) {
985 if (mEffectChains[i]->sessionId() == sessionId) {
986 return mEffectChains[i];
987 }
988 }
989 return 0;
990}
991
992void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
993{
994 Mutex::Autolock _l(mLock);
995 size_t size = mEffectChains.size();
996 for (size_t i = 0; i < size; i++) {
997 mEffectChains[i]->setMode_l(mode);
998 }
999}
1000
1001void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1002 EffectHandle *handle,
1003 bool unpinIfLast) {
1004
1005 Mutex::Autolock _l(mLock);
1006 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1007 // delete the effect module if removing last handle on it
1008 if (effect->removeHandle(handle) == 0) {
1009 if (!effect->isPinned() || unpinIfLast) {
1010 removeEffect_l(effect);
1011 AudioSystem::unregisterEffect(effect->id());
1012 }
1013 }
1014}
1015
1016// ----------------------------------------------------------------------------
1017// Playback
1018// ----------------------------------------------------------------------------
1019
1020AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1021 AudioStreamOut* output,
1022 audio_io_handle_t id,
1023 audio_devices_t device,
1024 type_t type)
1025 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001026 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001027 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001028 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001029 // mStreamTypes[] initialized in constructor body
1030 mOutput(output),
1031 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1032 mMixerStatus(MIXER_IDLE),
1033 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1034 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001035 mBytesRemaining(0),
1036 mCurrentWriteLength(0),
1037 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001038 mWriteAckSequence(0),
1039 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001040 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001041 mScreenState(AudioFlinger::mScreenState),
1042 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001043 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1044 // mLatchD, mLatchQ,
1045 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001046{
1047 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001048 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001049
1050 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1051 // it would be safer to explicitly pass initial masterVolume/masterMute as
1052 // parameter.
1053 //
1054 // If the HAL we are using has support for master volume or master mute,
1055 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1056 // and the mute set to false).
1057 mMasterVolume = audioFlinger->masterVolume_l();
1058 mMasterMute = audioFlinger->masterMute_l();
1059 if (mOutput && mOutput->audioHwDev) {
1060 if (mOutput->audioHwDev->canSetMasterVolume()) {
1061 mMasterVolume = 1.0;
1062 }
1063
1064 if (mOutput->audioHwDev->canSetMasterMute()) {
1065 mMasterMute = false;
1066 }
1067 }
1068
1069 readOutputParameters();
1070
1071 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1072 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1073 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1074 stream = (audio_stream_type_t) (stream + 1)) {
1075 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1076 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1077 }
1078 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1079 // because mAudioFlinger doesn't have one to copy from
1080}
1081
1082AudioFlinger::PlaybackThread::~PlaybackThread()
1083{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001084 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001085 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001086}
1087
1088void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1089{
1090 dumpInternals(fd, args);
1091 dumpTracks(fd, args);
1092 dumpEffectChains(fd, args);
1093}
1094
Glenn Kasten0f11b512014-01-31 16:18:54 -08001095void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001096{
1097 const size_t SIZE = 256;
1098 char buffer[SIZE];
1099 String8 result;
1100
1101 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1102 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1103 const stream_type_t *st = &mStreamTypes[i];
1104 if (i > 0) {
1105 result.appendFormat(", ");
1106 }
1107 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1108 if (st->mute) {
1109 result.append("M");
1110 }
1111 }
1112 result.append("\n");
1113 write(fd, result.string(), result.length());
1114 result.clear();
1115
1116 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1117 result.append(buffer);
1118 Track::appendDumpHeader(result);
1119 for (size_t i = 0; i < mTracks.size(); ++i) {
1120 sp<Track> track = mTracks[i];
1121 if (track != 0) {
1122 track->dump(buffer, SIZE);
1123 result.append(buffer);
1124 }
1125 }
1126
1127 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1128 result.append(buffer);
1129 Track::appendDumpHeader(result);
1130 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1131 sp<Track> track = mActiveTracks[i].promote();
1132 if (track != 0) {
1133 track->dump(buffer, SIZE);
1134 result.append(buffer);
1135 }
1136 }
1137 write(fd, result.string(), result.size());
1138
1139 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1140 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1141 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1142 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1143}
1144
1145void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1146{
1147 const size_t SIZE = 256;
1148 char buffer[SIZE];
1149 String8 result;
1150
1151 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1152 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001153 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1154 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001155 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1156 ns2ms(systemTime() - mLastWriteTime));
1157 result.append(buffer);
1158 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1159 result.append(buffer);
1160 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1161 result.append(buffer);
1162 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1163 result.append(buffer);
1164 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1165 result.append(buffer);
1166 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1167 result.append(buffer);
1168 write(fd, result.string(), result.size());
1169 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1170
1171 dumpBase(fd, args);
1172}
1173
1174// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001175
1176void AudioFlinger::PlaybackThread::onFirstRef()
1177{
1178 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1179}
1180
1181// ThreadBase virtuals
1182void AudioFlinger::PlaybackThread::preExit()
1183{
1184 ALOGV(" preExit()");
1185 // FIXME this is using hard-coded strings but in the future, this functionality will be
1186 // converted to use audio HAL extensions required to support tunneling
1187 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1188}
1189
1190// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1191sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1192 const sp<AudioFlinger::Client>& client,
1193 audio_stream_type_t streamType,
1194 uint32_t sampleRate,
1195 audio_format_t format,
1196 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001197 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001198 const sp<IMemory>& sharedBuffer,
1199 int sessionId,
1200 IAudioFlinger::track_flags_t *flags,
1201 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001202 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001203 status_t *status)
1204{
Glenn Kasten74935e42013-12-19 08:56:45 -08001205 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001206 sp<Track> track;
1207 status_t lStatus;
1208
1209 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1210
1211 // client expresses a preference for FAST, but we get the final say
1212 if (*flags & IAudioFlinger::TRACK_FAST) {
1213 if (
1214 // not timed
1215 (!isTimed) &&
1216 // either of these use cases:
1217 (
1218 // use case 1: shared buffer with any frame count
1219 (
1220 (sharedBuffer != 0)
1221 ) ||
1222 // use case 2: callback handler and frame count is default or at least as large as HAL
1223 (
1224 (tid != -1) &&
1225 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001226 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001227 )
1228 ) &&
1229 // PCM data
1230 audio_is_linear_pcm(format) &&
1231 // mono or stereo
1232 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1233 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1234#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1235 // hardware sample rate
1236 (sampleRate == mSampleRate) &&
1237#endif
1238 // normal mixer has an associated fast mixer
1239 hasFastMixer() &&
1240 // there are sufficient fast track slots available
1241 (mFastTrackAvailMask != 0)
1242 // FIXME test that MixerThread for this fast track has a capable output HAL
1243 // FIXME add a permission test also?
1244 ) {
1245 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1246 if (frameCount == 0) {
1247 frameCount = mFrameCount * kFastTrackMultiplier;
1248 }
1249 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1250 frameCount, mFrameCount);
1251 } else {
1252 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1253 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1254 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1255 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1256 audio_is_linear_pcm(format),
1257 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1258 *flags &= ~IAudioFlinger::TRACK_FAST;
1259 // For compatibility with AudioTrack calculation, buffer depth is forced
1260 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1261 // This is probably too conservative, but legacy application code may depend on it.
1262 // If you change this calculation, also review the start threshold which is related.
1263 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1264 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1265 if (minBufCount < 2) {
1266 minBufCount = 2;
1267 }
1268 size_t minFrameCount = mNormalFrameCount * minBufCount;
1269 if (frameCount < minFrameCount) {
1270 frameCount = minFrameCount;
1271 }
1272 }
1273 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001274 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001275
1276 if (mType == DIRECT) {
1277 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1278 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1279 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1280 "for output %p with format %d",
1281 sampleRate, format, channelMask, mOutput, mFormat);
1282 lStatus = BAD_VALUE;
1283 goto Exit;
1284 }
1285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001286 } else if (mType == OFFLOAD) {
1287 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1288 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1289 "for output %p with format %d",
1290 sampleRate, format, channelMask, mOutput, mFormat);
1291 lStatus = BAD_VALUE;
1292 goto Exit;
1293 }
Eric Laurent81784c32012-11-19 14:55:58 -08001294 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001295 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1296 ALOGE("createTrack_l() Bad parameter: format %d \""
1297 "for output %p with format %d",
1298 format, mOutput, mFormat);
1299 lStatus = BAD_VALUE;
1300 goto Exit;
1301 }
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1303 if (sampleRate > mSampleRate*2) {
1304 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1305 lStatus = BAD_VALUE;
1306 goto Exit;
1307 }
1308 }
1309
1310 lStatus = initCheck();
1311 if (lStatus != NO_ERROR) {
1312 ALOGE("Audio driver not initialized.");
1313 goto Exit;
1314 }
1315
1316 { // scope for mLock
1317 Mutex::Autolock _l(mLock);
1318
1319 // all tracks in same audio session must share the same routing strategy otherwise
1320 // conflicts will happen when tracks are moved from one output to another by audio policy
1321 // manager
1322 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1323 for (size_t i = 0; i < mTracks.size(); ++i) {
1324 sp<Track> t = mTracks[i];
1325 if (t != 0 && !t->isOutputTrack()) {
1326 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1327 if (sessionId == t->sessionId() && strategy != actual) {
1328 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1329 strategy, actual);
1330 lStatus = BAD_VALUE;
1331 goto Exit;
1332 }
1333 }
1334 }
1335
1336 if (!isTimed) {
1337 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001338 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001339 } else {
1340 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001341 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001342 }
Glenn Kasten03003332013-08-06 15:40:54 -07001343
1344 // new Track always returns non-NULL,
1345 // but TimedTrack::create() is a factory that could fail by returning NULL
1346 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1347 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001348 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07001349 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001350 goto Exit;
1351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001352
Eric Laurent81784c32012-11-19 14:55:58 -08001353 mTracks.add(track);
1354
1355 sp<EffectChain> chain = getEffectChain_l(sessionId);
1356 if (chain != 0) {
1357 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1358 track->setMainBuffer(chain->inBuffer());
1359 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1360 chain->incTrackCnt();
1361 }
1362
1363 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1364 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1365 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1366 // so ask activity manager to do this on our behalf
1367 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1368 }
1369 }
1370
1371 lStatus = NO_ERROR;
1372
1373Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001374 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001375 return track;
1376}
1377
1378uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1379{
1380 return latency;
1381}
1382
1383uint32_t AudioFlinger::PlaybackThread::latency() const
1384{
1385 Mutex::Autolock _l(mLock);
1386 return latency_l();
1387}
1388uint32_t AudioFlinger::PlaybackThread::latency_l() const
1389{
1390 if (initCheck() == NO_ERROR) {
1391 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1392 } else {
1393 return 0;
1394 }
1395}
1396
1397void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1398{
1399 Mutex::Autolock _l(mLock);
1400 // Don't apply master volume in SW if our HAL can do it for us.
1401 if (mOutput && mOutput->audioHwDev &&
1402 mOutput->audioHwDev->canSetMasterVolume()) {
1403 mMasterVolume = 1.0;
1404 } else {
1405 mMasterVolume = value;
1406 }
1407}
1408
1409void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1410{
1411 Mutex::Autolock _l(mLock);
1412 // Don't apply master mute in SW if our HAL can do it for us.
1413 if (mOutput && mOutput->audioHwDev &&
1414 mOutput->audioHwDev->canSetMasterMute()) {
1415 mMasterMute = false;
1416 } else {
1417 mMasterMute = muted;
1418 }
1419}
1420
1421void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1422{
1423 Mutex::Autolock _l(mLock);
1424 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001425 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001426}
1427
1428void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1429{
1430 Mutex::Autolock _l(mLock);
1431 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001432 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001433}
1434
1435float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1436{
1437 Mutex::Autolock _l(mLock);
1438 return mStreamTypes[stream].volume;
1439}
1440
1441// addTrack_l() must be called with ThreadBase::mLock held
1442status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1443{
1444 status_t status = ALREADY_EXISTS;
1445
1446 // set retry count for buffer fill
1447 track->mRetryCount = kMaxTrackStartupRetries;
1448 if (mActiveTracks.indexOf(track) < 0) {
1449 // the track is newly added, make sure it fills up all its
1450 // buffers before playing. This is to ensure the client will
1451 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001452 if (!track->isOutputTrack()) {
1453 TrackBase::track_state state = track->mState;
1454 mLock.unlock();
1455 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1456 mLock.lock();
1457 // abort track was stopped/paused while we released the lock
1458 if (state != track->mState) {
1459 if (status == NO_ERROR) {
1460 mLock.unlock();
1461 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1462 mLock.lock();
1463 }
1464 return INVALID_OPERATION;
1465 }
1466 // abort if start is rejected by audio policy manager
1467 if (status != NO_ERROR) {
1468 return PERMISSION_DENIED;
1469 }
1470#ifdef ADD_BATTERY_DATA
1471 // to track the speaker usage
1472 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1473#endif
1474 }
1475
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001476 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001477 track->mResetDone = false;
1478 track->mPresentationCompleteFrames = 0;
1479 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001480 mWakeLockUids.add(track->uid());
1481 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001482 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001483 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1484 if (chain != 0) {
1485 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1486 track->sessionId());
1487 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001488 }
1489
1490 status = NO_ERROR;
1491 }
1492
Eric Laurentede6c3b2013-09-19 14:37:46 -07001493 ALOGV("signal playback thread");
1494 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001495
1496 return status;
1497}
1498
Eric Laurentbfb1b832013-01-07 09:53:42 -08001499bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001500{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001501 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001502 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001503 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1504 track->mState = TrackBase::STOPPED;
1505 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001506 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001507 } else if (track->isFastTrack() || track->isOffloaded()) {
1508 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001509 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001510
1511 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001512}
1513
1514void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1515{
1516 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1517 mTracks.remove(track);
1518 deleteTrackName_l(track->name());
1519 // redundant as track is about to be destroyed, for dumpsys only
1520 track->mName = -1;
1521 if (track->isFastTrack()) {
1522 int index = track->mFastIndex;
1523 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1524 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1525 mFastTrackAvailMask |= 1 << index;
1526 // redundant as track is about to be destroyed, for dumpsys only
1527 track->mFastIndex = -1;
1528 }
1529 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1530 if (chain != 0) {
1531 chain->decTrackCnt();
1532 }
1533}
1534
Eric Laurentede6c3b2013-09-19 14:37:46 -07001535void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001536{
1537 // Thread could be blocked waiting for async
1538 // so signal it to handle state changes immediately
1539 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1540 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1541 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001542 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001543}
1544
Eric Laurent81784c32012-11-19 14:55:58 -08001545String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1546{
Eric Laurent81784c32012-11-19 14:55:58 -08001547 Mutex::Autolock _l(mLock);
1548 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001549 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001550 }
1551
Glenn Kastend8ea6992013-07-16 14:17:15 -07001552 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1553 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001554 free(s);
1555 return out_s8;
1556}
1557
1558// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1559void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1560 AudioSystem::OutputDescriptor desc;
1561 void *param2 = NULL;
1562
1563 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1564 param);
1565
1566 switch (event) {
1567 case AudioSystem::OUTPUT_OPENED:
1568 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001569 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001570 desc.samplingRate = mSampleRate;
1571 desc.format = mFormat;
1572 desc.frameCount = mNormalFrameCount; // FIXME see
1573 // AudioFlinger::frameCount(audio_io_handle_t)
1574 desc.latency = latency();
1575 param2 = &desc;
1576 break;
1577
1578 case AudioSystem::STREAM_CONFIG_CHANGED:
1579 param2 = &param;
1580 case AudioSystem::OUTPUT_CLOSED:
1581 default:
1582 break;
1583 }
1584 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1585}
1586
Eric Laurentbfb1b832013-01-07 09:53:42 -08001587void AudioFlinger::PlaybackThread::writeCallback()
1588{
1589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001590 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001591}
1592
1593void AudioFlinger::PlaybackThread::drainCallback()
1594{
1595 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001596 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001597}
1598
Eric Laurent3b4529e2013-09-05 18:09:19 -07001599void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600{
1601 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001602 // reject out of sequence requests
1603 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1604 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001605 mWaitWorkCV.signal();
1606 }
1607}
1608
Eric Laurent3b4529e2013-09-05 18:09:19 -07001609void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001610{
1611 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001612 // reject out of sequence requests
1613 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1614 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001615 mWaitWorkCV.signal();
1616 }
1617}
1618
1619// static
1620int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001621 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001622 void *cookie)
1623{
1624 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1625 ALOGV("asyncCallback() event %d", event);
1626 switch (event) {
1627 case STREAM_CBK_EVENT_WRITE_READY:
1628 me->writeCallback();
1629 break;
1630 case STREAM_CBK_EVENT_DRAIN_READY:
1631 me->drainCallback();
1632 break;
1633 default:
1634 ALOGW("asyncCallback() unknown event %d", event);
1635 break;
1636 }
1637 return 0;
1638}
1639
Eric Laurent81784c32012-11-19 14:55:58 -08001640void AudioFlinger::PlaybackThread::readOutputParameters()
1641{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001642 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001643 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1644 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001645 if (!audio_is_output_channel(mChannelMask)) {
1646 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1647 }
1648 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1649 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1650 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1651 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001652 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001653 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001654 if (!audio_is_valid_format(mFormat)) {
1655 LOG_FATAL("HAL format %d not valid for output", mFormat);
1656 }
1657 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1658 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1659 mFormat);
1660 }
Eric Laurent81784c32012-11-19 14:55:58 -08001661 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001662 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1663 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001664 if (mFrameCount & 15) {
1665 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1666 mFrameCount);
1667 }
1668
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1670 (mOutput->stream->set_callback != NULL)) {
1671 if (mOutput->stream->set_callback(mOutput->stream,
1672 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1673 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001674 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001675 }
1676 }
1677
Eric Laurent81784c32012-11-19 14:55:58 -08001678 // Calculate size of normal mix buffer relative to the HAL output buffer size
1679 double multiplier = 1.0;
1680 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1681 kUseFastMixer == FastMixer_Dynamic)) {
1682 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1683 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1684 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1685 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1686 maxNormalFrameCount = maxNormalFrameCount & ~15;
1687 if (maxNormalFrameCount < minNormalFrameCount) {
1688 maxNormalFrameCount = minNormalFrameCount;
1689 }
1690 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1691 if (multiplier <= 1.0) {
1692 multiplier = 1.0;
1693 } else if (multiplier <= 2.0) {
1694 if (2 * mFrameCount <= maxNormalFrameCount) {
1695 multiplier = 2.0;
1696 } else {
1697 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1698 }
1699 } else {
1700 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1701 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1702 // track, but we sometimes have to do this to satisfy the maximum frame count
1703 // constraint)
1704 // FIXME this rounding up should not be done if no HAL SRC
1705 uint32_t truncMult = (uint32_t) multiplier;
1706 if ((truncMult & 1)) {
1707 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1708 ++truncMult;
1709 }
1710 }
1711 multiplier = (double) truncMult;
1712 }
1713 }
1714 mNormalFrameCount = multiplier * mFrameCount;
1715 // round up to nearest 16 frames to satisfy AudioMixer
1716 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1717 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1718 mNormalFrameCount);
1719
Glenn Kastenc1fac192013-08-06 07:41:36 -07001720 delete[] mMixBuffer;
1721 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1722 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1723 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1724 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001725
1726 // force reconfiguration of effect chains and engines to take new buffer size and audio
1727 // parameters into account
1728 // Note that mLock is not held when readOutputParameters() is called from the constructor
1729 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1730 // matter.
1731 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1732 Vector< sp<EffectChain> > effectChains = mEffectChains;
1733 for (size_t i = 0; i < effectChains.size(); i ++) {
1734 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1735 }
1736}
1737
1738
1739status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1740{
1741 if (halFrames == NULL || dspFrames == NULL) {
1742 return BAD_VALUE;
1743 }
1744 Mutex::Autolock _l(mLock);
1745 if (initCheck() != NO_ERROR) {
1746 return INVALID_OPERATION;
1747 }
1748 size_t framesWritten = mBytesWritten / mFrameSize;
1749 *halFrames = framesWritten;
1750
1751 if (isSuspended()) {
1752 // return an estimation of rendered frames when the output is suspended
1753 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1754 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1755 return NO_ERROR;
1756 } else {
1757 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1758 }
1759}
1760
1761uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1762{
1763 Mutex::Autolock _l(mLock);
1764 uint32_t result = 0;
1765 if (getEffectChain_l(sessionId) != 0) {
1766 result = EFFECT_SESSION;
1767 }
1768
1769 for (size_t i = 0; i < mTracks.size(); ++i) {
1770 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001771 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001772 result |= TRACK_SESSION;
1773 break;
1774 }
1775 }
1776
1777 return result;
1778}
1779
1780uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1781{
1782 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1783 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1784 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1785 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1786 }
1787 for (size_t i = 0; i < mTracks.size(); i++) {
1788 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001789 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001790 return AudioSystem::getStrategyForStream(track->streamType());
1791 }
1792 }
1793 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1794}
1795
1796
1797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1798{
1799 Mutex::Autolock _l(mLock);
1800 return mOutput;
1801}
1802
1803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 AudioStreamOut *output = mOutput;
1807 mOutput = NULL;
1808 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1809 // must push a NULL and wait for ack
1810 mOutputSink.clear();
1811 mPipeSink.clear();
1812 mNormalSink.clear();
1813 return output;
1814}
1815
1816// this method must always be called either with ThreadBase mLock held or inside the thread loop
1817audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1818{
1819 if (mOutput == NULL) {
1820 return NULL;
1821 }
1822 return &mOutput->stream->common;
1823}
1824
1825uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1826{
1827 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1828}
1829
1830status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1831{
1832 if (!isValidSyncEvent(event)) {
1833 return BAD_VALUE;
1834 }
1835
1836 Mutex::Autolock _l(mLock);
1837
1838 for (size_t i = 0; i < mTracks.size(); ++i) {
1839 sp<Track> track = mTracks[i];
1840 if (event->triggerSession() == track->sessionId()) {
1841 (void) track->setSyncEvent(event);
1842 return NO_ERROR;
1843 }
1844 }
1845
1846 return NAME_NOT_FOUND;
1847}
1848
1849bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1850{
1851 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1852}
1853
1854void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1855 const Vector< sp<Track> >& tracksToRemove)
1856{
1857 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001858 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001859 for (size_t i = 0 ; i < count ; i++) {
1860 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001861 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001862 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001863#ifdef ADD_BATTERY_DATA
1864 // to track the speaker usage
1865 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1866#endif
1867 if (track->isTerminated()) {
1868 AudioSystem::releaseOutput(mId);
1869 }
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871 }
1872 }
Eric Laurent81784c32012-11-19 14:55:58 -08001873}
1874
1875void AudioFlinger::PlaybackThread::checkSilentMode_l()
1876{
1877 if (!mMasterMute) {
1878 char value[PROPERTY_VALUE_MAX];
1879 if (property_get("ro.audio.silent", value, "0") > 0) {
1880 char *endptr;
1881 unsigned long ul = strtoul(value, &endptr, 0);
1882 if (*endptr == '\0' && ul != 0) {
1883 ALOGD("Silence is golden");
1884 // The setprop command will not allow a property to be changed after
1885 // the first time it is set, so we don't have to worry about un-muting.
1886 setMasterMute_l(true);
1887 }
1888 }
1889 }
1890}
1891
1892// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001893ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001894{
1895 // FIXME rewrite to reduce number of system calls
1896 mLastWriteTime = systemTime();
1897 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001899
1900 // If an NBAIO sink is present, use it to write the normal mixer's submix
1901 if (mNormalSink != 0) {
1902#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001903 size_t count = mBytesRemaining >> mBitShift;
1904 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001905 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001906 // update the setpoint when AudioFlinger::mScreenState changes
1907 uint32_t screenState = AudioFlinger::mScreenState;
1908 if (screenState != mScreenState) {
1909 mScreenState = screenState;
1910 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1911 if (pipe != NULL) {
1912 pipe->setAvgFrames((mScreenState & 1) ?
1913 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1914 }
1915 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001916 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001917 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001918 if (framesWritten > 0) {
1919 bytesWritten = framesWritten << mBitShift;
1920 } else {
1921 bytesWritten = framesWritten;
1922 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001923 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001924 if (status == NO_ERROR) {
1925 size_t totalFramesWritten = mNormalSink->framesWritten();
1926 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1927 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1928 mLatchDValid = true;
1929 }
1930 }
Eric Laurent81784c32012-11-19 14:55:58 -08001931 // otherwise use the HAL / AudioStreamOut directly
1932 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001933 // Direct output and offload threads
Eric Laurent04733db2013-11-22 09:29:56 -08001934 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001936 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1937 mWriteAckSequence += 2;
1938 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001940 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001942 // FIXME We should have an implementation of timestamps for direct output threads.
1943 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent04733db2013-11-22 09:29:56 -08001945 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001946 if (mUseAsyncWrite &&
1947 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1948 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001949 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001951 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 }
Eric Laurent81784c32012-11-19 14:55:58 -08001953 }
1954
Eric Laurent81784c32012-11-19 14:55:58 -08001955 mNumWrites++;
1956 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001957 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 return bytesWritten;
1959}
1960
1961void AudioFlinger::PlaybackThread::threadLoop_drain()
1962{
1963 if (mOutput->stream->drain) {
1964 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1965 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001966 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1967 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001969 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 }
1971 mOutput->stream->drain(mOutput->stream,
1972 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1973 : AUDIO_DRAIN_ALL);
1974 }
1975}
1976
1977void AudioFlinger::PlaybackThread::threadLoop_exit()
1978{
1979 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001980}
1981
1982/*
1983The derived values that are cached:
1984 - mixBufferSize from frame count * frame size
1985 - activeSleepTime from activeSleepTimeUs()
1986 - idleSleepTime from idleSleepTimeUs()
1987 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1988 - maxPeriod from frame count and sample rate (MIXER only)
1989
1990The parameters that affect these derived values are:
1991 - frame count
1992 - frame size
1993 - sample rate
1994 - device type: A2DP or not
1995 - device latency
1996 - format: PCM or not
1997 - active sleep time
1998 - idle sleep time
1999*/
2000
2001void AudioFlinger::PlaybackThread::cacheParameters_l()
2002{
2003 mixBufferSize = mNormalFrameCount * mFrameSize;
2004 activeSleepTime = activeSleepTimeUs();
2005 idleSleepTime = idleSleepTimeUs();
2006}
2007
2008void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2009{
Glenn Kasten7c027242012-12-26 14:43:16 -08002010 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002011 this, streamType, mTracks.size());
2012 Mutex::Autolock _l(mLock);
2013
2014 size_t size = mTracks.size();
2015 for (size_t i = 0; i < size; i++) {
2016 sp<Track> t = mTracks[i];
2017 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002018 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002019 }
2020 }
2021}
2022
2023status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2024{
2025 int session = chain->sessionId();
2026 int16_t *buffer = mMixBuffer;
2027 bool ownsBuffer = false;
2028
2029 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2030 if (session > 0) {
2031 // Only one effect chain can be present in direct output thread and it uses
2032 // the mix buffer as input
2033 if (mType != DIRECT) {
2034 size_t numSamples = mNormalFrameCount * mChannelCount;
2035 buffer = new int16_t[numSamples];
2036 memset(buffer, 0, numSamples * sizeof(int16_t));
2037 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2038 ownsBuffer = true;
2039 }
2040
2041 // Attach all tracks with same session ID to this chain.
2042 for (size_t i = 0; i < mTracks.size(); ++i) {
2043 sp<Track> track = mTracks[i];
2044 if (session == track->sessionId()) {
2045 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2046 buffer);
2047 track->setMainBuffer(buffer);
2048 chain->incTrackCnt();
2049 }
2050 }
2051
2052 // indicate all active tracks in the chain
2053 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2054 sp<Track> track = mActiveTracks[i].promote();
2055 if (track == 0) {
2056 continue;
2057 }
2058 if (session == track->sessionId()) {
2059 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2060 chain->incActiveTrackCnt();
2061 }
2062 }
2063 }
2064
2065 chain->setInBuffer(buffer, ownsBuffer);
2066 chain->setOutBuffer(mMixBuffer);
2067 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2068 // chains list in order to be processed last as it contains output stage effects
2069 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2070 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2071 // after track specific effects and before output stage
2072 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2073 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2074 // Effect chain for other sessions are inserted at beginning of effect
2075 // chains list to be processed before output mix effects. Relative order between other
2076 // sessions is not important
2077 size_t size = mEffectChains.size();
2078 size_t i = 0;
2079 for (i = 0; i < size; i++) {
2080 if (mEffectChains[i]->sessionId() < session) {
2081 break;
2082 }
2083 }
2084 mEffectChains.insertAt(chain, i);
2085 checkSuspendOnAddEffectChain_l(chain);
2086
2087 return NO_ERROR;
2088}
2089
2090size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2091{
2092 int session = chain->sessionId();
2093
2094 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2095
2096 for (size_t i = 0; i < mEffectChains.size(); i++) {
2097 if (chain == mEffectChains[i]) {
2098 mEffectChains.removeAt(i);
2099 // detach all active tracks from the chain
2100 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2101 sp<Track> track = mActiveTracks[i].promote();
2102 if (track == 0) {
2103 continue;
2104 }
2105 if (session == track->sessionId()) {
2106 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2107 chain.get(), session);
2108 chain->decActiveTrackCnt();
2109 }
2110 }
2111
2112 // detach all tracks with same session ID from this chain
2113 for (size_t i = 0; i < mTracks.size(); ++i) {
2114 sp<Track> track = mTracks[i];
2115 if (session == track->sessionId()) {
2116 track->setMainBuffer(mMixBuffer);
2117 chain->decTrackCnt();
2118 }
2119 }
2120 break;
2121 }
2122 }
2123 return mEffectChains.size();
2124}
2125
2126status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2127 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2128{
2129 Mutex::Autolock _l(mLock);
2130 return attachAuxEffect_l(track, EffectId);
2131}
2132
2133status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2134 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2135{
2136 status_t status = NO_ERROR;
2137
2138 if (EffectId == 0) {
2139 track->setAuxBuffer(0, NULL);
2140 } else {
2141 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2142 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2143 if (effect != 0) {
2144 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2145 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2146 } else {
2147 status = INVALID_OPERATION;
2148 }
2149 } else {
2150 status = BAD_VALUE;
2151 }
2152 }
2153 return status;
2154}
2155
2156void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2157{
2158 for (size_t i = 0; i < mTracks.size(); ++i) {
2159 sp<Track> track = mTracks[i];
2160 if (track->auxEffectId() == effectId) {
2161 attachAuxEffect_l(track, 0);
2162 }
2163 }
2164}
2165
2166bool AudioFlinger::PlaybackThread::threadLoop()
2167{
2168 Vector< sp<Track> > tracksToRemove;
2169
2170 standbyTime = systemTime();
2171
2172 // MIXER
2173 nsecs_t lastWarning = 0;
2174
2175 // DUPLICATING
2176 // FIXME could this be made local to while loop?
2177 writeFrames = 0;
2178
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002179 int lastGeneration = 0;
2180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 cacheParameters_l();
2182 sleepTime = idleSleepTime;
2183
2184 if (mType == MIXER) {
2185 sleepTimeShift = 0;
2186 }
2187
2188 CpuStats cpuStats;
2189 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2190
2191 acquireWakeLock();
2192
Glenn Kasten9e58b552013-01-18 15:09:48 -08002193 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2194 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2195 // and then that string will be logged at the next convenient opportunity.
2196 const char *logString = NULL;
2197
Eric Laurent664539d2013-09-23 18:24:31 -07002198 checkSilentMode_l();
2199
Eric Laurent81784c32012-11-19 14:55:58 -08002200 while (!exitPending())
2201 {
2202 cpuStats.sample(myName);
2203
2204 Vector< sp<EffectChain> > effectChains;
2205
2206 processConfigEvents();
2207
2208 { // scope for mLock
2209
2210 Mutex::Autolock _l(mLock);
2211
Glenn Kasten9e58b552013-01-18 15:09:48 -08002212 if (logString != NULL) {
2213 mNBLogWriter->logTimestamp();
2214 mNBLogWriter->log(logString);
2215 logString = NULL;
2216 }
2217
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002218 if (mLatchDValid) {
2219 mLatchQ = mLatchD;
2220 mLatchDValid = false;
2221 mLatchQValid = true;
2222 }
2223
Eric Laurent81784c32012-11-19 14:55:58 -08002224 if (checkForNewParameters_l()) {
2225 cacheParameters_l();
2226 }
2227
2228 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002229 if (mSignalPending) {
2230 // A signal was raised while we were unlocked
2231 mSignalPending = false;
2232 } else if (waitingAsyncCallback_l()) {
2233 if (exitPending()) {
2234 break;
2235 }
2236 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002237 mWakeLockUids.clear();
2238 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002239 ALOGV("wait async completion");
2240 mWaitWorkCV.wait(mLock);
2241 ALOGV("async completion/wake");
2242 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002243 standbyTime = systemTime() + standbyDelay;
2244 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002245
2246 continue;
2247 }
2248 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 isSuspended()) {
2250 // put audio hardware into standby after short delay
2251 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002252
2253 threadLoop_standby();
2254
2255 mStandby = true;
2256 }
2257
2258 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2259 // we're about to wait, flush the binder command buffer
2260 IPCThreadState::self()->flushCommands();
2261
2262 clearOutputTracks();
2263
2264 if (exitPending()) {
2265 break;
2266 }
2267
2268 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002269 mWakeLockUids.clear();
2270 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002271 // wait until we have something to do...
2272 ALOGV("%s going to sleep", myName.string());
2273 mWaitWorkCV.wait(mLock);
2274 ALOGV("%s waking up", myName.string());
2275 acquireWakeLock_l();
2276
2277 mMixerStatus = MIXER_IDLE;
2278 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2279 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002281 checkSilentMode_l();
2282
2283 standbyTime = systemTime() + standbyDelay;
2284 sleepTime = idleSleepTime;
2285 if (mType == MIXER) {
2286 sleepTimeShift = 0;
2287 }
2288
2289 continue;
2290 }
2291 }
Eric Laurent81784c32012-11-19 14:55:58 -08002292 // mMixerStatusIgnoringFastTracks is also updated internally
2293 mMixerStatus = prepareTracks_l(&tracksToRemove);
2294
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002295 // compare with previously applied list
2296 if (lastGeneration != mActiveTracksGeneration) {
2297 // update wakelock
2298 updateWakeLockUids_l(mWakeLockUids);
2299 lastGeneration = mActiveTracksGeneration;
2300 }
2301
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // prevent any changes in effect chain list and in each effect chain
2303 // during mixing and effect process as the audio buffers could be deleted
2304 // or modified if an effect is created or deleted
2305 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002306 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002307
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 if (mBytesRemaining == 0) {
2309 mCurrentWriteLength = 0;
2310 if (mMixerStatus == MIXER_TRACKS_READY) {
2311 // threadLoop_mix() sets mCurrentWriteLength
2312 threadLoop_mix();
2313 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2314 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2315 // threadLoop_sleepTime sets sleepTime to 0 if data
2316 // must be written to HAL
2317 threadLoop_sleepTime();
2318 if (sleepTime == 0) {
2319 mCurrentWriteLength = mixBufferSize;
2320 }
2321 }
2322 mBytesRemaining = mCurrentWriteLength;
2323 if (isSuspended()) {
2324 sleepTime = suspendSleepTimeUs();
2325 // simulate write to HAL when suspended
2326 mBytesWritten += mixBufferSize;
2327 mBytesRemaining = 0;
2328 }
Eric Laurent81784c32012-11-19 14:55:58 -08002329
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002331 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002332 for (size_t i = 0; i < effectChains.size(); i ++) {
2333 effectChains[i]->process_l();
2334 }
Eric Laurent81784c32012-11-19 14:55:58 -08002335 }
2336 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002337 // Process effect chains for offloaded thread even if no audio
2338 // was read from audio track: process only updates effect state
2339 // and thus does have to be synchronized with audio writes but may have
2340 // to be called while waiting for async write callback
2341 if (mType == OFFLOAD) {
2342 for (size_t i = 0; i < effectChains.size(); i ++) {
2343 effectChains[i]->process_l();
2344 }
2345 }
Eric Laurent81784c32012-11-19 14:55:58 -08002346
2347 // enable changes in effect chain
2348 unlockEffectChains(effectChains);
2349
Eric Laurentbfb1b832013-01-07 09:53:42 -08002350 if (!waitingAsyncCallback()) {
2351 // sleepTime == 0 means we must write to audio hardware
2352 if (sleepTime == 0) {
2353 if (mBytesRemaining) {
2354 ssize_t ret = threadLoop_write();
2355 if (ret < 0) {
2356 mBytesRemaining = 0;
2357 } else {
2358 mBytesWritten += ret;
2359 mBytesRemaining -= ret;
2360 }
2361 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2362 (mMixerStatus == MIXER_DRAIN_ALL)) {
2363 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002364 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365if (mType == MIXER) {
2366 // write blocked detection
2367 nsecs_t now = systemTime();
2368 nsecs_t delta = now - mLastWriteTime;
2369 if (!mStandby && delta > maxPeriod) {
2370 mNumDelayedWrites++;
2371 if ((now - lastWarning) > kWarningThrottleNs) {
2372 ATRACE_NAME("underrun");
2373 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2374 ns2ms(delta), mNumDelayedWrites, this);
2375 lastWarning = now;
2376 }
2377 }
Eric Laurent81784c32012-11-19 14:55:58 -08002378}
2379
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 } else {
2381 usleep(sleepTime);
2382 }
Eric Laurent81784c32012-11-19 14:55:58 -08002383 }
2384
2385 // Finally let go of removed track(s), without the lock held
2386 // since we can't guarantee the destructors won't acquire that
2387 // same lock. This will also mutate and push a new fast mixer state.
2388 threadLoop_removeTracks(tracksToRemove);
2389 tracksToRemove.clear();
2390
2391 // FIXME I don't understand the need for this here;
2392 // it was in the original code but maybe the
2393 // assignment in saveOutputTracks() makes this unnecessary?
2394 clearOutputTracks();
2395
2396 // Effect chains will be actually deleted here if they were removed from
2397 // mEffectChains list during mixing or effects processing
2398 effectChains.clear();
2399
2400 // FIXME Note that the above .clear() is no longer necessary since effectChains
2401 // is now local to this block, but will keep it for now (at least until merge done).
2402 }
2403
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404 threadLoop_exit();
2405
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002408 // put output stream into standby mode
2409 if (!mStandby) {
2410 mOutput->stream->common.standby(&mOutput->stream->common);
2411 }
2412 }
2413
2414 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002415 mWakeLockUids.clear();
2416 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002417
2418 ALOGV("Thread %p type %d exiting", this, mType);
2419 return false;
2420}
2421
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422// removeTracks_l() must be called with ThreadBase::mLock held
2423void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2424{
2425 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002426 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002427 for (size_t i=0 ; i<count ; i++) {
2428 const sp<Track>& track = tracksToRemove.itemAt(i);
2429 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002430 mWakeLockUids.remove(track->uid());
2431 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002432 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2433 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2434 if (chain != 0) {
2435 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2436 track->sessionId());
2437 chain->decActiveTrackCnt();
2438 }
2439 if (track->isTerminated()) {
2440 removeTrack_l(track);
2441 }
2442 }
2443 }
2444
2445}
Eric Laurent81784c32012-11-19 14:55:58 -08002446
Eric Laurentaccc1472013-09-20 09:36:34 -07002447status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2448{
2449 if (mNormalSink != 0) {
2450 return mNormalSink->getTimestamp(timestamp);
2451 }
2452 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2453 uint64_t position64;
2454 int ret = mOutput->stream->get_presentation_position(
2455 mOutput->stream, &position64, &timestamp.mTime);
2456 if (ret == 0) {
2457 timestamp.mPosition = (uint32_t)position64;
2458 return NO_ERROR;
2459 }
2460 }
2461 return INVALID_OPERATION;
2462}
Eric Laurent81784c32012-11-19 14:55:58 -08002463// ----------------------------------------------------------------------------
2464
2465AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2466 audio_io_handle_t id, audio_devices_t device, type_t type)
2467 : PlaybackThread(audioFlinger, output, id, device, type),
2468 // mAudioMixer below
2469 // mFastMixer below
2470 mFastMixerFutex(0)
2471 // mOutputSink below
2472 // mPipeSink below
2473 // mNormalSink below
2474{
2475 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002476 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002477 "mFrameCount=%d, mNormalFrameCount=%d",
2478 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2479 mNormalFrameCount);
2480 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2481
2482 // FIXME - Current mixer implementation only supports stereo output
2483 if (mChannelCount != FCC_2) {
2484 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2485 }
2486
2487 // create an NBAIO sink for the HAL output stream, and negotiate
2488 mOutputSink = new AudioStreamOutSink(output->stream);
2489 size_t numCounterOffers = 0;
2490 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2491 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2492 ALOG_ASSERT(index == 0);
2493
2494 // initialize fast mixer depending on configuration
2495 bool initFastMixer;
2496 switch (kUseFastMixer) {
2497 case FastMixer_Never:
2498 initFastMixer = false;
2499 break;
2500 case FastMixer_Always:
2501 initFastMixer = true;
2502 break;
2503 case FastMixer_Static:
2504 case FastMixer_Dynamic:
2505 initFastMixer = mFrameCount < mNormalFrameCount;
2506 break;
2507 }
2508 if (initFastMixer) {
2509
2510 // create a MonoPipe to connect our submix to FastMixer
2511 NBAIO_Format format = mOutputSink->format();
2512 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2513 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2514 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2515 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2516 const NBAIO_Format offers[1] = {format};
2517 size_t numCounterOffers = 0;
2518 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2519 ALOG_ASSERT(index == 0);
2520 monoPipe->setAvgFrames((mScreenState & 1) ?
2521 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2522 mPipeSink = monoPipe;
2523
Glenn Kasten46909e72013-02-26 09:20:22 -08002524#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002525 if (mTeeSinkOutputEnabled) {
2526 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2527 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2528 numCounterOffers = 0;
2529 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2530 ALOG_ASSERT(index == 0);
2531 mTeeSink = teeSink;
2532 PipeReader *teeSource = new PipeReader(*teeSink);
2533 numCounterOffers = 0;
2534 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2535 ALOG_ASSERT(index == 0);
2536 mTeeSource = teeSource;
2537 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002538#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002539
2540 // create fast mixer and configure it initially with just one fast track for our submix
2541 mFastMixer = new FastMixer();
2542 FastMixerStateQueue *sq = mFastMixer->sq();
2543#ifdef STATE_QUEUE_DUMP
2544 sq->setObserverDump(&mStateQueueObserverDump);
2545 sq->setMutatorDump(&mStateQueueMutatorDump);
2546#endif
2547 FastMixerState *state = sq->begin();
2548 FastTrack *fastTrack = &state->mFastTracks[0];
2549 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2550 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2551 fastTrack->mVolumeProvider = NULL;
2552 fastTrack->mGeneration++;
2553 state->mFastTracksGen++;
2554 state->mTrackMask = 1;
2555 // fast mixer will use the HAL output sink
2556 state->mOutputSink = mOutputSink.get();
2557 state->mOutputSinkGen++;
2558 state->mFrameCount = mFrameCount;
2559 state->mCommand = FastMixerState::COLD_IDLE;
2560 // already done in constructor initialization list
2561 //mFastMixerFutex = 0;
2562 state->mColdFutexAddr = &mFastMixerFutex;
2563 state->mColdGen++;
2564 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002565#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002566 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002567#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002568 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2569 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002570 sq->end();
2571 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2572
2573 // start the fast mixer
2574 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2575 pid_t tid = mFastMixer->getTid();
2576 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2577 if (err != 0) {
2578 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2579 kPriorityFastMixer, getpid_cached, tid, err);
2580 }
2581
2582#ifdef AUDIO_WATCHDOG
2583 // create and start the watchdog
2584 mAudioWatchdog = new AudioWatchdog();
2585 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2586 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2587 tid = mAudioWatchdog->getTid();
2588 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2589 if (err != 0) {
2590 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2591 kPriorityFastMixer, getpid_cached, tid, err);
2592 }
2593#endif
2594
2595 } else {
2596 mFastMixer = NULL;
2597 }
2598
2599 switch (kUseFastMixer) {
2600 case FastMixer_Never:
2601 case FastMixer_Dynamic:
2602 mNormalSink = mOutputSink;
2603 break;
2604 case FastMixer_Always:
2605 mNormalSink = mPipeSink;
2606 break;
2607 case FastMixer_Static:
2608 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2609 break;
2610 }
2611}
2612
2613AudioFlinger::MixerThread::~MixerThread()
2614{
2615 if (mFastMixer != NULL) {
2616 FastMixerStateQueue *sq = mFastMixer->sq();
2617 FastMixerState *state = sq->begin();
2618 if (state->mCommand == FastMixerState::COLD_IDLE) {
2619 int32_t old = android_atomic_inc(&mFastMixerFutex);
2620 if (old == -1) {
2621 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2622 }
2623 }
2624 state->mCommand = FastMixerState::EXIT;
2625 sq->end();
2626 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2627 mFastMixer->join();
2628 // Though the fast mixer thread has exited, it's state queue is still valid.
2629 // We'll use that extract the final state which contains one remaining fast track
2630 // corresponding to our sub-mix.
2631 state = sq->begin();
2632 ALOG_ASSERT(state->mTrackMask == 1);
2633 FastTrack *fastTrack = &state->mFastTracks[0];
2634 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2635 delete fastTrack->mBufferProvider;
2636 sq->end(false /*didModify*/);
2637 delete mFastMixer;
2638#ifdef AUDIO_WATCHDOG
2639 if (mAudioWatchdog != 0) {
2640 mAudioWatchdog->requestExit();
2641 mAudioWatchdog->requestExitAndWait();
2642 mAudioWatchdog.clear();
2643 }
2644#endif
2645 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002646 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002647 delete mAudioMixer;
2648}
2649
2650
2651uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2652{
2653 if (mFastMixer != NULL) {
2654 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2655 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2656 }
2657 return latency;
2658}
2659
2660
2661void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2662{
2663 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2664}
2665
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002667{
2668 // FIXME we should only do one push per cycle; confirm this is true
2669 // Start the fast mixer if it's not already running
2670 if (mFastMixer != NULL) {
2671 FastMixerStateQueue *sq = mFastMixer->sq();
2672 FastMixerState *state = sq->begin();
2673 if (state->mCommand != FastMixerState::MIX_WRITE &&
2674 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2675 if (state->mCommand == FastMixerState::COLD_IDLE) {
2676 int32_t old = android_atomic_inc(&mFastMixerFutex);
2677 if (old == -1) {
2678 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2679 }
2680#ifdef AUDIO_WATCHDOG
2681 if (mAudioWatchdog != 0) {
2682 mAudioWatchdog->resume();
2683 }
2684#endif
2685 }
2686 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002687 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2688 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002689 sq->end();
2690 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2691 if (kUseFastMixer == FastMixer_Dynamic) {
2692 mNormalSink = mPipeSink;
2693 }
2694 } else {
2695 sq->end(false /*didModify*/);
2696 }
2697 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002699}
2700
2701void AudioFlinger::MixerThread::threadLoop_standby()
2702{
2703 // Idle the fast mixer if it's currently running
2704 if (mFastMixer != NULL) {
2705 FastMixerStateQueue *sq = mFastMixer->sq();
2706 FastMixerState *state = sq->begin();
2707 if (!(state->mCommand & FastMixerState::IDLE)) {
2708 state->mCommand = FastMixerState::COLD_IDLE;
2709 state->mColdFutexAddr = &mFastMixerFutex;
2710 state->mColdGen++;
2711 mFastMixerFutex = 0;
2712 sq->end();
2713 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2714 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2715 if (kUseFastMixer == FastMixer_Dynamic) {
2716 mNormalSink = mOutputSink;
2717 }
2718#ifdef AUDIO_WATCHDOG
2719 if (mAudioWatchdog != 0) {
2720 mAudioWatchdog->pause();
2721 }
2722#endif
2723 } else {
2724 sq->end(false /*didModify*/);
2725 }
2726 }
2727 PlaybackThread::threadLoop_standby();
2728}
2729
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730// Empty implementation for standard mixer
2731// Overridden for offloaded playback
2732void AudioFlinger::PlaybackThread::flushOutput_l()
2733{
2734}
2735
2736bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2737{
2738 return false;
2739}
2740
2741bool AudioFlinger::PlaybackThread::shouldStandby_l()
2742{
2743 return !mStandby;
2744}
2745
2746bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2747{
2748 Mutex::Autolock _l(mLock);
2749 return waitingAsyncCallback_l();
2750}
2751
Eric Laurent81784c32012-11-19 14:55:58 -08002752// shared by MIXER and DIRECT, overridden by DUPLICATING
2753void AudioFlinger::PlaybackThread::threadLoop_standby()
2754{
2755 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2756 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002757 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002758 // discard any pending drain or write ack by incrementing sequence
2759 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2760 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002761 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002762 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2763 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002764 }
Eric Laurent81784c32012-11-19 14:55:58 -08002765}
2766
2767void AudioFlinger::MixerThread::threadLoop_mix()
2768{
2769 // obtain the presentation timestamp of the next output buffer
2770 int64_t pts;
2771 status_t status = INVALID_OPERATION;
2772
2773 if (mNormalSink != 0) {
2774 status = mNormalSink->getNextWriteTimestamp(&pts);
2775 } else {
2776 status = mOutputSink->getNextWriteTimestamp(&pts);
2777 }
2778
2779 if (status != NO_ERROR) {
2780 pts = AudioBufferProvider::kInvalidPTS;
2781 }
2782
2783 // mix buffers...
2784 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002786 // increase sleep time progressively when application underrun condition clears.
2787 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2788 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2789 // such that we would underrun the audio HAL.
2790 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2791 sleepTimeShift--;
2792 }
2793 sleepTime = 0;
2794 standbyTime = systemTime() + standbyDelay;
2795 //TODO: delay standby when effects have a tail
2796}
2797
2798void AudioFlinger::MixerThread::threadLoop_sleepTime()
2799{
2800 // If no tracks are ready, sleep once for the duration of an output
2801 // buffer size, then write 0s to the output
2802 if (sleepTime == 0) {
2803 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2804 sleepTime = activeSleepTime >> sleepTimeShift;
2805 if (sleepTime < kMinThreadSleepTimeUs) {
2806 sleepTime = kMinThreadSleepTimeUs;
2807 }
2808 // reduce sleep time in case of consecutive application underruns to avoid
2809 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2810 // duration we would end up writing less data than needed by the audio HAL if
2811 // the condition persists.
2812 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2813 sleepTimeShift++;
2814 }
2815 } else {
2816 sleepTime = idleSleepTime;
2817 }
2818 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002819 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002820 sleepTime = 0;
2821 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2822 "anticipated start");
2823 }
2824 // TODO add standby time extension fct of effect tail
2825}
2826
2827// prepareTracks_l() must be called with ThreadBase::mLock held
2828AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2829 Vector< sp<Track> > *tracksToRemove)
2830{
2831
2832 mixer_state mixerStatus = MIXER_IDLE;
2833 // find out which tracks need to be processed
2834 size_t count = mActiveTracks.size();
2835 size_t mixedTracks = 0;
2836 size_t tracksWithEffect = 0;
2837 // counts only _active_ fast tracks
2838 size_t fastTracks = 0;
2839 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2840
2841 float masterVolume = mMasterVolume;
2842 bool masterMute = mMasterMute;
2843
2844 if (masterMute) {
2845 masterVolume = 0;
2846 }
2847 // Delegate master volume control to effect in output mix effect chain if needed
2848 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2849 if (chain != 0) {
2850 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2851 chain->setVolume_l(&v, &v);
2852 masterVolume = (float)((v + (1 << 23)) >> 24);
2853 chain.clear();
2854 }
2855
2856 // prepare a new state to push
2857 FastMixerStateQueue *sq = NULL;
2858 FastMixerState *state = NULL;
2859 bool didModify = false;
2860 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2861 if (mFastMixer != NULL) {
2862 sq = mFastMixer->sq();
2863 state = sq->begin();
2864 }
2865
2866 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002867 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002868 if (t == 0) {
2869 continue;
2870 }
2871
2872 // this const just means the local variable doesn't change
2873 Track* const track = t.get();
2874
2875 // process fast tracks
2876 if (track->isFastTrack()) {
2877
2878 // It's theoretically possible (though unlikely) for a fast track to be created
2879 // and then removed within the same normal mix cycle. This is not a problem, as
2880 // the track never becomes active so it's fast mixer slot is never touched.
2881 // The converse, of removing an (active) track and then creating a new track
2882 // at the identical fast mixer slot within the same normal mix cycle,
2883 // is impossible because the slot isn't marked available until the end of each cycle.
2884 int j = track->mFastIndex;
2885 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2886 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2887 FastTrack *fastTrack = &state->mFastTracks[j];
2888
2889 // Determine whether the track is currently in underrun condition,
2890 // and whether it had a recent underrun.
2891 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2892 FastTrackUnderruns underruns = ftDump->mUnderruns;
2893 uint32_t recentFull = (underruns.mBitFields.mFull -
2894 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2895 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2896 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2897 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2898 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2899 uint32_t recentUnderruns = recentPartial + recentEmpty;
2900 track->mObservedUnderruns = underruns;
2901 // don't count underruns that occur while stopping or pausing
2902 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002903 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2904 recentUnderruns > 0) {
2905 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2906 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
2908
2909 // This is similar to the state machine for normal tracks,
2910 // with a few modifications for fast tracks.
2911 bool isActive = true;
2912 switch (track->mState) {
2913 case TrackBase::STOPPING_1:
2914 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002916 track->mState = TrackBase::STOPPING_2;
2917 }
2918 break;
2919 case TrackBase::PAUSING:
2920 // ramp down is not yet implemented
2921 track->setPaused();
2922 break;
2923 case TrackBase::RESUMING:
2924 // ramp up is not yet implemented
2925 track->mState = TrackBase::ACTIVE;
2926 break;
2927 case TrackBase::ACTIVE:
2928 if (recentFull > 0 || recentPartial > 0) {
2929 // track has provided at least some frames recently: reset retry count
2930 track->mRetryCount = kMaxTrackRetries;
2931 }
2932 if (recentUnderruns == 0) {
2933 // no recent underruns: stay active
2934 break;
2935 }
2936 // there has recently been an underrun of some kind
2937 if (track->sharedBuffer() == 0) {
2938 // were any of the recent underruns "empty" (no frames available)?
2939 if (recentEmpty == 0) {
2940 // no, then ignore the partial underruns as they are allowed indefinitely
2941 break;
2942 }
2943 // there has recently been an "empty" underrun: decrement the retry counter
2944 if (--(track->mRetryCount) > 0) {
2945 break;
2946 }
2947 // indicate to client process that the track was disabled because of underrun;
2948 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002949 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002950 // remove from active list, but state remains ACTIVE [confusing but true]
2951 isActive = false;
2952 break;
2953 }
2954 // fall through
2955 case TrackBase::STOPPING_2:
2956 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002957 case TrackBase::STOPPED:
2958 case TrackBase::FLUSHED: // flush() while active
2959 // Check for presentation complete if track is inactive
2960 // We have consumed all the buffers of this track.
2961 // This would be incomplete if we auto-paused on underrun
2962 {
2963 size_t audioHALFrames =
2964 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2965 size_t framesWritten = mBytesWritten / mFrameSize;
2966 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2967 // track stays in active list until presentation is complete
2968 break;
2969 }
2970 }
2971 if (track->isStopping_2()) {
2972 track->mState = TrackBase::STOPPED;
2973 }
2974 if (track->isStopped()) {
2975 // Can't reset directly, as fast mixer is still polling this track
2976 // track->reset();
2977 // So instead mark this track as needing to be reset after push with ack
2978 resetMask |= 1 << i;
2979 }
2980 isActive = false;
2981 break;
2982 case TrackBase::IDLE:
2983 default:
2984 LOG_FATAL("unexpected track state %d", track->mState);
2985 }
2986
2987 if (isActive) {
2988 // was it previously inactive?
2989 if (!(state->mTrackMask & (1 << j))) {
2990 ExtendedAudioBufferProvider *eabp = track;
2991 VolumeProvider *vp = track;
2992 fastTrack->mBufferProvider = eabp;
2993 fastTrack->mVolumeProvider = vp;
2994 fastTrack->mSampleRate = track->mSampleRate;
2995 fastTrack->mChannelMask = track->mChannelMask;
2996 fastTrack->mGeneration++;
2997 state->mTrackMask |= 1 << j;
2998 didModify = true;
2999 // no acknowledgement required for newly active tracks
3000 }
3001 // cache the combined master volume and stream type volume for fast mixer; this
3002 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003003 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003004 ++fastTracks;
3005 } else {
3006 // was it previously active?
3007 if (state->mTrackMask & (1 << j)) {
3008 fastTrack->mBufferProvider = NULL;
3009 fastTrack->mGeneration++;
3010 state->mTrackMask &= ~(1 << j);
3011 didModify = true;
3012 // If any fast tracks were removed, we must wait for acknowledgement
3013 // because we're about to decrement the last sp<> on those tracks.
3014 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3015 } else {
3016 LOG_FATAL("fast track %d should have been active", j);
3017 }
3018 tracksToRemove->add(track);
3019 // Avoids a misleading display in dumpsys
3020 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3021 }
3022 continue;
3023 }
3024
3025 { // local variable scope to avoid goto warning
3026
3027 audio_track_cblk_t* cblk = track->cblk();
3028
3029 // The first time a track is added we wait
3030 // for all its buffers to be filled before processing it
3031 int name = track->name();
3032 // make sure that we have enough frames to mix one full buffer.
3033 // enforce this condition only once to enable draining the buffer in case the client
3034 // app does not call stop() and relies on underrun to stop:
3035 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3036 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003037 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003038 uint32_t sr = track->sampleRate();
3039 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003040 desiredFrames = mNormalFrameCount;
3041 } else {
3042 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003043 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003044 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003045 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003046 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003047#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003048 // the minimum track buffer size is normally twice the number of frames necessary
3049 // to fill one buffer and the resampler should not leave more than one buffer worth
3050 // of unreleased frames after each pass, but just in case...
3051 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003052#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003053 }
Eric Laurent81784c32012-11-19 14:55:58 -08003054 uint32_t minFrames = 1;
3055 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3056 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003057 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003058 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003059
3060 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003061 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003062 !track->isPaused() && !track->isTerminated())
3063 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003064 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003065
3066 mixedTracks++;
3067
3068 // track->mainBuffer() != mMixBuffer means there is an effect chain
3069 // connected to the track
3070 chain.clear();
3071 if (track->mainBuffer() != mMixBuffer) {
3072 chain = getEffectChain_l(track->sessionId());
3073 // Delegate volume control to effect in track effect chain if needed
3074 if (chain != 0) {
3075 tracksWithEffect++;
3076 } else {
3077 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3078 "session %d",
3079 name, track->sessionId());
3080 }
3081 }
3082
3083
3084 int param = AudioMixer::VOLUME;
3085 if (track->mFillingUpStatus == Track::FS_FILLED) {
3086 // no ramp for the first volume setting
3087 track->mFillingUpStatus = Track::FS_ACTIVE;
3088 if (track->mState == TrackBase::RESUMING) {
3089 track->mState = TrackBase::ACTIVE;
3090 param = AudioMixer::RAMP_VOLUME;
3091 }
3092 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003093 // FIXME should not make a decision based on mServer
3094 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003095 // If the track is stopped before the first frame was mixed,
3096 // do not apply ramp
3097 param = AudioMixer::RAMP_VOLUME;
3098 }
3099
3100 // compute volume for this track
3101 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003102 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003103 vl = vr = va = 0;
3104 if (track->isPausing()) {
3105 track->setPaused();
3106 }
3107 } else {
3108
3109 // read original volumes with volume control
3110 float typeVolume = mStreamTypes[track->streamType()].volume;
3111 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003112 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003113 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003114 vl = vlr & 0xFFFF;
3115 vr = vlr >> 16;
3116 // track volumes come from shared memory, so can't be trusted and must be clamped
3117 if (vl > MAX_GAIN_INT) {
3118 ALOGV("Track left volume out of range: %04X", vl);
3119 vl = MAX_GAIN_INT;
3120 }
3121 if (vr > MAX_GAIN_INT) {
3122 ALOGV("Track right volume out of range: %04X", vr);
3123 vr = MAX_GAIN_INT;
3124 }
3125 // now apply the master volume and stream type volume
3126 vl = (uint32_t)(v * vl) << 12;
3127 vr = (uint32_t)(v * vr) << 12;
3128 // assuming master volume and stream type volume each go up to 1.0,
3129 // vl and vr are now in 8.24 format
3130
Glenn Kastene3aa6592012-12-04 12:22:46 -08003131 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003132 // send level comes from shared memory and so may be corrupt
3133 if (sendLevel > MAX_GAIN_INT) {
3134 ALOGV("Track send level out of range: %04X", sendLevel);
3135 sendLevel = MAX_GAIN_INT;
3136 }
3137 va = (uint32_t)(v * sendLevel);
3138 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139
Eric Laurent81784c32012-11-19 14:55:58 -08003140 // Delegate volume control to effect in track effect chain if needed
3141 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3142 // Do not ramp volume if volume is controlled by effect
3143 param = AudioMixer::VOLUME;
3144 track->mHasVolumeController = true;
3145 } else {
3146 // force no volume ramp when volume controller was just disabled or removed
3147 // from effect chain to avoid volume spike
3148 if (track->mHasVolumeController) {
3149 param = AudioMixer::VOLUME;
3150 }
3151 track->mHasVolumeController = false;
3152 }
3153
3154 // Convert volumes from 8.24 to 4.12 format
3155 // This additional clamping is needed in case chain->setVolume_l() overshot
3156 vl = (vl + (1 << 11)) >> 12;
3157 if (vl > MAX_GAIN_INT) {
3158 vl = MAX_GAIN_INT;
3159 }
3160 vr = (vr + (1 << 11)) >> 12;
3161 if (vr > MAX_GAIN_INT) {
3162 vr = MAX_GAIN_INT;
3163 }
3164
3165 if (va > MAX_GAIN_INT) {
3166 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3167 }
3168
3169 // XXX: these things DON'T need to be done each time
3170 mAudioMixer->setBufferProvider(name, track);
3171 mAudioMixer->enable(name);
3172
3173 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3174 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3175 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3176 mAudioMixer->setParameter(
3177 name,
3178 AudioMixer::TRACK,
3179 AudioMixer::FORMAT, (void *)track->format());
3180 mAudioMixer->setParameter(
3181 name,
3182 AudioMixer::TRACK,
3183 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003184 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3185 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003186 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003187 if (reqSampleRate == 0) {
3188 reqSampleRate = mSampleRate;
3189 } else if (reqSampleRate > maxSampleRate) {
3190 reqSampleRate = maxSampleRate;
3191 }
Eric Laurent81784c32012-11-19 14:55:58 -08003192 mAudioMixer->setParameter(
3193 name,
3194 AudioMixer::RESAMPLE,
3195 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003196 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003197 mAudioMixer->setParameter(
3198 name,
3199 AudioMixer::TRACK,
3200 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3201 mAudioMixer->setParameter(
3202 name,
3203 AudioMixer::TRACK,
3204 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3205
3206 // reset retry count
3207 track->mRetryCount = kMaxTrackRetries;
3208
3209 // If one track is ready, set the mixer ready if:
3210 // - the mixer was not ready during previous round OR
3211 // - no other track is not ready
3212 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3213 mixerStatus != MIXER_TRACKS_ENABLED) {
3214 mixerStatus = MIXER_TRACKS_READY;
3215 }
3216 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003217 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003218 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003219 }
Eric Laurent81784c32012-11-19 14:55:58 -08003220 // clear effect chain input buffer if an active track underruns to avoid sending
3221 // previous audio buffer again to effects
3222 chain = getEffectChain_l(track->sessionId());
3223 if (chain != 0) {
3224 chain->clearInputBuffer();
3225 }
3226
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003227 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003228 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3229 track->isStopped() || track->isPaused()) {
3230 // We have consumed all the buffers of this track.
3231 // Remove it from the list of active tracks.
3232 // TODO: use actual buffer filling status instead of latency when available from
3233 // audio HAL
3234 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3235 size_t framesWritten = mBytesWritten / mFrameSize;
3236 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3237 if (track->isStopped()) {
3238 track->reset();
3239 }
3240 tracksToRemove->add(track);
3241 }
3242 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003243 // No buffers for this track. Give it a few chances to
3244 // fill a buffer, then remove it from active list.
3245 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003246 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003247 tracksToRemove->add(track);
3248 // indicate to client process that the track was disabled because of underrun;
3249 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003250 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003251 // If one track is not ready, mark the mixer also not ready if:
3252 // - the mixer was ready during previous round OR
3253 // - no other track is ready
3254 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3255 mixerStatus != MIXER_TRACKS_READY) {
3256 mixerStatus = MIXER_TRACKS_ENABLED;
3257 }
3258 }
3259 mAudioMixer->disable(name);
3260 }
3261
3262 } // local variable scope to avoid goto warning
3263track_is_ready: ;
3264
3265 }
3266
3267 // Push the new FastMixer state if necessary
3268 bool pauseAudioWatchdog = false;
3269 if (didModify) {
3270 state->mFastTracksGen++;
3271 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3272 if (kUseFastMixer == FastMixer_Dynamic &&
3273 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3274 state->mCommand = FastMixerState::COLD_IDLE;
3275 state->mColdFutexAddr = &mFastMixerFutex;
3276 state->mColdGen++;
3277 mFastMixerFutex = 0;
3278 if (kUseFastMixer == FastMixer_Dynamic) {
3279 mNormalSink = mOutputSink;
3280 }
3281 // If we go into cold idle, need to wait for acknowledgement
3282 // so that fast mixer stops doing I/O.
3283 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3284 pauseAudioWatchdog = true;
3285 }
Eric Laurent81784c32012-11-19 14:55:58 -08003286 }
3287 if (sq != NULL) {
3288 sq->end(didModify);
3289 sq->push(block);
3290 }
3291#ifdef AUDIO_WATCHDOG
3292 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3293 mAudioWatchdog->pause();
3294 }
3295#endif
3296
3297 // Now perform the deferred reset on fast tracks that have stopped
3298 while (resetMask != 0) {
3299 size_t i = __builtin_ctz(resetMask);
3300 ALOG_ASSERT(i < count);
3301 resetMask &= ~(1 << i);
3302 sp<Track> t = mActiveTracks[i].promote();
3303 if (t == 0) {
3304 continue;
3305 }
3306 Track* track = t.get();
3307 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3308 track->reset();
3309 }
3310
3311 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003312 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003313
3314 // mix buffer must be cleared if all tracks are connected to an
3315 // effect chain as in this case the mixer will not write to
3316 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003317 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3318 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003319 // FIXME as a performance optimization, should remember previous zero status
3320 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3321 }
3322
3323 // if any fast tracks, then status is ready
3324 mMixerStatusIgnoringFastTracks = mixerStatus;
3325 if (fastTracks > 0) {
3326 mixerStatus = MIXER_TRACKS_READY;
3327 }
3328 return mixerStatus;
3329}
3330
3331// getTrackName_l() must be called with ThreadBase::mLock held
3332int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3333{
3334 return mAudioMixer->getTrackName(channelMask, sessionId);
3335}
3336
3337// deleteTrackName_l() must be called with ThreadBase::mLock held
3338void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3339{
3340 ALOGV("remove track (%d) and delete from mixer", name);
3341 mAudioMixer->deleteTrackName(name);
3342}
3343
3344// checkForNewParameters_l() must be called with ThreadBase::mLock held
3345bool AudioFlinger::MixerThread::checkForNewParameters_l()
3346{
3347 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3348 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3349 bool reconfig = false;
3350
3351 while (!mNewParameters.isEmpty()) {
3352
3353 if (mFastMixer != NULL) {
3354 FastMixerStateQueue *sq = mFastMixer->sq();
3355 FastMixerState *state = sq->begin();
3356 if (!(state->mCommand & FastMixerState::IDLE)) {
3357 previousCommand = state->mCommand;
3358 state->mCommand = FastMixerState::HOT_IDLE;
3359 sq->end();
3360 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3361 } else {
3362 sq->end(false /*didModify*/);
3363 }
3364 }
3365
3366 status_t status = NO_ERROR;
3367 String8 keyValuePair = mNewParameters[0];
3368 AudioParameter param = AudioParameter(keyValuePair);
3369 int value;
3370
3371 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3372 reconfig = true;
3373 }
3374 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3375 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3376 status = BAD_VALUE;
3377 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003378 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003379 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 {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003386 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003387 reconfig = true;
3388 }
3389 }
3390 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3391 // do not accept frame count changes if tracks are open as the track buffer
3392 // size depends on frame count and correct behavior would not be guaranteed
3393 // if frame count is changed after track creation
3394 if (!mTracks.isEmpty()) {
3395 status = INVALID_OPERATION;
3396 } else {
3397 reconfig = true;
3398 }
3399 }
3400 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3401#ifdef ADD_BATTERY_DATA
3402 // when changing the audio output device, call addBatteryData to notify
3403 // the change
3404 if (mOutDevice != value) {
3405 uint32_t params = 0;
3406 // check whether speaker is on
3407 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3408 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3409 }
3410
3411 audio_devices_t deviceWithoutSpeaker
3412 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3413 // check if any other device (except speaker) is on
3414 if (value & deviceWithoutSpeaker ) {
3415 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3416 }
3417
3418 if (params != 0) {
3419 addBatteryData(params);
3420 }
3421 }
3422#endif
3423
3424 // forward device change to effects that have requested to be
3425 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003426 if (value != AUDIO_DEVICE_NONE) {
3427 mOutDevice = value;
3428 for (size_t i = 0; i < mEffectChains.size(); i++) {
3429 mEffectChains[i]->setDevice_l(mOutDevice);
3430 }
Eric Laurent81784c32012-11-19 14:55:58 -08003431 }
3432 }
3433
3434 if (status == NO_ERROR) {
3435 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3436 keyValuePair.string());
3437 if (!mStandby && status == INVALID_OPERATION) {
3438 mOutput->stream->common.standby(&mOutput->stream->common);
3439 mStandby = true;
3440 mBytesWritten = 0;
3441 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3442 keyValuePair.string());
3443 }
3444 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003445 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003446 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003447 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3448 for (size_t i = 0; i < mTracks.size() ; i++) {
3449 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3450 if (name < 0) {
3451 break;
3452 }
3453 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003454 }
3455 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3456 }
3457 }
3458
3459 mNewParameters.removeAt(0);
3460
3461 mParamStatus = status;
3462 mParamCond.signal();
3463 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3464 // already timed out waiting for the status and will never signal the condition.
3465 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3466 }
3467
3468 if (!(previousCommand & FastMixerState::IDLE)) {
3469 ALOG_ASSERT(mFastMixer != NULL);
3470 FastMixerStateQueue *sq = mFastMixer->sq();
3471 FastMixerState *state = sq->begin();
3472 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3473 state->mCommand = previousCommand;
3474 sq->end();
3475 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3476 }
3477
3478 return reconfig;
3479}
3480
3481
3482void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3483{
3484 const size_t SIZE = 256;
3485 char buffer[SIZE];
3486 String8 result;
3487
3488 PlaybackThread::dumpInternals(fd, args);
3489
3490 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3491 result.append(buffer);
3492 write(fd, result.string(), result.size());
3493
3494 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003495 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 copy.dump(fd);
3497
3498#ifdef STATE_QUEUE_DUMP
3499 // Similar for state queue
3500 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3501 observerCopy.dump(fd);
3502 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3503 mutatorCopy.dump(fd);
3504#endif
3505
Glenn Kasten46909e72013-02-26 09:20:22 -08003506#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003507 // Write the tee output to a .wav file
3508 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003509#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003510
3511#ifdef AUDIO_WATCHDOG
3512 if (mAudioWatchdog != 0) {
3513 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3514 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3515 wdCopy.dump(fd);
3516 }
3517#endif
3518}
3519
3520uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3521{
3522 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3523}
3524
3525uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3526{
3527 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3528}
3529
3530void AudioFlinger::MixerThread::cacheParameters_l()
3531{
3532 PlaybackThread::cacheParameters_l();
3533
3534 // FIXME: Relaxed timing because of a certain device that can't meet latency
3535 // Should be reduced to 2x after the vendor fixes the driver issue
3536 // increase threshold again due to low power audio mode. The way this warning
3537 // threshold is calculated and its usefulness should be reconsidered anyway.
3538 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3539}
3540
3541// ----------------------------------------------------------------------------
3542
3543AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3544 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3545 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3546 // mLeftVolFloat, mRightVolFloat
3547{
3548}
3549
Eric Laurentbfb1b832013-01-07 09:53:42 -08003550AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3551 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3552 ThreadBase::type_t type)
3553 : PlaybackThread(audioFlinger, output, id, device, type)
3554 // mLeftVolFloat, mRightVolFloat
3555{
3556}
3557
Eric Laurent81784c32012-11-19 14:55:58 -08003558AudioFlinger::DirectOutputThread::~DirectOutputThread()
3559{
3560}
3561
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3563{
3564 audio_track_cblk_t* cblk = track->cblk();
3565 float left, right;
3566
3567 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3568 left = right = 0;
3569 } else {
3570 float typeVolume = mStreamTypes[track->streamType()].volume;
3571 float v = mMasterVolume * typeVolume;
3572 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3573 uint32_t vlr = proxy->getVolumeLR();
3574 float v_clamped = v * (vlr & 0xFFFF);
3575 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3576 left = v_clamped/MAX_GAIN;
3577 v_clamped = v * (vlr >> 16);
3578 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3579 right = v_clamped/MAX_GAIN;
3580 }
3581
3582 if (lastTrack) {
3583 if (left != mLeftVolFloat || right != mRightVolFloat) {
3584 mLeftVolFloat = left;
3585 mRightVolFloat = right;
3586
3587 // Convert volumes from float to 8.24
3588 uint32_t vl = (uint32_t)(left * (1 << 24));
3589 uint32_t vr = (uint32_t)(right * (1 << 24));
3590
3591 // Delegate volume control to effect in track effect chain if needed
3592 // only one effect chain can be present on DirectOutputThread, so if
3593 // there is one, the track is connected to it
3594 if (!mEffectChains.isEmpty()) {
3595 mEffectChains[0]->setVolume_l(&vl, &vr);
3596 left = (float)vl / (1 << 24);
3597 right = (float)vr / (1 << 24);
3598 }
3599 if (mOutput->stream->set_volume) {
3600 mOutput->stream->set_volume(mOutput->stream, left, right);
3601 }
3602 }
3603 }
3604}
3605
3606
Eric Laurent81784c32012-11-19 14:55:58 -08003607AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3608 Vector< sp<Track> > *tracksToRemove
3609)
3610{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003611 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003612 mixer_state mixerStatus = MIXER_IDLE;
3613
3614 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003615 for (size_t i = 0; i < count; i++) {
3616 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003617 // The track died recently
3618 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003619 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003620 }
3621
3622 Track* const track = t.get();
3623 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003624 // Only consider last track started for volume and mixer state control.
3625 // In theory an older track could underrun and restart after the new one starts
3626 // but as we only care about the transition phase between two tracks on a
3627 // direct output, it is not a problem to ignore the underrun case.
3628 sp<Track> l = mLatestActiveTrack.promote();
3629 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003630
3631 // The first time a track is added we wait
3632 // for all its buffers to be filled before processing it
3633 uint32_t minFrames;
3634 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3635 minFrames = mNormalFrameCount;
3636 } else {
3637 minFrames = 1;
3638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639
Eric Laurent81784c32012-11-19 14:55:58 -08003640 if ((track->framesReady() >= minFrames) && track->isReady() &&
3641 !track->isPaused() && !track->isTerminated())
3642 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003643 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003644
3645 if (track->mFillingUpStatus == Track::FS_FILLED) {
3646 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003647 // make sure processVolume_l() will apply new volume even if 0
3648 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003649 if (track->mState == TrackBase::RESUMING) {
3650 track->mState = TrackBase::ACTIVE;
3651 }
3652 }
3653
3654 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003655 processVolume_l(track, last);
3656 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003657 // reset retry count
3658 track->mRetryCount = kMaxTrackRetriesDirect;
3659 mActiveTrack = t;
3660 mixerStatus = MIXER_TRACKS_READY;
3661 }
Eric Laurent81784c32012-11-19 14:55:58 -08003662 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003663 // clear effect chain input buffer if the last active track started underruns
3664 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003665 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003666 mEffectChains[0]->clearInputBuffer();
3667 }
3668
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003669 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003670 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3671 track->isStopped() || track->isPaused()) {
3672 // We have consumed all the buffers of this track.
3673 // Remove it from the list of active tracks.
3674 // TODO: implement behavior for compressed audio
3675 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3676 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003677 if (mStandby || !last ||
3678 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003679 if (track->isStopped()) {
3680 track->reset();
3681 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003682 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003683 }
3684 } else {
3685 // No buffers for this track. Give it a few chances to
3686 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003687 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003688 if (--(track->mRetryCount) <= 0) {
3689 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003690 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003691 // indicate to client process that the track was disabled because of underrun;
3692 // it will then automatically call start() when data is available
3693 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003694 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003695 mixerStatus = MIXER_TRACKS_ENABLED;
3696 }
3697 }
3698 }
3699 }
3700
Eric Laurent81784c32012-11-19 14:55:58 -08003701 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003702 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003703
3704 return mixerStatus;
3705}
3706
3707void AudioFlinger::DirectOutputThread::threadLoop_mix()
3708{
Eric Laurent81784c32012-11-19 14:55:58 -08003709 size_t frameCount = mFrameCount;
3710 int8_t *curBuf = (int8_t *)mMixBuffer;
3711 // output audio to hardware
3712 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003713 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003714 buffer.frameCount = frameCount;
3715 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003716 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003717 memset(curBuf, 0, frameCount * mFrameSize);
3718 break;
3719 }
3720 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3721 frameCount -= buffer.frameCount;
3722 curBuf += buffer.frameCount * mFrameSize;
3723 mActiveTrack->releaseBuffer(&buffer);
3724 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003725 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003726 sleepTime = 0;
3727 standbyTime = systemTime() + standbyDelay;
3728 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003729}
3730
3731void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3732{
3733 if (sleepTime == 0) {
3734 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3735 sleepTime = activeSleepTime;
3736 } else {
3737 sleepTime = idleSleepTime;
3738 }
3739 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3740 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3741 sleepTime = 0;
3742 }
3743}
3744
3745// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003746int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3747 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003748{
3749 return 0;
3750}
3751
3752// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003753void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003754{
3755}
3756
3757// checkForNewParameters_l() must be called with ThreadBase::mLock held
3758bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3759{
3760 bool reconfig = false;
3761
3762 while (!mNewParameters.isEmpty()) {
3763 status_t status = NO_ERROR;
3764 String8 keyValuePair = mNewParameters[0];
3765 AudioParameter param = AudioParameter(keyValuePair);
3766 int value;
3767
3768 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3769 // do not accept frame count changes if tracks are open as the track buffer
3770 // size depends on frame count and correct behavior would not be garantied
3771 // if frame count is changed after track creation
3772 if (!mTracks.isEmpty()) {
3773 status = INVALID_OPERATION;
3774 } else {
3775 reconfig = true;
3776 }
3777 }
3778 if (status == NO_ERROR) {
3779 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3780 keyValuePair.string());
3781 if (!mStandby && status == INVALID_OPERATION) {
3782 mOutput->stream->common.standby(&mOutput->stream->common);
3783 mStandby = true;
3784 mBytesWritten = 0;
3785 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3786 keyValuePair.string());
3787 }
3788 if (status == NO_ERROR && reconfig) {
3789 readOutputParameters();
3790 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3791 }
3792 }
3793
3794 mNewParameters.removeAt(0);
3795
3796 mParamStatus = status;
3797 mParamCond.signal();
3798 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3799 // already timed out waiting for the status and will never signal the condition.
3800 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3801 }
3802 return reconfig;
3803}
3804
3805uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3806{
3807 uint32_t time;
3808 if (audio_is_linear_pcm(mFormat)) {
3809 time = PlaybackThread::activeSleepTimeUs();
3810 } else {
3811 time = 10000;
3812 }
3813 return time;
3814}
3815
3816uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3817{
3818 uint32_t time;
3819 if (audio_is_linear_pcm(mFormat)) {
3820 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3821 } else {
3822 time = 10000;
3823 }
3824 return time;
3825}
3826
3827uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3828{
3829 uint32_t time;
3830 if (audio_is_linear_pcm(mFormat)) {
3831 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3832 } else {
3833 time = 10000;
3834 }
3835 return time;
3836}
3837
3838void AudioFlinger::DirectOutputThread::cacheParameters_l()
3839{
3840 PlaybackThread::cacheParameters_l();
3841
3842 // use shorter standby delay as on normal output to release
3843 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003844 if (audio_is_linear_pcm(mFormat)) {
3845 standbyDelay = microseconds(activeSleepTime*2);
3846 } else {
3847 standbyDelay = kOffloadStandbyDelayNs;
3848 }
Eric Laurent81784c32012-11-19 14:55:58 -08003849}
3850
3851// ----------------------------------------------------------------------------
3852
Eric Laurentbfb1b832013-01-07 09:53:42 -08003853AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003854 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003855 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003856 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003857 mWriteAckSequence(0),
3858 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859{
3860}
3861
3862AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3863{
3864}
3865
3866void AudioFlinger::AsyncCallbackThread::onFirstRef()
3867{
3868 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3869}
3870
3871bool AudioFlinger::AsyncCallbackThread::threadLoop()
3872{
3873 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003874 uint32_t writeAckSequence;
3875 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876
3877 {
3878 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003879 while (!((mWriteAckSequence & 1) ||
3880 (mDrainSequence & 1) ||
3881 exitPending())) {
3882 mWaitWorkCV.wait(mLock);
3883 }
3884
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 if (exitPending()) {
3886 break;
3887 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003888 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3889 mWriteAckSequence, mDrainSequence);
3890 writeAckSequence = mWriteAckSequence;
3891 mWriteAckSequence &= ~1;
3892 drainSequence = mDrainSequence;
3893 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 }
3895 {
Eric Laurent4de95592013-09-26 15:28:21 -07003896 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3897 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003898 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003899 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003901 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003902 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 }
3904 }
3905 }
3906 }
3907 return false;
3908}
3909
3910void AudioFlinger::AsyncCallbackThread::exit()
3911{
3912 ALOGV("AsyncCallbackThread::exit");
3913 Mutex::Autolock _l(mLock);
3914 requestExit();
3915 mWaitWorkCV.broadcast();
3916}
3917
Eric Laurent3b4529e2013-09-05 18:09:19 -07003918void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919{
3920 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003921 // bit 0 is cleared
3922 mWriteAckSequence = sequence << 1;
3923}
3924
3925void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3926{
3927 Mutex::Autolock _l(mLock);
3928 // ignore unexpected callbacks
3929 if (mWriteAckSequence & 2) {
3930 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 mWaitWorkCV.signal();
3932 }
3933}
3934
Eric Laurent3b4529e2013-09-05 18:09:19 -07003935void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003936{
3937 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003938 // bit 0 is cleared
3939 mDrainSequence = sequence << 1;
3940}
3941
3942void AudioFlinger::AsyncCallbackThread::resetDraining()
3943{
3944 Mutex::Autolock _l(mLock);
3945 // ignore unexpected callbacks
3946 if (mDrainSequence & 2) {
3947 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003948 mWaitWorkCV.signal();
3949 }
3950}
3951
3952
3953// ----------------------------------------------------------------------------
3954AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3955 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3956 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3957 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003958 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003959 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960{
Eric Laurentfd477972013-10-25 18:10:40 -07003961 //FIXME: mStandby should be set to true by ThreadBase constructor
3962 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003963}
3964
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965void AudioFlinger::OffloadThread::threadLoop_exit()
3966{
3967 if (mFlushPending || mHwPaused) {
3968 // If a flush is pending or track was paused, just discard buffered data
3969 flushHw_l();
3970 } else {
3971 mMixerStatus = MIXER_DRAIN_ALL;
3972 threadLoop_drain();
3973 }
3974 mCallbackThread->exit();
3975 PlaybackThread::threadLoop_exit();
3976}
3977
3978AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3979 Vector< sp<Track> > *tracksToRemove
3980)
3981{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003982 size_t count = mActiveTracks.size();
3983
3984 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003985 bool doHwPause = false;
3986 bool doHwResume = false;
3987
Eric Laurentede6c3b2013-09-19 14:37:46 -07003988 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3989
Eric Laurentbfb1b832013-01-07 09:53:42 -08003990 // find out which tracks need to be processed
3991 for (size_t i = 0; i < count; i++) {
3992 sp<Track> t = mActiveTracks[i].promote();
3993 // The track died recently
3994 if (t == 0) {
3995 continue;
3996 }
3997 Track* const track = t.get();
3998 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003999 // Only consider last track started for volume and mixer state control.
4000 // In theory an older track could underrun and restart after the new one starts
4001 // but as we only care about the transition phase between two tracks on a
4002 // direct output, it is not a problem to ignore the underrun case.
4003 sp<Track> l = mLatestActiveTrack.promote();
4004 bool last = l.get() == track;
4005
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006 if (track->isPausing()) {
4007 track->setPaused();
4008 if (last) {
4009 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004010 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004011 mHwPaused = true;
4012 }
4013 // If we were part way through writing the mixbuffer to
4014 // the HAL we must save this until we resume
4015 // BUG - this will be wrong if a different track is made active,
4016 // in that case we want to discard the pending data in the
4017 // mixbuffer and tell the client to present it again when the
4018 // track is resumed
4019 mPausedWriteLength = mCurrentWriteLength;
4020 mPausedBytesRemaining = mBytesRemaining;
4021 mBytesRemaining = 0; // stop writing
4022 }
4023 tracksToRemove->add(track);
4024 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004025 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004026 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 if (track->mFillingUpStatus == Track::FS_FILLED) {
4028 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004029 // make sure processVolume_l() will apply new volume even if 0
4030 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004032 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004033 if (last) {
4034 if (mPausedBytesRemaining) {
4035 // Need to continue write that was interrupted
4036 mCurrentWriteLength = mPausedWriteLength;
4037 mBytesRemaining = mPausedBytesRemaining;
4038 mPausedBytesRemaining = 0;
4039 }
4040 if (mHwPaused) {
4041 doHwResume = true;
4042 mHwPaused = false;
4043 // threadLoop_mix() will handle the case that we need to
4044 // resume an interrupted write
4045 }
4046 // enable write to audio HAL
4047 sleepTime = 0;
4048 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049 }
4050 }
4051
4052 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004053 sp<Track> previousTrack = mPreviousTrack.promote();
4054 if (previousTrack != 0) {
4055 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004056 // Flush any data still being written from last track
4057 mBytesRemaining = 0;
4058 if (mPausedBytesRemaining) {
4059 // Last track was paused so we also need to flush saved
4060 // mixbuffer state and invalidate track so that it will
4061 // re-submit that unwritten data when it is next resumed
4062 mPausedBytesRemaining = 0;
4063 // Invalidate is a bit drastic - would be more efficient
4064 // to have a flag to tell client that some of the
4065 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004066 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004067 }
4068 // flush data already sent to the DSP if changing audio session as audio
4069 // comes from a different source. Also invalidate previous track to force a
4070 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004071 if (previousTrack->sessionId() != track->sessionId()) {
4072 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004073 mFlushPending = true;
4074 }
4075 }
4076 }
4077 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 // reset retry count
4079 track->mRetryCount = kMaxTrackRetriesOffload;
4080 mActiveTrack = t;
4081 mixerStatus = MIXER_TRACKS_READY;
4082 }
4083 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004084 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085 if (track->isStopping_1()) {
4086 // Hardware buffer can hold a large amount of audio so we must
4087 // wait for all current track's data to drain before we say
4088 // that the track is stopped.
4089 if (mBytesRemaining == 0) {
4090 // Only start draining when all data in mixbuffer
4091 // has been written
4092 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4093 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004094 // do not drain if no data was ever sent to HAL (mStandby == true)
4095 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004096 // do not modify drain sequence if we are already draining. This happens
4097 // when resuming from pause after drain.
4098 if ((mDrainSequence & 1) == 0) {
4099 sleepTime = 0;
4100 standbyTime = systemTime() + standbyDelay;
4101 mixerStatus = MIXER_DRAIN_TRACK;
4102 mDrainSequence += 2;
4103 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004104 if (mHwPaused) {
4105 // It is possible to move from PAUSED to STOPPING_1 without
4106 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004107 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 mHwPaused = false;
4109 }
4110 }
4111 }
4112 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004113 // Drain has completed or we are in standby, signal presentation complete
4114 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004115 track->mState = TrackBase::STOPPED;
4116 size_t audioHALFrames =
4117 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4118 size_t framesWritten =
4119 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4120 track->presentationComplete(framesWritten, audioHALFrames);
4121 track->reset();
4122 tracksToRemove->add(track);
4123 }
4124 } else {
4125 // No buffers for this track. Give it a few chances to
4126 // fill a buffer, then remove it from active list.
4127 if (--(track->mRetryCount) <= 0) {
4128 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4129 track->name());
4130 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004131 // indicate to client process that the track was disabled because of underrun;
4132 // it will then automatically call start() when data is available
4133 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 } else if (last){
4135 mixerStatus = MIXER_TRACKS_ENABLED;
4136 }
4137 }
4138 }
4139 // compute volume for this track
4140 processVolume_l(track, last);
4141 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004142
Eric Laurentea0fade2013-10-04 16:23:48 -07004143 // make sure the pause/flush/resume sequence is executed in the right order.
4144 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4145 // before flush and then resume HW. This can happen in case of pause/flush/resume
4146 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004147 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004148 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004149 if (!doHwPause) {
4150 doHwResume = true;
4151 }
Eric Laurent972a1732013-09-04 09:42:59 -07004152 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004153 if (mFlushPending) {
4154 flushHw_l();
4155 mFlushPending = false;
4156 }
Eric Laurentfd477972013-10-25 18:10:40 -07004157 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004158 mOutput->stream->resume(mOutput->stream);
4159 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004160
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 // remove all the tracks that need to be...
4162 removeTracks_l(*tracksToRemove);
4163
4164 return mixerStatus;
4165}
4166
4167void AudioFlinger::OffloadThread::flushOutput_l()
4168{
4169 mFlushPending = true;
4170}
4171
4172// must be called with thread mutex locked
4173bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4174{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004175 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4176 mWriteAckSequence, mDrainSequence);
4177 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178 return true;
4179 }
4180 return false;
4181}
4182
4183// must be called with thread mutex locked
4184bool AudioFlinger::OffloadThread::shouldStandby_l()
4185{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004186 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187
4188 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4189 // after a timeout and we will enter standby then.
4190 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004191 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 }
4193
Glenn Kastene6f35b12013-08-19 09:58:50 -07004194 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195}
4196
4197
4198bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4199{
4200 Mutex::Autolock _l(mLock);
4201 return waitingAsyncCallback_l();
4202}
4203
4204void AudioFlinger::OffloadThread::flushHw_l()
4205{
4206 mOutput->stream->flush(mOutput->stream);
4207 // Flush anything still waiting in the mixbuffer
4208 mCurrentWriteLength = 0;
4209 mBytesRemaining = 0;
4210 mPausedWriteLength = 0;
4211 mPausedBytesRemaining = 0;
4212 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004213 // discard any pending drain or write ack by incrementing sequence
4214 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4215 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004217 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4218 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 }
4220}
4221
4222// ----------------------------------------------------------------------------
4223
Eric Laurent81784c32012-11-19 14:55:58 -08004224AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4225 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4226 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4227 DUPLICATING),
4228 mWaitTimeMs(UINT_MAX)
4229{
4230 addOutputTrack(mainThread);
4231}
4232
4233AudioFlinger::DuplicatingThread::~DuplicatingThread()
4234{
4235 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4236 mOutputTracks[i]->destroy();
4237 }
4238}
4239
4240void AudioFlinger::DuplicatingThread::threadLoop_mix()
4241{
4242 // mix buffers...
4243 if (outputsReady(outputTracks)) {
4244 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4245 } else {
4246 memset(mMixBuffer, 0, mixBufferSize);
4247 }
4248 sleepTime = 0;
4249 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004251 standbyTime = systemTime() + standbyDelay;
4252}
4253
4254void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4255{
4256 if (sleepTime == 0) {
4257 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4258 sleepTime = activeSleepTime;
4259 } else {
4260 sleepTime = idleSleepTime;
4261 }
4262 } else if (mBytesWritten != 0) {
4263 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4264 writeFrames = mNormalFrameCount;
4265 memset(mMixBuffer, 0, mixBufferSize);
4266 } else {
4267 // flush remaining overflow buffers in output tracks
4268 writeFrames = 0;
4269 }
4270 sleepTime = 0;
4271 }
4272}
4273
Eric Laurentbfb1b832013-01-07 09:53:42 -08004274ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004275{
4276 for (size_t i = 0; i < outputTracks.size(); i++) {
4277 outputTracks[i]->write(mMixBuffer, writeFrames);
4278 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004279 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004281}
4282
4283void AudioFlinger::DuplicatingThread::threadLoop_standby()
4284{
4285 // DuplicatingThread implements standby by stopping all tracks
4286 for (size_t i = 0; i < outputTracks.size(); i++) {
4287 outputTracks[i]->stop();
4288 }
4289}
4290
4291void AudioFlinger::DuplicatingThread::saveOutputTracks()
4292{
4293 outputTracks = mOutputTracks;
4294}
4295
4296void AudioFlinger::DuplicatingThread::clearOutputTracks()
4297{
4298 outputTracks.clear();
4299}
4300
4301void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4302{
4303 Mutex::Autolock _l(mLock);
4304 // FIXME explain this formula
4305 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4306 OutputTrack *outputTrack = new OutputTrack(thread,
4307 this,
4308 mSampleRate,
4309 mFormat,
4310 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004311 frameCount,
4312 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004313 if (outputTrack->cblk() != NULL) {
4314 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4315 mOutputTracks.add(outputTrack);
4316 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4317 updateWaitTime_l();
4318 }
4319}
4320
4321void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4322{
4323 Mutex::Autolock _l(mLock);
4324 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4325 if (mOutputTracks[i]->thread() == thread) {
4326 mOutputTracks[i]->destroy();
4327 mOutputTracks.removeAt(i);
4328 updateWaitTime_l();
4329 return;
4330 }
4331 }
4332 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4333}
4334
4335// caller must hold mLock
4336void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4337{
4338 mWaitTimeMs = UINT_MAX;
4339 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4340 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4341 if (strong != 0) {
4342 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4343 if (waitTimeMs < mWaitTimeMs) {
4344 mWaitTimeMs = waitTimeMs;
4345 }
4346 }
4347 }
4348}
4349
4350
4351bool AudioFlinger::DuplicatingThread::outputsReady(
4352 const SortedVector< sp<OutputTrack> > &outputTracks)
4353{
4354 for (size_t i = 0; i < outputTracks.size(); i++) {
4355 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4356 if (thread == 0) {
4357 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4358 outputTracks[i].get());
4359 return false;
4360 }
4361 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4362 // see note at standby() declaration
4363 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4364 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4365 thread.get());
4366 return false;
4367 }
4368 }
4369 return true;
4370}
4371
4372uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4373{
4374 return (mWaitTimeMs * 1000) / 2;
4375}
4376
4377void AudioFlinger::DuplicatingThread::cacheParameters_l()
4378{
4379 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4380 updateWaitTime_l();
4381
4382 MixerThread::cacheParameters_l();
4383}
4384
4385// ----------------------------------------------------------------------------
4386// Record
4387// ----------------------------------------------------------------------------
4388
4389AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4390 AudioStreamIn *input,
4391 uint32_t sampleRate,
4392 audio_channel_mask_t channelMask,
4393 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004394 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004395 audio_devices_t inDevice
4396#ifdef TEE_SINK
4397 , const sp<NBAIO_Sink>& teeSink
4398#endif
4399 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004400 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten2b806402013-11-20 16:37:38 -08004401 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten85948432013-08-19 12:09:05 -07004402 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear
4403 // are set by readInputParameters()
4404 // mRsmpInIndex LEGACY
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);
Glenn Kasten481fb672013-09-30 14:39:28 -07004414 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004415
4416 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004417}
4418
4419
4420AudioFlinger::RecordThread::~RecordThread()
4421{
Glenn Kasten481fb672013-09-30 14:39:28 -07004422 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004423 delete[] mRsmpInBuffer;
4424 delete mResampler;
4425 delete[] mRsmpOutBuffer;
4426}
4427
4428void AudioFlinger::RecordThread::onFirstRef()
4429{
4430 run(mName, PRIORITY_URGENT_AUDIO);
4431}
4432
Eric Laurent81784c32012-11-19 14:55:58 -08004433bool AudioFlinger::RecordThread::threadLoop()
4434{
Eric Laurent81784c32012-11-19 14:55:58 -08004435 nsecs_t lastWarning = 0;
4436
4437 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004438
4439 // used to verify we've read at least once before evaluating how many bytes were read
4440 bool readOnce = false;
4441
Glenn Kasten5edadd42013-08-14 16:30:49 -07004442 // used to request a deferred sleep, to be executed later while mutex is unlocked
4443 bool doSleep = false;
4444
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004445reacquire_wakelock:
4446 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004447 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004448 {
4449 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004450 size_t size = mActiveTracks.size();
4451 activeTracksGen = mActiveTracksGen;
4452 if (size > 0) {
4453 // FIXME an arbitrary choice
4454 activeTrack = mActiveTracks[0];
4455 acquireWakeLock_l(activeTrack->uid());
4456 if (size > 1) {
4457 SortedVector<int> tmp;
4458 for (size_t i = 0; i < size; i++) {
4459 tmp.add(mActiveTracks[i]->uid());
4460 }
4461 updateWakeLockUids_l(tmp);
4462 }
4463 } else {
4464 acquireWakeLock_l(-1);
4465 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004466 }
4467
Eric Laurent81784c32012-11-19 14:55:58 -08004468 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004469 for (;;) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004470 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004471 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004472
Glenn Kasten5edadd42013-08-14 16:30:49 -07004473 // sleep with mutex unlocked
4474 if (doSleep) {
4475 doSleep = false;
4476 usleep(kRecordThreadSleepUs);
4477 }
4478
Eric Laurent81784c32012-11-19 14:55:58 -08004479 { // scope for mLock
4480 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004481
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004482 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004483 // return value 'reconfig' is currently unused
4484 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004485
Eric Laurent000a4192014-01-29 15:17:32 -08004486 // check exitPending here because checkForNewParameters_l() and
4487 // checkForNewParameters_l() can temporarily release mLock
4488 if (exitPending()) {
4489 break;
4490 }
4491
Glenn Kasten2b806402013-11-20 16:37:38 -08004492 // if no active track(s), then standby and release wakelock
4493 size_t size = mActiveTracks.size();
4494 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004495 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004496 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004497 releaseWakeLock_l();
4498 ALOGV("RecordThread: loop stopping");
4499 // go to sleep
4500 mWaitWorkCV.wait(mLock);
4501 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004502 goto reacquire_wakelock;
4503 }
4504
Glenn Kasten2b806402013-11-20 16:37:38 -08004505 if (mActiveTracksGen != activeTracksGen) {
4506 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004507 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004508 for (size_t i = 0; i < size; i++) {
4509 tmp.add(mActiveTracks[i]->uid());
4510 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004511 updateWakeLockUids_l(tmp);
Glenn Kasten2b806402013-11-20 16:37:38 -08004512 // FIXME an arbitrary choice
4513 activeTrack = mActiveTracks[0];
Eric Laurent81784c32012-11-19 14:55:58 -08004514 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004515
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004516 if (activeTrack->isTerminated()) {
4517 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004518 mActiveTracks.remove(activeTrack);
4519 mActiveTracksGen++;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004520 continue;
4521 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004522
Glenn Kastenb86432b2013-08-14 15:08:12 -07004523 activeTrackState = activeTrack->mState;
4524 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004525 case TrackBase::PAUSING:
Glenn Kasten93e471f2013-08-19 08:40:07 -07004526 standbyIfNotAlreadyInStandby();
Glenn Kasten2b806402013-11-20 16:37:38 -08004527 mActiveTracks.remove(activeTrack);
4528 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004529 mStartStopCond.broadcast();
4530 doSleep = true;
4531 continue;
4532
4533 case TrackBase::RESUMING:
4534 mStandby = false;
4535 if (mReqChannelCount != activeTrack->channelCount()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004536 mActiveTracks.remove(activeTrack);
4537 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004538 mStartStopCond.broadcast();
4539 continue;
4540 }
4541 if (readOnce) {
4542 mStartStopCond.broadcast();
4543 // record start succeeds only if first read from audio input succeeds
4544 if (mBytesRead < 0) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004545 mActiveTracks.remove(activeTrack);
4546 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004547 continue;
4548 }
4549 activeTrack->mState = TrackBase::ACTIVE;
4550 }
4551 break;
4552
4553 case TrackBase::ACTIVE:
4554 break;
4555
4556 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004557 doSleep = true;
4558 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004559
4560 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004561 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004562 }
4563
Eric Laurent81784c32012-11-19 14:55:58 -08004564 lockEffectChains_l(effectChains);
4565 }
4566
Glenn Kasten2b806402013-11-20 16:37:38 -08004567 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004568 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4569
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004570 for (size_t i = 0; i < effectChains.size(); i ++) {
4571 // thread mutex is not locked, but effect chain is locked
4572 effectChains[i]->process_l();
4573 }
4574
Glenn Kastenb91aa632013-08-19 08:40:21 -07004575 AudioBufferProvider::Buffer buffer;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004576 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004577 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004578 if (status == NO_ERROR) {
4579 readOnce = true;
4580 size_t framesOut = buffer.frameCount;
4581 if (mResampler == NULL) {
4582 // no resampling
4583 while (framesOut) {
4584 size_t framesIn = mFrameCount - mRsmpInIndex;
4585 if (framesIn > 0) {
4586 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4587 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004588 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004589 if (framesIn > framesOut) {
4590 framesIn = framesOut;
4591 }
4592 mRsmpInIndex += framesIn;
4593 framesOut -= framesIn;
4594 if (mChannelCount == mReqChannelCount) {
4595 memcpy(dst, src, framesIn * mFrameSize);
4596 } else {
4597 if (mChannelCount == 1) {
4598 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4599 (int16_t *)src, framesIn);
4600 } else {
4601 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4602 (int16_t *)src, framesIn);
4603 }
4604 }
4605 }
4606 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4607 void *readInto;
4608 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4609 readInto = buffer.raw;
4610 framesOut = 0;
4611 } else {
4612 readInto = mRsmpInBuffer;
4613 mRsmpInIndex = 0;
4614 }
4615 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4616 mBufferSize);
4617 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004618 // TODO: verify that it's benign to use a stale track state
4619 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004620 {
4621 ALOGE("Error reading audio input");
4622 // Force input into standby so that it tries to
4623 // recover at next read attempt
4624 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004625 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004626 }
4627 mRsmpInIndex = mFrameCount;
4628 framesOut = 0;
4629 buffer.frameCount = 0;
4630 }
4631#ifdef TEE_SINK
4632 else if (mTeeSink != 0) {
4633 (void) mTeeSink->write(readInto,
4634 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4635 }
4636#endif
4637 }
4638 }
4639 } else {
4640 // resampling
4641
Glenn Kasten85948432013-08-19 12:09:05 -07004642 // avoid busy-waiting if client doesn't keep up
4643 bool madeProgress = false;
4644
4645 // keep mRsmpInBuffer full so resampler always has sufficient input
4646 for (;;) {
4647 int32_t rear = mRsmpInRear;
4648 ssize_t filled = rear - mRsmpInFront;
4649 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
4650 // exit once there is enough data in buffer for resampler
4651 if ((size_t) filled >= mRsmpInFrames) {
4652 break;
4653 }
4654 size_t avail = mRsmpInFramesP2 - filled;
4655 // Only try to read full HAL buffers.
4656 // But if the HAL read returns a partial buffer, use it.
4657 if (avail < mFrameCount) {
4658 ALOGE("insufficient space to read: avail %d < mFrameCount %d",
4659 avail, mFrameCount);
4660 break;
4661 }
4662 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then
4663 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
4664 rear &= mRsmpInFramesP2 - 1;
4665 mBytesRead = mInput->stream->read(mInput->stream,
4666 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4667 if (mBytesRead <= 0) {
4668 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize);
4669 break;
4670 }
4671 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize);
4672 size_t framesRead = mBytesRead / mFrameSize;
4673 ALOG_ASSERT(framesRead > 0);
4674 madeProgress = true;
4675 // If 'avail' was non-contiguous, we now correct for reading past end of buffer.
4676 size_t part1 = mRsmpInFramesP2 - rear;
4677 if (framesRead > part1) {
4678 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4679 (framesRead - part1) * mFrameSize);
4680 }
4681 mRsmpInRear += framesRead;
4682 }
4683
4684 if (!madeProgress) {
4685 ALOGV("Did not make progress");
4686 usleep(((mFrameCount * 1000) / mSampleRate) * 1000);
4687 }
4688
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004689 // resampler accumulates, but we only have one source track
4690 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004691 mResampler->resample(mRsmpOutBuffer, framesOut,
4692 this /* AudioBufferProvider* */);
4693 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004694 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten85948432013-08-19 12:09:05 -07004695 if (mReqChannelCount == 1) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004696 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4697 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4698 // the resampler always outputs stereo samples:
4699 // do post stereo to mono conversion
4700 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4701 framesOut);
4702 } else {
4703 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4704 }
4705 // now done with mRsmpOutBuffer
4706
4707 }
4708 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004709 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004710 } else {
4711 if (mFramestoDrop > 0) {
4712 mFramestoDrop -= buffer.frameCount;
4713 if (mFramestoDrop <= 0) {
4714 clearSyncStartEvent();
4715 }
4716 } else {
4717 mFramestoDrop += buffer.frameCount;
4718 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4719 mSyncStartEvent->isCancelled()) {
4720 ALOGW("Synced record %s, session %d, trigger session %d",
4721 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004722 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004723 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4724 clearSyncStartEvent();
4725 }
4726 }
4727 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004728 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004729 }
4730 // client isn't retrieving buffers fast enough
4731 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004732 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004733 nsecs_t now = systemTime();
4734 if ((now - lastWarning) > kWarningThrottleNs) {
4735 ALOGW("RecordThread: buffer overflow");
4736 lastWarning = now;
4737 }
4738 }
4739 // Release the processor for a while before asking for a new buffer.
4740 // This will give the application more chance to read from the buffer and
4741 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004742 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004743 }
4744
Eric Laurent81784c32012-11-19 14:55:58 -08004745 // enable changes in effect chain
4746 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004747 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004748 }
4749
Glenn Kasten93e471f2013-08-19 08:40:07 -07004750 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004751
4752 {
4753 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004754 for (size_t i = 0; i < mTracks.size(); i++) {
4755 sp<RecordTrack> track = mTracks[i];
4756 track->invalidate();
4757 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004758 mActiveTracks.clear();
4759 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004760 mStartStopCond.broadcast();
4761 }
4762
4763 releaseWakeLock();
4764
4765 ALOGV("RecordThread %p exiting", this);
4766 return false;
4767}
4768
Glenn Kasten93e471f2013-08-19 08:40:07 -07004769void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004770{
4771 if (!mStandby) {
4772 inputStandBy();
4773 mStandby = true;
4774 }
4775}
4776
4777void AudioFlinger::RecordThread::inputStandBy()
4778{
4779 mInput->stream->common.standby(&mInput->stream->common);
4780}
4781
Glenn Kastene198c362013-08-13 09:13:36 -07004782sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004783 const sp<AudioFlinger::Client>& client,
4784 uint32_t sampleRate,
4785 audio_format_t format,
4786 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08004787 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08004788 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004789 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004790 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004791 pid_t tid,
4792 status_t *status)
4793{
Glenn Kasten74935e42013-12-19 08:56:45 -08004794 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004795 sp<RecordTrack> track;
4796 status_t lStatus;
4797
4798 lStatus = initCheck();
4799 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004800 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004801 goto Exit;
4802 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004803 // client expresses a preference for FAST, but we get the final say
4804 if (*flags & IAudioFlinger::TRACK_FAST) {
4805 if (
4806 // use case: callback handler and frame count is default or at least as large as HAL
4807 (
4808 (tid != -1) &&
4809 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004810 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004811 ) &&
4812 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4813 // mono or stereo
4814 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4815 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4816 // hardware sample rate
4817 (sampleRate == mSampleRate) &&
4818 // record thread has an associated fast recorder
4819 hasFastRecorder()
4820 // FIXME test that RecordThread for this fast track has a capable output HAL
4821 // FIXME add a permission test also?
4822 ) {
4823 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4824 if (frameCount == 0) {
4825 frameCount = mFrameCount * kFastTrackMultiplier;
4826 }
4827 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4828 frameCount, mFrameCount);
4829 } else {
4830 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4831 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4832 "hasFastRecorder=%d tid=%d",
4833 frameCount, mFrameCount, format,
4834 audio_is_linear_pcm(format),
4835 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4836 *flags &= ~IAudioFlinger::TRACK_FAST;
4837 // For compatibility with AudioRecord calculation, buffer depth is forced
4838 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4839 // This is probably too conservative, but legacy application code may depend on it.
4840 // If you change this calculation, also review the start threshold which is related.
4841 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4842 size_t mNormalFrameCount = 2048; // FIXME
4843 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4844 if (minBufCount < 2) {
4845 minBufCount = 2;
4846 }
4847 size_t minFrameCount = mNormalFrameCount * minBufCount;
4848 if (frameCount < minFrameCount) {
4849 frameCount = minFrameCount;
4850 }
4851 }
4852 }
Glenn Kasten74935e42013-12-19 08:56:45 -08004853 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07004854
Eric Laurent81784c32012-11-19 14:55:58 -08004855 // FIXME use flags and tid similar to createTrack_l()
4856
4857 { // scope for mLock
4858 Mutex::Autolock _l(mLock);
4859
4860 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004861 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004862
Glenn Kasten03003332013-08-06 15:40:54 -07004863 lStatus = track->initCheck();
4864 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004865 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07004866 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004867 goto Exit;
4868 }
4869 mTracks.add(track);
4870
4871 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4872 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4873 mAudioFlinger->btNrecIsOff();
4874 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4875 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004876
4877 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4878 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4879 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4880 // so ask activity manager to do this on our behalf
4881 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4882 }
Eric Laurent81784c32012-11-19 14:55:58 -08004883 }
4884 lStatus = NO_ERROR;
4885
4886Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004887 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004888 return track;
4889}
4890
4891status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4892 AudioSystem::sync_event_t event,
4893 int triggerSession)
4894{
4895 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4896 sp<ThreadBase> strongMe = this;
4897 status_t status = NO_ERROR;
4898
4899 if (event == AudioSystem::SYNC_EVENT_NONE) {
4900 clearSyncStartEvent();
4901 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4902 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4903 triggerSession,
4904 recordTrack->sessionId(),
4905 syncStartEventCallback,
4906 this);
4907 // Sync event can be cancelled by the trigger session if the track is not in a
4908 // compatible state in which case we start record immediately
4909 if (mSyncStartEvent->isCancelled()) {
4910 clearSyncStartEvent();
4911 } else {
4912 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4913 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4914 }
4915 }
4916
4917 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004918 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004919 AutoMutex lock(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004920 if (mActiveTracks.size() > 0) {
4921 // FIXME does not work for multiple active tracks
4922 if (mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004923 status = -EBUSY;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004924 } else if (recordTrack->mState == TrackBase::PAUSING) {
4925 recordTrack->mState = TrackBase::ACTIVE;
Eric Laurent81784c32012-11-19 14:55:58 -08004926 }
4927 return status;
4928 }
4929
Glenn Kasten47c20702013-08-13 15:37:35 -07004930 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004931 recordTrack->mState = TrackBase::IDLE;
Glenn Kasten2b806402013-11-20 16:37:38 -08004932 mActiveTracks.add(recordTrack);
4933 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004934 mLock.unlock();
4935 status_t status = AudioSystem::startInput(mId);
4936 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004937 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004938 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004939 mActiveTracks.remove(recordTrack);
4940 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004941 clearSyncStartEvent();
4942 return status;
4943 }
Glenn Kasten85948432013-08-19 12:09:05 -07004944 // FIXME LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004945 mRsmpInIndex = mFrameCount;
Glenn Kasten85948432013-08-19 12:09:05 -07004946 mRsmpInFront = 0;
4947 mRsmpInRear = 0;
4948 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004949 mBytesRead = 0;
4950 if (mResampler != NULL) {
4951 mResampler->reset();
4952 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004953 // FIXME hijacking a playback track state name which was intended for start after pause;
4954 // here 'STARTING_2' would be more accurate
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004955 recordTrack->mState = TrackBase::RESUMING;
Eric Laurent81784c32012-11-19 14:55:58 -08004956 // signal thread to start
4957 ALOGV("Signal record thread");
4958 mWaitWorkCV.broadcast();
4959 // do not wait for mStartStopCond if exiting
4960 if (exitPending()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004961 mActiveTracks.remove(recordTrack);
4962 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004963 status = INVALID_OPERATION;
4964 goto startError;
4965 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004966 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004967 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004968 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004969 ALOGV("Record failed to start");
4970 status = BAD_VALUE;
4971 goto startError;
4972 }
4973 ALOGV("Record started OK");
4974 return status;
4975 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004976
Eric Laurent81784c32012-11-19 14:55:58 -08004977startError:
4978 AudioSystem::stopInput(mId);
4979 clearSyncStartEvent();
4980 return status;
4981}
4982
4983void AudioFlinger::RecordThread::clearSyncStartEvent()
4984{
4985 if (mSyncStartEvent != 0) {
4986 mSyncStartEvent->cancel();
4987 }
4988 mSyncStartEvent.clear();
4989 mFramestoDrop = 0;
4990}
4991
4992void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4993{
4994 sp<SyncEvent> strongEvent = event.promote();
4995
4996 if (strongEvent != 0) {
4997 RecordThread *me = (RecordThread *)strongEvent->cookie();
4998 me->handleSyncStartEvent(strongEvent);
4999 }
5000}
5001
5002void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5003{
5004 if (event == mSyncStartEvent) {
5005 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5006 // from audio HAL
5007 mFramestoDrop = mFrameCount * 2;
5008 }
5009}
5010
Glenn Kastena8356f62013-07-25 14:37:52 -07005011bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005012 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005013 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005014 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005015 return false;
5016 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005017 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005018 recordTrack->mState = TrackBase::PAUSING;
5019 // do not wait for mStartStopCond if exiting
5020 if (exitPending()) {
5021 return true;
5022 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005023 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005024 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005025 // if we have been restarted, recordTrack is in mActiveTracks here
5026 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005027 ALOGV("Record stopped OK");
5028 return true;
5029 }
5030 return false;
5031}
5032
Glenn Kasten0f11b512014-01-31 16:18:54 -08005033bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005034{
5035 return false;
5036}
5037
Glenn Kasten0f11b512014-01-31 16:18:54 -08005038status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005039{
5040#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5041 if (!isValidSyncEvent(event)) {
5042 return BAD_VALUE;
5043 }
5044
5045 int eventSession = event->triggerSession();
5046 status_t ret = NAME_NOT_FOUND;
5047
5048 Mutex::Autolock _l(mLock);
5049
5050 for (size_t i = 0; i < mTracks.size(); i++) {
5051 sp<RecordTrack> track = mTracks[i];
5052 if (eventSession == track->sessionId()) {
5053 (void) track->setSyncEvent(event);
5054 ret = NO_ERROR;
5055 }
5056 }
5057 return ret;
5058#else
5059 return BAD_VALUE;
5060#endif
5061}
5062
5063// destroyTrack_l() must be called with ThreadBase::mLock held
5064void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5065{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005066 track->terminate();
5067 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005068 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005069 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005070 removeTrack_l(track);
5071 }
5072}
5073
5074void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5075{
5076 mTracks.remove(track);
5077 // need anything related to effects here?
5078}
5079
5080void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5081{
5082 dumpInternals(fd, args);
5083 dumpTracks(fd, args);
5084 dumpEffectChains(fd, args);
5085}
5086
5087void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5088{
5089 const size_t SIZE = 256;
5090 char buffer[SIZE];
5091 String8 result;
5092
5093 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5094 result.append(buffer);
5095
Glenn Kasten2b806402013-11-20 16:37:38 -08005096 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005097 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5098 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08005099 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005100 result.append(buffer);
5101 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5102 result.append(buffer);
5103 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
5104 result.append(buffer);
5105 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
5106 result.append(buffer);
5107 } else {
5108 result.append("No active record client\n");
5109 }
5110
5111 write(fd, result.string(), result.size());
5112
5113 dumpBase(fd, args);
5114}
5115
Glenn Kasten0f11b512014-01-31 16:18:54 -08005116void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005117{
5118 const size_t SIZE = 256;
5119 char buffer[SIZE];
5120 String8 result;
5121
5122 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5123 result.append(buffer);
5124 RecordTrack::appendDumpHeader(result);
5125 for (size_t i = 0; i < mTracks.size(); ++i) {
5126 sp<RecordTrack> track = mTracks[i];
5127 if (track != 0) {
5128 track->dump(buffer, SIZE);
5129 result.append(buffer);
5130 }
5131 }
5132
Glenn Kasten2b806402013-11-20 16:37:38 -08005133 size_t size = mActiveTracks.size();
5134 if (size > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005135 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5136 result.append(buffer);
5137 RecordTrack::appendDumpHeader(result);
Glenn Kasten2b806402013-11-20 16:37:38 -08005138 for (size_t i = 0; i < size; ++i) {
5139 sp<RecordTrack> track = mActiveTracks[i];
5140 track->dump(buffer, SIZE);
5141 result.append(buffer);
5142 }
Eric Laurent81784c32012-11-19 14:55:58 -08005143
5144 }
5145 write(fd, result.string(), result.size());
5146}
5147
5148// AudioBufferProvider interface
Glenn Kasten0f11b512014-01-31 16:18:54 -08005149status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005150{
Glenn Kasten85948432013-08-19 12:09:05 -07005151 int32_t rear = mRsmpInRear;
5152 int32_t front = mRsmpInFront;
5153 ssize_t filled = rear - front;
5154 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
5155 // 'filled' may be non-contiguous, so return only the first contiguous chunk
5156 front &= mRsmpInFramesP2 - 1;
5157 size_t part1 = mRsmpInFramesP2 - front;
5158 if (part1 > (size_t) filled) {
5159 part1 = filled;
5160 }
5161 size_t ask = buffer->frameCount;
5162 ALOG_ASSERT(ask > 0);
5163 if (part1 > ask) {
5164 part1 = ask;
5165 }
5166 if (part1 == 0) {
5167 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5168 ALOGE("RecordThread::getNextBuffer() starved");
5169 buffer->raw = NULL;
5170 buffer->frameCount = 0;
5171 mRsmpInUnrel = 0;
5172 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005173 }
5174
Glenn Kasten85948432013-08-19 12:09:05 -07005175 buffer->raw = mRsmpInBuffer + front * mChannelCount;
5176 buffer->frameCount = part1;
5177 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005178 return NO_ERROR;
5179}
5180
5181// AudioBufferProvider interface
5182void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5183{
Glenn Kasten85948432013-08-19 12:09:05 -07005184 size_t stepCount = buffer->frameCount;
5185 if (stepCount == 0) {
5186 return;
5187 }
5188 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
5189 mRsmpInUnrel -= stepCount;
5190 mRsmpInFront += stepCount;
5191 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005192 buffer->frameCount = 0;
5193}
5194
5195bool AudioFlinger::RecordThread::checkForNewParameters_l()
5196{
5197 bool reconfig = false;
5198
5199 while (!mNewParameters.isEmpty()) {
5200 status_t status = NO_ERROR;
5201 String8 keyValuePair = mNewParameters[0];
5202 AudioParameter param = AudioParameter(keyValuePair);
5203 int value;
5204 audio_format_t reqFormat = mFormat;
5205 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005206 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005207
5208 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5209 reqSamplingRate = value;
5210 reconfig = true;
5211 }
5212 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005213 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5214 status = BAD_VALUE;
5215 } else {
5216 reqFormat = (audio_format_t) value;
5217 reconfig = true;
5218 }
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005221 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5222 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5223 status = BAD_VALUE;
5224 } else {
5225 reqChannelMask = mask;
5226 reconfig = true;
5227 }
Eric Laurent81784c32012-11-19 14:55:58 -08005228 }
5229 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5230 // do not accept frame count changes if tracks are open as the track buffer
5231 // size depends on frame count and correct behavior would not be guaranteed
5232 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005233 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005234 status = INVALID_OPERATION;
5235 } else {
5236 reconfig = true;
5237 }
5238 }
5239 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5240 // forward device change to effects that have requested to be
5241 // aware of attached audio device.
5242 for (size_t i = 0; i < mEffectChains.size(); i++) {
5243 mEffectChains[i]->setDevice_l(value);
5244 }
5245
5246 // store input device and output device but do not forward output device to audio HAL.
5247 // Note that status is ignored by the caller for output device
5248 // (see AudioFlinger::setParameters()
5249 if (audio_is_output_devices(value)) {
5250 mOutDevice = value;
5251 status = BAD_VALUE;
5252 } else {
5253 mInDevice = value;
5254 // disable AEC and NS if the device is a BT SCO headset supporting those
5255 // pre processings
5256 if (mTracks.size() > 0) {
5257 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5258 mAudioFlinger->btNrecIsOff();
5259 for (size_t i = 0; i < mTracks.size(); i++) {
5260 sp<RecordTrack> track = mTracks[i];
5261 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5262 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5263 }
5264 }
5265 }
5266 }
5267 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5268 mAudioSource != (audio_source_t)value) {
5269 // forward device change to effects that have requested to be
5270 // aware of attached audio device.
5271 for (size_t i = 0; i < mEffectChains.size(); i++) {
5272 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5273 }
5274 mAudioSource = (audio_source_t)value;
5275 }
Glenn Kastene198c362013-08-13 09:13:36 -07005276
Eric Laurent81784c32012-11-19 14:55:58 -08005277 if (status == NO_ERROR) {
5278 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5279 keyValuePair.string());
5280 if (status == INVALID_OPERATION) {
5281 inputStandBy();
5282 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5283 keyValuePair.string());
5284 }
5285 if (reconfig) {
5286 if (status == BAD_VALUE &&
5287 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5288 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005289 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005290 <= (2 * reqSamplingRate)) &&
5291 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5292 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005293 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5294 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005295 status = NO_ERROR;
5296 }
5297 if (status == NO_ERROR) {
5298 readInputParameters();
5299 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5300 }
5301 }
5302 }
5303
5304 mNewParameters.removeAt(0);
5305
5306 mParamStatus = status;
5307 mParamCond.signal();
5308 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5309 // already timed out waiting for the status and will never signal the condition.
5310 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5311 }
5312 return reconfig;
5313}
5314
5315String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5316{
Eric Laurent81784c32012-11-19 14:55:58 -08005317 Mutex::Autolock _l(mLock);
5318 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005319 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005320 }
5321
Glenn Kastend8ea6992013-07-16 14:17:15 -07005322 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5323 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005324 free(s);
5325 return out_s8;
5326}
5327
Glenn Kasten0f11b512014-01-31 16:18:54 -08005328void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005329 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005330 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005331
5332 switch (event) {
5333 case AudioSystem::INPUT_OPENED:
5334 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005335 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 desc.samplingRate = mSampleRate;
5337 desc.format = mFormat;
5338 desc.frameCount = mFrameCount;
5339 desc.latency = 0;
5340 param2 = &desc;
5341 break;
5342
5343 case AudioSystem::INPUT_CLOSED:
5344 default:
5345 break;
5346 }
5347 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5348}
5349
5350void AudioFlinger::RecordThread::readInputParameters()
5351{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005352 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005353 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005354 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005355 mRsmpOutBuffer = NULL;
5356 delete mResampler;
5357 mResampler = NULL;
5358
5359 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5360 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005361 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005362 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005363 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5364 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5365 }
Eric Laurent81784c32012-11-19 14:55:58 -08005366 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005367 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5368 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07005369 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5370 // 1 full output buffer, regardless of the alignment of the available input.
5371 mRsmpInFrames = mFrameCount * 3;
5372 mRsmpInFramesP2 = roundup(mRsmpInFrames);
5373 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5374 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5375 mRsmpInFront = 0;
5376 mRsmpInRear = 0;
5377 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005378
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005379 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Glenn Kasten579dd272013-11-08 14:26:14 -08005380 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005381 mResampler->setSampleRate(mSampleRate);
5382 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten85948432013-08-19 12:09:05 -07005383 // resampler always outputs stereo
Glenn Kasten34af0262013-07-30 11:52:39 -07005384 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005385 }
5386 mRsmpInIndex = mFrameCount;
5387}
5388
Glenn Kasten5f972c02014-01-13 09:59:31 -08005389uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005390{
5391 Mutex::Autolock _l(mLock);
5392 if (initCheck() != NO_ERROR) {
5393 return 0;
5394 }
5395
5396 return mInput->stream->get_input_frames_lost(mInput->stream);
5397}
5398
5399uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5400{
5401 Mutex::Autolock _l(mLock);
5402 uint32_t result = 0;
5403 if (getEffectChain_l(sessionId) != 0) {
5404 result = EFFECT_SESSION;
5405 }
5406
5407 for (size_t i = 0; i < mTracks.size(); ++i) {
5408 if (sessionId == mTracks[i]->sessionId()) {
5409 result |= TRACK_SESSION;
5410 break;
5411 }
5412 }
5413
5414 return result;
5415}
5416
5417KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5418{
5419 KeyedVector<int, bool> ids;
5420 Mutex::Autolock _l(mLock);
5421 for (size_t j = 0; j < mTracks.size(); ++j) {
5422 sp<RecordThread::RecordTrack> track = mTracks[j];
5423 int sessionId = track->sessionId();
5424 if (ids.indexOfKey(sessionId) < 0) {
5425 ids.add(sessionId, true);
5426 }
5427 }
5428 return ids;
5429}
5430
5431AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5432{
5433 Mutex::Autolock _l(mLock);
5434 AudioStreamIn *input = mInput;
5435 mInput = NULL;
5436 return input;
5437}
5438
5439// this method must always be called either with ThreadBase mLock held or inside the thread loop
5440audio_stream_t* AudioFlinger::RecordThread::stream() const
5441{
5442 if (mInput == NULL) {
5443 return NULL;
5444 }
5445 return &mInput->stream->common;
5446}
5447
5448status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5449{
5450 // only one chain per input thread
5451 if (mEffectChains.size() != 0) {
5452 return INVALID_OPERATION;
5453 }
5454 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5455
5456 chain->setInBuffer(NULL);
5457 chain->setOutBuffer(NULL);
5458
5459 checkSuspendOnAddEffectChain_l(chain);
5460
5461 mEffectChains.add(chain);
5462
5463 return NO_ERROR;
5464}
5465
5466size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5467{
5468 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5469 ALOGW_IF(mEffectChains.size() != 1,
5470 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5471 chain.get(), mEffectChains.size(), this);
5472 if (mEffectChains.size() == 1) {
5473 mEffectChains.removeAt(0);
5474 }
5475 return 0;
5476}
5477
5478}; // namespace android