blob: 7751b083e33c1e17d5f2b0078986726f009e8a2f [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
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001493 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001494 return status;
1495}
1496
Eric Laurentbfb1b832013-01-07 09:53:42 -08001497bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001498{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001499 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001500 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001501 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1502 track->mState = TrackBase::STOPPED;
1503 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001504 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001505 } else if (track->isFastTrack() || track->isOffloaded()) {
1506 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001507 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001508
1509 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001510}
1511
1512void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1513{
1514 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1515 mTracks.remove(track);
1516 deleteTrackName_l(track->name());
1517 // redundant as track is about to be destroyed, for dumpsys only
1518 track->mName = -1;
1519 if (track->isFastTrack()) {
1520 int index = track->mFastIndex;
1521 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1522 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1523 mFastTrackAvailMask |= 1 << index;
1524 // redundant as track is about to be destroyed, for dumpsys only
1525 track->mFastIndex = -1;
1526 }
1527 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1528 if (chain != 0) {
1529 chain->decTrackCnt();
1530 }
1531}
1532
Eric Laurentede6c3b2013-09-19 14:37:46 -07001533void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001534{
1535 // Thread could be blocked waiting for async
1536 // so signal it to handle state changes immediately
1537 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1538 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1539 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001540 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001541}
1542
Eric Laurent81784c32012-11-19 14:55:58 -08001543String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1544{
Eric Laurent81784c32012-11-19 14:55:58 -08001545 Mutex::Autolock _l(mLock);
1546 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001547 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001548 }
1549
Glenn Kastend8ea6992013-07-16 14:17:15 -07001550 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1551 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001552 free(s);
1553 return out_s8;
1554}
1555
1556// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1557void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1558 AudioSystem::OutputDescriptor desc;
1559 void *param2 = NULL;
1560
1561 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1562 param);
1563
1564 switch (event) {
1565 case AudioSystem::OUTPUT_OPENED:
1566 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001567 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001568 desc.samplingRate = mSampleRate;
1569 desc.format = mFormat;
1570 desc.frameCount = mNormalFrameCount; // FIXME see
1571 // AudioFlinger::frameCount(audio_io_handle_t)
1572 desc.latency = latency();
1573 param2 = &desc;
1574 break;
1575
1576 case AudioSystem::STREAM_CONFIG_CHANGED:
1577 param2 = &param;
1578 case AudioSystem::OUTPUT_CLOSED:
1579 default:
1580 break;
1581 }
1582 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1583}
1584
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585void AudioFlinger::PlaybackThread::writeCallback()
1586{
1587 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001588 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001589}
1590
1591void AudioFlinger::PlaybackThread::drainCallback()
1592{
1593 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001594 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001595}
1596
Eric Laurent3b4529e2013-09-05 18:09:19 -07001597void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001598{
1599 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001600 // reject out of sequence requests
1601 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1602 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001603 mWaitWorkCV.signal();
1604 }
1605}
1606
Eric Laurent3b4529e2013-09-05 18:09:19 -07001607void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001608{
1609 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001610 // reject out of sequence requests
1611 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1612 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001613 mWaitWorkCV.signal();
1614 }
1615}
1616
1617// static
1618int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001619 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001620 void *cookie)
1621{
1622 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1623 ALOGV("asyncCallback() event %d", event);
1624 switch (event) {
1625 case STREAM_CBK_EVENT_WRITE_READY:
1626 me->writeCallback();
1627 break;
1628 case STREAM_CBK_EVENT_DRAIN_READY:
1629 me->drainCallback();
1630 break;
1631 default:
1632 ALOGW("asyncCallback() unknown event %d", event);
1633 break;
1634 }
1635 return 0;
1636}
1637
Eric Laurent81784c32012-11-19 14:55:58 -08001638void AudioFlinger::PlaybackThread::readOutputParameters()
1639{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001640 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001641 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1642 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001643 if (!audio_is_output_channel(mChannelMask)) {
1644 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1645 }
1646 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1647 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1648 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1649 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001650 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001651 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001652 if (!audio_is_valid_format(mFormat)) {
1653 LOG_FATAL("HAL format %d not valid for output", mFormat);
1654 }
1655 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1656 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1657 mFormat);
1658 }
Eric Laurent81784c32012-11-19 14:55:58 -08001659 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001660 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1661 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001662 if (mFrameCount & 15) {
1663 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1664 mFrameCount);
1665 }
1666
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1668 (mOutput->stream->set_callback != NULL)) {
1669 if (mOutput->stream->set_callback(mOutput->stream,
1670 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1671 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001672 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001673 }
1674 }
1675
Eric Laurent81784c32012-11-19 14:55:58 -08001676 // Calculate size of normal mix buffer relative to the HAL output buffer size
1677 double multiplier = 1.0;
1678 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1679 kUseFastMixer == FastMixer_Dynamic)) {
1680 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1681 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1682 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1683 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1684 maxNormalFrameCount = maxNormalFrameCount & ~15;
1685 if (maxNormalFrameCount < minNormalFrameCount) {
1686 maxNormalFrameCount = minNormalFrameCount;
1687 }
1688 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1689 if (multiplier <= 1.0) {
1690 multiplier = 1.0;
1691 } else if (multiplier <= 2.0) {
1692 if (2 * mFrameCount <= maxNormalFrameCount) {
1693 multiplier = 2.0;
1694 } else {
1695 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1696 }
1697 } else {
1698 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1699 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1700 // track, but we sometimes have to do this to satisfy the maximum frame count
1701 // constraint)
1702 // FIXME this rounding up should not be done if no HAL SRC
1703 uint32_t truncMult = (uint32_t) multiplier;
1704 if ((truncMult & 1)) {
1705 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1706 ++truncMult;
1707 }
1708 }
1709 multiplier = (double) truncMult;
1710 }
1711 }
1712 mNormalFrameCount = multiplier * mFrameCount;
1713 // round up to nearest 16 frames to satisfy AudioMixer
1714 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1715 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1716 mNormalFrameCount);
1717
Glenn Kastenc1fac192013-08-06 07:41:36 -07001718 delete[] mMixBuffer;
1719 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1720 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1721 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1722 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001723
1724 // force reconfiguration of effect chains and engines to take new buffer size and audio
1725 // parameters into account
1726 // Note that mLock is not held when readOutputParameters() is called from the constructor
1727 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1728 // matter.
1729 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1730 Vector< sp<EffectChain> > effectChains = mEffectChains;
1731 for (size_t i = 0; i < effectChains.size(); i ++) {
1732 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1733 }
1734}
1735
1736
1737status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1738{
1739 if (halFrames == NULL || dspFrames == NULL) {
1740 return BAD_VALUE;
1741 }
1742 Mutex::Autolock _l(mLock);
1743 if (initCheck() != NO_ERROR) {
1744 return INVALID_OPERATION;
1745 }
1746 size_t framesWritten = mBytesWritten / mFrameSize;
1747 *halFrames = framesWritten;
1748
1749 if (isSuspended()) {
1750 // return an estimation of rendered frames when the output is suspended
1751 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1752 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1753 return NO_ERROR;
1754 } else {
1755 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1756 }
1757}
1758
1759uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1760{
1761 Mutex::Autolock _l(mLock);
1762 uint32_t result = 0;
1763 if (getEffectChain_l(sessionId) != 0) {
1764 result = EFFECT_SESSION;
1765 }
1766
1767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001769 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001770 result |= TRACK_SESSION;
1771 break;
1772 }
1773 }
1774
1775 return result;
1776}
1777
1778uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1779{
1780 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1781 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1782 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1783 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1784 }
1785 for (size_t i = 0; i < mTracks.size(); i++) {
1786 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001787 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001788 return AudioSystem::getStrategyForStream(track->streamType());
1789 }
1790 }
1791 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1792}
1793
1794
1795AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1796{
1797 Mutex::Autolock _l(mLock);
1798 return mOutput;
1799}
1800
1801AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1802{
1803 Mutex::Autolock _l(mLock);
1804 AudioStreamOut *output = mOutput;
1805 mOutput = NULL;
1806 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1807 // must push a NULL and wait for ack
1808 mOutputSink.clear();
1809 mPipeSink.clear();
1810 mNormalSink.clear();
1811 return output;
1812}
1813
1814// this method must always be called either with ThreadBase mLock held or inside the thread loop
1815audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1816{
1817 if (mOutput == NULL) {
1818 return NULL;
1819 }
1820 return &mOutput->stream->common;
1821}
1822
1823uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1824{
1825 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1826}
1827
1828status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1829{
1830 if (!isValidSyncEvent(event)) {
1831 return BAD_VALUE;
1832 }
1833
1834 Mutex::Autolock _l(mLock);
1835
1836 for (size_t i = 0; i < mTracks.size(); ++i) {
1837 sp<Track> track = mTracks[i];
1838 if (event->triggerSession() == track->sessionId()) {
1839 (void) track->setSyncEvent(event);
1840 return NO_ERROR;
1841 }
1842 }
1843
1844 return NAME_NOT_FOUND;
1845}
1846
1847bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1848{
1849 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1850}
1851
1852void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1853 const Vector< sp<Track> >& tracksToRemove)
1854{
1855 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001856 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001857 for (size_t i = 0 ; i < count ; i++) {
1858 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001860 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001861#ifdef ADD_BATTERY_DATA
1862 // to track the speaker usage
1863 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1864#endif
1865 if (track->isTerminated()) {
1866 AudioSystem::releaseOutput(mId);
1867 }
Eric Laurent81784c32012-11-19 14:55:58 -08001868 }
1869 }
1870 }
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873void AudioFlinger::PlaybackThread::checkSilentMode_l()
1874{
1875 if (!mMasterMute) {
1876 char value[PROPERTY_VALUE_MAX];
1877 if (property_get("ro.audio.silent", value, "0") > 0) {
1878 char *endptr;
1879 unsigned long ul = strtoul(value, &endptr, 0);
1880 if (*endptr == '\0' && ul != 0) {
1881 ALOGD("Silence is golden");
1882 // The setprop command will not allow a property to be changed after
1883 // the first time it is set, so we don't have to worry about un-muting.
1884 setMasterMute_l(true);
1885 }
1886 }
1887 }
1888}
1889
1890// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
1893 // FIXME rewrite to reduce number of system calls
1894 mLastWriteTime = systemTime();
1895 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001897
1898 // If an NBAIO sink is present, use it to write the normal mixer's submix
1899 if (mNormalSink != 0) {
1900#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001901 size_t count = mBytesRemaining >> mBitShift;
1902 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001903 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001904 // update the setpoint when AudioFlinger::mScreenState changes
1905 uint32_t screenState = AudioFlinger::mScreenState;
1906 if (screenState != mScreenState) {
1907 mScreenState = screenState;
1908 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1909 if (pipe != NULL) {
1910 pipe->setAvgFrames((mScreenState & 1) ?
1911 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1912 }
1913 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001914 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001915 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001916 if (framesWritten > 0) {
1917 bytesWritten = framesWritten << mBitShift;
1918 } else {
1919 bytesWritten = framesWritten;
1920 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001921 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001922 if (status == NO_ERROR) {
1923 size_t totalFramesWritten = mNormalSink->framesWritten();
1924 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1925 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1926 mLatchDValid = true;
1927 }
1928 }
Eric Laurent81784c32012-11-19 14:55:58 -08001929 // otherwise use the HAL / AudioStreamOut directly
1930 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001931 // Direct output and offload threads
Eric Laurent04733db2013-11-22 09:29:56 -08001932 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001933 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001934 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1935 mWriteAckSequence += 2;
1936 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001937 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001938 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001940 // FIXME We should have an implementation of timestamps for direct output threads.
1941 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent04733db2013-11-22 09:29:56 -08001943 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 if (mUseAsyncWrite &&
1945 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1946 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001947 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001949 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 }
Eric Laurent81784c32012-11-19 14:55:58 -08001951 }
1952
Eric Laurent81784c32012-11-19 14:55:58 -08001953 mNumWrites++;
1954 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001955 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956 return bytesWritten;
1957}
1958
1959void AudioFlinger::PlaybackThread::threadLoop_drain()
1960{
1961 if (mOutput->stream->drain) {
1962 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1963 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001964 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1965 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001967 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 }
1969 mOutput->stream->drain(mOutput->stream,
1970 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1971 : AUDIO_DRAIN_ALL);
1972 }
1973}
1974
1975void AudioFlinger::PlaybackThread::threadLoop_exit()
1976{
1977 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001978}
1979
1980/*
1981The derived values that are cached:
1982 - mixBufferSize from frame count * frame size
1983 - activeSleepTime from activeSleepTimeUs()
1984 - idleSleepTime from idleSleepTimeUs()
1985 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1986 - maxPeriod from frame count and sample rate (MIXER only)
1987
1988The parameters that affect these derived values are:
1989 - frame count
1990 - frame size
1991 - sample rate
1992 - device type: A2DP or not
1993 - device latency
1994 - format: PCM or not
1995 - active sleep time
1996 - idle sleep time
1997*/
1998
1999void AudioFlinger::PlaybackThread::cacheParameters_l()
2000{
2001 mixBufferSize = mNormalFrameCount * mFrameSize;
2002 activeSleepTime = activeSleepTimeUs();
2003 idleSleepTime = idleSleepTimeUs();
2004}
2005
2006void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2007{
Glenn Kasten7c027242012-12-26 14:43:16 -08002008 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002009 this, streamType, mTracks.size());
2010 Mutex::Autolock _l(mLock);
2011
2012 size_t size = mTracks.size();
2013 for (size_t i = 0; i < size; i++) {
2014 sp<Track> t = mTracks[i];
2015 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002016 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
2018 }
2019}
2020
2021status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2022{
2023 int session = chain->sessionId();
2024 int16_t *buffer = mMixBuffer;
2025 bool ownsBuffer = false;
2026
2027 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2028 if (session > 0) {
2029 // Only one effect chain can be present in direct output thread and it uses
2030 // the mix buffer as input
2031 if (mType != DIRECT) {
2032 size_t numSamples = mNormalFrameCount * mChannelCount;
2033 buffer = new int16_t[numSamples];
2034 memset(buffer, 0, numSamples * sizeof(int16_t));
2035 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2036 ownsBuffer = true;
2037 }
2038
2039 // Attach all tracks with same session ID to this chain.
2040 for (size_t i = 0; i < mTracks.size(); ++i) {
2041 sp<Track> track = mTracks[i];
2042 if (session == track->sessionId()) {
2043 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2044 buffer);
2045 track->setMainBuffer(buffer);
2046 chain->incTrackCnt();
2047 }
2048 }
2049
2050 // indicate all active tracks in the chain
2051 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2052 sp<Track> track = mActiveTracks[i].promote();
2053 if (track == 0) {
2054 continue;
2055 }
2056 if (session == track->sessionId()) {
2057 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2058 chain->incActiveTrackCnt();
2059 }
2060 }
2061 }
2062
2063 chain->setInBuffer(buffer, ownsBuffer);
2064 chain->setOutBuffer(mMixBuffer);
2065 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2066 // chains list in order to be processed last as it contains output stage effects
2067 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2068 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2069 // after track specific effects and before output stage
2070 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2071 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2072 // Effect chain for other sessions are inserted at beginning of effect
2073 // chains list to be processed before output mix effects. Relative order between other
2074 // sessions is not important
2075 size_t size = mEffectChains.size();
2076 size_t i = 0;
2077 for (i = 0; i < size; i++) {
2078 if (mEffectChains[i]->sessionId() < session) {
2079 break;
2080 }
2081 }
2082 mEffectChains.insertAt(chain, i);
2083 checkSuspendOnAddEffectChain_l(chain);
2084
2085 return NO_ERROR;
2086}
2087
2088size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2089{
2090 int session = chain->sessionId();
2091
2092 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2093
2094 for (size_t i = 0; i < mEffectChains.size(); i++) {
2095 if (chain == mEffectChains[i]) {
2096 mEffectChains.removeAt(i);
2097 // detach all active tracks from the chain
2098 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2099 sp<Track> track = mActiveTracks[i].promote();
2100 if (track == 0) {
2101 continue;
2102 }
2103 if (session == track->sessionId()) {
2104 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2105 chain.get(), session);
2106 chain->decActiveTrackCnt();
2107 }
2108 }
2109
2110 // detach all tracks with same session ID from this chain
2111 for (size_t i = 0; i < mTracks.size(); ++i) {
2112 sp<Track> track = mTracks[i];
2113 if (session == track->sessionId()) {
2114 track->setMainBuffer(mMixBuffer);
2115 chain->decTrackCnt();
2116 }
2117 }
2118 break;
2119 }
2120 }
2121 return mEffectChains.size();
2122}
2123
2124status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2125 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2126{
2127 Mutex::Autolock _l(mLock);
2128 return attachAuxEffect_l(track, EffectId);
2129}
2130
2131status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2132 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2133{
2134 status_t status = NO_ERROR;
2135
2136 if (EffectId == 0) {
2137 track->setAuxBuffer(0, NULL);
2138 } else {
2139 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2140 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2141 if (effect != 0) {
2142 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2143 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2144 } else {
2145 status = INVALID_OPERATION;
2146 }
2147 } else {
2148 status = BAD_VALUE;
2149 }
2150 }
2151 return status;
2152}
2153
2154void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2155{
2156 for (size_t i = 0; i < mTracks.size(); ++i) {
2157 sp<Track> track = mTracks[i];
2158 if (track->auxEffectId() == effectId) {
2159 attachAuxEffect_l(track, 0);
2160 }
2161 }
2162}
2163
2164bool AudioFlinger::PlaybackThread::threadLoop()
2165{
2166 Vector< sp<Track> > tracksToRemove;
2167
2168 standbyTime = systemTime();
2169
2170 // MIXER
2171 nsecs_t lastWarning = 0;
2172
2173 // DUPLICATING
2174 // FIXME could this be made local to while loop?
2175 writeFrames = 0;
2176
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002177 int lastGeneration = 0;
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 cacheParameters_l();
2180 sleepTime = idleSleepTime;
2181
2182 if (mType == MIXER) {
2183 sleepTimeShift = 0;
2184 }
2185
2186 CpuStats cpuStats;
2187 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2188
2189 acquireWakeLock();
2190
Glenn Kasten9e58b552013-01-18 15:09:48 -08002191 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2192 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2193 // and then that string will be logged at the next convenient opportunity.
2194 const char *logString = NULL;
2195
Eric Laurent664539d2013-09-23 18:24:31 -07002196 checkSilentMode_l();
2197
Eric Laurent81784c32012-11-19 14:55:58 -08002198 while (!exitPending())
2199 {
2200 cpuStats.sample(myName);
2201
2202 Vector< sp<EffectChain> > effectChains;
2203
2204 processConfigEvents();
2205
2206 { // scope for mLock
2207
2208 Mutex::Autolock _l(mLock);
2209
Glenn Kasten9e58b552013-01-18 15:09:48 -08002210 if (logString != NULL) {
2211 mNBLogWriter->logTimestamp();
2212 mNBLogWriter->log(logString);
2213 logString = NULL;
2214 }
2215
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002216 if (mLatchDValid) {
2217 mLatchQ = mLatchD;
2218 mLatchDValid = false;
2219 mLatchQValid = true;
2220 }
2221
Eric Laurent81784c32012-11-19 14:55:58 -08002222 if (checkForNewParameters_l()) {
2223 cacheParameters_l();
2224 }
2225
2226 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 if (mSignalPending) {
2228 // A signal was raised while we were unlocked
2229 mSignalPending = false;
2230 } else if (waitingAsyncCallback_l()) {
2231 if (exitPending()) {
2232 break;
2233 }
2234 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002235 mWakeLockUids.clear();
2236 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237 ALOGV("wait async completion");
2238 mWaitWorkCV.wait(mLock);
2239 ALOGV("async completion/wake");
2240 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002241 standbyTime = systemTime() + standbyDelay;
2242 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002243
2244 continue;
2245 }
2246 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 isSuspended()) {
2248 // put audio hardware into standby after short delay
2249 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002250
2251 threadLoop_standby();
2252
2253 mStandby = true;
2254 }
2255
2256 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2257 // we're about to wait, flush the binder command buffer
2258 IPCThreadState::self()->flushCommands();
2259
2260 clearOutputTracks();
2261
2262 if (exitPending()) {
2263 break;
2264 }
2265
2266 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002267 mWakeLockUids.clear();
2268 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002269 // wait until we have something to do...
2270 ALOGV("%s going to sleep", myName.string());
2271 mWaitWorkCV.wait(mLock);
2272 ALOGV("%s waking up", myName.string());
2273 acquireWakeLock_l();
2274
2275 mMixerStatus = MIXER_IDLE;
2276 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2277 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002279 checkSilentMode_l();
2280
2281 standbyTime = systemTime() + standbyDelay;
2282 sleepTime = idleSleepTime;
2283 if (mType == MIXER) {
2284 sleepTimeShift = 0;
2285 }
2286
2287 continue;
2288 }
2289 }
Eric Laurent81784c32012-11-19 14:55:58 -08002290 // mMixerStatusIgnoringFastTracks is also updated internally
2291 mMixerStatus = prepareTracks_l(&tracksToRemove);
2292
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002293 // compare with previously applied list
2294 if (lastGeneration != mActiveTracksGeneration) {
2295 // update wakelock
2296 updateWakeLockUids_l(mWakeLockUids);
2297 lastGeneration = mActiveTracksGeneration;
2298 }
2299
Eric Laurent81784c32012-11-19 14:55:58 -08002300 // prevent any changes in effect chain list and in each effect chain
2301 // during mixing and effect process as the audio buffers could be deleted
2302 // or modified if an effect is created or deleted
2303 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002304 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002305
Eric Laurentbfb1b832013-01-07 09:53:42 -08002306 if (mBytesRemaining == 0) {
2307 mCurrentWriteLength = 0;
2308 if (mMixerStatus == MIXER_TRACKS_READY) {
2309 // threadLoop_mix() sets mCurrentWriteLength
2310 threadLoop_mix();
2311 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2312 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2313 // threadLoop_sleepTime sets sleepTime to 0 if data
2314 // must be written to HAL
2315 threadLoop_sleepTime();
2316 if (sleepTime == 0) {
2317 mCurrentWriteLength = mixBufferSize;
2318 }
2319 }
2320 mBytesRemaining = mCurrentWriteLength;
2321 if (isSuspended()) {
2322 sleepTime = suspendSleepTimeUs();
2323 // simulate write to HAL when suspended
2324 mBytesWritten += mixBufferSize;
2325 mBytesRemaining = 0;
2326 }
Eric Laurent81784c32012-11-19 14:55:58 -08002327
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002329 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 for (size_t i = 0; i < effectChains.size(); i ++) {
2331 effectChains[i]->process_l();
2332 }
Eric Laurent81784c32012-11-19 14:55:58 -08002333 }
2334 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002335 // Process effect chains for offloaded thread even if no audio
2336 // was read from audio track: process only updates effect state
2337 // and thus does have to be synchronized with audio writes but may have
2338 // to be called while waiting for async write callback
2339 if (mType == OFFLOAD) {
2340 for (size_t i = 0; i < effectChains.size(); i ++) {
2341 effectChains[i]->process_l();
2342 }
2343 }
Eric Laurent81784c32012-11-19 14:55:58 -08002344
2345 // enable changes in effect chain
2346 unlockEffectChains(effectChains);
2347
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348 if (!waitingAsyncCallback()) {
2349 // sleepTime == 0 means we must write to audio hardware
2350 if (sleepTime == 0) {
2351 if (mBytesRemaining) {
2352 ssize_t ret = threadLoop_write();
2353 if (ret < 0) {
2354 mBytesRemaining = 0;
2355 } else {
2356 mBytesWritten += ret;
2357 mBytesRemaining -= ret;
2358 }
2359 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2360 (mMixerStatus == MIXER_DRAIN_ALL)) {
2361 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002362 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002363 if (mType == MIXER) {
2364 // write blocked detection
2365 nsecs_t now = systemTime();
2366 nsecs_t delta = now - mLastWriteTime;
2367 if (!mStandby && delta > maxPeriod) {
2368 mNumDelayedWrites++;
2369 if ((now - lastWarning) > kWarningThrottleNs) {
2370 ATRACE_NAME("underrun");
2371 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2372 ns2ms(delta), mNumDelayedWrites, this);
2373 lastWarning = now;
2374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002375 }
2376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 } else {
2379 usleep(sleepTime);
2380 }
Eric Laurent81784c32012-11-19 14:55:58 -08002381 }
2382
2383 // Finally let go of removed track(s), without the lock held
2384 // since we can't guarantee the destructors won't acquire that
2385 // same lock. This will also mutate and push a new fast mixer state.
2386 threadLoop_removeTracks(tracksToRemove);
2387 tracksToRemove.clear();
2388
2389 // FIXME I don't understand the need for this here;
2390 // it was in the original code but maybe the
2391 // assignment in saveOutputTracks() makes this unnecessary?
2392 clearOutputTracks();
2393
2394 // Effect chains will be actually deleted here if they were removed from
2395 // mEffectChains list during mixing or effects processing
2396 effectChains.clear();
2397
2398 // FIXME Note that the above .clear() is no longer necessary since effectChains
2399 // is now local to this block, but will keep it for now (at least until merge done).
2400 }
2401
Eric Laurentbfb1b832013-01-07 09:53:42 -08002402 threadLoop_exit();
2403
Eric Laurent81784c32012-11-19 14:55:58 -08002404 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // put output stream into standby mode
2407 if (!mStandby) {
2408 mOutput->stream->common.standby(&mOutput->stream->common);
2409 }
2410 }
2411
2412 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002413 mWakeLockUids.clear();
2414 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002415
2416 ALOGV("Thread %p type %d exiting", this, mType);
2417 return false;
2418}
2419
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420// removeTracks_l() must be called with ThreadBase::mLock held
2421void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2422{
2423 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002424 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 for (size_t i=0 ; i<count ; i++) {
2426 const sp<Track>& track = tracksToRemove.itemAt(i);
2427 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002428 mWakeLockUids.remove(track->uid());
2429 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002430 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2431 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2432 if (chain != 0) {
2433 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2434 track->sessionId());
2435 chain->decActiveTrackCnt();
2436 }
2437 if (track->isTerminated()) {
2438 removeTrack_l(track);
2439 }
2440 }
2441 }
2442
2443}
Eric Laurent81784c32012-11-19 14:55:58 -08002444
Eric Laurentaccc1472013-09-20 09:36:34 -07002445status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2446{
2447 if (mNormalSink != 0) {
2448 return mNormalSink->getTimestamp(timestamp);
2449 }
2450 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2451 uint64_t position64;
2452 int ret = mOutput->stream->get_presentation_position(
2453 mOutput->stream, &position64, &timestamp.mTime);
2454 if (ret == 0) {
2455 timestamp.mPosition = (uint32_t)position64;
2456 return NO_ERROR;
2457 }
2458 }
2459 return INVALID_OPERATION;
2460}
Eric Laurent81784c32012-11-19 14:55:58 -08002461// ----------------------------------------------------------------------------
2462
2463AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2464 audio_io_handle_t id, audio_devices_t device, type_t type)
2465 : PlaybackThread(audioFlinger, output, id, device, type),
2466 // mAudioMixer below
2467 // mFastMixer below
2468 mFastMixerFutex(0)
2469 // mOutputSink below
2470 // mPipeSink below
2471 // mNormalSink below
2472{
2473 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002474 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002475 "mFrameCount=%d, mNormalFrameCount=%d",
2476 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2477 mNormalFrameCount);
2478 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2479
2480 // FIXME - Current mixer implementation only supports stereo output
2481 if (mChannelCount != FCC_2) {
2482 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2483 }
2484
2485 // create an NBAIO sink for the HAL output stream, and negotiate
2486 mOutputSink = new AudioStreamOutSink(output->stream);
2487 size_t numCounterOffers = 0;
2488 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2489 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2490 ALOG_ASSERT(index == 0);
2491
2492 // initialize fast mixer depending on configuration
2493 bool initFastMixer;
2494 switch (kUseFastMixer) {
2495 case FastMixer_Never:
2496 initFastMixer = false;
2497 break;
2498 case FastMixer_Always:
2499 initFastMixer = true;
2500 break;
2501 case FastMixer_Static:
2502 case FastMixer_Dynamic:
2503 initFastMixer = mFrameCount < mNormalFrameCount;
2504 break;
2505 }
2506 if (initFastMixer) {
2507
2508 // create a MonoPipe to connect our submix to FastMixer
2509 NBAIO_Format format = mOutputSink->format();
2510 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2511 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2512 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2513 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2514 const NBAIO_Format offers[1] = {format};
2515 size_t numCounterOffers = 0;
2516 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2517 ALOG_ASSERT(index == 0);
2518 monoPipe->setAvgFrames((mScreenState & 1) ?
2519 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2520 mPipeSink = monoPipe;
2521
Glenn Kasten46909e72013-02-26 09:20:22 -08002522#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002523 if (mTeeSinkOutputEnabled) {
2524 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2525 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2526 numCounterOffers = 0;
2527 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2528 ALOG_ASSERT(index == 0);
2529 mTeeSink = teeSink;
2530 PipeReader *teeSource = new PipeReader(*teeSink);
2531 numCounterOffers = 0;
2532 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2533 ALOG_ASSERT(index == 0);
2534 mTeeSource = teeSource;
2535 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002536#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002537
2538 // create fast mixer and configure it initially with just one fast track for our submix
2539 mFastMixer = new FastMixer();
2540 FastMixerStateQueue *sq = mFastMixer->sq();
2541#ifdef STATE_QUEUE_DUMP
2542 sq->setObserverDump(&mStateQueueObserverDump);
2543 sq->setMutatorDump(&mStateQueueMutatorDump);
2544#endif
2545 FastMixerState *state = sq->begin();
2546 FastTrack *fastTrack = &state->mFastTracks[0];
2547 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2548 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2549 fastTrack->mVolumeProvider = NULL;
2550 fastTrack->mGeneration++;
2551 state->mFastTracksGen++;
2552 state->mTrackMask = 1;
2553 // fast mixer will use the HAL output sink
2554 state->mOutputSink = mOutputSink.get();
2555 state->mOutputSinkGen++;
2556 state->mFrameCount = mFrameCount;
2557 state->mCommand = FastMixerState::COLD_IDLE;
2558 // already done in constructor initialization list
2559 //mFastMixerFutex = 0;
2560 state->mColdFutexAddr = &mFastMixerFutex;
2561 state->mColdGen++;
2562 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002563#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002564 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002565#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002566 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2567 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002568 sq->end();
2569 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2570
2571 // start the fast mixer
2572 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2573 pid_t tid = mFastMixer->getTid();
2574 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2575 if (err != 0) {
2576 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2577 kPriorityFastMixer, getpid_cached, tid, err);
2578 }
2579
2580#ifdef AUDIO_WATCHDOG
2581 // create and start the watchdog
2582 mAudioWatchdog = new AudioWatchdog();
2583 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2584 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2585 tid = mAudioWatchdog->getTid();
2586 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2587 if (err != 0) {
2588 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2589 kPriorityFastMixer, getpid_cached, tid, err);
2590 }
2591#endif
2592
2593 } else {
2594 mFastMixer = NULL;
2595 }
2596
2597 switch (kUseFastMixer) {
2598 case FastMixer_Never:
2599 case FastMixer_Dynamic:
2600 mNormalSink = mOutputSink;
2601 break;
2602 case FastMixer_Always:
2603 mNormalSink = mPipeSink;
2604 break;
2605 case FastMixer_Static:
2606 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2607 break;
2608 }
2609}
2610
2611AudioFlinger::MixerThread::~MixerThread()
2612{
2613 if (mFastMixer != NULL) {
2614 FastMixerStateQueue *sq = mFastMixer->sq();
2615 FastMixerState *state = sq->begin();
2616 if (state->mCommand == FastMixerState::COLD_IDLE) {
2617 int32_t old = android_atomic_inc(&mFastMixerFutex);
2618 if (old == -1) {
2619 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2620 }
2621 }
2622 state->mCommand = FastMixerState::EXIT;
2623 sq->end();
2624 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2625 mFastMixer->join();
2626 // Though the fast mixer thread has exited, it's state queue is still valid.
2627 // We'll use that extract the final state which contains one remaining fast track
2628 // corresponding to our sub-mix.
2629 state = sq->begin();
2630 ALOG_ASSERT(state->mTrackMask == 1);
2631 FastTrack *fastTrack = &state->mFastTracks[0];
2632 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2633 delete fastTrack->mBufferProvider;
2634 sq->end(false /*didModify*/);
2635 delete mFastMixer;
2636#ifdef AUDIO_WATCHDOG
2637 if (mAudioWatchdog != 0) {
2638 mAudioWatchdog->requestExit();
2639 mAudioWatchdog->requestExitAndWait();
2640 mAudioWatchdog.clear();
2641 }
2642#endif
2643 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002644 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002645 delete mAudioMixer;
2646}
2647
2648
2649uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2650{
2651 if (mFastMixer != NULL) {
2652 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2653 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2654 }
2655 return latency;
2656}
2657
2658
2659void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2660{
2661 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2662}
2663
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002665{
2666 // FIXME we should only do one push per cycle; confirm this is true
2667 // Start the fast mixer if it's not already running
2668 if (mFastMixer != NULL) {
2669 FastMixerStateQueue *sq = mFastMixer->sq();
2670 FastMixerState *state = sq->begin();
2671 if (state->mCommand != FastMixerState::MIX_WRITE &&
2672 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2673 if (state->mCommand == FastMixerState::COLD_IDLE) {
2674 int32_t old = android_atomic_inc(&mFastMixerFutex);
2675 if (old == -1) {
2676 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2677 }
2678#ifdef AUDIO_WATCHDOG
2679 if (mAudioWatchdog != 0) {
2680 mAudioWatchdog->resume();
2681 }
2682#endif
2683 }
2684 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002685 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2686 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002687 sq->end();
2688 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2689 if (kUseFastMixer == FastMixer_Dynamic) {
2690 mNormalSink = mPipeSink;
2691 }
2692 } else {
2693 sq->end(false /*didModify*/);
2694 }
2695 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002696 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002697}
2698
2699void AudioFlinger::MixerThread::threadLoop_standby()
2700{
2701 // Idle the fast mixer if it's currently running
2702 if (mFastMixer != NULL) {
2703 FastMixerStateQueue *sq = mFastMixer->sq();
2704 FastMixerState *state = sq->begin();
2705 if (!(state->mCommand & FastMixerState::IDLE)) {
2706 state->mCommand = FastMixerState::COLD_IDLE;
2707 state->mColdFutexAddr = &mFastMixerFutex;
2708 state->mColdGen++;
2709 mFastMixerFutex = 0;
2710 sq->end();
2711 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2712 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2713 if (kUseFastMixer == FastMixer_Dynamic) {
2714 mNormalSink = mOutputSink;
2715 }
2716#ifdef AUDIO_WATCHDOG
2717 if (mAudioWatchdog != 0) {
2718 mAudioWatchdog->pause();
2719 }
2720#endif
2721 } else {
2722 sq->end(false /*didModify*/);
2723 }
2724 }
2725 PlaybackThread::threadLoop_standby();
2726}
2727
Eric Laurentbfb1b832013-01-07 09:53:42 -08002728bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2729{
2730 return false;
2731}
2732
2733bool AudioFlinger::PlaybackThread::shouldStandby_l()
2734{
2735 return !mStandby;
2736}
2737
2738bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2739{
2740 Mutex::Autolock _l(mLock);
2741 return waitingAsyncCallback_l();
2742}
2743
Eric Laurent81784c32012-11-19 14:55:58 -08002744// shared by MIXER and DIRECT, overridden by DUPLICATING
2745void AudioFlinger::PlaybackThread::threadLoop_standby()
2746{
2747 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2748 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002750 // discard any pending drain or write ack by incrementing sequence
2751 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2752 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002754 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2755 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002756 }
Eric Laurent81784c32012-11-19 14:55:58 -08002757}
2758
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002759void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2760{
2761 ALOGV("signal playback thread");
2762 broadcast_l();
2763}
2764
Eric Laurent81784c32012-11-19 14:55:58 -08002765void AudioFlinger::MixerThread::threadLoop_mix()
2766{
2767 // obtain the presentation timestamp of the next output buffer
2768 int64_t pts;
2769 status_t status = INVALID_OPERATION;
2770
2771 if (mNormalSink != 0) {
2772 status = mNormalSink->getNextWriteTimestamp(&pts);
2773 } else {
2774 status = mOutputSink->getNextWriteTimestamp(&pts);
2775 }
2776
2777 if (status != NO_ERROR) {
2778 pts = AudioBufferProvider::kInvalidPTS;
2779 }
2780
2781 // mix buffers...
2782 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002783 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002784 // increase sleep time progressively when application underrun condition clears.
2785 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2786 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2787 // such that we would underrun the audio HAL.
2788 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2789 sleepTimeShift--;
2790 }
2791 sleepTime = 0;
2792 standbyTime = systemTime() + standbyDelay;
2793 //TODO: delay standby when effects have a tail
2794}
2795
2796void AudioFlinger::MixerThread::threadLoop_sleepTime()
2797{
2798 // If no tracks are ready, sleep once for the duration of an output
2799 // buffer size, then write 0s to the output
2800 if (sleepTime == 0) {
2801 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2802 sleepTime = activeSleepTime >> sleepTimeShift;
2803 if (sleepTime < kMinThreadSleepTimeUs) {
2804 sleepTime = kMinThreadSleepTimeUs;
2805 }
2806 // reduce sleep time in case of consecutive application underruns to avoid
2807 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2808 // duration we would end up writing less data than needed by the audio HAL if
2809 // the condition persists.
2810 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2811 sleepTimeShift++;
2812 }
2813 } else {
2814 sleepTime = idleSleepTime;
2815 }
2816 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002817 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002818 sleepTime = 0;
2819 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2820 "anticipated start");
2821 }
2822 // TODO add standby time extension fct of effect tail
2823}
2824
2825// prepareTracks_l() must be called with ThreadBase::mLock held
2826AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2827 Vector< sp<Track> > *tracksToRemove)
2828{
2829
2830 mixer_state mixerStatus = MIXER_IDLE;
2831 // find out which tracks need to be processed
2832 size_t count = mActiveTracks.size();
2833 size_t mixedTracks = 0;
2834 size_t tracksWithEffect = 0;
2835 // counts only _active_ fast tracks
2836 size_t fastTracks = 0;
2837 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2838
2839 float masterVolume = mMasterVolume;
2840 bool masterMute = mMasterMute;
2841
2842 if (masterMute) {
2843 masterVolume = 0;
2844 }
2845 // Delegate master volume control to effect in output mix effect chain if needed
2846 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2847 if (chain != 0) {
2848 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2849 chain->setVolume_l(&v, &v);
2850 masterVolume = (float)((v + (1 << 23)) >> 24);
2851 chain.clear();
2852 }
2853
2854 // prepare a new state to push
2855 FastMixerStateQueue *sq = NULL;
2856 FastMixerState *state = NULL;
2857 bool didModify = false;
2858 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2859 if (mFastMixer != NULL) {
2860 sq = mFastMixer->sq();
2861 state = sq->begin();
2862 }
2863
2864 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002865 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002866 if (t == 0) {
2867 continue;
2868 }
2869
2870 // this const just means the local variable doesn't change
2871 Track* const track = t.get();
2872
2873 // process fast tracks
2874 if (track->isFastTrack()) {
2875
2876 // It's theoretically possible (though unlikely) for a fast track to be created
2877 // and then removed within the same normal mix cycle. This is not a problem, as
2878 // the track never becomes active so it's fast mixer slot is never touched.
2879 // The converse, of removing an (active) track and then creating a new track
2880 // at the identical fast mixer slot within the same normal mix cycle,
2881 // is impossible because the slot isn't marked available until the end of each cycle.
2882 int j = track->mFastIndex;
2883 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2884 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2885 FastTrack *fastTrack = &state->mFastTracks[j];
2886
2887 // Determine whether the track is currently in underrun condition,
2888 // and whether it had a recent underrun.
2889 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2890 FastTrackUnderruns underruns = ftDump->mUnderruns;
2891 uint32_t recentFull = (underruns.mBitFields.mFull -
2892 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2893 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2894 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2895 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2896 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2897 uint32_t recentUnderruns = recentPartial + recentEmpty;
2898 track->mObservedUnderruns = underruns;
2899 // don't count underruns that occur while stopping or pausing
2900 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002901 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2902 recentUnderruns > 0) {
2903 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2904 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002905 }
2906
2907 // This is similar to the state machine for normal tracks,
2908 // with a few modifications for fast tracks.
2909 bool isActive = true;
2910 switch (track->mState) {
2911 case TrackBase::STOPPING_1:
2912 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002914 track->mState = TrackBase::STOPPING_2;
2915 }
2916 break;
2917 case TrackBase::PAUSING:
2918 // ramp down is not yet implemented
2919 track->setPaused();
2920 break;
2921 case TrackBase::RESUMING:
2922 // ramp up is not yet implemented
2923 track->mState = TrackBase::ACTIVE;
2924 break;
2925 case TrackBase::ACTIVE:
2926 if (recentFull > 0 || recentPartial > 0) {
2927 // track has provided at least some frames recently: reset retry count
2928 track->mRetryCount = kMaxTrackRetries;
2929 }
2930 if (recentUnderruns == 0) {
2931 // no recent underruns: stay active
2932 break;
2933 }
2934 // there has recently been an underrun of some kind
2935 if (track->sharedBuffer() == 0) {
2936 // were any of the recent underruns "empty" (no frames available)?
2937 if (recentEmpty == 0) {
2938 // no, then ignore the partial underruns as they are allowed indefinitely
2939 break;
2940 }
2941 // there has recently been an "empty" underrun: decrement the retry counter
2942 if (--(track->mRetryCount) > 0) {
2943 break;
2944 }
2945 // indicate to client process that the track was disabled because of underrun;
2946 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002947 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002948 // remove from active list, but state remains ACTIVE [confusing but true]
2949 isActive = false;
2950 break;
2951 }
2952 // fall through
2953 case TrackBase::STOPPING_2:
2954 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002955 case TrackBase::STOPPED:
2956 case TrackBase::FLUSHED: // flush() while active
2957 // Check for presentation complete if track is inactive
2958 // We have consumed all the buffers of this track.
2959 // This would be incomplete if we auto-paused on underrun
2960 {
2961 size_t audioHALFrames =
2962 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2963 size_t framesWritten = mBytesWritten / mFrameSize;
2964 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2965 // track stays in active list until presentation is complete
2966 break;
2967 }
2968 }
2969 if (track->isStopping_2()) {
2970 track->mState = TrackBase::STOPPED;
2971 }
2972 if (track->isStopped()) {
2973 // Can't reset directly, as fast mixer is still polling this track
2974 // track->reset();
2975 // So instead mark this track as needing to be reset after push with ack
2976 resetMask |= 1 << i;
2977 }
2978 isActive = false;
2979 break;
2980 case TrackBase::IDLE:
2981 default:
2982 LOG_FATAL("unexpected track state %d", track->mState);
2983 }
2984
2985 if (isActive) {
2986 // was it previously inactive?
2987 if (!(state->mTrackMask & (1 << j))) {
2988 ExtendedAudioBufferProvider *eabp = track;
2989 VolumeProvider *vp = track;
2990 fastTrack->mBufferProvider = eabp;
2991 fastTrack->mVolumeProvider = vp;
2992 fastTrack->mSampleRate = track->mSampleRate;
2993 fastTrack->mChannelMask = track->mChannelMask;
2994 fastTrack->mGeneration++;
2995 state->mTrackMask |= 1 << j;
2996 didModify = true;
2997 // no acknowledgement required for newly active tracks
2998 }
2999 // cache the combined master volume and stream type volume for fast mixer; this
3000 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003001 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003002 ++fastTracks;
3003 } else {
3004 // was it previously active?
3005 if (state->mTrackMask & (1 << j)) {
3006 fastTrack->mBufferProvider = NULL;
3007 fastTrack->mGeneration++;
3008 state->mTrackMask &= ~(1 << j);
3009 didModify = true;
3010 // If any fast tracks were removed, we must wait for acknowledgement
3011 // because we're about to decrement the last sp<> on those tracks.
3012 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3013 } else {
3014 LOG_FATAL("fast track %d should have been active", j);
3015 }
3016 tracksToRemove->add(track);
3017 // Avoids a misleading display in dumpsys
3018 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3019 }
3020 continue;
3021 }
3022
3023 { // local variable scope to avoid goto warning
3024
3025 audio_track_cblk_t* cblk = track->cblk();
3026
3027 // The first time a track is added we wait
3028 // for all its buffers to be filled before processing it
3029 int name = track->name();
3030 // make sure that we have enough frames to mix one full buffer.
3031 // enforce this condition only once to enable draining the buffer in case the client
3032 // app does not call stop() and relies on underrun to stop:
3033 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3034 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003035 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003036 uint32_t sr = track->sampleRate();
3037 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003038 desiredFrames = mNormalFrameCount;
3039 } else {
3040 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003041 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003042 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003043 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003044 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003045#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003046 // the minimum track buffer size is normally twice the number of frames necessary
3047 // to fill one buffer and the resampler should not leave more than one buffer worth
3048 // of unreleased frames after each pass, but just in case...
3049 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003050#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003051 }
Eric Laurent81784c32012-11-19 14:55:58 -08003052 uint32_t minFrames = 1;
3053 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3054 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003055 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003056 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003057
3058 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003059 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003060 !track->isPaused() && !track->isTerminated())
3061 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003062 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003063
3064 mixedTracks++;
3065
3066 // track->mainBuffer() != mMixBuffer means there is an effect chain
3067 // connected to the track
3068 chain.clear();
3069 if (track->mainBuffer() != mMixBuffer) {
3070 chain = getEffectChain_l(track->sessionId());
3071 // Delegate volume control to effect in track effect chain if needed
3072 if (chain != 0) {
3073 tracksWithEffect++;
3074 } else {
3075 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3076 "session %d",
3077 name, track->sessionId());
3078 }
3079 }
3080
3081
3082 int param = AudioMixer::VOLUME;
3083 if (track->mFillingUpStatus == Track::FS_FILLED) {
3084 // no ramp for the first volume setting
3085 track->mFillingUpStatus = Track::FS_ACTIVE;
3086 if (track->mState == TrackBase::RESUMING) {
3087 track->mState = TrackBase::ACTIVE;
3088 param = AudioMixer::RAMP_VOLUME;
3089 }
3090 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003091 // FIXME should not make a decision based on mServer
3092 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // If the track is stopped before the first frame was mixed,
3094 // do not apply ramp
3095 param = AudioMixer::RAMP_VOLUME;
3096 }
3097
3098 // compute volume for this track
3099 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003100 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003101 vl = vr = va = 0;
3102 if (track->isPausing()) {
3103 track->setPaused();
3104 }
3105 } else {
3106
3107 // read original volumes with volume control
3108 float typeVolume = mStreamTypes[track->streamType()].volume;
3109 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003110 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003111 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003112 vl = vlr & 0xFFFF;
3113 vr = vlr >> 16;
3114 // track volumes come from shared memory, so can't be trusted and must be clamped
3115 if (vl > MAX_GAIN_INT) {
3116 ALOGV("Track left volume out of range: %04X", vl);
3117 vl = MAX_GAIN_INT;
3118 }
3119 if (vr > MAX_GAIN_INT) {
3120 ALOGV("Track right volume out of range: %04X", vr);
3121 vr = MAX_GAIN_INT;
3122 }
3123 // now apply the master volume and stream type volume
3124 vl = (uint32_t)(v * vl) << 12;
3125 vr = (uint32_t)(v * vr) << 12;
3126 // assuming master volume and stream type volume each go up to 1.0,
3127 // vl and vr are now in 8.24 format
3128
Glenn Kastene3aa6592012-12-04 12:22:46 -08003129 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003130 // send level comes from shared memory and so may be corrupt
3131 if (sendLevel > MAX_GAIN_INT) {
3132 ALOGV("Track send level out of range: %04X", sendLevel);
3133 sendLevel = MAX_GAIN_INT;
3134 }
3135 va = (uint32_t)(v * sendLevel);
3136 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137
Eric Laurent81784c32012-11-19 14:55:58 -08003138 // Delegate volume control to effect in track effect chain if needed
3139 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3140 // Do not ramp volume if volume is controlled by effect
3141 param = AudioMixer::VOLUME;
3142 track->mHasVolumeController = true;
3143 } else {
3144 // force no volume ramp when volume controller was just disabled or removed
3145 // from effect chain to avoid volume spike
3146 if (track->mHasVolumeController) {
3147 param = AudioMixer::VOLUME;
3148 }
3149 track->mHasVolumeController = false;
3150 }
3151
3152 // Convert volumes from 8.24 to 4.12 format
3153 // This additional clamping is needed in case chain->setVolume_l() overshot
3154 vl = (vl + (1 << 11)) >> 12;
3155 if (vl > MAX_GAIN_INT) {
3156 vl = MAX_GAIN_INT;
3157 }
3158 vr = (vr + (1 << 11)) >> 12;
3159 if (vr > MAX_GAIN_INT) {
3160 vr = MAX_GAIN_INT;
3161 }
3162
3163 if (va > MAX_GAIN_INT) {
3164 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3165 }
3166
3167 // XXX: these things DON'T need to be done each time
3168 mAudioMixer->setBufferProvider(name, track);
3169 mAudioMixer->enable(name);
3170
3171 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3172 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3173 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3174 mAudioMixer->setParameter(
3175 name,
3176 AudioMixer::TRACK,
3177 AudioMixer::FORMAT, (void *)track->format());
3178 mAudioMixer->setParameter(
3179 name,
3180 AudioMixer::TRACK,
3181 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003182 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3183 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003184 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003185 if (reqSampleRate == 0) {
3186 reqSampleRate = mSampleRate;
3187 } else if (reqSampleRate > maxSampleRate) {
3188 reqSampleRate = maxSampleRate;
3189 }
Eric Laurent81784c32012-11-19 14:55:58 -08003190 mAudioMixer->setParameter(
3191 name,
3192 AudioMixer::RESAMPLE,
3193 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003194 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003195 mAudioMixer->setParameter(
3196 name,
3197 AudioMixer::TRACK,
3198 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3199 mAudioMixer->setParameter(
3200 name,
3201 AudioMixer::TRACK,
3202 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3203
3204 // reset retry count
3205 track->mRetryCount = kMaxTrackRetries;
3206
3207 // If one track is ready, set the mixer ready if:
3208 // - the mixer was not ready during previous round OR
3209 // - no other track is not ready
3210 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3211 mixerStatus != MIXER_TRACKS_ENABLED) {
3212 mixerStatus = MIXER_TRACKS_READY;
3213 }
3214 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003215 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003216 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003217 }
Eric Laurent81784c32012-11-19 14:55:58 -08003218 // clear effect chain input buffer if an active track underruns to avoid sending
3219 // previous audio buffer again to effects
3220 chain = getEffectChain_l(track->sessionId());
3221 if (chain != 0) {
3222 chain->clearInputBuffer();
3223 }
3224
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003225 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003226 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3227 track->isStopped() || track->isPaused()) {
3228 // We have consumed all the buffers of this track.
3229 // Remove it from the list of active tracks.
3230 // TODO: use actual buffer filling status instead of latency when available from
3231 // audio HAL
3232 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3233 size_t framesWritten = mBytesWritten / mFrameSize;
3234 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3235 if (track->isStopped()) {
3236 track->reset();
3237 }
3238 tracksToRemove->add(track);
3239 }
3240 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003241 // No buffers for this track. Give it a few chances to
3242 // fill a buffer, then remove it from active list.
3243 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003244 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003245 tracksToRemove->add(track);
3246 // indicate to client process that the track was disabled because of underrun;
3247 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003248 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003249 // If one track is not ready, mark the mixer also not ready if:
3250 // - the mixer was ready during previous round OR
3251 // - no other track is ready
3252 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3253 mixerStatus != MIXER_TRACKS_READY) {
3254 mixerStatus = MIXER_TRACKS_ENABLED;
3255 }
3256 }
3257 mAudioMixer->disable(name);
3258 }
3259
3260 } // local variable scope to avoid goto warning
3261track_is_ready: ;
3262
3263 }
3264
3265 // Push the new FastMixer state if necessary
3266 bool pauseAudioWatchdog = false;
3267 if (didModify) {
3268 state->mFastTracksGen++;
3269 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3270 if (kUseFastMixer == FastMixer_Dynamic &&
3271 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3272 state->mCommand = FastMixerState::COLD_IDLE;
3273 state->mColdFutexAddr = &mFastMixerFutex;
3274 state->mColdGen++;
3275 mFastMixerFutex = 0;
3276 if (kUseFastMixer == FastMixer_Dynamic) {
3277 mNormalSink = mOutputSink;
3278 }
3279 // If we go into cold idle, need to wait for acknowledgement
3280 // so that fast mixer stops doing I/O.
3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3282 pauseAudioWatchdog = true;
3283 }
Eric Laurent81784c32012-11-19 14:55:58 -08003284 }
3285 if (sq != NULL) {
3286 sq->end(didModify);
3287 sq->push(block);
3288 }
3289#ifdef AUDIO_WATCHDOG
3290 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3291 mAudioWatchdog->pause();
3292 }
3293#endif
3294
3295 // Now perform the deferred reset on fast tracks that have stopped
3296 while (resetMask != 0) {
3297 size_t i = __builtin_ctz(resetMask);
3298 ALOG_ASSERT(i < count);
3299 resetMask &= ~(1 << i);
3300 sp<Track> t = mActiveTracks[i].promote();
3301 if (t == 0) {
3302 continue;
3303 }
3304 Track* track = t.get();
3305 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3306 track->reset();
3307 }
3308
3309 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003311
3312 // mix buffer must be cleared if all tracks are connected to an
3313 // effect chain as in this case the mixer will not write to
3314 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3316 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003317 // FIXME as a performance optimization, should remember previous zero status
3318 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3319 }
3320
3321 // if any fast tracks, then status is ready
3322 mMixerStatusIgnoringFastTracks = mixerStatus;
3323 if (fastTracks > 0) {
3324 mixerStatus = MIXER_TRACKS_READY;
3325 }
3326 return mixerStatus;
3327}
3328
3329// getTrackName_l() must be called with ThreadBase::mLock held
3330int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3331{
3332 return mAudioMixer->getTrackName(channelMask, sessionId);
3333}
3334
3335// deleteTrackName_l() must be called with ThreadBase::mLock held
3336void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3337{
3338 ALOGV("remove track (%d) and delete from mixer", name);
3339 mAudioMixer->deleteTrackName(name);
3340}
3341
3342// checkForNewParameters_l() must be called with ThreadBase::mLock held
3343bool AudioFlinger::MixerThread::checkForNewParameters_l()
3344{
3345 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3346 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3347 bool reconfig = false;
3348
3349 while (!mNewParameters.isEmpty()) {
3350
3351 if (mFastMixer != NULL) {
3352 FastMixerStateQueue *sq = mFastMixer->sq();
3353 FastMixerState *state = sq->begin();
3354 if (!(state->mCommand & FastMixerState::IDLE)) {
3355 previousCommand = state->mCommand;
3356 state->mCommand = FastMixerState::HOT_IDLE;
3357 sq->end();
3358 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3359 } else {
3360 sq->end(false /*didModify*/);
3361 }
3362 }
3363
3364 status_t status = NO_ERROR;
3365 String8 keyValuePair = mNewParameters[0];
3366 AudioParameter param = AudioParameter(keyValuePair);
3367 int value;
3368
3369 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3370 reconfig = true;
3371 }
3372 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3373 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3374 status = BAD_VALUE;
3375 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003376 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003377 reconfig = true;
3378 }
3379 }
3380 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003381 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003382 status = BAD_VALUE;
3383 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003384 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003385 reconfig = true;
3386 }
3387 }
3388 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3389 // do not accept frame count changes if tracks are open as the track buffer
3390 // size depends on frame count and correct behavior would not be guaranteed
3391 // if frame count is changed after track creation
3392 if (!mTracks.isEmpty()) {
3393 status = INVALID_OPERATION;
3394 } else {
3395 reconfig = true;
3396 }
3397 }
3398 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3399#ifdef ADD_BATTERY_DATA
3400 // when changing the audio output device, call addBatteryData to notify
3401 // the change
3402 if (mOutDevice != value) {
3403 uint32_t params = 0;
3404 // check whether speaker is on
3405 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3406 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3407 }
3408
3409 audio_devices_t deviceWithoutSpeaker
3410 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3411 // check if any other device (except speaker) is on
3412 if (value & deviceWithoutSpeaker ) {
3413 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3414 }
3415
3416 if (params != 0) {
3417 addBatteryData(params);
3418 }
3419 }
3420#endif
3421
3422 // forward device change to effects that have requested to be
3423 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003424 if (value != AUDIO_DEVICE_NONE) {
3425 mOutDevice = value;
3426 for (size_t i = 0; i < mEffectChains.size(); i++) {
3427 mEffectChains[i]->setDevice_l(mOutDevice);
3428 }
Eric Laurent81784c32012-11-19 14:55:58 -08003429 }
3430 }
3431
3432 if (status == NO_ERROR) {
3433 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3434 keyValuePair.string());
3435 if (!mStandby && status == INVALID_OPERATION) {
3436 mOutput->stream->common.standby(&mOutput->stream->common);
3437 mStandby = true;
3438 mBytesWritten = 0;
3439 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3440 keyValuePair.string());
3441 }
3442 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003443 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003444 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003445 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3446 for (size_t i = 0; i < mTracks.size() ; i++) {
3447 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3448 if (name < 0) {
3449 break;
3450 }
3451 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003452 }
3453 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3454 }
3455 }
3456
3457 mNewParameters.removeAt(0);
3458
3459 mParamStatus = status;
3460 mParamCond.signal();
3461 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3462 // already timed out waiting for the status and will never signal the condition.
3463 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3464 }
3465
3466 if (!(previousCommand & FastMixerState::IDLE)) {
3467 ALOG_ASSERT(mFastMixer != NULL);
3468 FastMixerStateQueue *sq = mFastMixer->sq();
3469 FastMixerState *state = sq->begin();
3470 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3471 state->mCommand = previousCommand;
3472 sq->end();
3473 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3474 }
3475
3476 return reconfig;
3477}
3478
3479
3480void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3481{
3482 const size_t SIZE = 256;
3483 char buffer[SIZE];
3484 String8 result;
3485
3486 PlaybackThread::dumpInternals(fd, args);
3487
3488 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3489 result.append(buffer);
3490 write(fd, result.string(), result.size());
3491
3492 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003493 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003494 copy.dump(fd);
3495
3496#ifdef STATE_QUEUE_DUMP
3497 // Similar for state queue
3498 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3499 observerCopy.dump(fd);
3500 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3501 mutatorCopy.dump(fd);
3502#endif
3503
Glenn Kasten46909e72013-02-26 09:20:22 -08003504#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003505 // Write the tee output to a .wav file
3506 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003507#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003508
3509#ifdef AUDIO_WATCHDOG
3510 if (mAudioWatchdog != 0) {
3511 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3512 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3513 wdCopy.dump(fd);
3514 }
3515#endif
3516}
3517
3518uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3519{
3520 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3521}
3522
3523uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3524{
3525 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3526}
3527
3528void AudioFlinger::MixerThread::cacheParameters_l()
3529{
3530 PlaybackThread::cacheParameters_l();
3531
3532 // FIXME: Relaxed timing because of a certain device that can't meet latency
3533 // Should be reduced to 2x after the vendor fixes the driver issue
3534 // increase threshold again due to low power audio mode. The way this warning
3535 // threshold is calculated and its usefulness should be reconsidered anyway.
3536 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3537}
3538
3539// ----------------------------------------------------------------------------
3540
3541AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3542 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3543 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3544 // mLeftVolFloat, mRightVolFloat
3545{
3546}
3547
Eric Laurentbfb1b832013-01-07 09:53:42 -08003548AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3549 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3550 ThreadBase::type_t type)
3551 : PlaybackThread(audioFlinger, output, id, device, type)
3552 // mLeftVolFloat, mRightVolFloat
3553{
3554}
3555
Eric Laurent81784c32012-11-19 14:55:58 -08003556AudioFlinger::DirectOutputThread::~DirectOutputThread()
3557{
3558}
3559
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3561{
3562 audio_track_cblk_t* cblk = track->cblk();
3563 float left, right;
3564
3565 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3566 left = right = 0;
3567 } else {
3568 float typeVolume = mStreamTypes[track->streamType()].volume;
3569 float v = mMasterVolume * typeVolume;
3570 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3571 uint32_t vlr = proxy->getVolumeLR();
3572 float v_clamped = v * (vlr & 0xFFFF);
3573 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3574 left = v_clamped/MAX_GAIN;
3575 v_clamped = v * (vlr >> 16);
3576 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3577 right = v_clamped/MAX_GAIN;
3578 }
3579
3580 if (lastTrack) {
3581 if (left != mLeftVolFloat || right != mRightVolFloat) {
3582 mLeftVolFloat = left;
3583 mRightVolFloat = right;
3584
3585 // Convert volumes from float to 8.24
3586 uint32_t vl = (uint32_t)(left * (1 << 24));
3587 uint32_t vr = (uint32_t)(right * (1 << 24));
3588
3589 // Delegate volume control to effect in track effect chain if needed
3590 // only one effect chain can be present on DirectOutputThread, so if
3591 // there is one, the track is connected to it
3592 if (!mEffectChains.isEmpty()) {
3593 mEffectChains[0]->setVolume_l(&vl, &vr);
3594 left = (float)vl / (1 << 24);
3595 right = (float)vr / (1 << 24);
3596 }
3597 if (mOutput->stream->set_volume) {
3598 mOutput->stream->set_volume(mOutput->stream, left, right);
3599 }
3600 }
3601 }
3602}
3603
3604
Eric Laurent81784c32012-11-19 14:55:58 -08003605AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3606 Vector< sp<Track> > *tracksToRemove
3607)
3608{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003609 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003610 mixer_state mixerStatus = MIXER_IDLE;
3611
3612 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003613 for (size_t i = 0; i < count; i++) {
3614 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // The track died recently
3616 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003617 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003618 }
3619
3620 Track* const track = t.get();
3621 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003622 // Only consider last track started for volume and mixer state control.
3623 // In theory an older track could underrun and restart after the new one starts
3624 // but as we only care about the transition phase between two tracks on a
3625 // direct output, it is not a problem to ignore the underrun case.
3626 sp<Track> l = mLatestActiveTrack.promote();
3627 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003628
3629 // The first time a track is added we wait
3630 // for all its buffers to be filled before processing it
3631 uint32_t minFrames;
3632 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3633 minFrames = mNormalFrameCount;
3634 } else {
3635 minFrames = 1;
3636 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003637
Eric Laurent81784c32012-11-19 14:55:58 -08003638 if ((track->framesReady() >= minFrames) && track->isReady() &&
3639 !track->isPaused() && !track->isTerminated())
3640 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003641 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003642
3643 if (track->mFillingUpStatus == Track::FS_FILLED) {
3644 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003645 // make sure processVolume_l() will apply new volume even if 0
3646 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003647 if (track->mState == TrackBase::RESUMING) {
3648 track->mState = TrackBase::ACTIVE;
3649 }
3650 }
3651
3652 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653 processVolume_l(track, last);
3654 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003655 // reset retry count
3656 track->mRetryCount = kMaxTrackRetriesDirect;
3657 mActiveTrack = t;
3658 mixerStatus = MIXER_TRACKS_READY;
3659 }
Eric Laurent81784c32012-11-19 14:55:58 -08003660 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003661 // clear effect chain input buffer if the last active track started underruns
3662 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003663 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003664 mEffectChains[0]->clearInputBuffer();
3665 }
3666
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003667 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003668 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3669 track->isStopped() || track->isPaused()) {
3670 // We have consumed all the buffers of this track.
3671 // Remove it from the list of active tracks.
3672 // TODO: implement behavior for compressed audio
3673 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3674 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003675 if (mStandby || !last ||
3676 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003677 if (track->isStopped()) {
3678 track->reset();
3679 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003680 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003681 }
3682 } else {
3683 // No buffers for this track. Give it a few chances to
3684 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003685 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003686 if (--(track->mRetryCount) <= 0) {
3687 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003688 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003689 // indicate to client process that the track was disabled because of underrun;
3690 // it will then automatically call start() when data is available
3691 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003692 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003693 mixerStatus = MIXER_TRACKS_ENABLED;
3694 }
3695 }
3696 }
3697 }
3698
Eric Laurent81784c32012-11-19 14:55:58 -08003699 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003700 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003701
3702 return mixerStatus;
3703}
3704
3705void AudioFlinger::DirectOutputThread::threadLoop_mix()
3706{
Eric Laurent81784c32012-11-19 14:55:58 -08003707 size_t frameCount = mFrameCount;
3708 int8_t *curBuf = (int8_t *)mMixBuffer;
3709 // output audio to hardware
3710 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003711 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003712 buffer.frameCount = frameCount;
3713 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003714 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003715 memset(curBuf, 0, frameCount * mFrameSize);
3716 break;
3717 }
3718 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3719 frameCount -= buffer.frameCount;
3720 curBuf += buffer.frameCount * mFrameSize;
3721 mActiveTrack->releaseBuffer(&buffer);
3722 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003723 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003724 sleepTime = 0;
3725 standbyTime = systemTime() + standbyDelay;
3726 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003727}
3728
3729void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3730{
3731 if (sleepTime == 0) {
3732 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3733 sleepTime = activeSleepTime;
3734 } else {
3735 sleepTime = idleSleepTime;
3736 }
3737 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3738 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3739 sleepTime = 0;
3740 }
3741}
3742
3743// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003744int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3745 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003746{
3747 return 0;
3748}
3749
3750// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003751void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003752{
3753}
3754
3755// checkForNewParameters_l() must be called with ThreadBase::mLock held
3756bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3757{
3758 bool reconfig = false;
3759
3760 while (!mNewParameters.isEmpty()) {
3761 status_t status = NO_ERROR;
3762 String8 keyValuePair = mNewParameters[0];
3763 AudioParameter param = AudioParameter(keyValuePair);
3764 int value;
3765
3766 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3767 // do not accept frame count changes if tracks are open as the track buffer
3768 // size depends on frame count and correct behavior would not be garantied
3769 // if frame count is changed after track creation
3770 if (!mTracks.isEmpty()) {
3771 status = INVALID_OPERATION;
3772 } else {
3773 reconfig = true;
3774 }
3775 }
3776 if (status == NO_ERROR) {
3777 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3778 keyValuePair.string());
3779 if (!mStandby && status == INVALID_OPERATION) {
3780 mOutput->stream->common.standby(&mOutput->stream->common);
3781 mStandby = true;
3782 mBytesWritten = 0;
3783 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3784 keyValuePair.string());
3785 }
3786 if (status == NO_ERROR && reconfig) {
3787 readOutputParameters();
3788 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3789 }
3790 }
3791
3792 mNewParameters.removeAt(0);
3793
3794 mParamStatus = status;
3795 mParamCond.signal();
3796 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3797 // already timed out waiting for the status and will never signal the condition.
3798 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3799 }
3800 return reconfig;
3801}
3802
3803uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3804{
3805 uint32_t time;
3806 if (audio_is_linear_pcm(mFormat)) {
3807 time = PlaybackThread::activeSleepTimeUs();
3808 } else {
3809 time = 10000;
3810 }
3811 return time;
3812}
3813
3814uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3815{
3816 uint32_t time;
3817 if (audio_is_linear_pcm(mFormat)) {
3818 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3819 } else {
3820 time = 10000;
3821 }
3822 return time;
3823}
3824
3825uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3826{
3827 uint32_t time;
3828 if (audio_is_linear_pcm(mFormat)) {
3829 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3830 } else {
3831 time = 10000;
3832 }
3833 return time;
3834}
3835
3836void AudioFlinger::DirectOutputThread::cacheParameters_l()
3837{
3838 PlaybackThread::cacheParameters_l();
3839
3840 // use shorter standby delay as on normal output to release
3841 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003842 if (audio_is_linear_pcm(mFormat)) {
3843 standbyDelay = microseconds(activeSleepTime*2);
3844 } else {
3845 standbyDelay = kOffloadStandbyDelayNs;
3846 }
Eric Laurent81784c32012-11-19 14:55:58 -08003847}
3848
3849// ----------------------------------------------------------------------------
3850
Eric Laurentbfb1b832013-01-07 09:53:42 -08003851AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003852 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003853 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003854 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003855 mWriteAckSequence(0),
3856 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857{
3858}
3859
3860AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3861{
3862}
3863
3864void AudioFlinger::AsyncCallbackThread::onFirstRef()
3865{
3866 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3867}
3868
3869bool AudioFlinger::AsyncCallbackThread::threadLoop()
3870{
3871 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003872 uint32_t writeAckSequence;
3873 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874
3875 {
3876 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003877 while (!((mWriteAckSequence & 1) ||
3878 (mDrainSequence & 1) ||
3879 exitPending())) {
3880 mWaitWorkCV.wait(mLock);
3881 }
3882
Eric Laurentbfb1b832013-01-07 09:53:42 -08003883 if (exitPending()) {
3884 break;
3885 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003886 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3887 mWriteAckSequence, mDrainSequence);
3888 writeAckSequence = mWriteAckSequence;
3889 mWriteAckSequence &= ~1;
3890 drainSequence = mDrainSequence;
3891 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003892 }
3893 {
Eric Laurent4de95592013-09-26 15:28:21 -07003894 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3895 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003896 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003897 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003898 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003899 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003900 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901 }
3902 }
3903 }
3904 }
3905 return false;
3906}
3907
3908void AudioFlinger::AsyncCallbackThread::exit()
3909{
3910 ALOGV("AsyncCallbackThread::exit");
3911 Mutex::Autolock _l(mLock);
3912 requestExit();
3913 mWaitWorkCV.broadcast();
3914}
3915
Eric Laurent3b4529e2013-09-05 18:09:19 -07003916void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003917{
3918 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003919 // bit 0 is cleared
3920 mWriteAckSequence = sequence << 1;
3921}
3922
3923void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3924{
3925 Mutex::Autolock _l(mLock);
3926 // ignore unexpected callbacks
3927 if (mWriteAckSequence & 2) {
3928 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003929 mWaitWorkCV.signal();
3930 }
3931}
3932
Eric Laurent3b4529e2013-09-05 18:09:19 -07003933void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003934{
3935 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003936 // bit 0 is cleared
3937 mDrainSequence = sequence << 1;
3938}
3939
3940void AudioFlinger::AsyncCallbackThread::resetDraining()
3941{
3942 Mutex::Autolock _l(mLock);
3943 // ignore unexpected callbacks
3944 if (mDrainSequence & 2) {
3945 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003946 mWaitWorkCV.signal();
3947 }
3948}
3949
3950
3951// ----------------------------------------------------------------------------
3952AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3953 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3954 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3955 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003956 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003957 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958{
Eric Laurentfd477972013-10-25 18:10:40 -07003959 //FIXME: mStandby should be set to true by ThreadBase constructor
3960 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961}
3962
Eric Laurentbfb1b832013-01-07 09:53:42 -08003963void AudioFlinger::OffloadThread::threadLoop_exit()
3964{
3965 if (mFlushPending || mHwPaused) {
3966 // If a flush is pending or track was paused, just discard buffered data
3967 flushHw_l();
3968 } else {
3969 mMixerStatus = MIXER_DRAIN_ALL;
3970 threadLoop_drain();
3971 }
3972 mCallbackThread->exit();
3973 PlaybackThread::threadLoop_exit();
3974}
3975
3976AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3977 Vector< sp<Track> > *tracksToRemove
3978)
3979{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003980 size_t count = mActiveTracks.size();
3981
3982 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003983 bool doHwPause = false;
3984 bool doHwResume = false;
3985
Eric Laurentede6c3b2013-09-19 14:37:46 -07003986 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3987
Eric Laurentbfb1b832013-01-07 09:53:42 -08003988 // find out which tracks need to be processed
3989 for (size_t i = 0; i < count; i++) {
3990 sp<Track> t = mActiveTracks[i].promote();
3991 // The track died recently
3992 if (t == 0) {
3993 continue;
3994 }
3995 Track* const track = t.get();
3996 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003997 // Only consider last track started for volume and mixer state control.
3998 // In theory an older track could underrun and restart after the new one starts
3999 // but as we only care about the transition phase between two tracks on a
4000 // direct output, it is not a problem to ignore the underrun case.
4001 sp<Track> l = mLatestActiveTrack.promote();
4002 bool last = l.get() == track;
4003
Haynes Mathew George7844f672014-01-15 12:32:55 -08004004 if (track->isInvalid()) {
4005 ALOGW("An invalidated track shouldn't be in active list");
4006 tracksToRemove->add(track);
4007 continue;
4008 }
4009
4010 if (track->mState == TrackBase::IDLE) {
4011 ALOGW("An idle track shouldn't be in active list");
4012 continue;
4013 }
4014
Eric Laurentbfb1b832013-01-07 09:53:42 -08004015 if (track->isPausing()) {
4016 track->setPaused();
4017 if (last) {
4018 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004019 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 mHwPaused = true;
4021 }
4022 // If we were part way through writing the mixbuffer to
4023 // the HAL we must save this until we resume
4024 // BUG - this will be wrong if a different track is made active,
4025 // in that case we want to discard the pending data in the
4026 // mixbuffer and tell the client to present it again when the
4027 // track is resumed
4028 mPausedWriteLength = mCurrentWriteLength;
4029 mPausedBytesRemaining = mBytesRemaining;
4030 mBytesRemaining = 0; // stop writing
4031 }
4032 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004033 } else if (track->isFlushPending()) {
4034 track->flushAck();
4035 if (last) {
4036 mFlushPending = true;
4037 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004038 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004039 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004040 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 if (track->mFillingUpStatus == Track::FS_FILLED) {
4042 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004043 // make sure processVolume_l() will apply new volume even if 0
4044 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004047 if (last) {
4048 if (mPausedBytesRemaining) {
4049 // Need to continue write that was interrupted
4050 mCurrentWriteLength = mPausedWriteLength;
4051 mBytesRemaining = mPausedBytesRemaining;
4052 mPausedBytesRemaining = 0;
4053 }
4054 if (mHwPaused) {
4055 doHwResume = true;
4056 mHwPaused = false;
4057 // threadLoop_mix() will handle the case that we need to
4058 // resume an interrupted write
4059 }
4060 // enable write to audio HAL
4061 sleepTime = 0;
4062 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004063 }
4064 }
4065
4066 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004067 sp<Track> previousTrack = mPreviousTrack.promote();
4068 if (previousTrack != 0) {
4069 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004070 // Flush any data still being written from last track
4071 mBytesRemaining = 0;
4072 if (mPausedBytesRemaining) {
4073 // Last track was paused so we also need to flush saved
4074 // mixbuffer state and invalidate track so that it will
4075 // re-submit that unwritten data when it is next resumed
4076 mPausedBytesRemaining = 0;
4077 // Invalidate is a bit drastic - would be more efficient
4078 // to have a flag to tell client that some of the
4079 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004080 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004081 }
4082 // flush data already sent to the DSP if changing audio session as audio
4083 // comes from a different source. Also invalidate previous track to force a
4084 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004085 if (previousTrack->sessionId() != track->sessionId()) {
4086 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004087 }
4088 }
4089 }
4090 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004091 // reset retry count
4092 track->mRetryCount = kMaxTrackRetriesOffload;
4093 mActiveTrack = t;
4094 mixerStatus = MIXER_TRACKS_READY;
4095 }
4096 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004097 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004098 if (track->isStopping_1()) {
4099 // Hardware buffer can hold a large amount of audio so we must
4100 // wait for all current track's data to drain before we say
4101 // that the track is stopped.
4102 if (mBytesRemaining == 0) {
4103 // Only start draining when all data in mixbuffer
4104 // has been written
4105 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4106 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004107 // do not drain if no data was ever sent to HAL (mStandby == true)
4108 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004109 // do not modify drain sequence if we are already draining. This happens
4110 // when resuming from pause after drain.
4111 if ((mDrainSequence & 1) == 0) {
4112 sleepTime = 0;
4113 standbyTime = systemTime() + standbyDelay;
4114 mixerStatus = MIXER_DRAIN_TRACK;
4115 mDrainSequence += 2;
4116 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004117 if (mHwPaused) {
4118 // It is possible to move from PAUSED to STOPPING_1 without
4119 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004120 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 mHwPaused = false;
4122 }
4123 }
4124 }
4125 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004126 // Drain has completed or we are in standby, signal presentation complete
4127 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004128 track->mState = TrackBase::STOPPED;
4129 size_t audioHALFrames =
4130 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4131 size_t framesWritten =
4132 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4133 track->presentationComplete(framesWritten, audioHALFrames);
4134 track->reset();
4135 tracksToRemove->add(track);
4136 }
4137 } else {
4138 // No buffers for this track. Give it a few chances to
4139 // fill a buffer, then remove it from active list.
4140 if (--(track->mRetryCount) <= 0) {
4141 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4142 track->name());
4143 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004144 // indicate to client process that the track was disabled because of underrun;
4145 // it will then automatically call start() when data is available
4146 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004147 } else if (last){
4148 mixerStatus = MIXER_TRACKS_ENABLED;
4149 }
4150 }
4151 }
4152 // compute volume for this track
4153 processVolume_l(track, last);
4154 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004155
Eric Laurentea0fade2013-10-04 16:23:48 -07004156 // make sure the pause/flush/resume sequence is executed in the right order.
4157 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4158 // before flush and then resume HW. This can happen in case of pause/flush/resume
4159 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004160 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004161 mOutput->stream->pause(mOutput->stream);
4162 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004163 if (mFlushPending) {
4164 flushHw_l();
4165 mFlushPending = false;
4166 }
Eric Laurentfd477972013-10-25 18:10:40 -07004167 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004168 mOutput->stream->resume(mOutput->stream);
4169 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004170
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 // remove all the tracks that need to be...
4172 removeTracks_l(*tracksToRemove);
4173
4174 return mixerStatus;
4175}
4176
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177// must be called with thread mutex locked
4178bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4179{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004180 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4181 mWriteAckSequence, mDrainSequence);
4182 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183 return true;
4184 }
4185 return false;
4186}
4187
4188// must be called with thread mutex locked
4189bool AudioFlinger::OffloadThread::shouldStandby_l()
4190{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004191 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192
4193 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4194 // after a timeout and we will enter standby then.
4195 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004196 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 }
4198
Glenn Kastene6f35b12013-08-19 09:58:50 -07004199 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200}
4201
4202
4203bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4204{
4205 Mutex::Autolock _l(mLock);
4206 return waitingAsyncCallback_l();
4207}
4208
4209void AudioFlinger::OffloadThread::flushHw_l()
4210{
4211 mOutput->stream->flush(mOutput->stream);
4212 // Flush anything still waiting in the mixbuffer
4213 mCurrentWriteLength = 0;
4214 mBytesRemaining = 0;
4215 mPausedWriteLength = 0;
4216 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004217 mHwPaused = false;
4218
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004220 // discard any pending drain or write ack by incrementing sequence
4221 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4222 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004224 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4225 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226 }
4227}
4228
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004229void AudioFlinger::OffloadThread::onAddNewTrack_l()
4230{
4231 sp<Track> previousTrack = mPreviousTrack.promote();
4232 sp<Track> latestTrack = mLatestActiveTrack.promote();
4233
4234 if (previousTrack != 0 && latestTrack != 0 &&
4235 (previousTrack->sessionId() != latestTrack->sessionId())) {
4236 mFlushPending = true;
4237 }
4238 PlaybackThread::onAddNewTrack_l();
4239}
4240
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241// ----------------------------------------------------------------------------
4242
Eric Laurent81784c32012-11-19 14:55:58 -08004243AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4244 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4245 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4246 DUPLICATING),
4247 mWaitTimeMs(UINT_MAX)
4248{
4249 addOutputTrack(mainThread);
4250}
4251
4252AudioFlinger::DuplicatingThread::~DuplicatingThread()
4253{
4254 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4255 mOutputTracks[i]->destroy();
4256 }
4257}
4258
4259void AudioFlinger::DuplicatingThread::threadLoop_mix()
4260{
4261 // mix buffers...
4262 if (outputsReady(outputTracks)) {
4263 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4264 } else {
4265 memset(mMixBuffer, 0, mixBufferSize);
4266 }
4267 sleepTime = 0;
4268 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004270 standbyTime = systemTime() + standbyDelay;
4271}
4272
4273void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4274{
4275 if (sleepTime == 0) {
4276 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4277 sleepTime = activeSleepTime;
4278 } else {
4279 sleepTime = idleSleepTime;
4280 }
4281 } else if (mBytesWritten != 0) {
4282 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4283 writeFrames = mNormalFrameCount;
4284 memset(mMixBuffer, 0, mixBufferSize);
4285 } else {
4286 // flush remaining overflow buffers in output tracks
4287 writeFrames = 0;
4288 }
4289 sleepTime = 0;
4290 }
4291}
4292
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004294{
4295 for (size_t i = 0; i < outputTracks.size(); i++) {
4296 outputTracks[i]->write(mMixBuffer, writeFrames);
4297 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004298 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004300}
4301
4302void AudioFlinger::DuplicatingThread::threadLoop_standby()
4303{
4304 // DuplicatingThread implements standby by stopping all tracks
4305 for (size_t i = 0; i < outputTracks.size(); i++) {
4306 outputTracks[i]->stop();
4307 }
4308}
4309
4310void AudioFlinger::DuplicatingThread::saveOutputTracks()
4311{
4312 outputTracks = mOutputTracks;
4313}
4314
4315void AudioFlinger::DuplicatingThread::clearOutputTracks()
4316{
4317 outputTracks.clear();
4318}
4319
4320void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4321{
4322 Mutex::Autolock _l(mLock);
4323 // FIXME explain this formula
4324 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4325 OutputTrack *outputTrack = new OutputTrack(thread,
4326 this,
4327 mSampleRate,
4328 mFormat,
4329 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004330 frameCount,
4331 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004332 if (outputTrack->cblk() != NULL) {
4333 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4334 mOutputTracks.add(outputTrack);
4335 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4336 updateWaitTime_l();
4337 }
4338}
4339
4340void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4341{
4342 Mutex::Autolock _l(mLock);
4343 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4344 if (mOutputTracks[i]->thread() == thread) {
4345 mOutputTracks[i]->destroy();
4346 mOutputTracks.removeAt(i);
4347 updateWaitTime_l();
4348 return;
4349 }
4350 }
4351 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4352}
4353
4354// caller must hold mLock
4355void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4356{
4357 mWaitTimeMs = UINT_MAX;
4358 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4359 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4360 if (strong != 0) {
4361 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4362 if (waitTimeMs < mWaitTimeMs) {
4363 mWaitTimeMs = waitTimeMs;
4364 }
4365 }
4366 }
4367}
4368
4369
4370bool AudioFlinger::DuplicatingThread::outputsReady(
4371 const SortedVector< sp<OutputTrack> > &outputTracks)
4372{
4373 for (size_t i = 0; i < outputTracks.size(); i++) {
4374 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4375 if (thread == 0) {
4376 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4377 outputTracks[i].get());
4378 return false;
4379 }
4380 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4381 // see note at standby() declaration
4382 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4383 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4384 thread.get());
4385 return false;
4386 }
4387 }
4388 return true;
4389}
4390
4391uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4392{
4393 return (mWaitTimeMs * 1000) / 2;
4394}
4395
4396void AudioFlinger::DuplicatingThread::cacheParameters_l()
4397{
4398 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4399 updateWaitTime_l();
4400
4401 MixerThread::cacheParameters_l();
4402}
4403
4404// ----------------------------------------------------------------------------
4405// Record
4406// ----------------------------------------------------------------------------
4407
4408AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4409 AudioStreamIn *input,
4410 uint32_t sampleRate,
4411 audio_channel_mask_t channelMask,
4412 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004413 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004414 audio_devices_t inDevice
4415#ifdef TEE_SINK
4416 , const sp<NBAIO_Sink>& teeSink
4417#endif
4418 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004419 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten2b806402013-11-20 16:37:38 -08004420 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten85948432013-08-19 12:09:05 -07004421 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear
4422 // are set by readInputParameters()
4423 // mRsmpInIndex LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004424 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004425 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004426 // mBytesRead is only meaningful while active, and so is cleared in start()
4427 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004428#ifdef TEE_SINK
4429 , mTeeSink(teeSink)
4430#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004431{
4432 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004433 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004434
4435 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004436}
4437
4438
4439AudioFlinger::RecordThread::~RecordThread()
4440{
Glenn Kasten481fb672013-09-30 14:39:28 -07004441 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004442 delete[] mRsmpInBuffer;
4443 delete mResampler;
4444 delete[] mRsmpOutBuffer;
4445}
4446
4447void AudioFlinger::RecordThread::onFirstRef()
4448{
4449 run(mName, PRIORITY_URGENT_AUDIO);
4450}
4451
Eric Laurent81784c32012-11-19 14:55:58 -08004452bool AudioFlinger::RecordThread::threadLoop()
4453{
Eric Laurent81784c32012-11-19 14:55:58 -08004454 nsecs_t lastWarning = 0;
4455
4456 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004457
4458 // used to verify we've read at least once before evaluating how many bytes were read
4459 bool readOnce = false;
4460
Glenn Kasten5edadd42013-08-14 16:30:49 -07004461 // used to request a deferred sleep, to be executed later while mutex is unlocked
4462 bool doSleep = false;
4463
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004464reacquire_wakelock:
4465 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004466 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004467 {
4468 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004469 size_t size = mActiveTracks.size();
4470 activeTracksGen = mActiveTracksGen;
4471 if (size > 0) {
4472 // FIXME an arbitrary choice
4473 activeTrack = mActiveTracks[0];
4474 acquireWakeLock_l(activeTrack->uid());
4475 if (size > 1) {
4476 SortedVector<int> tmp;
4477 for (size_t i = 0; i < size; i++) {
4478 tmp.add(mActiveTracks[i]->uid());
4479 }
4480 updateWakeLockUids_l(tmp);
4481 }
4482 } else {
4483 acquireWakeLock_l(-1);
4484 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004485 }
4486
Eric Laurent81784c32012-11-19 14:55:58 -08004487 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004488 for (;;) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004489 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004490 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004491
Glenn Kasten5edadd42013-08-14 16:30:49 -07004492 // sleep with mutex unlocked
4493 if (doSleep) {
4494 doSleep = false;
4495 usleep(kRecordThreadSleepUs);
4496 }
4497
Eric Laurent81784c32012-11-19 14:55:58 -08004498 { // scope for mLock
4499 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004500
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004501 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004502 // return value 'reconfig' is currently unused
4503 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004504
Eric Laurent000a4192014-01-29 15:17:32 -08004505 // check exitPending here because checkForNewParameters_l() and
4506 // checkForNewParameters_l() can temporarily release mLock
4507 if (exitPending()) {
4508 break;
4509 }
4510
Glenn Kasten2b806402013-11-20 16:37:38 -08004511 // if no active track(s), then standby and release wakelock
4512 size_t size = mActiveTracks.size();
4513 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004514 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004515 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004516 releaseWakeLock_l();
4517 ALOGV("RecordThread: loop stopping");
4518 // go to sleep
4519 mWaitWorkCV.wait(mLock);
4520 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004521 goto reacquire_wakelock;
4522 }
4523
Glenn Kasten2b806402013-11-20 16:37:38 -08004524 if (mActiveTracksGen != activeTracksGen) {
4525 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004526 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004527 for (size_t i = 0; i < size; i++) {
4528 tmp.add(mActiveTracks[i]->uid());
4529 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004530 updateWakeLockUids_l(tmp);
Glenn Kasten2b806402013-11-20 16:37:38 -08004531 // FIXME an arbitrary choice
4532 activeTrack = mActiveTracks[0];
Eric Laurent81784c32012-11-19 14:55:58 -08004533 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004534
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004535 if (activeTrack->isTerminated()) {
4536 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004537 mActiveTracks.remove(activeTrack);
4538 mActiveTracksGen++;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004539 continue;
4540 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004541
Glenn Kastenb86432b2013-08-14 15:08:12 -07004542 activeTrackState = activeTrack->mState;
4543 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004544 case TrackBase::PAUSING:
Glenn Kasten93e471f2013-08-19 08:40:07 -07004545 standbyIfNotAlreadyInStandby();
Glenn Kasten2b806402013-11-20 16:37:38 -08004546 mActiveTracks.remove(activeTrack);
4547 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004548 mStartStopCond.broadcast();
4549 doSleep = true;
4550 continue;
4551
4552 case TrackBase::RESUMING:
4553 mStandby = false;
4554 if (mReqChannelCount != activeTrack->channelCount()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004555 mActiveTracks.remove(activeTrack);
4556 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004557 mStartStopCond.broadcast();
4558 continue;
4559 }
4560 if (readOnce) {
4561 mStartStopCond.broadcast();
4562 // record start succeeds only if first read from audio input succeeds
4563 if (mBytesRead < 0) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004564 mActiveTracks.remove(activeTrack);
4565 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004566 continue;
4567 }
4568 activeTrack->mState = TrackBase::ACTIVE;
4569 }
4570 break;
4571
4572 case TrackBase::ACTIVE:
4573 break;
4574
4575 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004576 doSleep = true;
4577 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004578
4579 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004580 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004581 }
4582
Eric Laurent81784c32012-11-19 14:55:58 -08004583 lockEffectChains_l(effectChains);
4584 }
4585
Glenn Kasten2b806402013-11-20 16:37:38 -08004586 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004587 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4588
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004589 for (size_t i = 0; i < effectChains.size(); i ++) {
4590 // thread mutex is not locked, but effect chain is locked
4591 effectChains[i]->process_l();
4592 }
4593
Glenn Kastenb91aa632013-08-19 08:40:21 -07004594 AudioBufferProvider::Buffer buffer;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004595 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004596 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004597 if (status == NO_ERROR) {
4598 readOnce = true;
4599 size_t framesOut = buffer.frameCount;
4600 if (mResampler == NULL) {
4601 // no resampling
4602 while (framesOut) {
4603 size_t framesIn = mFrameCount - mRsmpInIndex;
4604 if (framesIn > 0) {
4605 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4606 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004607 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004608 if (framesIn > framesOut) {
4609 framesIn = framesOut;
4610 }
4611 mRsmpInIndex += framesIn;
4612 framesOut -= framesIn;
4613 if (mChannelCount == mReqChannelCount) {
4614 memcpy(dst, src, framesIn * mFrameSize);
4615 } else {
4616 if (mChannelCount == 1) {
4617 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4618 (int16_t *)src, framesIn);
4619 } else {
4620 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4621 (int16_t *)src, framesIn);
4622 }
4623 }
4624 }
4625 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4626 void *readInto;
4627 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4628 readInto = buffer.raw;
4629 framesOut = 0;
4630 } else {
4631 readInto = mRsmpInBuffer;
4632 mRsmpInIndex = 0;
4633 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07004634 mBytesRead = mInput->stream->read(mInput->stream, readInto, mBufferSize);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004635 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004636 // TODO: verify that it's benign to use a stale track state
4637 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004638 {
4639 ALOGE("Error reading audio input");
4640 // Force input into standby so that it tries to
4641 // recover at next read attempt
4642 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004643 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004644 }
4645 mRsmpInIndex = mFrameCount;
4646 framesOut = 0;
4647 buffer.frameCount = 0;
4648 }
4649#ifdef TEE_SINK
4650 else if (mTeeSink != 0) {
4651 (void) mTeeSink->write(readInto,
4652 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4653 }
4654#endif
4655 }
4656 }
4657 } else {
4658 // resampling
4659
Glenn Kasten85948432013-08-19 12:09:05 -07004660 // avoid busy-waiting if client doesn't keep up
4661 bool madeProgress = false;
4662
4663 // keep mRsmpInBuffer full so resampler always has sufficient input
4664 for (;;) {
4665 int32_t rear = mRsmpInRear;
4666 ssize_t filled = rear - mRsmpInFront;
4667 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
4668 // exit once there is enough data in buffer for resampler
4669 if ((size_t) filled >= mRsmpInFrames) {
4670 break;
4671 }
4672 size_t avail = mRsmpInFramesP2 - filled;
4673 // Only try to read full HAL buffers.
4674 // But if the HAL read returns a partial buffer, use it.
4675 if (avail < mFrameCount) {
4676 ALOGE("insufficient space to read: avail %d < mFrameCount %d",
4677 avail, mFrameCount);
4678 break;
4679 }
4680 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then
4681 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
4682 rear &= mRsmpInFramesP2 - 1;
4683 mBytesRead = mInput->stream->read(mInput->stream,
4684 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4685 if (mBytesRead <= 0) {
4686 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize);
4687 break;
4688 }
4689 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize);
4690 size_t framesRead = mBytesRead / mFrameSize;
4691 ALOG_ASSERT(framesRead > 0);
4692 madeProgress = true;
4693 // If 'avail' was non-contiguous, we now correct for reading past end of buffer.
4694 size_t part1 = mRsmpInFramesP2 - rear;
4695 if (framesRead > part1) {
4696 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4697 (framesRead - part1) * mFrameSize);
4698 }
4699 mRsmpInRear += framesRead;
4700 }
4701
4702 if (!madeProgress) {
4703 ALOGV("Did not make progress");
4704 usleep(((mFrameCount * 1000) / mSampleRate) * 1000);
4705 }
4706
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004707 // resampler accumulates, but we only have one source track
4708 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004709 mResampler->resample(mRsmpOutBuffer, framesOut,
4710 this /* AudioBufferProvider* */);
4711 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004712 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten85948432013-08-19 12:09:05 -07004713 if (mReqChannelCount == 1) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004714 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4715 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4716 // the resampler always outputs stereo samples:
4717 // do post stereo to mono conversion
4718 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4719 framesOut);
4720 } else {
4721 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4722 }
4723 // now done with mRsmpOutBuffer
4724
4725 }
4726 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004727 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004728 } else {
4729 if (mFramestoDrop > 0) {
4730 mFramestoDrop -= buffer.frameCount;
4731 if (mFramestoDrop <= 0) {
4732 clearSyncStartEvent();
4733 }
4734 } else {
4735 mFramestoDrop += buffer.frameCount;
4736 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4737 mSyncStartEvent->isCancelled()) {
4738 ALOGW("Synced record %s, session %d, trigger session %d",
4739 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004740 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004741 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4742 clearSyncStartEvent();
4743 }
4744 }
4745 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004746 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004747 }
4748 // client isn't retrieving buffers fast enough
4749 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004750 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004751 nsecs_t now = systemTime();
4752 if ((now - lastWarning) > kWarningThrottleNs) {
4753 ALOGW("RecordThread: buffer overflow");
4754 lastWarning = now;
4755 }
4756 }
4757 // Release the processor for a while before asking for a new buffer.
4758 // This will give the application more chance to read from the buffer and
4759 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004760 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004761 }
4762
Eric Laurent81784c32012-11-19 14:55:58 -08004763 // enable changes in effect chain
4764 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004765 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004766 }
4767
Glenn Kasten93e471f2013-08-19 08:40:07 -07004768 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004769
4770 {
4771 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004772 for (size_t i = 0; i < mTracks.size(); i++) {
4773 sp<RecordTrack> track = mTracks[i];
4774 track->invalidate();
4775 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004776 mActiveTracks.clear();
4777 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004778 mStartStopCond.broadcast();
4779 }
4780
4781 releaseWakeLock();
4782
4783 ALOGV("RecordThread %p exiting", this);
4784 return false;
4785}
4786
Glenn Kasten93e471f2013-08-19 08:40:07 -07004787void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004788{
4789 if (!mStandby) {
4790 inputStandBy();
4791 mStandby = true;
4792 }
4793}
4794
4795void AudioFlinger::RecordThread::inputStandBy()
4796{
4797 mInput->stream->common.standby(&mInput->stream->common);
4798}
4799
Glenn Kastene198c362013-08-13 09:13:36 -07004800sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004801 const sp<AudioFlinger::Client>& client,
4802 uint32_t sampleRate,
4803 audio_format_t format,
4804 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08004805 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08004806 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004807 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004808 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004809 pid_t tid,
4810 status_t *status)
4811{
Glenn Kasten74935e42013-12-19 08:56:45 -08004812 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004813 sp<RecordTrack> track;
4814 status_t lStatus;
4815
4816 lStatus = initCheck();
4817 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004818 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004819 goto Exit;
4820 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07004821
Glenn Kasten90e58b12013-07-31 16:16:02 -07004822 // client expresses a preference for FAST, but we get the final say
4823 if (*flags & IAudioFlinger::TRACK_FAST) {
4824 if (
4825 // use case: callback handler and frame count is default or at least as large as HAL
4826 (
4827 (tid != -1) &&
4828 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004829 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004830 ) &&
4831 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4832 // mono or stereo
4833 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4834 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4835 // hardware sample rate
4836 (sampleRate == mSampleRate) &&
4837 // record thread has an associated fast recorder
4838 hasFastRecorder()
4839 // FIXME test that RecordThread for this fast track has a capable output HAL
4840 // FIXME add a permission test also?
4841 ) {
4842 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4843 if (frameCount == 0) {
4844 frameCount = mFrameCount * kFastTrackMultiplier;
4845 }
4846 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4847 frameCount, mFrameCount);
4848 } else {
4849 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4850 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4851 "hasFastRecorder=%d tid=%d",
4852 frameCount, mFrameCount, format,
4853 audio_is_linear_pcm(format),
4854 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4855 *flags &= ~IAudioFlinger::TRACK_FAST;
4856 // For compatibility with AudioRecord calculation, buffer depth is forced
4857 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4858 // This is probably too conservative, but legacy application code may depend on it.
4859 // If you change this calculation, also review the start threshold which is related.
4860 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4861 size_t mNormalFrameCount = 2048; // FIXME
4862 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4863 if (minBufCount < 2) {
4864 minBufCount = 2;
4865 }
4866 size_t minFrameCount = mNormalFrameCount * minBufCount;
4867 if (frameCount < minFrameCount) {
4868 frameCount = minFrameCount;
4869 }
4870 }
4871 }
Glenn Kasten74935e42013-12-19 08:56:45 -08004872 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07004873
Eric Laurent81784c32012-11-19 14:55:58 -08004874 // FIXME use flags and tid similar to createTrack_l()
4875
4876 { // scope for mLock
4877 Mutex::Autolock _l(mLock);
4878
4879 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004880 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004881
Glenn Kasten03003332013-08-06 15:40:54 -07004882 lStatus = track->initCheck();
4883 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004884 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08004885 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004886 goto Exit;
4887 }
4888 mTracks.add(track);
4889
4890 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4891 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4892 mAudioFlinger->btNrecIsOff();
4893 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4894 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004895
4896 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4897 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4898 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4899 // so ask activity manager to do this on our behalf
4900 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4901 }
Eric Laurent81784c32012-11-19 14:55:58 -08004902 }
4903 lStatus = NO_ERROR;
4904
4905Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004906 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004907 return track;
4908}
4909
4910status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4911 AudioSystem::sync_event_t event,
4912 int triggerSession)
4913{
4914 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4915 sp<ThreadBase> strongMe = this;
4916 status_t status = NO_ERROR;
4917
4918 if (event == AudioSystem::SYNC_EVENT_NONE) {
4919 clearSyncStartEvent();
4920 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4921 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4922 triggerSession,
4923 recordTrack->sessionId(),
4924 syncStartEventCallback,
4925 this);
4926 // Sync event can be cancelled by the trigger session if the track is not in a
4927 // compatible state in which case we start record immediately
4928 if (mSyncStartEvent->isCancelled()) {
4929 clearSyncStartEvent();
4930 } else {
4931 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4932 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4933 }
4934 }
4935
4936 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004937 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004938 AutoMutex lock(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004939 if (mActiveTracks.size() > 0) {
4940 // FIXME does not work for multiple active tracks
4941 if (mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004942 status = -EBUSY;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004943 } else if (recordTrack->mState == TrackBase::PAUSING) {
4944 recordTrack->mState = TrackBase::ACTIVE;
Eric Laurent81784c32012-11-19 14:55:58 -08004945 }
4946 return status;
4947 }
4948
Glenn Kasten47c20702013-08-13 15:37:35 -07004949 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004950 recordTrack->mState = TrackBase::IDLE;
Glenn Kasten2b806402013-11-20 16:37:38 -08004951 mActiveTracks.add(recordTrack);
4952 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004953 mLock.unlock();
4954 status_t status = AudioSystem::startInput(mId);
4955 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004956 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004957 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004958 mActiveTracks.remove(recordTrack);
4959 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004960 clearSyncStartEvent();
4961 return status;
4962 }
Glenn Kasten85948432013-08-19 12:09:05 -07004963 // FIXME LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004964 mRsmpInIndex = mFrameCount;
Glenn Kasten85948432013-08-19 12:09:05 -07004965 mRsmpInFront = 0;
4966 mRsmpInRear = 0;
4967 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004968 mBytesRead = 0;
4969 if (mResampler != NULL) {
4970 mResampler->reset();
4971 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004972 // FIXME hijacking a playback track state name which was intended for start after pause;
4973 // here 'STARTING_2' would be more accurate
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004974 recordTrack->mState = TrackBase::RESUMING;
Eric Laurent81784c32012-11-19 14:55:58 -08004975 // signal thread to start
4976 ALOGV("Signal record thread");
4977 mWaitWorkCV.broadcast();
4978 // do not wait for mStartStopCond if exiting
4979 if (exitPending()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004980 mActiveTracks.remove(recordTrack);
4981 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004982 status = INVALID_OPERATION;
4983 goto startError;
4984 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004985 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004986 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004987 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004988 ALOGV("Record failed to start");
4989 status = BAD_VALUE;
4990 goto startError;
4991 }
4992 ALOGV("Record started OK");
4993 return status;
4994 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004995
Eric Laurent81784c32012-11-19 14:55:58 -08004996startError:
4997 AudioSystem::stopInput(mId);
4998 clearSyncStartEvent();
4999 return status;
5000}
5001
5002void AudioFlinger::RecordThread::clearSyncStartEvent()
5003{
5004 if (mSyncStartEvent != 0) {
5005 mSyncStartEvent->cancel();
5006 }
5007 mSyncStartEvent.clear();
5008 mFramestoDrop = 0;
5009}
5010
5011void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5012{
5013 sp<SyncEvent> strongEvent = event.promote();
5014
5015 if (strongEvent != 0) {
5016 RecordThread *me = (RecordThread *)strongEvent->cookie();
5017 me->handleSyncStartEvent(strongEvent);
5018 }
5019}
5020
5021void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5022{
5023 if (event == mSyncStartEvent) {
5024 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5025 // from audio HAL
5026 mFramestoDrop = mFrameCount * 2;
5027 }
5028}
5029
Glenn Kastena8356f62013-07-25 14:37:52 -07005030bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005031 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005032 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005033 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005034 return false;
5035 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005036 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005037 recordTrack->mState = TrackBase::PAUSING;
5038 // do not wait for mStartStopCond if exiting
5039 if (exitPending()) {
5040 return true;
5041 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005042 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005043 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005044 // if we have been restarted, recordTrack is in mActiveTracks here
5045 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005046 ALOGV("Record stopped OK");
5047 return true;
5048 }
5049 return false;
5050}
5051
Glenn Kasten0f11b512014-01-31 16:18:54 -08005052bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005053{
5054 return false;
5055}
5056
Glenn Kasten0f11b512014-01-31 16:18:54 -08005057status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005058{
5059#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5060 if (!isValidSyncEvent(event)) {
5061 return BAD_VALUE;
5062 }
5063
5064 int eventSession = event->triggerSession();
5065 status_t ret = NAME_NOT_FOUND;
5066
5067 Mutex::Autolock _l(mLock);
5068
5069 for (size_t i = 0; i < mTracks.size(); i++) {
5070 sp<RecordTrack> track = mTracks[i];
5071 if (eventSession == track->sessionId()) {
5072 (void) track->setSyncEvent(event);
5073 ret = NO_ERROR;
5074 }
5075 }
5076 return ret;
5077#else
5078 return BAD_VALUE;
5079#endif
5080}
5081
5082// destroyTrack_l() must be called with ThreadBase::mLock held
5083void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5084{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005085 track->terminate();
5086 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005087 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005088 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 removeTrack_l(track);
5090 }
5091}
5092
5093void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5094{
5095 mTracks.remove(track);
5096 // need anything related to effects here?
5097}
5098
5099void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5100{
5101 dumpInternals(fd, args);
5102 dumpTracks(fd, args);
5103 dumpEffectChains(fd, args);
5104}
5105
5106void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5107{
5108 const size_t SIZE = 256;
5109 char buffer[SIZE];
5110 String8 result;
5111
5112 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5113 result.append(buffer);
5114
Glenn Kasten2b806402013-11-20 16:37:38 -08005115 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005116 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5117 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08005118 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005119 result.append(buffer);
5120 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5121 result.append(buffer);
5122 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
5123 result.append(buffer);
5124 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
5125 result.append(buffer);
5126 } else {
5127 result.append("No active record client\n");
5128 }
5129
5130 write(fd, result.string(), result.size());
5131
5132 dumpBase(fd, args);
5133}
5134
Glenn Kasten0f11b512014-01-31 16:18:54 -08005135void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005136{
5137 const size_t SIZE = 256;
5138 char buffer[SIZE];
5139 String8 result;
5140
5141 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5142 result.append(buffer);
5143 RecordTrack::appendDumpHeader(result);
5144 for (size_t i = 0; i < mTracks.size(); ++i) {
5145 sp<RecordTrack> track = mTracks[i];
5146 if (track != 0) {
5147 track->dump(buffer, SIZE);
5148 result.append(buffer);
5149 }
5150 }
5151
Glenn Kasten2b806402013-11-20 16:37:38 -08005152 size_t size = mActiveTracks.size();
5153 if (size > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005154 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5155 result.append(buffer);
5156 RecordTrack::appendDumpHeader(result);
Glenn Kasten2b806402013-11-20 16:37:38 -08005157 for (size_t i = 0; i < size; ++i) {
5158 sp<RecordTrack> track = mActiveTracks[i];
5159 track->dump(buffer, SIZE);
5160 result.append(buffer);
5161 }
Eric Laurent81784c32012-11-19 14:55:58 -08005162
5163 }
5164 write(fd, result.string(), result.size());
5165}
5166
5167// AudioBufferProvider interface
Glenn Kasten0f11b512014-01-31 16:18:54 -08005168status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005169{
Glenn Kasten85948432013-08-19 12:09:05 -07005170 int32_t rear = mRsmpInRear;
5171 int32_t front = mRsmpInFront;
5172 ssize_t filled = rear - front;
5173 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
5174 // 'filled' may be non-contiguous, so return only the first contiguous chunk
5175 front &= mRsmpInFramesP2 - 1;
5176 size_t part1 = mRsmpInFramesP2 - front;
5177 if (part1 > (size_t) filled) {
5178 part1 = filled;
5179 }
5180 size_t ask = buffer->frameCount;
5181 ALOG_ASSERT(ask > 0);
5182 if (part1 > ask) {
5183 part1 = ask;
5184 }
5185 if (part1 == 0) {
5186 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5187 ALOGE("RecordThread::getNextBuffer() starved");
5188 buffer->raw = NULL;
5189 buffer->frameCount = 0;
5190 mRsmpInUnrel = 0;
5191 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005192 }
5193
Glenn Kasten85948432013-08-19 12:09:05 -07005194 buffer->raw = mRsmpInBuffer + front * mChannelCount;
5195 buffer->frameCount = part1;
5196 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005197 return NO_ERROR;
5198}
5199
5200// AudioBufferProvider interface
5201void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5202{
Glenn Kasten85948432013-08-19 12:09:05 -07005203 size_t stepCount = buffer->frameCount;
5204 if (stepCount == 0) {
5205 return;
5206 }
5207 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
5208 mRsmpInUnrel -= stepCount;
5209 mRsmpInFront += stepCount;
5210 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005211 buffer->frameCount = 0;
5212}
5213
5214bool AudioFlinger::RecordThread::checkForNewParameters_l()
5215{
5216 bool reconfig = false;
5217
5218 while (!mNewParameters.isEmpty()) {
5219 status_t status = NO_ERROR;
5220 String8 keyValuePair = mNewParameters[0];
5221 AudioParameter param = AudioParameter(keyValuePair);
5222 int value;
5223 audio_format_t reqFormat = mFormat;
5224 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005225 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005226
5227 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5228 reqSamplingRate = value;
5229 reconfig = true;
5230 }
5231 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005232 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5233 status = BAD_VALUE;
5234 } else {
5235 reqFormat = (audio_format_t) value;
5236 reconfig = true;
5237 }
Eric Laurent81784c32012-11-19 14:55:58 -08005238 }
5239 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005240 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5241 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5242 status = BAD_VALUE;
5243 } else {
5244 reqChannelMask = mask;
5245 reconfig = true;
5246 }
Eric Laurent81784c32012-11-19 14:55:58 -08005247 }
5248 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5249 // do not accept frame count changes if tracks are open as the track buffer
5250 // size depends on frame count and correct behavior would not be guaranteed
5251 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005252 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005253 status = INVALID_OPERATION;
5254 } else {
5255 reconfig = true;
5256 }
5257 }
5258 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5259 // forward device change to effects that have requested to be
5260 // aware of attached audio device.
5261 for (size_t i = 0; i < mEffectChains.size(); i++) {
5262 mEffectChains[i]->setDevice_l(value);
5263 }
5264
5265 // store input device and output device but do not forward output device to audio HAL.
5266 // Note that status is ignored by the caller for output device
5267 // (see AudioFlinger::setParameters()
5268 if (audio_is_output_devices(value)) {
5269 mOutDevice = value;
5270 status = BAD_VALUE;
5271 } else {
5272 mInDevice = value;
5273 // disable AEC and NS if the device is a BT SCO headset supporting those
5274 // pre processings
5275 if (mTracks.size() > 0) {
5276 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5277 mAudioFlinger->btNrecIsOff();
5278 for (size_t i = 0; i < mTracks.size(); i++) {
5279 sp<RecordTrack> track = mTracks[i];
5280 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5281 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5282 }
5283 }
5284 }
5285 }
5286 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5287 mAudioSource != (audio_source_t)value) {
5288 // forward device change to effects that have requested to be
5289 // aware of attached audio device.
5290 for (size_t i = 0; i < mEffectChains.size(); i++) {
5291 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5292 }
5293 mAudioSource = (audio_source_t)value;
5294 }
Glenn Kastene198c362013-08-13 09:13:36 -07005295
Eric Laurent81784c32012-11-19 14:55:58 -08005296 if (status == NO_ERROR) {
5297 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5298 keyValuePair.string());
5299 if (status == INVALID_OPERATION) {
5300 inputStandBy();
5301 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5302 keyValuePair.string());
5303 }
5304 if (reconfig) {
5305 if (status == BAD_VALUE &&
5306 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5307 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005308 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005309 <= (2 * reqSamplingRate)) &&
5310 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5311 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005312 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5313 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005314 status = NO_ERROR;
5315 }
5316 if (status == NO_ERROR) {
5317 readInputParameters();
5318 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5319 }
5320 }
5321 }
5322
5323 mNewParameters.removeAt(0);
5324
5325 mParamStatus = status;
5326 mParamCond.signal();
5327 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5328 // already timed out waiting for the status and will never signal the condition.
5329 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5330 }
5331 return reconfig;
5332}
5333
5334String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5335{
Eric Laurent81784c32012-11-19 14:55:58 -08005336 Mutex::Autolock _l(mLock);
5337 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005338 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005339 }
5340
Glenn Kastend8ea6992013-07-16 14:17:15 -07005341 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5342 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005343 free(s);
5344 return out_s8;
5345}
5346
Glenn Kasten0f11b512014-01-31 16:18:54 -08005347void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005348 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005349 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005350
5351 switch (event) {
5352 case AudioSystem::INPUT_OPENED:
5353 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005354 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005355 desc.samplingRate = mSampleRate;
5356 desc.format = mFormat;
5357 desc.frameCount = mFrameCount;
5358 desc.latency = 0;
5359 param2 = &desc;
5360 break;
5361
5362 case AudioSystem::INPUT_CLOSED:
5363 default:
5364 break;
5365 }
5366 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5367}
5368
5369void AudioFlinger::RecordThread::readInputParameters()
5370{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005371 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005372 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005373 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005374 mRsmpOutBuffer = NULL;
5375 delete mResampler;
5376 mResampler = NULL;
5377
5378 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5379 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005380 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005381 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005382 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5383 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5384 }
Eric Laurent81784c32012-11-19 14:55:58 -08005385 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005386 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5387 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07005388 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5389 // 1 full output buffer, regardless of the alignment of the available input.
5390 mRsmpInFrames = mFrameCount * 3;
5391 mRsmpInFramesP2 = roundup(mRsmpInFrames);
5392 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5393 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5394 mRsmpInFront = 0;
5395 mRsmpInRear = 0;
5396 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005397
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005398 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Glenn Kasten579dd272013-11-08 14:26:14 -08005399 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005400 mResampler->setSampleRate(mSampleRate);
5401 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten85948432013-08-19 12:09:05 -07005402 // resampler always outputs stereo
Glenn Kasten34af0262013-07-30 11:52:39 -07005403 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005404 }
5405 mRsmpInIndex = mFrameCount;
5406}
5407
Glenn Kasten5f972c02014-01-13 09:59:31 -08005408uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005409{
5410 Mutex::Autolock _l(mLock);
5411 if (initCheck() != NO_ERROR) {
5412 return 0;
5413 }
5414
5415 return mInput->stream->get_input_frames_lost(mInput->stream);
5416}
5417
5418uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5419{
5420 Mutex::Autolock _l(mLock);
5421 uint32_t result = 0;
5422 if (getEffectChain_l(sessionId) != 0) {
5423 result = EFFECT_SESSION;
5424 }
5425
5426 for (size_t i = 0; i < mTracks.size(); ++i) {
5427 if (sessionId == mTracks[i]->sessionId()) {
5428 result |= TRACK_SESSION;
5429 break;
5430 }
5431 }
5432
5433 return result;
5434}
5435
5436KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5437{
5438 KeyedVector<int, bool> ids;
5439 Mutex::Autolock _l(mLock);
5440 for (size_t j = 0; j < mTracks.size(); ++j) {
5441 sp<RecordThread::RecordTrack> track = mTracks[j];
5442 int sessionId = track->sessionId();
5443 if (ids.indexOfKey(sessionId) < 0) {
5444 ids.add(sessionId, true);
5445 }
5446 }
5447 return ids;
5448}
5449
5450AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5451{
5452 Mutex::Autolock _l(mLock);
5453 AudioStreamIn *input = mInput;
5454 mInput = NULL;
5455 return input;
5456}
5457
5458// this method must always be called either with ThreadBase mLock held or inside the thread loop
5459audio_stream_t* AudioFlinger::RecordThread::stream() const
5460{
5461 if (mInput == NULL) {
5462 return NULL;
5463 }
5464 return &mInput->stream->common;
5465}
5466
5467status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5468{
5469 // only one chain per input thread
5470 if (mEffectChains.size() != 0) {
5471 return INVALID_OPERATION;
5472 }
5473 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5474
5475 chain->setInBuffer(NULL);
5476 chain->setOutBuffer(NULL);
5477
5478 checkSuspendOnAddEffectChain_l(chain);
5479
5480 mEffectChains.add(chain);
5481
5482 return NO_ERROR;
5483}
5484
5485size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5486{
5487 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5488 ALOGW_IF(mEffectChains.size() != 1,
5489 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5490 chain.get(), mEffectChains.size(), this);
5491 if (mEffectChains.size() == 1) {
5492 mEffectChains.removeAt(0);
5493 }
5494 return 0;
5495}
5496
5497}; // namespace android