blob: cecb3dc3095fec2775d975c2fe5751726d8c0b80 [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);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001349 // track must be cleared from the caller as the caller has the AF lock
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 -08002730bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2731{
2732 return false;
2733}
2734
2735bool AudioFlinger::PlaybackThread::shouldStandby_l()
2736{
2737 return !mStandby;
2738}
2739
2740bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2741{
2742 Mutex::Autolock _l(mLock);
2743 return waitingAsyncCallback_l();
2744}
2745
Eric Laurent81784c32012-11-19 14:55:58 -08002746// shared by MIXER and DIRECT, overridden by DUPLICATING
2747void AudioFlinger::PlaybackThread::threadLoop_standby()
2748{
2749 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2750 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002751 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002752 // discard any pending drain or write ack by incrementing sequence
2753 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2754 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002756 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2757 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758 }
Eric Laurent81784c32012-11-19 14:55:58 -08002759}
2760
2761void AudioFlinger::MixerThread::threadLoop_mix()
2762{
2763 // obtain the presentation timestamp of the next output buffer
2764 int64_t pts;
2765 status_t status = INVALID_OPERATION;
2766
2767 if (mNormalSink != 0) {
2768 status = mNormalSink->getNextWriteTimestamp(&pts);
2769 } else {
2770 status = mOutputSink->getNextWriteTimestamp(&pts);
2771 }
2772
2773 if (status != NO_ERROR) {
2774 pts = AudioBufferProvider::kInvalidPTS;
2775 }
2776
2777 // mix buffers...
2778 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002780 // increase sleep time progressively when application underrun condition clears.
2781 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2782 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2783 // such that we would underrun the audio HAL.
2784 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2785 sleepTimeShift--;
2786 }
2787 sleepTime = 0;
2788 standbyTime = systemTime() + standbyDelay;
2789 //TODO: delay standby when effects have a tail
2790}
2791
2792void AudioFlinger::MixerThread::threadLoop_sleepTime()
2793{
2794 // If no tracks are ready, sleep once for the duration of an output
2795 // buffer size, then write 0s to the output
2796 if (sleepTime == 0) {
2797 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2798 sleepTime = activeSleepTime >> sleepTimeShift;
2799 if (sleepTime < kMinThreadSleepTimeUs) {
2800 sleepTime = kMinThreadSleepTimeUs;
2801 }
2802 // reduce sleep time in case of consecutive application underruns to avoid
2803 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2804 // duration we would end up writing less data than needed by the audio HAL if
2805 // the condition persists.
2806 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2807 sleepTimeShift++;
2808 }
2809 } else {
2810 sleepTime = idleSleepTime;
2811 }
2812 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002813 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 sleepTime = 0;
2815 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2816 "anticipated start");
2817 }
2818 // TODO add standby time extension fct of effect tail
2819}
2820
2821// prepareTracks_l() must be called with ThreadBase::mLock held
2822AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2823 Vector< sp<Track> > *tracksToRemove)
2824{
2825
2826 mixer_state mixerStatus = MIXER_IDLE;
2827 // find out which tracks need to be processed
2828 size_t count = mActiveTracks.size();
2829 size_t mixedTracks = 0;
2830 size_t tracksWithEffect = 0;
2831 // counts only _active_ fast tracks
2832 size_t fastTracks = 0;
2833 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2834
2835 float masterVolume = mMasterVolume;
2836 bool masterMute = mMasterMute;
2837
2838 if (masterMute) {
2839 masterVolume = 0;
2840 }
2841 // Delegate master volume control to effect in output mix effect chain if needed
2842 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2843 if (chain != 0) {
2844 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2845 chain->setVolume_l(&v, &v);
2846 masterVolume = (float)((v + (1 << 23)) >> 24);
2847 chain.clear();
2848 }
2849
2850 // prepare a new state to push
2851 FastMixerStateQueue *sq = NULL;
2852 FastMixerState *state = NULL;
2853 bool didModify = false;
2854 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2855 if (mFastMixer != NULL) {
2856 sq = mFastMixer->sq();
2857 state = sq->begin();
2858 }
2859
2860 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002861 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002862 if (t == 0) {
2863 continue;
2864 }
2865
2866 // this const just means the local variable doesn't change
2867 Track* const track = t.get();
2868
2869 // process fast tracks
2870 if (track->isFastTrack()) {
2871
2872 // It's theoretically possible (though unlikely) for a fast track to be created
2873 // and then removed within the same normal mix cycle. This is not a problem, as
2874 // the track never becomes active so it's fast mixer slot is never touched.
2875 // The converse, of removing an (active) track and then creating a new track
2876 // at the identical fast mixer slot within the same normal mix cycle,
2877 // is impossible because the slot isn't marked available until the end of each cycle.
2878 int j = track->mFastIndex;
2879 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2880 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2881 FastTrack *fastTrack = &state->mFastTracks[j];
2882
2883 // Determine whether the track is currently in underrun condition,
2884 // and whether it had a recent underrun.
2885 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2886 FastTrackUnderruns underruns = ftDump->mUnderruns;
2887 uint32_t recentFull = (underruns.mBitFields.mFull -
2888 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2889 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2890 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2891 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2892 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2893 uint32_t recentUnderruns = recentPartial + recentEmpty;
2894 track->mObservedUnderruns = underruns;
2895 // don't count underruns that occur while stopping or pausing
2896 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002897 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2898 recentUnderruns > 0) {
2899 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2900 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
2902
2903 // This is similar to the state machine for normal tracks,
2904 // with a few modifications for fast tracks.
2905 bool isActive = true;
2906 switch (track->mState) {
2907 case TrackBase::STOPPING_1:
2908 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002910 track->mState = TrackBase::STOPPING_2;
2911 }
2912 break;
2913 case TrackBase::PAUSING:
2914 // ramp down is not yet implemented
2915 track->setPaused();
2916 break;
2917 case TrackBase::RESUMING:
2918 // ramp up is not yet implemented
2919 track->mState = TrackBase::ACTIVE;
2920 break;
2921 case TrackBase::ACTIVE:
2922 if (recentFull > 0 || recentPartial > 0) {
2923 // track has provided at least some frames recently: reset retry count
2924 track->mRetryCount = kMaxTrackRetries;
2925 }
2926 if (recentUnderruns == 0) {
2927 // no recent underruns: stay active
2928 break;
2929 }
2930 // there has recently been an underrun of some kind
2931 if (track->sharedBuffer() == 0) {
2932 // were any of the recent underruns "empty" (no frames available)?
2933 if (recentEmpty == 0) {
2934 // no, then ignore the partial underruns as they are allowed indefinitely
2935 break;
2936 }
2937 // there has recently been an "empty" underrun: decrement the retry counter
2938 if (--(track->mRetryCount) > 0) {
2939 break;
2940 }
2941 // indicate to client process that the track was disabled because of underrun;
2942 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002943 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002944 // remove from active list, but state remains ACTIVE [confusing but true]
2945 isActive = false;
2946 break;
2947 }
2948 // fall through
2949 case TrackBase::STOPPING_2:
2950 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002951 case TrackBase::STOPPED:
2952 case TrackBase::FLUSHED: // flush() while active
2953 // Check for presentation complete if track is inactive
2954 // We have consumed all the buffers of this track.
2955 // This would be incomplete if we auto-paused on underrun
2956 {
2957 size_t audioHALFrames =
2958 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2959 size_t framesWritten = mBytesWritten / mFrameSize;
2960 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2961 // track stays in active list until presentation is complete
2962 break;
2963 }
2964 }
2965 if (track->isStopping_2()) {
2966 track->mState = TrackBase::STOPPED;
2967 }
2968 if (track->isStopped()) {
2969 // Can't reset directly, as fast mixer is still polling this track
2970 // track->reset();
2971 // So instead mark this track as needing to be reset after push with ack
2972 resetMask |= 1 << i;
2973 }
2974 isActive = false;
2975 break;
2976 case TrackBase::IDLE:
2977 default:
2978 LOG_FATAL("unexpected track state %d", track->mState);
2979 }
2980
2981 if (isActive) {
2982 // was it previously inactive?
2983 if (!(state->mTrackMask & (1 << j))) {
2984 ExtendedAudioBufferProvider *eabp = track;
2985 VolumeProvider *vp = track;
2986 fastTrack->mBufferProvider = eabp;
2987 fastTrack->mVolumeProvider = vp;
2988 fastTrack->mSampleRate = track->mSampleRate;
2989 fastTrack->mChannelMask = track->mChannelMask;
2990 fastTrack->mGeneration++;
2991 state->mTrackMask |= 1 << j;
2992 didModify = true;
2993 // no acknowledgement required for newly active tracks
2994 }
2995 // cache the combined master volume and stream type volume for fast mixer; this
2996 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002997 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 ++fastTracks;
2999 } else {
3000 // was it previously active?
3001 if (state->mTrackMask & (1 << j)) {
3002 fastTrack->mBufferProvider = NULL;
3003 fastTrack->mGeneration++;
3004 state->mTrackMask &= ~(1 << j);
3005 didModify = true;
3006 // If any fast tracks were removed, we must wait for acknowledgement
3007 // because we're about to decrement the last sp<> on those tracks.
3008 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3009 } else {
3010 LOG_FATAL("fast track %d should have been active", j);
3011 }
3012 tracksToRemove->add(track);
3013 // Avoids a misleading display in dumpsys
3014 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3015 }
3016 continue;
3017 }
3018
3019 { // local variable scope to avoid goto warning
3020
3021 audio_track_cblk_t* cblk = track->cblk();
3022
3023 // The first time a track is added we wait
3024 // for all its buffers to be filled before processing it
3025 int name = track->name();
3026 // make sure that we have enough frames to mix one full buffer.
3027 // enforce this condition only once to enable draining the buffer in case the client
3028 // app does not call stop() and relies on underrun to stop:
3029 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3030 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003031 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003032 uint32_t sr = track->sampleRate();
3033 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003034 desiredFrames = mNormalFrameCount;
3035 } else {
3036 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003037 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003038 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003039 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003040 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003041#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003042 // the minimum track buffer size is normally twice the number of frames necessary
3043 // to fill one buffer and the resampler should not leave more than one buffer worth
3044 // of unreleased frames after each pass, but just in case...
3045 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003046#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003047 }
Eric Laurent81784c32012-11-19 14:55:58 -08003048 uint32_t minFrames = 1;
3049 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3050 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003051 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003052 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003053
3054 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003055 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003056 !track->isPaused() && !track->isTerminated())
3057 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003058 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003059
3060 mixedTracks++;
3061
3062 // track->mainBuffer() != mMixBuffer means there is an effect chain
3063 // connected to the track
3064 chain.clear();
3065 if (track->mainBuffer() != mMixBuffer) {
3066 chain = getEffectChain_l(track->sessionId());
3067 // Delegate volume control to effect in track effect chain if needed
3068 if (chain != 0) {
3069 tracksWithEffect++;
3070 } else {
3071 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3072 "session %d",
3073 name, track->sessionId());
3074 }
3075 }
3076
3077
3078 int param = AudioMixer::VOLUME;
3079 if (track->mFillingUpStatus == Track::FS_FILLED) {
3080 // no ramp for the first volume setting
3081 track->mFillingUpStatus = Track::FS_ACTIVE;
3082 if (track->mState == TrackBase::RESUMING) {
3083 track->mState = TrackBase::ACTIVE;
3084 param = AudioMixer::RAMP_VOLUME;
3085 }
3086 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003087 // FIXME should not make a decision based on mServer
3088 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003089 // If the track is stopped before the first frame was mixed,
3090 // do not apply ramp
3091 param = AudioMixer::RAMP_VOLUME;
3092 }
3093
3094 // compute volume for this track
3095 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003096 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003097 vl = vr = va = 0;
3098 if (track->isPausing()) {
3099 track->setPaused();
3100 }
3101 } else {
3102
3103 // read original volumes with volume control
3104 float typeVolume = mStreamTypes[track->streamType()].volume;
3105 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003106 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003107 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003108 vl = vlr & 0xFFFF;
3109 vr = vlr >> 16;
3110 // track volumes come from shared memory, so can't be trusted and must be clamped
3111 if (vl > MAX_GAIN_INT) {
3112 ALOGV("Track left volume out of range: %04X", vl);
3113 vl = MAX_GAIN_INT;
3114 }
3115 if (vr > MAX_GAIN_INT) {
3116 ALOGV("Track right volume out of range: %04X", vr);
3117 vr = MAX_GAIN_INT;
3118 }
3119 // now apply the master volume and stream type volume
3120 vl = (uint32_t)(v * vl) << 12;
3121 vr = (uint32_t)(v * vr) << 12;
3122 // assuming master volume and stream type volume each go up to 1.0,
3123 // vl and vr are now in 8.24 format
3124
Glenn Kastene3aa6592012-12-04 12:22:46 -08003125 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003126 // send level comes from shared memory and so may be corrupt
3127 if (sendLevel > MAX_GAIN_INT) {
3128 ALOGV("Track send level out of range: %04X", sendLevel);
3129 sendLevel = MAX_GAIN_INT;
3130 }
3131 va = (uint32_t)(v * sendLevel);
3132 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133
Eric Laurent81784c32012-11-19 14:55:58 -08003134 // Delegate volume control to effect in track effect chain if needed
3135 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3136 // Do not ramp volume if volume is controlled by effect
3137 param = AudioMixer::VOLUME;
3138 track->mHasVolumeController = true;
3139 } else {
3140 // force no volume ramp when volume controller was just disabled or removed
3141 // from effect chain to avoid volume spike
3142 if (track->mHasVolumeController) {
3143 param = AudioMixer::VOLUME;
3144 }
3145 track->mHasVolumeController = false;
3146 }
3147
3148 // Convert volumes from 8.24 to 4.12 format
3149 // This additional clamping is needed in case chain->setVolume_l() overshot
3150 vl = (vl + (1 << 11)) >> 12;
3151 if (vl > MAX_GAIN_INT) {
3152 vl = MAX_GAIN_INT;
3153 }
3154 vr = (vr + (1 << 11)) >> 12;
3155 if (vr > MAX_GAIN_INT) {
3156 vr = MAX_GAIN_INT;
3157 }
3158
3159 if (va > MAX_GAIN_INT) {
3160 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3161 }
3162
3163 // XXX: these things DON'T need to be done each time
3164 mAudioMixer->setBufferProvider(name, track);
3165 mAudioMixer->enable(name);
3166
3167 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3168 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3169 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3170 mAudioMixer->setParameter(
3171 name,
3172 AudioMixer::TRACK,
3173 AudioMixer::FORMAT, (void *)track->format());
3174 mAudioMixer->setParameter(
3175 name,
3176 AudioMixer::TRACK,
3177 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003178 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3179 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003180 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003181 if (reqSampleRate == 0) {
3182 reqSampleRate = mSampleRate;
3183 } else if (reqSampleRate > maxSampleRate) {
3184 reqSampleRate = maxSampleRate;
3185 }
Eric Laurent81784c32012-11-19 14:55:58 -08003186 mAudioMixer->setParameter(
3187 name,
3188 AudioMixer::RESAMPLE,
3189 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003190 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003191 mAudioMixer->setParameter(
3192 name,
3193 AudioMixer::TRACK,
3194 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3195 mAudioMixer->setParameter(
3196 name,
3197 AudioMixer::TRACK,
3198 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3199
3200 // reset retry count
3201 track->mRetryCount = kMaxTrackRetries;
3202
3203 // If one track is ready, set the mixer ready if:
3204 // - the mixer was not ready during previous round OR
3205 // - no other track is not ready
3206 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3207 mixerStatus != MIXER_TRACKS_ENABLED) {
3208 mixerStatus = MIXER_TRACKS_READY;
3209 }
3210 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003211 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003212 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003213 }
Eric Laurent81784c32012-11-19 14:55:58 -08003214 // clear effect chain input buffer if an active track underruns to avoid sending
3215 // previous audio buffer again to effects
3216 chain = getEffectChain_l(track->sessionId());
3217 if (chain != 0) {
3218 chain->clearInputBuffer();
3219 }
3220
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003221 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003222 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3223 track->isStopped() || track->isPaused()) {
3224 // We have consumed all the buffers of this track.
3225 // Remove it from the list of active tracks.
3226 // TODO: use actual buffer filling status instead of latency when available from
3227 // audio HAL
3228 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3229 size_t framesWritten = mBytesWritten / mFrameSize;
3230 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3231 if (track->isStopped()) {
3232 track->reset();
3233 }
3234 tracksToRemove->add(track);
3235 }
3236 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003237 // No buffers for this track. Give it a few chances to
3238 // fill a buffer, then remove it from active list.
3239 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003240 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003241 tracksToRemove->add(track);
3242 // indicate to client process that the track was disabled because of underrun;
3243 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003244 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003245 // If one track is not ready, mark the mixer also not ready if:
3246 // - the mixer was ready during previous round OR
3247 // - no other track is ready
3248 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3249 mixerStatus != MIXER_TRACKS_READY) {
3250 mixerStatus = MIXER_TRACKS_ENABLED;
3251 }
3252 }
3253 mAudioMixer->disable(name);
3254 }
3255
3256 } // local variable scope to avoid goto warning
3257track_is_ready: ;
3258
3259 }
3260
3261 // Push the new FastMixer state if necessary
3262 bool pauseAudioWatchdog = false;
3263 if (didModify) {
3264 state->mFastTracksGen++;
3265 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3266 if (kUseFastMixer == FastMixer_Dynamic &&
3267 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3268 state->mCommand = FastMixerState::COLD_IDLE;
3269 state->mColdFutexAddr = &mFastMixerFutex;
3270 state->mColdGen++;
3271 mFastMixerFutex = 0;
3272 if (kUseFastMixer == FastMixer_Dynamic) {
3273 mNormalSink = mOutputSink;
3274 }
3275 // If we go into cold idle, need to wait for acknowledgement
3276 // so that fast mixer stops doing I/O.
3277 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3278 pauseAudioWatchdog = true;
3279 }
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
3281 if (sq != NULL) {
3282 sq->end(didModify);
3283 sq->push(block);
3284 }
3285#ifdef AUDIO_WATCHDOG
3286 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3287 mAudioWatchdog->pause();
3288 }
3289#endif
3290
3291 // Now perform the deferred reset on fast tracks that have stopped
3292 while (resetMask != 0) {
3293 size_t i = __builtin_ctz(resetMask);
3294 ALOG_ASSERT(i < count);
3295 resetMask &= ~(1 << i);
3296 sp<Track> t = mActiveTracks[i].promote();
3297 if (t == 0) {
3298 continue;
3299 }
3300 Track* track = t.get();
3301 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3302 track->reset();
3303 }
3304
3305 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003307
3308 // mix buffer must be cleared if all tracks are connected to an
3309 // effect chain as in this case the mixer will not write to
3310 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3312 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003313 // FIXME as a performance optimization, should remember previous zero status
3314 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3315 }
3316
3317 // if any fast tracks, then status is ready
3318 mMixerStatusIgnoringFastTracks = mixerStatus;
3319 if (fastTracks > 0) {
3320 mixerStatus = MIXER_TRACKS_READY;
3321 }
3322 return mixerStatus;
3323}
3324
3325// getTrackName_l() must be called with ThreadBase::mLock held
3326int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3327{
3328 return mAudioMixer->getTrackName(channelMask, sessionId);
3329}
3330
3331// deleteTrackName_l() must be called with ThreadBase::mLock held
3332void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3333{
3334 ALOGV("remove track (%d) and delete from mixer", name);
3335 mAudioMixer->deleteTrackName(name);
3336}
3337
3338// checkForNewParameters_l() must be called with ThreadBase::mLock held
3339bool AudioFlinger::MixerThread::checkForNewParameters_l()
3340{
3341 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3342 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3343 bool reconfig = false;
3344
3345 while (!mNewParameters.isEmpty()) {
3346
3347 if (mFastMixer != NULL) {
3348 FastMixerStateQueue *sq = mFastMixer->sq();
3349 FastMixerState *state = sq->begin();
3350 if (!(state->mCommand & FastMixerState::IDLE)) {
3351 previousCommand = state->mCommand;
3352 state->mCommand = FastMixerState::HOT_IDLE;
3353 sq->end();
3354 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3355 } else {
3356 sq->end(false /*didModify*/);
3357 }
3358 }
3359
3360 status_t status = NO_ERROR;
3361 String8 keyValuePair = mNewParameters[0];
3362 AudioParameter param = AudioParameter(keyValuePair);
3363 int value;
3364
3365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3366 reconfig = true;
3367 }
3368 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3369 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3370 status = BAD_VALUE;
3371 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003372 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003373 reconfig = true;
3374 }
3375 }
3376 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003377 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003378 status = BAD_VALUE;
3379 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003380 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003381 reconfig = true;
3382 }
3383 }
3384 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3385 // do not accept frame count changes if tracks are open as the track buffer
3386 // size depends on frame count and correct behavior would not be guaranteed
3387 // if frame count is changed after track creation
3388 if (!mTracks.isEmpty()) {
3389 status = INVALID_OPERATION;
3390 } else {
3391 reconfig = true;
3392 }
3393 }
3394 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3395#ifdef ADD_BATTERY_DATA
3396 // when changing the audio output device, call addBatteryData to notify
3397 // the change
3398 if (mOutDevice != value) {
3399 uint32_t params = 0;
3400 // check whether speaker is on
3401 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3402 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3403 }
3404
3405 audio_devices_t deviceWithoutSpeaker
3406 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3407 // check if any other device (except speaker) is on
3408 if (value & deviceWithoutSpeaker ) {
3409 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3410 }
3411
3412 if (params != 0) {
3413 addBatteryData(params);
3414 }
3415 }
3416#endif
3417
3418 // forward device change to effects that have requested to be
3419 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003420 if (value != AUDIO_DEVICE_NONE) {
3421 mOutDevice = value;
3422 for (size_t i = 0; i < mEffectChains.size(); i++) {
3423 mEffectChains[i]->setDevice_l(mOutDevice);
3424 }
Eric Laurent81784c32012-11-19 14:55:58 -08003425 }
3426 }
3427
3428 if (status == NO_ERROR) {
3429 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3430 keyValuePair.string());
3431 if (!mStandby && status == INVALID_OPERATION) {
3432 mOutput->stream->common.standby(&mOutput->stream->common);
3433 mStandby = true;
3434 mBytesWritten = 0;
3435 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3436 keyValuePair.string());
3437 }
3438 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003439 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003440 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003441 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3442 for (size_t i = 0; i < mTracks.size() ; i++) {
3443 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3444 if (name < 0) {
3445 break;
3446 }
3447 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003448 }
3449 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3450 }
3451 }
3452
3453 mNewParameters.removeAt(0);
3454
3455 mParamStatus = status;
3456 mParamCond.signal();
3457 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3458 // already timed out waiting for the status and will never signal the condition.
3459 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3460 }
3461
3462 if (!(previousCommand & FastMixerState::IDLE)) {
3463 ALOG_ASSERT(mFastMixer != NULL);
3464 FastMixerStateQueue *sq = mFastMixer->sq();
3465 FastMixerState *state = sq->begin();
3466 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3467 state->mCommand = previousCommand;
3468 sq->end();
3469 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3470 }
3471
3472 return reconfig;
3473}
3474
3475
3476void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3477{
3478 const size_t SIZE = 256;
3479 char buffer[SIZE];
3480 String8 result;
3481
3482 PlaybackThread::dumpInternals(fd, args);
3483
3484 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3485 result.append(buffer);
3486 write(fd, result.string(), result.size());
3487
3488 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003489 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003490 copy.dump(fd);
3491
3492#ifdef STATE_QUEUE_DUMP
3493 // Similar for state queue
3494 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3495 observerCopy.dump(fd);
3496 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3497 mutatorCopy.dump(fd);
3498#endif
3499
Glenn Kasten46909e72013-02-26 09:20:22 -08003500#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003501 // Write the tee output to a .wav file
3502 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003503#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003504
3505#ifdef AUDIO_WATCHDOG
3506 if (mAudioWatchdog != 0) {
3507 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3508 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3509 wdCopy.dump(fd);
3510 }
3511#endif
3512}
3513
3514uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3515{
3516 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3517}
3518
3519uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3520{
3521 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3522}
3523
3524void AudioFlinger::MixerThread::cacheParameters_l()
3525{
3526 PlaybackThread::cacheParameters_l();
3527
3528 // FIXME: Relaxed timing because of a certain device that can't meet latency
3529 // Should be reduced to 2x after the vendor fixes the driver issue
3530 // increase threshold again due to low power audio mode. The way this warning
3531 // threshold is calculated and its usefulness should be reconsidered anyway.
3532 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3533}
3534
3535// ----------------------------------------------------------------------------
3536
3537AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3538 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3539 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3540 // mLeftVolFloat, mRightVolFloat
3541{
3542}
3543
Eric Laurentbfb1b832013-01-07 09:53:42 -08003544AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3545 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3546 ThreadBase::type_t type)
3547 : PlaybackThread(audioFlinger, output, id, device, type)
3548 // mLeftVolFloat, mRightVolFloat
3549{
3550}
3551
Eric Laurent81784c32012-11-19 14:55:58 -08003552AudioFlinger::DirectOutputThread::~DirectOutputThread()
3553{
3554}
3555
Eric Laurentbfb1b832013-01-07 09:53:42 -08003556void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3557{
3558 audio_track_cblk_t* cblk = track->cblk();
3559 float left, right;
3560
3561 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3562 left = right = 0;
3563 } else {
3564 float typeVolume = mStreamTypes[track->streamType()].volume;
3565 float v = mMasterVolume * typeVolume;
3566 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3567 uint32_t vlr = proxy->getVolumeLR();
3568 float v_clamped = v * (vlr & 0xFFFF);
3569 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3570 left = v_clamped/MAX_GAIN;
3571 v_clamped = v * (vlr >> 16);
3572 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3573 right = v_clamped/MAX_GAIN;
3574 }
3575
3576 if (lastTrack) {
3577 if (left != mLeftVolFloat || right != mRightVolFloat) {
3578 mLeftVolFloat = left;
3579 mRightVolFloat = right;
3580
3581 // Convert volumes from float to 8.24
3582 uint32_t vl = (uint32_t)(left * (1 << 24));
3583 uint32_t vr = (uint32_t)(right * (1 << 24));
3584
3585 // Delegate volume control to effect in track effect chain if needed
3586 // only one effect chain can be present on DirectOutputThread, so if
3587 // there is one, the track is connected to it
3588 if (!mEffectChains.isEmpty()) {
3589 mEffectChains[0]->setVolume_l(&vl, &vr);
3590 left = (float)vl / (1 << 24);
3591 right = (float)vr / (1 << 24);
3592 }
3593 if (mOutput->stream->set_volume) {
3594 mOutput->stream->set_volume(mOutput->stream, left, right);
3595 }
3596 }
3597 }
3598}
3599
3600
Eric Laurent81784c32012-11-19 14:55:58 -08003601AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3602 Vector< sp<Track> > *tracksToRemove
3603)
3604{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003605 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003606 mixer_state mixerStatus = MIXER_IDLE;
3607
3608 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003609 for (size_t i = 0; i < count; i++) {
3610 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // The track died recently
3612 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003613 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
3615
3616 Track* const track = t.get();
3617 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003618 // Only consider last track started for volume and mixer state control.
3619 // In theory an older track could underrun and restart after the new one starts
3620 // but as we only care about the transition phase between two tracks on a
3621 // direct output, it is not a problem to ignore the underrun case.
3622 sp<Track> l = mLatestActiveTrack.promote();
3623 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003624
3625 // The first time a track is added we wait
3626 // for all its buffers to be filled before processing it
3627 uint32_t minFrames;
3628 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3629 minFrames = mNormalFrameCount;
3630 } else {
3631 minFrames = 1;
3632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633
Eric Laurent81784c32012-11-19 14:55:58 -08003634 if ((track->framesReady() >= minFrames) && track->isReady() &&
3635 !track->isPaused() && !track->isTerminated())
3636 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003637 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003638
3639 if (track->mFillingUpStatus == Track::FS_FILLED) {
3640 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003641 // make sure processVolume_l() will apply new volume even if 0
3642 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003643 if (track->mState == TrackBase::RESUMING) {
3644 track->mState = TrackBase::ACTIVE;
3645 }
3646 }
3647
3648 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 processVolume_l(track, last);
3650 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003651 // reset retry count
3652 track->mRetryCount = kMaxTrackRetriesDirect;
3653 mActiveTrack = t;
3654 mixerStatus = MIXER_TRACKS_READY;
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003657 // clear effect chain input buffer if the last active track started underruns
3658 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003659 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003660 mEffectChains[0]->clearInputBuffer();
3661 }
3662
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003663 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003664 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3665 track->isStopped() || track->isPaused()) {
3666 // We have consumed all the buffers of this track.
3667 // Remove it from the list of active tracks.
3668 // TODO: implement behavior for compressed audio
3669 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3670 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003671 if (mStandby || !last ||
3672 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003673 if (track->isStopped()) {
3674 track->reset();
3675 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003676 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003677 }
3678 } else {
3679 // No buffers for this track. Give it a few chances to
3680 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003681 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003682 if (--(track->mRetryCount) <= 0) {
3683 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003684 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003685 // indicate to client process that the track was disabled because of underrun;
3686 // it will then automatically call start() when data is available
3687 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003688 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003689 mixerStatus = MIXER_TRACKS_ENABLED;
3690 }
3691 }
3692 }
3693 }
3694
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003696 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003697
3698 return mixerStatus;
3699}
3700
3701void AudioFlinger::DirectOutputThread::threadLoop_mix()
3702{
Eric Laurent81784c32012-11-19 14:55:58 -08003703 size_t frameCount = mFrameCount;
3704 int8_t *curBuf = (int8_t *)mMixBuffer;
3705 // output audio to hardware
3706 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003707 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003708 buffer.frameCount = frameCount;
3709 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003710 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003711 memset(curBuf, 0, frameCount * mFrameSize);
3712 break;
3713 }
3714 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3715 frameCount -= buffer.frameCount;
3716 curBuf += buffer.frameCount * mFrameSize;
3717 mActiveTrack->releaseBuffer(&buffer);
3718 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003719 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003720 sleepTime = 0;
3721 standbyTime = systemTime() + standbyDelay;
3722 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003723}
3724
3725void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3726{
3727 if (sleepTime == 0) {
3728 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3729 sleepTime = activeSleepTime;
3730 } else {
3731 sleepTime = idleSleepTime;
3732 }
3733 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3734 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3735 sleepTime = 0;
3736 }
3737}
3738
3739// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003740int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3741 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003742{
3743 return 0;
3744}
3745
3746// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003747void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003748{
3749}
3750
3751// checkForNewParameters_l() must be called with ThreadBase::mLock held
3752bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3753{
3754 bool reconfig = false;
3755
3756 while (!mNewParameters.isEmpty()) {
3757 status_t status = NO_ERROR;
3758 String8 keyValuePair = mNewParameters[0];
3759 AudioParameter param = AudioParameter(keyValuePair);
3760 int value;
3761
3762 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3763 // do not accept frame count changes if tracks are open as the track buffer
3764 // size depends on frame count and correct behavior would not be garantied
3765 // if frame count is changed after track creation
3766 if (!mTracks.isEmpty()) {
3767 status = INVALID_OPERATION;
3768 } else {
3769 reconfig = true;
3770 }
3771 }
3772 if (status == NO_ERROR) {
3773 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3774 keyValuePair.string());
3775 if (!mStandby && status == INVALID_OPERATION) {
3776 mOutput->stream->common.standby(&mOutput->stream->common);
3777 mStandby = true;
3778 mBytesWritten = 0;
3779 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3780 keyValuePair.string());
3781 }
3782 if (status == NO_ERROR && reconfig) {
3783 readOutputParameters();
3784 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3785 }
3786 }
3787
3788 mNewParameters.removeAt(0);
3789
3790 mParamStatus = status;
3791 mParamCond.signal();
3792 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3793 // already timed out waiting for the status and will never signal the condition.
3794 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3795 }
3796 return reconfig;
3797}
3798
3799uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3800{
3801 uint32_t time;
3802 if (audio_is_linear_pcm(mFormat)) {
3803 time = PlaybackThread::activeSleepTimeUs();
3804 } else {
3805 time = 10000;
3806 }
3807 return time;
3808}
3809
3810uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3811{
3812 uint32_t time;
3813 if (audio_is_linear_pcm(mFormat)) {
3814 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3815 } else {
3816 time = 10000;
3817 }
3818 return time;
3819}
3820
3821uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3822{
3823 uint32_t time;
3824 if (audio_is_linear_pcm(mFormat)) {
3825 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3826 } else {
3827 time = 10000;
3828 }
3829 return time;
3830}
3831
3832void AudioFlinger::DirectOutputThread::cacheParameters_l()
3833{
3834 PlaybackThread::cacheParameters_l();
3835
3836 // use shorter standby delay as on normal output to release
3837 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003838 if (audio_is_linear_pcm(mFormat)) {
3839 standbyDelay = microseconds(activeSleepTime*2);
3840 } else {
3841 standbyDelay = kOffloadStandbyDelayNs;
3842 }
Eric Laurent81784c32012-11-19 14:55:58 -08003843}
3844
3845// ----------------------------------------------------------------------------
3846
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003848 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003849 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003850 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003851 mWriteAckSequence(0),
3852 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003853{
3854}
3855
3856AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3857{
3858}
3859
3860void AudioFlinger::AsyncCallbackThread::onFirstRef()
3861{
3862 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3863}
3864
3865bool AudioFlinger::AsyncCallbackThread::threadLoop()
3866{
3867 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003868 uint32_t writeAckSequence;
3869 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003870
3871 {
3872 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003873 while (!((mWriteAckSequence & 1) ||
3874 (mDrainSequence & 1) ||
3875 exitPending())) {
3876 mWaitWorkCV.wait(mLock);
3877 }
3878
Eric Laurentbfb1b832013-01-07 09:53:42 -08003879 if (exitPending()) {
3880 break;
3881 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003882 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3883 mWriteAckSequence, mDrainSequence);
3884 writeAckSequence = mWriteAckSequence;
3885 mWriteAckSequence &= ~1;
3886 drainSequence = mDrainSequence;
3887 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003888 }
3889 {
Eric Laurent4de95592013-09-26 15:28:21 -07003890 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3891 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003892 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003893 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003895 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003896 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 }
3898 }
3899 }
3900 }
3901 return false;
3902}
3903
3904void AudioFlinger::AsyncCallbackThread::exit()
3905{
3906 ALOGV("AsyncCallbackThread::exit");
3907 Mutex::Autolock _l(mLock);
3908 requestExit();
3909 mWaitWorkCV.broadcast();
3910}
3911
Eric Laurent3b4529e2013-09-05 18:09:19 -07003912void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003913{
3914 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003915 // bit 0 is cleared
3916 mWriteAckSequence = sequence << 1;
3917}
3918
3919void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3920{
3921 Mutex::Autolock _l(mLock);
3922 // ignore unexpected callbacks
3923 if (mWriteAckSequence & 2) {
3924 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925 mWaitWorkCV.signal();
3926 }
3927}
3928
Eric Laurent3b4529e2013-09-05 18:09:19 -07003929void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930{
3931 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003932 // bit 0 is cleared
3933 mDrainSequence = sequence << 1;
3934}
3935
3936void AudioFlinger::AsyncCallbackThread::resetDraining()
3937{
3938 Mutex::Autolock _l(mLock);
3939 // ignore unexpected callbacks
3940 if (mDrainSequence & 2) {
3941 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003942 mWaitWorkCV.signal();
3943 }
3944}
3945
3946
3947// ----------------------------------------------------------------------------
3948AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3949 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3950 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3951 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003952 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003953 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003954{
Eric Laurentfd477972013-10-25 18:10:40 -07003955 //FIXME: mStandby should be set to true by ThreadBase constructor
3956 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957}
3958
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959void AudioFlinger::OffloadThread::threadLoop_exit()
3960{
3961 if (mFlushPending || mHwPaused) {
3962 // If a flush is pending or track was paused, just discard buffered data
3963 flushHw_l();
3964 } else {
3965 mMixerStatus = MIXER_DRAIN_ALL;
3966 threadLoop_drain();
3967 }
3968 mCallbackThread->exit();
3969 PlaybackThread::threadLoop_exit();
3970}
3971
3972AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3973 Vector< sp<Track> > *tracksToRemove
3974)
3975{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003976 size_t count = mActiveTracks.size();
3977
3978 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003979 bool doHwPause = false;
3980 bool doHwResume = false;
3981
Eric Laurentede6c3b2013-09-19 14:37:46 -07003982 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3983
Eric Laurentbfb1b832013-01-07 09:53:42 -08003984 // find out which tracks need to be processed
3985 for (size_t i = 0; i < count; i++) {
3986 sp<Track> t = mActiveTracks[i].promote();
3987 // The track died recently
3988 if (t == 0) {
3989 continue;
3990 }
3991 Track* const track = t.get();
3992 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003993 // Only consider last track started for volume and mixer state control.
3994 // In theory an older track could underrun and restart after the new one starts
3995 // but as we only care about the transition phase between two tracks on a
3996 // direct output, it is not a problem to ignore the underrun case.
3997 sp<Track> l = mLatestActiveTrack.promote();
3998 bool last = l.get() == track;
3999
Haynes Mathew George7844f672014-01-15 12:32:55 -08004000 if (track->isInvalid()) {
4001 ALOGW("An invalidated track shouldn't be in active list");
4002 tracksToRemove->add(track);
4003 continue;
4004 }
4005
4006 if (track->mState == TrackBase::IDLE) {
4007 ALOGW("An idle track shouldn't be in active list");
4008 continue;
4009 }
4010
Eric Laurentbfb1b832013-01-07 09:53:42 -08004011 if (track->isPausing()) {
4012 track->setPaused();
4013 if (last) {
4014 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004015 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004016 mHwPaused = true;
4017 }
4018 // If we were part way through writing the mixbuffer to
4019 // the HAL we must save this until we resume
4020 // BUG - this will be wrong if a different track is made active,
4021 // in that case we want to discard the pending data in the
4022 // mixbuffer and tell the client to present it again when the
4023 // track is resumed
4024 mPausedWriteLength = mCurrentWriteLength;
4025 mPausedBytesRemaining = mBytesRemaining;
4026 mBytesRemaining = 0; // stop writing
4027 }
4028 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004029 } else if (track->isFlushPending()) {
4030 track->flushAck();
4031 if (last) {
4032 mFlushPending = true;
4033 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004035 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004036 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004037 if (track->mFillingUpStatus == Track::FS_FILLED) {
4038 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004039 // make sure processVolume_l() will apply new volume even if 0
4040 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004042 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004043 if (last) {
4044 if (mPausedBytesRemaining) {
4045 // Need to continue write that was interrupted
4046 mCurrentWriteLength = mPausedWriteLength;
4047 mBytesRemaining = mPausedBytesRemaining;
4048 mPausedBytesRemaining = 0;
4049 }
4050 if (mHwPaused) {
4051 doHwResume = true;
4052 mHwPaused = false;
4053 // threadLoop_mix() will handle the case that we need to
4054 // resume an interrupted write
4055 }
4056 // enable write to audio HAL
4057 sleepTime = 0;
4058 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 }
4060 }
4061
4062 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004063 sp<Track> previousTrack = mPreviousTrack.promote();
4064 if (previousTrack != 0) {
4065 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004066 // Flush any data still being written from last track
4067 mBytesRemaining = 0;
4068 if (mPausedBytesRemaining) {
4069 // Last track was paused so we also need to flush saved
4070 // mixbuffer state and invalidate track so that it will
4071 // re-submit that unwritten data when it is next resumed
4072 mPausedBytesRemaining = 0;
4073 // Invalidate is a bit drastic - would be more efficient
4074 // to have a flag to tell client that some of the
4075 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004076 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004077 }
4078 // flush data already sent to the DSP if changing audio session as audio
4079 // comes from a different source. Also invalidate previous track to force a
4080 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004081 if (previousTrack->sessionId() != track->sessionId()) {
4082 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004083 mFlushPending = true;
4084 }
4085 }
4086 }
4087 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004088 // reset retry count
4089 track->mRetryCount = kMaxTrackRetriesOffload;
4090 mActiveTrack = t;
4091 mixerStatus = MIXER_TRACKS_READY;
4092 }
4093 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004094 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004095 if (track->isStopping_1()) {
4096 // Hardware buffer can hold a large amount of audio so we must
4097 // wait for all current track's data to drain before we say
4098 // that the track is stopped.
4099 if (mBytesRemaining == 0) {
4100 // Only start draining when all data in mixbuffer
4101 // has been written
4102 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4103 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004104 // do not drain if no data was ever sent to HAL (mStandby == true)
4105 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004106 // do not modify drain sequence if we are already draining. This happens
4107 // when resuming from pause after drain.
4108 if ((mDrainSequence & 1) == 0) {
4109 sleepTime = 0;
4110 standbyTime = systemTime() + standbyDelay;
4111 mixerStatus = MIXER_DRAIN_TRACK;
4112 mDrainSequence += 2;
4113 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004114 if (mHwPaused) {
4115 // It is possible to move from PAUSED to STOPPING_1 without
4116 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004117 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004118 mHwPaused = false;
4119 }
4120 }
4121 }
4122 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004123 // Drain has completed or we are in standby, signal presentation complete
4124 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 track->mState = TrackBase::STOPPED;
4126 size_t audioHALFrames =
4127 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4128 size_t framesWritten =
4129 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4130 track->presentationComplete(framesWritten, audioHALFrames);
4131 track->reset();
4132 tracksToRemove->add(track);
4133 }
4134 } else {
4135 // No buffers for this track. Give it a few chances to
4136 // fill a buffer, then remove it from active list.
4137 if (--(track->mRetryCount) <= 0) {
4138 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4139 track->name());
4140 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004141 // indicate to client process that the track was disabled because of underrun;
4142 // it will then automatically call start() when data is available
4143 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004144 } else if (last){
4145 mixerStatus = MIXER_TRACKS_ENABLED;
4146 }
4147 }
4148 }
4149 // compute volume for this track
4150 processVolume_l(track, last);
4151 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004152
Eric Laurentea0fade2013-10-04 16:23:48 -07004153 // make sure the pause/flush/resume sequence is executed in the right order.
4154 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4155 // before flush and then resume HW. This can happen in case of pause/flush/resume
4156 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004157 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004158 mOutput->stream->pause(mOutput->stream);
4159 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004160 if (mFlushPending) {
4161 flushHw_l();
4162 mFlushPending = false;
4163 }
Eric Laurentfd477972013-10-25 18:10:40 -07004164 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004165 mOutput->stream->resume(mOutput->stream);
4166 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004167
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168 // remove all the tracks that need to be...
4169 removeTracks_l(*tracksToRemove);
4170
4171 return mixerStatus;
4172}
4173
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174// must be called with thread mutex locked
4175bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4176{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004177 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4178 mWriteAckSequence, mDrainSequence);
4179 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180 return true;
4181 }
4182 return false;
4183}
4184
4185// must be called with thread mutex locked
4186bool AudioFlinger::OffloadThread::shouldStandby_l()
4187{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004188 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004189
4190 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4191 // after a timeout and we will enter standby then.
4192 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004193 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004194 }
4195
Glenn Kastene6f35b12013-08-19 09:58:50 -07004196 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197}
4198
4199
4200bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4201{
4202 Mutex::Autolock _l(mLock);
4203 return waitingAsyncCallback_l();
4204}
4205
4206void AudioFlinger::OffloadThread::flushHw_l()
4207{
4208 mOutput->stream->flush(mOutput->stream);
4209 // Flush anything still waiting in the mixbuffer
4210 mCurrentWriteLength = 0;
4211 mBytesRemaining = 0;
4212 mPausedWriteLength = 0;
4213 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004214 mHwPaused = false;
4215
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004217 // discard any pending drain or write ack by incrementing sequence
4218 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4219 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004220 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004221 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4222 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 }
4224}
4225
4226// ----------------------------------------------------------------------------
4227
Eric Laurent81784c32012-11-19 14:55:58 -08004228AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4229 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4230 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4231 DUPLICATING),
4232 mWaitTimeMs(UINT_MAX)
4233{
4234 addOutputTrack(mainThread);
4235}
4236
4237AudioFlinger::DuplicatingThread::~DuplicatingThread()
4238{
4239 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4240 mOutputTracks[i]->destroy();
4241 }
4242}
4243
4244void AudioFlinger::DuplicatingThread::threadLoop_mix()
4245{
4246 // mix buffers...
4247 if (outputsReady(outputTracks)) {
4248 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4249 } else {
4250 memset(mMixBuffer, 0, mixBufferSize);
4251 }
4252 sleepTime = 0;
4253 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004254 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004255 standbyTime = systemTime() + standbyDelay;
4256}
4257
4258void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4259{
4260 if (sleepTime == 0) {
4261 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4262 sleepTime = activeSleepTime;
4263 } else {
4264 sleepTime = idleSleepTime;
4265 }
4266 } else if (mBytesWritten != 0) {
4267 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4268 writeFrames = mNormalFrameCount;
4269 memset(mMixBuffer, 0, mixBufferSize);
4270 } else {
4271 // flush remaining overflow buffers in output tracks
4272 writeFrames = 0;
4273 }
4274 sleepTime = 0;
4275 }
4276}
4277
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004279{
4280 for (size_t i = 0; i < outputTracks.size(); i++) {
4281 outputTracks[i]->write(mMixBuffer, writeFrames);
4282 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004283 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004285}
4286
4287void AudioFlinger::DuplicatingThread::threadLoop_standby()
4288{
4289 // DuplicatingThread implements standby by stopping all tracks
4290 for (size_t i = 0; i < outputTracks.size(); i++) {
4291 outputTracks[i]->stop();
4292 }
4293}
4294
4295void AudioFlinger::DuplicatingThread::saveOutputTracks()
4296{
4297 outputTracks = mOutputTracks;
4298}
4299
4300void AudioFlinger::DuplicatingThread::clearOutputTracks()
4301{
4302 outputTracks.clear();
4303}
4304
4305void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4306{
4307 Mutex::Autolock _l(mLock);
4308 // FIXME explain this formula
4309 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4310 OutputTrack *outputTrack = new OutputTrack(thread,
4311 this,
4312 mSampleRate,
4313 mFormat,
4314 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004315 frameCount,
4316 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004317 if (outputTrack->cblk() != NULL) {
4318 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4319 mOutputTracks.add(outputTrack);
4320 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4321 updateWaitTime_l();
4322 }
4323}
4324
4325void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4326{
4327 Mutex::Autolock _l(mLock);
4328 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4329 if (mOutputTracks[i]->thread() == thread) {
4330 mOutputTracks[i]->destroy();
4331 mOutputTracks.removeAt(i);
4332 updateWaitTime_l();
4333 return;
4334 }
4335 }
4336 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4337}
4338
4339// caller must hold mLock
4340void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4341{
4342 mWaitTimeMs = UINT_MAX;
4343 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4344 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4345 if (strong != 0) {
4346 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4347 if (waitTimeMs < mWaitTimeMs) {
4348 mWaitTimeMs = waitTimeMs;
4349 }
4350 }
4351 }
4352}
4353
4354
4355bool AudioFlinger::DuplicatingThread::outputsReady(
4356 const SortedVector< sp<OutputTrack> > &outputTracks)
4357{
4358 for (size_t i = 0; i < outputTracks.size(); i++) {
4359 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4360 if (thread == 0) {
4361 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4362 outputTracks[i].get());
4363 return false;
4364 }
4365 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4366 // see note at standby() declaration
4367 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4368 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4369 thread.get());
4370 return false;
4371 }
4372 }
4373 return true;
4374}
4375
4376uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4377{
4378 return (mWaitTimeMs * 1000) / 2;
4379}
4380
4381void AudioFlinger::DuplicatingThread::cacheParameters_l()
4382{
4383 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4384 updateWaitTime_l();
4385
4386 MixerThread::cacheParameters_l();
4387}
4388
4389// ----------------------------------------------------------------------------
4390// Record
4391// ----------------------------------------------------------------------------
4392
4393AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4394 AudioStreamIn *input,
4395 uint32_t sampleRate,
4396 audio_channel_mask_t channelMask,
4397 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004398 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004399 audio_devices_t inDevice
4400#ifdef TEE_SINK
4401 , const sp<NBAIO_Sink>& teeSink
4402#endif
4403 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004404 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten2b806402013-11-20 16:37:38 -08004405 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten85948432013-08-19 12:09:05 -07004406 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear
4407 // are set by readInputParameters()
4408 // mRsmpInIndex LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004409 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004410 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // mBytesRead is only meaningful while active, and so is cleared in start()
4412 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004413#ifdef TEE_SINK
4414 , mTeeSink(teeSink)
4415#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004416{
4417 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004418 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004419
4420 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004421}
4422
4423
4424AudioFlinger::RecordThread::~RecordThread()
4425{
Glenn Kasten481fb672013-09-30 14:39:28 -07004426 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004427 delete[] mRsmpInBuffer;
4428 delete mResampler;
4429 delete[] mRsmpOutBuffer;
4430}
4431
4432void AudioFlinger::RecordThread::onFirstRef()
4433{
4434 run(mName, PRIORITY_URGENT_AUDIO);
4435}
4436
Eric Laurent81784c32012-11-19 14:55:58 -08004437bool AudioFlinger::RecordThread::threadLoop()
4438{
Eric Laurent81784c32012-11-19 14:55:58 -08004439 nsecs_t lastWarning = 0;
4440
4441 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004442
4443 // used to verify we've read at least once before evaluating how many bytes were read
4444 bool readOnce = false;
4445
Glenn Kasten5edadd42013-08-14 16:30:49 -07004446 // used to request a deferred sleep, to be executed later while mutex is unlocked
4447 bool doSleep = false;
4448
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004449reacquire_wakelock:
4450 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004451 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004452 {
4453 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004454 size_t size = mActiveTracks.size();
4455 activeTracksGen = mActiveTracksGen;
4456 if (size > 0) {
4457 // FIXME an arbitrary choice
4458 activeTrack = mActiveTracks[0];
4459 acquireWakeLock_l(activeTrack->uid());
4460 if (size > 1) {
4461 SortedVector<int> tmp;
4462 for (size_t i = 0; i < size; i++) {
4463 tmp.add(mActiveTracks[i]->uid());
4464 }
4465 updateWakeLockUids_l(tmp);
4466 }
4467 } else {
4468 acquireWakeLock_l(-1);
4469 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004470 }
4471
Eric Laurent81784c32012-11-19 14:55:58 -08004472 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004473 for (;;) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004474 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004475 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004476
Glenn Kasten5edadd42013-08-14 16:30:49 -07004477 // sleep with mutex unlocked
4478 if (doSleep) {
4479 doSleep = false;
4480 usleep(kRecordThreadSleepUs);
4481 }
4482
Eric Laurent81784c32012-11-19 14:55:58 -08004483 { // scope for mLock
4484 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004485
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004486 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004487 // return value 'reconfig' is currently unused
4488 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004489
Eric Laurent000a4192014-01-29 15:17:32 -08004490 // check exitPending here because checkForNewParameters_l() and
4491 // checkForNewParameters_l() can temporarily release mLock
4492 if (exitPending()) {
4493 break;
4494 }
4495
Glenn Kasten2b806402013-11-20 16:37:38 -08004496 // if no active track(s), then standby and release wakelock
4497 size_t size = mActiveTracks.size();
4498 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004499 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004500 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004501 releaseWakeLock_l();
4502 ALOGV("RecordThread: loop stopping");
4503 // go to sleep
4504 mWaitWorkCV.wait(mLock);
4505 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004506 goto reacquire_wakelock;
4507 }
4508
Glenn Kasten2b806402013-11-20 16:37:38 -08004509 if (mActiveTracksGen != activeTracksGen) {
4510 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004511 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004512 for (size_t i = 0; i < size; i++) {
4513 tmp.add(mActiveTracks[i]->uid());
4514 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004515 updateWakeLockUids_l(tmp);
Glenn Kasten2b806402013-11-20 16:37:38 -08004516 // FIXME an arbitrary choice
4517 activeTrack = mActiveTracks[0];
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004519
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004520 if (activeTrack->isTerminated()) {
4521 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004522 mActiveTracks.remove(activeTrack);
4523 mActiveTracksGen++;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004524 continue;
4525 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004526
Glenn Kastenb86432b2013-08-14 15:08:12 -07004527 activeTrackState = activeTrack->mState;
4528 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004529 case TrackBase::PAUSING:
Glenn Kasten93e471f2013-08-19 08:40:07 -07004530 standbyIfNotAlreadyInStandby();
Glenn Kasten2b806402013-11-20 16:37:38 -08004531 mActiveTracks.remove(activeTrack);
4532 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004533 mStartStopCond.broadcast();
4534 doSleep = true;
4535 continue;
4536
4537 case TrackBase::RESUMING:
4538 mStandby = false;
4539 if (mReqChannelCount != activeTrack->channelCount()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004540 mActiveTracks.remove(activeTrack);
4541 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004542 mStartStopCond.broadcast();
4543 continue;
4544 }
4545 if (readOnce) {
4546 mStartStopCond.broadcast();
4547 // record start succeeds only if first read from audio input succeeds
4548 if (mBytesRead < 0) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004549 mActiveTracks.remove(activeTrack);
4550 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004551 continue;
4552 }
4553 activeTrack->mState = TrackBase::ACTIVE;
4554 }
4555 break;
4556
4557 case TrackBase::ACTIVE:
4558 break;
4559
4560 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004561 doSleep = true;
4562 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004563
4564 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004565 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004566 }
4567
Eric Laurent81784c32012-11-19 14:55:58 -08004568 lockEffectChains_l(effectChains);
4569 }
4570
Glenn Kasten2b806402013-11-20 16:37:38 -08004571 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004572 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4573
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004574 for (size_t i = 0; i < effectChains.size(); i ++) {
4575 // thread mutex is not locked, but effect chain is locked
4576 effectChains[i]->process_l();
4577 }
4578
Glenn Kastenb91aa632013-08-19 08:40:21 -07004579 AudioBufferProvider::Buffer buffer;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004580 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004581 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004582 if (status == NO_ERROR) {
4583 readOnce = true;
4584 size_t framesOut = buffer.frameCount;
4585 if (mResampler == NULL) {
4586 // no resampling
4587 while (framesOut) {
4588 size_t framesIn = mFrameCount - mRsmpInIndex;
4589 if (framesIn > 0) {
4590 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4591 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004592 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004593 if (framesIn > framesOut) {
4594 framesIn = framesOut;
4595 }
4596 mRsmpInIndex += framesIn;
4597 framesOut -= framesIn;
4598 if (mChannelCount == mReqChannelCount) {
4599 memcpy(dst, src, framesIn * mFrameSize);
4600 } else {
4601 if (mChannelCount == 1) {
4602 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4603 (int16_t *)src, framesIn);
4604 } else {
4605 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4606 (int16_t *)src, framesIn);
4607 }
4608 }
4609 }
4610 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4611 void *readInto;
4612 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4613 readInto = buffer.raw;
4614 framesOut = 0;
4615 } else {
4616 readInto = mRsmpInBuffer;
4617 mRsmpInIndex = 0;
4618 }
4619 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4620 mBufferSize);
4621 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004622 // TODO: verify that it's benign to use a stale track state
4623 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004624 {
4625 ALOGE("Error reading audio input");
4626 // Force input into standby so that it tries to
4627 // recover at next read attempt
4628 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004629 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004630 }
4631 mRsmpInIndex = mFrameCount;
4632 framesOut = 0;
4633 buffer.frameCount = 0;
4634 }
4635#ifdef TEE_SINK
4636 else if (mTeeSink != 0) {
4637 (void) mTeeSink->write(readInto,
4638 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4639 }
4640#endif
4641 }
4642 }
4643 } else {
4644 // resampling
4645
Glenn Kasten85948432013-08-19 12:09:05 -07004646 // avoid busy-waiting if client doesn't keep up
4647 bool madeProgress = false;
4648
4649 // keep mRsmpInBuffer full so resampler always has sufficient input
4650 for (;;) {
4651 int32_t rear = mRsmpInRear;
4652 ssize_t filled = rear - mRsmpInFront;
4653 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
4654 // exit once there is enough data in buffer for resampler
4655 if ((size_t) filled >= mRsmpInFrames) {
4656 break;
4657 }
4658 size_t avail = mRsmpInFramesP2 - filled;
4659 // Only try to read full HAL buffers.
4660 // But if the HAL read returns a partial buffer, use it.
4661 if (avail < mFrameCount) {
4662 ALOGE("insufficient space to read: avail %d < mFrameCount %d",
4663 avail, mFrameCount);
4664 break;
4665 }
4666 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then
4667 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
4668 rear &= mRsmpInFramesP2 - 1;
4669 mBytesRead = mInput->stream->read(mInput->stream,
4670 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4671 if (mBytesRead <= 0) {
4672 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize);
4673 break;
4674 }
4675 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize);
4676 size_t framesRead = mBytesRead / mFrameSize;
4677 ALOG_ASSERT(framesRead > 0);
4678 madeProgress = true;
4679 // If 'avail' was non-contiguous, we now correct for reading past end of buffer.
4680 size_t part1 = mRsmpInFramesP2 - rear;
4681 if (framesRead > part1) {
4682 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4683 (framesRead - part1) * mFrameSize);
4684 }
4685 mRsmpInRear += framesRead;
4686 }
4687
4688 if (!madeProgress) {
4689 ALOGV("Did not make progress");
4690 usleep(((mFrameCount * 1000) / mSampleRate) * 1000);
4691 }
4692
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004693 // resampler accumulates, but we only have one source track
4694 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004695 mResampler->resample(mRsmpOutBuffer, framesOut,
4696 this /* AudioBufferProvider* */);
4697 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004698 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten85948432013-08-19 12:09:05 -07004699 if (mReqChannelCount == 1) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004700 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4701 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4702 // the resampler always outputs stereo samples:
4703 // do post stereo to mono conversion
4704 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4705 framesOut);
4706 } else {
4707 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4708 }
4709 // now done with mRsmpOutBuffer
4710
4711 }
4712 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004713 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004714 } else {
4715 if (mFramestoDrop > 0) {
4716 mFramestoDrop -= buffer.frameCount;
4717 if (mFramestoDrop <= 0) {
4718 clearSyncStartEvent();
4719 }
4720 } else {
4721 mFramestoDrop += buffer.frameCount;
4722 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4723 mSyncStartEvent->isCancelled()) {
4724 ALOGW("Synced record %s, session %d, trigger session %d",
4725 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004726 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004727 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4728 clearSyncStartEvent();
4729 }
4730 }
4731 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004732 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004733 }
4734 // client isn't retrieving buffers fast enough
4735 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004736 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004737 nsecs_t now = systemTime();
4738 if ((now - lastWarning) > kWarningThrottleNs) {
4739 ALOGW("RecordThread: buffer overflow");
4740 lastWarning = now;
4741 }
4742 }
4743 // Release the processor for a while before asking for a new buffer.
4744 // This will give the application more chance to read from the buffer and
4745 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004746 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004747 }
4748
Eric Laurent81784c32012-11-19 14:55:58 -08004749 // enable changes in effect chain
4750 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004751 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004752 }
4753
Glenn Kasten93e471f2013-08-19 08:40:07 -07004754 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004755
4756 {
4757 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004758 for (size_t i = 0; i < mTracks.size(); i++) {
4759 sp<RecordTrack> track = mTracks[i];
4760 track->invalidate();
4761 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004762 mActiveTracks.clear();
4763 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004764 mStartStopCond.broadcast();
4765 }
4766
4767 releaseWakeLock();
4768
4769 ALOGV("RecordThread %p exiting", this);
4770 return false;
4771}
4772
Glenn Kasten93e471f2013-08-19 08:40:07 -07004773void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004774{
4775 if (!mStandby) {
4776 inputStandBy();
4777 mStandby = true;
4778 }
4779}
4780
4781void AudioFlinger::RecordThread::inputStandBy()
4782{
4783 mInput->stream->common.standby(&mInput->stream->common);
4784}
4785
Glenn Kastene198c362013-08-13 09:13:36 -07004786sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004787 const sp<AudioFlinger::Client>& client,
4788 uint32_t sampleRate,
4789 audio_format_t format,
4790 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08004791 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08004792 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004793 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004794 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004795 pid_t tid,
4796 status_t *status)
4797{
Glenn Kasten74935e42013-12-19 08:56:45 -08004798 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004799 sp<RecordTrack> track;
4800 status_t lStatus;
4801
4802 lStatus = initCheck();
4803 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004804 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004805 goto Exit;
4806 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004807 // client expresses a preference for FAST, but we get the final say
4808 if (*flags & IAudioFlinger::TRACK_FAST) {
4809 if (
4810 // use case: callback handler and frame count is default or at least as large as HAL
4811 (
4812 (tid != -1) &&
4813 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004814 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004815 ) &&
4816 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4817 // mono or stereo
4818 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4819 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4820 // hardware sample rate
4821 (sampleRate == mSampleRate) &&
4822 // record thread has an associated fast recorder
4823 hasFastRecorder()
4824 // FIXME test that RecordThread for this fast track has a capable output HAL
4825 // FIXME add a permission test also?
4826 ) {
4827 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4828 if (frameCount == 0) {
4829 frameCount = mFrameCount * kFastTrackMultiplier;
4830 }
4831 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4832 frameCount, mFrameCount);
4833 } else {
4834 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4835 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4836 "hasFastRecorder=%d tid=%d",
4837 frameCount, mFrameCount, format,
4838 audio_is_linear_pcm(format),
4839 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4840 *flags &= ~IAudioFlinger::TRACK_FAST;
4841 // For compatibility with AudioRecord calculation, buffer depth is forced
4842 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4843 // This is probably too conservative, but legacy application code may depend on it.
4844 // If you change this calculation, also review the start threshold which is related.
4845 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4846 size_t mNormalFrameCount = 2048; // FIXME
4847 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4848 if (minBufCount < 2) {
4849 minBufCount = 2;
4850 }
4851 size_t minFrameCount = mNormalFrameCount * minBufCount;
4852 if (frameCount < minFrameCount) {
4853 frameCount = minFrameCount;
4854 }
4855 }
4856 }
Glenn Kasten74935e42013-12-19 08:56:45 -08004857 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07004858
Eric Laurent81784c32012-11-19 14:55:58 -08004859 // FIXME use flags and tid similar to createTrack_l()
4860
4861 { // scope for mLock
4862 Mutex::Autolock _l(mLock);
4863
4864 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004865 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004866
Glenn Kasten03003332013-08-06 15:40:54 -07004867 lStatus = track->initCheck();
4868 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004869 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08004870 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004871 goto Exit;
4872 }
4873 mTracks.add(track);
4874
4875 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4876 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4877 mAudioFlinger->btNrecIsOff();
4878 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4879 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004880
4881 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4882 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4883 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4884 // so ask activity manager to do this on our behalf
4885 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4886 }
Eric Laurent81784c32012-11-19 14:55:58 -08004887 }
4888 lStatus = NO_ERROR;
4889
4890Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004891 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004892 return track;
4893}
4894
4895status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4896 AudioSystem::sync_event_t event,
4897 int triggerSession)
4898{
4899 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4900 sp<ThreadBase> strongMe = this;
4901 status_t status = NO_ERROR;
4902
4903 if (event == AudioSystem::SYNC_EVENT_NONE) {
4904 clearSyncStartEvent();
4905 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4906 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4907 triggerSession,
4908 recordTrack->sessionId(),
4909 syncStartEventCallback,
4910 this);
4911 // Sync event can be cancelled by the trigger session if the track is not in a
4912 // compatible state in which case we start record immediately
4913 if (mSyncStartEvent->isCancelled()) {
4914 clearSyncStartEvent();
4915 } else {
4916 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4917 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4918 }
4919 }
4920
4921 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004922 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004923 AutoMutex lock(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004924 if (mActiveTracks.size() > 0) {
4925 // FIXME does not work for multiple active tracks
4926 if (mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004927 status = -EBUSY;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004928 } else if (recordTrack->mState == TrackBase::PAUSING) {
4929 recordTrack->mState = TrackBase::ACTIVE;
Eric Laurent81784c32012-11-19 14:55:58 -08004930 }
4931 return status;
4932 }
4933
Glenn Kasten47c20702013-08-13 15:37:35 -07004934 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004935 recordTrack->mState = TrackBase::IDLE;
Glenn Kasten2b806402013-11-20 16:37:38 -08004936 mActiveTracks.add(recordTrack);
4937 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004938 mLock.unlock();
4939 status_t status = AudioSystem::startInput(mId);
4940 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004941 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004942 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004943 mActiveTracks.remove(recordTrack);
4944 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004945 clearSyncStartEvent();
4946 return status;
4947 }
Glenn Kasten85948432013-08-19 12:09:05 -07004948 // FIXME LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004949 mRsmpInIndex = mFrameCount;
Glenn Kasten85948432013-08-19 12:09:05 -07004950 mRsmpInFront = 0;
4951 mRsmpInRear = 0;
4952 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004953 mBytesRead = 0;
4954 if (mResampler != NULL) {
4955 mResampler->reset();
4956 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004957 // FIXME hijacking a playback track state name which was intended for start after pause;
4958 // here 'STARTING_2' would be more accurate
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004959 recordTrack->mState = TrackBase::RESUMING;
Eric Laurent81784c32012-11-19 14:55:58 -08004960 // signal thread to start
4961 ALOGV("Signal record thread");
4962 mWaitWorkCV.broadcast();
4963 // do not wait for mStartStopCond if exiting
4964 if (exitPending()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004965 mActiveTracks.remove(recordTrack);
4966 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004967 status = INVALID_OPERATION;
4968 goto startError;
4969 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004970 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004971 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004972 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004973 ALOGV("Record failed to start");
4974 status = BAD_VALUE;
4975 goto startError;
4976 }
4977 ALOGV("Record started OK");
4978 return status;
4979 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004980
Eric Laurent81784c32012-11-19 14:55:58 -08004981startError:
4982 AudioSystem::stopInput(mId);
4983 clearSyncStartEvent();
4984 return status;
4985}
4986
4987void AudioFlinger::RecordThread::clearSyncStartEvent()
4988{
4989 if (mSyncStartEvent != 0) {
4990 mSyncStartEvent->cancel();
4991 }
4992 mSyncStartEvent.clear();
4993 mFramestoDrop = 0;
4994}
4995
4996void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4997{
4998 sp<SyncEvent> strongEvent = event.promote();
4999
5000 if (strongEvent != 0) {
5001 RecordThread *me = (RecordThread *)strongEvent->cookie();
5002 me->handleSyncStartEvent(strongEvent);
5003 }
5004}
5005
5006void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5007{
5008 if (event == mSyncStartEvent) {
5009 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5010 // from audio HAL
5011 mFramestoDrop = mFrameCount * 2;
5012 }
5013}
5014
Glenn Kastena8356f62013-07-25 14:37:52 -07005015bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005016 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005017 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005018 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005019 return false;
5020 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005021 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005022 recordTrack->mState = TrackBase::PAUSING;
5023 // do not wait for mStartStopCond if exiting
5024 if (exitPending()) {
5025 return true;
5026 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005027 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005028 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005029 // if we have been restarted, recordTrack is in mActiveTracks here
5030 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005031 ALOGV("Record stopped OK");
5032 return true;
5033 }
5034 return false;
5035}
5036
Glenn Kasten0f11b512014-01-31 16:18:54 -08005037bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005038{
5039 return false;
5040}
5041
Glenn Kasten0f11b512014-01-31 16:18:54 -08005042status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005043{
5044#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5045 if (!isValidSyncEvent(event)) {
5046 return BAD_VALUE;
5047 }
5048
5049 int eventSession = event->triggerSession();
5050 status_t ret = NAME_NOT_FOUND;
5051
5052 Mutex::Autolock _l(mLock);
5053
5054 for (size_t i = 0; i < mTracks.size(); i++) {
5055 sp<RecordTrack> track = mTracks[i];
5056 if (eventSession == track->sessionId()) {
5057 (void) track->setSyncEvent(event);
5058 ret = NO_ERROR;
5059 }
5060 }
5061 return ret;
5062#else
5063 return BAD_VALUE;
5064#endif
5065}
5066
5067// destroyTrack_l() must be called with ThreadBase::mLock held
5068void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5069{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005070 track->terminate();
5071 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005072 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005073 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005074 removeTrack_l(track);
5075 }
5076}
5077
5078void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5079{
5080 mTracks.remove(track);
5081 // need anything related to effects here?
5082}
5083
5084void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5085{
5086 dumpInternals(fd, args);
5087 dumpTracks(fd, args);
5088 dumpEffectChains(fd, args);
5089}
5090
5091void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5092{
5093 const size_t SIZE = 256;
5094 char buffer[SIZE];
5095 String8 result;
5096
5097 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5098 result.append(buffer);
5099
Glenn Kasten2b806402013-11-20 16:37:38 -08005100 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005101 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5102 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08005103 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005104 result.append(buffer);
5105 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5106 result.append(buffer);
5107 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
5108 result.append(buffer);
5109 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
5110 result.append(buffer);
5111 } else {
5112 result.append("No active record client\n");
5113 }
5114
5115 write(fd, result.string(), result.size());
5116
5117 dumpBase(fd, args);
5118}
5119
Glenn Kasten0f11b512014-01-31 16:18:54 -08005120void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005121{
5122 const size_t SIZE = 256;
5123 char buffer[SIZE];
5124 String8 result;
5125
5126 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5127 result.append(buffer);
5128 RecordTrack::appendDumpHeader(result);
5129 for (size_t i = 0; i < mTracks.size(); ++i) {
5130 sp<RecordTrack> track = mTracks[i];
5131 if (track != 0) {
5132 track->dump(buffer, SIZE);
5133 result.append(buffer);
5134 }
5135 }
5136
Glenn Kasten2b806402013-11-20 16:37:38 -08005137 size_t size = mActiveTracks.size();
5138 if (size > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005139 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5140 result.append(buffer);
5141 RecordTrack::appendDumpHeader(result);
Glenn Kasten2b806402013-11-20 16:37:38 -08005142 for (size_t i = 0; i < size; ++i) {
5143 sp<RecordTrack> track = mActiveTracks[i];
5144 track->dump(buffer, SIZE);
5145 result.append(buffer);
5146 }
Eric Laurent81784c32012-11-19 14:55:58 -08005147
5148 }
5149 write(fd, result.string(), result.size());
5150}
5151
5152// AudioBufferProvider interface
Glenn Kasten0f11b512014-01-31 16:18:54 -08005153status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005154{
Glenn Kasten85948432013-08-19 12:09:05 -07005155 int32_t rear = mRsmpInRear;
5156 int32_t front = mRsmpInFront;
5157 ssize_t filled = rear - front;
5158 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
5159 // 'filled' may be non-contiguous, so return only the first contiguous chunk
5160 front &= mRsmpInFramesP2 - 1;
5161 size_t part1 = mRsmpInFramesP2 - front;
5162 if (part1 > (size_t) filled) {
5163 part1 = filled;
5164 }
5165 size_t ask = buffer->frameCount;
5166 ALOG_ASSERT(ask > 0);
5167 if (part1 > ask) {
5168 part1 = ask;
5169 }
5170 if (part1 == 0) {
5171 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5172 ALOGE("RecordThread::getNextBuffer() starved");
5173 buffer->raw = NULL;
5174 buffer->frameCount = 0;
5175 mRsmpInUnrel = 0;
5176 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005177 }
5178
Glenn Kasten85948432013-08-19 12:09:05 -07005179 buffer->raw = mRsmpInBuffer + front * mChannelCount;
5180 buffer->frameCount = part1;
5181 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005182 return NO_ERROR;
5183}
5184
5185// AudioBufferProvider interface
5186void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5187{
Glenn Kasten85948432013-08-19 12:09:05 -07005188 size_t stepCount = buffer->frameCount;
5189 if (stepCount == 0) {
5190 return;
5191 }
5192 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
5193 mRsmpInUnrel -= stepCount;
5194 mRsmpInFront += stepCount;
5195 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005196 buffer->frameCount = 0;
5197}
5198
5199bool AudioFlinger::RecordThread::checkForNewParameters_l()
5200{
5201 bool reconfig = false;
5202
5203 while (!mNewParameters.isEmpty()) {
5204 status_t status = NO_ERROR;
5205 String8 keyValuePair = mNewParameters[0];
5206 AudioParameter param = AudioParameter(keyValuePair);
5207 int value;
5208 audio_format_t reqFormat = mFormat;
5209 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005210 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005211
5212 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5213 reqSamplingRate = value;
5214 reconfig = true;
5215 }
5216 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005217 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5218 status = BAD_VALUE;
5219 } else {
5220 reqFormat = (audio_format_t) value;
5221 reconfig = true;
5222 }
Eric Laurent81784c32012-11-19 14:55:58 -08005223 }
5224 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005225 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5226 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5227 status = BAD_VALUE;
5228 } else {
5229 reqChannelMask = mask;
5230 reconfig = true;
5231 }
Eric Laurent81784c32012-11-19 14:55:58 -08005232 }
5233 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5234 // do not accept frame count changes if tracks are open as the track buffer
5235 // size depends on frame count and correct behavior would not be guaranteed
5236 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005237 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005238 status = INVALID_OPERATION;
5239 } else {
5240 reconfig = true;
5241 }
5242 }
5243 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5244 // forward device change to effects that have requested to be
5245 // aware of attached audio device.
5246 for (size_t i = 0; i < mEffectChains.size(); i++) {
5247 mEffectChains[i]->setDevice_l(value);
5248 }
5249
5250 // store input device and output device but do not forward output device to audio HAL.
5251 // Note that status is ignored by the caller for output device
5252 // (see AudioFlinger::setParameters()
5253 if (audio_is_output_devices(value)) {
5254 mOutDevice = value;
5255 status = BAD_VALUE;
5256 } else {
5257 mInDevice = value;
5258 // disable AEC and NS if the device is a BT SCO headset supporting those
5259 // pre processings
5260 if (mTracks.size() > 0) {
5261 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5262 mAudioFlinger->btNrecIsOff();
5263 for (size_t i = 0; i < mTracks.size(); i++) {
5264 sp<RecordTrack> track = mTracks[i];
5265 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5266 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5267 }
5268 }
5269 }
5270 }
5271 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5272 mAudioSource != (audio_source_t)value) {
5273 // forward device change to effects that have requested to be
5274 // aware of attached audio device.
5275 for (size_t i = 0; i < mEffectChains.size(); i++) {
5276 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5277 }
5278 mAudioSource = (audio_source_t)value;
5279 }
Glenn Kastene198c362013-08-13 09:13:36 -07005280
Eric Laurent81784c32012-11-19 14:55:58 -08005281 if (status == NO_ERROR) {
5282 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5283 keyValuePair.string());
5284 if (status == INVALID_OPERATION) {
5285 inputStandBy();
5286 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5287 keyValuePair.string());
5288 }
5289 if (reconfig) {
5290 if (status == BAD_VALUE &&
5291 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5292 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005293 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005294 <= (2 * reqSamplingRate)) &&
5295 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5296 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005297 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5298 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005299 status = NO_ERROR;
5300 }
5301 if (status == NO_ERROR) {
5302 readInputParameters();
5303 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5304 }
5305 }
5306 }
5307
5308 mNewParameters.removeAt(0);
5309
5310 mParamStatus = status;
5311 mParamCond.signal();
5312 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5313 // already timed out waiting for the status and will never signal the condition.
5314 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5315 }
5316 return reconfig;
5317}
5318
5319String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5320{
Eric Laurent81784c32012-11-19 14:55:58 -08005321 Mutex::Autolock _l(mLock);
5322 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005323 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005324 }
5325
Glenn Kastend8ea6992013-07-16 14:17:15 -07005326 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5327 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005328 free(s);
5329 return out_s8;
5330}
5331
Glenn Kasten0f11b512014-01-31 16:18:54 -08005332void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005333 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005334 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005335
5336 switch (event) {
5337 case AudioSystem::INPUT_OPENED:
5338 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005339 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005340 desc.samplingRate = mSampleRate;
5341 desc.format = mFormat;
5342 desc.frameCount = mFrameCount;
5343 desc.latency = 0;
5344 param2 = &desc;
5345 break;
5346
5347 case AudioSystem::INPUT_CLOSED:
5348 default:
5349 break;
5350 }
5351 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5352}
5353
5354void AudioFlinger::RecordThread::readInputParameters()
5355{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005356 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005357 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005358 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005359 mRsmpOutBuffer = NULL;
5360 delete mResampler;
5361 mResampler = NULL;
5362
5363 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5364 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005365 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005366 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005367 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5368 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5369 }
Eric Laurent81784c32012-11-19 14:55:58 -08005370 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005371 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5372 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07005373 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5374 // 1 full output buffer, regardless of the alignment of the available input.
5375 mRsmpInFrames = mFrameCount * 3;
5376 mRsmpInFramesP2 = roundup(mRsmpInFrames);
5377 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5378 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5379 mRsmpInFront = 0;
5380 mRsmpInRear = 0;
5381 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005382
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005383 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Glenn Kasten579dd272013-11-08 14:26:14 -08005384 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005385 mResampler->setSampleRate(mSampleRate);
5386 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten85948432013-08-19 12:09:05 -07005387 // resampler always outputs stereo
Glenn Kasten34af0262013-07-30 11:52:39 -07005388 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005389 }
5390 mRsmpInIndex = mFrameCount;
5391}
5392
Glenn Kasten5f972c02014-01-13 09:59:31 -08005393uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005394{
5395 Mutex::Autolock _l(mLock);
5396 if (initCheck() != NO_ERROR) {
5397 return 0;
5398 }
5399
5400 return mInput->stream->get_input_frames_lost(mInput->stream);
5401}
5402
5403uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5404{
5405 Mutex::Autolock _l(mLock);
5406 uint32_t result = 0;
5407 if (getEffectChain_l(sessionId) != 0) {
5408 result = EFFECT_SESSION;
5409 }
5410
5411 for (size_t i = 0; i < mTracks.size(); ++i) {
5412 if (sessionId == mTracks[i]->sessionId()) {
5413 result |= TRACK_SESSION;
5414 break;
5415 }
5416 }
5417
5418 return result;
5419}
5420
5421KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5422{
5423 KeyedVector<int, bool> ids;
5424 Mutex::Autolock _l(mLock);
5425 for (size_t j = 0; j < mTracks.size(); ++j) {
5426 sp<RecordThread::RecordTrack> track = mTracks[j];
5427 int sessionId = track->sessionId();
5428 if (ids.indexOfKey(sessionId) < 0) {
5429 ids.add(sessionId, true);
5430 }
5431 }
5432 return ids;
5433}
5434
5435AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5436{
5437 Mutex::Autolock _l(mLock);
5438 AudioStreamIn *input = mInput;
5439 mInput = NULL;
5440 return input;
5441}
5442
5443// this method must always be called either with ThreadBase mLock held or inside the thread loop
5444audio_stream_t* AudioFlinger::RecordThread::stream() const
5445{
5446 if (mInput == NULL) {
5447 return NULL;
5448 }
5449 return &mInput->stream->common;
5450}
5451
5452status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5453{
5454 // only one chain per input thread
5455 if (mEffectChains.size() != 0) {
5456 return INVALID_OPERATION;
5457 }
5458 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5459
5460 chain->setInBuffer(NULL);
5461 chain->setOutBuffer(NULL);
5462
5463 checkSuspendOnAddEffectChain_l(chain);
5464
5465 mEffectChains.add(chain);
5466
5467 return NO_ERROR;
5468}
5469
5470size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5471{
5472 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5473 ALOGW_IF(mEffectChains.size() != 1,
5474 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5475 chain.get(), mEffectChains.size(), this);
5476 if (mEffectChains.size() == 1) {
5477 mEffectChains.removeAt(0);
5478 }
5479 return 0;
5480}
5481
5482}; // namespace android