blob: d5a0e2162ebe23c1078a6e9eab0eaca5993fecf1 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
188void CpuStats::sample(const String8 &title) {
189#ifdef DEBUG_CPU_USAGE
190 // get current thread's delta CPU time in wall clock ns
191 double wcNs;
192 bool valid = mCpuUsage.sampleAndEnable(wcNs);
193
194 // record sample for wall clock statistics
195 if (valid) {
196 mWcStats.sample(wcNs);
197 }
198
199 // get the current CPU number
200 int cpuNum = sched_getcpu();
201
202 // get the current CPU frequency in kHz
203 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
204
205 // check if either CPU number or frequency changed
206 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
207 mCpuNum = cpuNum;
208 mCpukHz = cpukHz;
209 // ignore sample for purposes of cycles
210 valid = false;
211 }
212
213 // if no change in CPU number or frequency, then record sample for cycle statistics
214 if (valid && mCpukHz > 0) {
215 double cycles = wcNs * cpukHz * 0.000001;
216 mHzStats.sample(cycles);
217 }
218
219 unsigned n = mWcStats.n();
220 // mCpuUsage.elapsed() is expensive, so don't call it every loop
221 if ((n & 127) == 1) {
222 long long elapsed = mCpuUsage.elapsed();
223 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
224 double perLoop = elapsed / (double) n;
225 double perLoop100 = perLoop * 0.01;
226 double perLoop1k = perLoop * 0.001;
227 double mean = mWcStats.mean();
228 double stddev = mWcStats.stddev();
229 double minimum = mWcStats.minimum();
230 double maximum = mWcStats.maximum();
231 double meanCycles = mHzStats.mean();
232 double stddevCycles = mHzStats.stddev();
233 double minCycles = mHzStats.minimum();
234 double maxCycles = mHzStats.maximum();
235 mCpuUsage.resetElapsed();
236 mWcStats.reset();
237 mHzStats.reset();
238 ALOGD("CPU usage for %s over past %.1f secs\n"
239 " (%u mixer loops at %.1f mean ms per loop):\n"
240 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
241 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
242 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
243 title.string(),
244 elapsed * .000000001, n, perLoop * .000001,
245 mean * .001,
246 stddev * .001,
247 minimum * .001,
248 maximum * .001,
249 mean / perLoop100,
250 stddev / perLoop100,
251 minimum / perLoop100,
252 maximum / perLoop100,
253 meanCycles / perLoop1k,
254 stddevCycles / perLoop1k,
255 minCycles / perLoop1k,
256 maxCycles / perLoop1k);
257
258 }
259 }
260#endif
261};
262
263// ----------------------------------------------------------------------------
264// ThreadBase
265// ----------------------------------------------------------------------------
266
267AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
268 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
269 : Thread(false /*canCallJava*/),
270 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700271 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700272 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
273 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800274 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700275 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800276 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
277 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
278 // mName will be set by concrete (non-virtual) subclass
279 mDeathRecipient(new PMDeathRecipient(this))
280{
281}
282
283AudioFlinger::ThreadBase::~ThreadBase()
284{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700285 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
286 for (size_t i = 0; i < mConfigEvents.size(); i++) {
287 delete mConfigEvents[i];
288 }
289 mConfigEvents.clear();
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291 mParamCond.broadcast();
292 // do not lock the mutex in destructor
293 releaseWakeLock_l();
294 if (mPowerManager != 0) {
295 sp<IBinder> binder = mPowerManager->asBinder();
296 binder->unlinkToDeath(mDeathRecipient);
297 }
298}
299
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700300status_t AudioFlinger::ThreadBase::readyToRun()
301{
302 status_t status = initCheck();
303 if (status == NO_ERROR) {
304 ALOGI("AudioFlinger's thread %p ready to run", this);
305 } else {
306 ALOGE("No working audio driver found.");
307 }
308 return status;
309}
310
Eric Laurent81784c32012-11-19 14:55:58 -0800311void AudioFlinger::ThreadBase::exit()
312{
313 ALOGV("ThreadBase::exit");
314 // do any cleanup required for exit to succeed
315 preExit();
316 {
317 // This lock prevents the following race in thread (uniprocessor for illustration):
318 // if (!exitPending()) {
319 // // context switch from here to exit()
320 // // exit() calls requestExit(), what exitPending() observes
321 // // exit() calls signal(), which is dropped since no waiters
322 // // context switch back from exit() to here
323 // mWaitWorkCV.wait(...);
324 // // now thread is hung
325 // }
326 AutoMutex lock(mLock);
327 requestExit();
328 mWaitWorkCV.broadcast();
329 }
330 // When Thread::requestExitAndWait is made virtual and this method is renamed to
331 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
332 requestExitAndWait();
333}
334
335status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
336{
337 status_t status;
338
339 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
340 Mutex::Autolock _l(mLock);
341
342 mNewParameters.add(keyValuePairs);
343 mWaitWorkCV.signal();
344 // wait condition with timeout in case the thread loop has exited
345 // before the request could be processed
346 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
347 status = mParamStatus;
348 mWaitWorkCV.signal();
349 } else {
350 status = TIMED_OUT;
351 }
352 return status;
353}
354
355void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
356{
357 Mutex::Autolock _l(mLock);
358 sendIoConfigEvent_l(event, param);
359}
360
361// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
362void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
363{
364 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
365 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
366 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
367 param);
368 mWaitWorkCV.signal();
369}
370
371// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
372void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
373{
374 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
375 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
376 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
377 mConfigEvents.size(), pid, tid, prio);
378 mWaitWorkCV.signal();
379}
380
381void AudioFlinger::ThreadBase::processConfigEvents()
382{
Glenn Kastenf7773312013-08-13 16:00:42 -0700383 Mutex::Autolock _l(mLock);
384 processConfigEvents_l();
385}
386
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700387// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700388void AudioFlinger::ThreadBase::processConfigEvents_l()
389{
Eric Laurent81784c32012-11-19 14:55:58 -0800390 while (!mConfigEvents.isEmpty()) {
391 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
392 ConfigEvent *event = mConfigEvents[0];
393 mConfigEvents.removeAt(0);
394 // release mLock before locking AudioFlinger mLock: lock order is always
395 // AudioFlinger then ThreadBase to avoid cross deadlock
396 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700397 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700398 case CFG_EVENT_PRIO: {
399 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
400 // FIXME Need to understand why this has be done asynchronously
401 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
402 true /*asynchronous*/);
403 if (err != 0) {
404 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
405 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
406 }
407 } break;
408 case CFG_EVENT_IO: {
409 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700410 {
411 Mutex::Autolock _l(mAudioFlinger->mLock);
412 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
413 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700414 } break;
415 default:
416 ALOGE("processConfigEvents() unknown event type %d", event->type());
417 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800418 }
419 delete event;
420 mLock.lock();
421 }
Eric Laurent81784c32012-11-19 14:55:58 -0800422}
423
424void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
425{
426 const size_t SIZE = 256;
427 char buffer[SIZE];
428 String8 result;
429
430 bool locked = AudioFlinger::dumpTryLock(mLock);
431 if (!locked) {
432 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
433 write(fd, buffer, strlen(buffer));
434 }
435
436 snprintf(buffer, SIZE, "io handle: %d\n", mId);
437 result.append(buffer);
438 snprintf(buffer, SIZE, "TID: %d\n", getTid());
439 result.append(buffer);
440 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
441 result.append(buffer);
442 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
443 result.append(buffer);
444 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
445 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700446 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
447 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700448 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800449 result.append(buffer);
450 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
451 result.append(buffer);
452 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
453 result.append(buffer);
454 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
455 result.append(buffer);
456
457 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
458 result.append(buffer);
459 result.append(" Index Command");
460 for (size_t i = 0; i < mNewParameters.size(); ++i) {
461 snprintf(buffer, SIZE, "\n %02d ", i);
462 result.append(buffer);
463 result.append(mNewParameters[i]);
464 }
465
466 snprintf(buffer, SIZE, "\n\nPending config events: \n");
467 result.append(buffer);
468 for (size_t i = 0; i < mConfigEvents.size(); i++) {
469 mConfigEvents[i]->dump(buffer, SIZE);
470 result.append(buffer);
471 }
472 result.append("\n");
473
474 write(fd, result.string(), result.size());
475
476 if (locked) {
477 mLock.unlock();
478 }
479}
480
481void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
482{
483 const size_t SIZE = 256;
484 char buffer[SIZE];
485 String8 result;
486
487 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
488 write(fd, buffer, strlen(buffer));
489
490 for (size_t i = 0; i < mEffectChains.size(); ++i) {
491 sp<EffectChain> chain = mEffectChains[i];
492 if (chain != 0) {
493 chain->dump(fd, args);
494 }
495 }
496}
497
Marco Nelissene14a5d62013-10-03 08:51:24 -0700498void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800499{
500 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700501 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800502}
503
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100504String16 AudioFlinger::ThreadBase::getWakeLockTag()
505{
506 switch (mType) {
507 case MIXER:
508 return String16("AudioMix");
509 case DIRECT:
510 return String16("AudioDirectOut");
511 case DUPLICATING:
512 return String16("AudioDup");
513 case RECORD:
514 return String16("AudioIn");
515 case OFFLOAD:
516 return String16("AudioOffload");
517 default:
518 ALOG_ASSERT(false);
519 return String16("AudioUnknown");
520 }
521}
522
Marco Nelissene14a5d62013-10-03 08:51:24 -0700523void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800524{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800525 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800526 if (mPowerManager != 0) {
527 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700528 status_t status;
529 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700530 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700531 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100532 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700533 String16("media"),
534 uid);
535 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700536 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700537 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100538 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700539 String16("media"));
540 }
Eric Laurent81784c32012-11-19 14:55:58 -0800541 if (status == NO_ERROR) {
542 mWakeLockToken = binder;
543 }
544 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
545 }
546}
547
548void AudioFlinger::ThreadBase::releaseWakeLock()
549{
550 Mutex::Autolock _l(mLock);
551 releaseWakeLock_l();
552}
553
554void AudioFlinger::ThreadBase::releaseWakeLock_l()
555{
556 if (mWakeLockToken != 0) {
557 ALOGV("releaseWakeLock_l() %s", mName);
558 if (mPowerManager != 0) {
559 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
560 }
561 mWakeLockToken.clear();
562 }
563}
564
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800565void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
566 Mutex::Autolock _l(mLock);
567 updateWakeLockUids_l(uids);
568}
569
570void AudioFlinger::ThreadBase::getPowerManager_l() {
571
572 if (mPowerManager == 0) {
573 // use checkService() to avoid blocking if power service is not up yet
574 sp<IBinder> binder =
575 defaultServiceManager()->checkService(String16("power"));
576 if (binder == 0) {
577 ALOGW("Thread %s cannot connect to the power manager service", mName);
578 } else {
579 mPowerManager = interface_cast<IPowerManager>(binder);
580 binder->linkToDeath(mDeathRecipient);
581 }
582 }
583}
584
585void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
586
587 getPowerManager_l();
588 if (mWakeLockToken == NULL) {
589 ALOGE("no wake lock to update!");
590 return;
591 }
592 if (mPowerManager != 0) {
593 sp<IBinder> binder = new BBinder();
594 status_t status;
595 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
596 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
597 }
598}
599
Eric Laurent81784c32012-11-19 14:55:58 -0800600void AudioFlinger::ThreadBase::clearPowerManager()
601{
602 Mutex::Autolock _l(mLock);
603 releaseWakeLock_l();
604 mPowerManager.clear();
605}
606
607void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
608{
609 sp<ThreadBase> thread = mThread.promote();
610 if (thread != 0) {
611 thread->clearPowerManager();
612 }
613 ALOGW("power manager service died !!!");
614}
615
616void AudioFlinger::ThreadBase::setEffectSuspended(
617 const effect_uuid_t *type, bool suspend, int sessionId)
618{
619 Mutex::Autolock _l(mLock);
620 setEffectSuspended_l(type, suspend, sessionId);
621}
622
623void AudioFlinger::ThreadBase::setEffectSuspended_l(
624 const effect_uuid_t *type, bool suspend, int sessionId)
625{
626 sp<EffectChain> chain = getEffectChain_l(sessionId);
627 if (chain != 0) {
628 if (type != NULL) {
629 chain->setEffectSuspended_l(type, suspend);
630 } else {
631 chain->setEffectSuspendedAll_l(suspend);
632 }
633 }
634
635 updateSuspendedSessions_l(type, suspend, sessionId);
636}
637
638void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
639{
640 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
641 if (index < 0) {
642 return;
643 }
644
645 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
646 mSuspendedSessions.valueAt(index);
647
648 for (size_t i = 0; i < sessionEffects.size(); i++) {
649 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
650 for (int j = 0; j < desc->mRefCount; j++) {
651 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
652 chain->setEffectSuspendedAll_l(true);
653 } else {
654 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
655 desc->mType.timeLow);
656 chain->setEffectSuspended_l(&desc->mType, true);
657 }
658 }
659 }
660}
661
662void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
663 bool suspend,
664 int sessionId)
665{
666 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
667
668 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
669
670 if (suspend) {
671 if (index >= 0) {
672 sessionEffects = mSuspendedSessions.valueAt(index);
673 } else {
674 mSuspendedSessions.add(sessionId, sessionEffects);
675 }
676 } else {
677 if (index < 0) {
678 return;
679 }
680 sessionEffects = mSuspendedSessions.valueAt(index);
681 }
682
683
684 int key = EffectChain::kKeyForSuspendAll;
685 if (type != NULL) {
686 key = type->timeLow;
687 }
688 index = sessionEffects.indexOfKey(key);
689
690 sp<SuspendedSessionDesc> desc;
691 if (suspend) {
692 if (index >= 0) {
693 desc = sessionEffects.valueAt(index);
694 } else {
695 desc = new SuspendedSessionDesc();
696 if (type != NULL) {
697 desc->mType = *type;
698 }
699 sessionEffects.add(key, desc);
700 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
701 }
702 desc->mRefCount++;
703 } else {
704 if (index < 0) {
705 return;
706 }
707 desc = sessionEffects.valueAt(index);
708 if (--desc->mRefCount == 0) {
709 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
710 sessionEffects.removeItemsAt(index);
711 if (sessionEffects.isEmpty()) {
712 ALOGV("updateSuspendedSessions_l() restore removing session %d",
713 sessionId);
714 mSuspendedSessions.removeItem(sessionId);
715 }
716 }
717 }
718 if (!sessionEffects.isEmpty()) {
719 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
720 }
721}
722
723void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
724 bool enabled,
725 int sessionId)
726{
727 Mutex::Autolock _l(mLock);
728 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
729}
730
731void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
732 bool enabled,
733 int sessionId)
734{
735 if (mType != RECORD) {
736 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
737 // another session. This gives the priority to well behaved effect control panels
738 // and applications not using global effects.
739 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
740 // global effects
741 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
742 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
743 }
744 }
745
746 sp<EffectChain> chain = getEffectChain_l(sessionId);
747 if (chain != 0) {
748 chain->checkSuspendOnEffectEnabled(effect, enabled);
749 }
750}
751
752// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
753sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
754 const sp<AudioFlinger::Client>& client,
755 const sp<IEffectClient>& effectClient,
756 int32_t priority,
757 int sessionId,
758 effect_descriptor_t *desc,
759 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700760 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800761{
762 sp<EffectModule> effect;
763 sp<EffectHandle> handle;
764 status_t lStatus;
765 sp<EffectChain> chain;
766 bool chainCreated = false;
767 bool effectCreated = false;
768 bool effectRegistered = false;
769
770 lStatus = initCheck();
771 if (lStatus != NO_ERROR) {
772 ALOGW("createEffect_l() Audio driver not initialized.");
773 goto Exit;
774 }
775
Eric Laurent5baf2af2013-09-12 17:37:00 -0700776 // Allow global effects only on offloaded and mixer threads
777 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
778 switch (mType) {
779 case MIXER:
780 case OFFLOAD:
781 break;
782 case DIRECT:
783 case DUPLICATING:
784 case RECORD:
785 default:
786 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
787 lStatus = BAD_VALUE;
788 goto Exit;
789 }
Eric Laurent81784c32012-11-19 14:55:58 -0800790 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700791
Eric Laurent81784c32012-11-19 14:55:58 -0800792 // Only Pre processor effects are allowed on input threads and only on input threads
793 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
794 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
795 desc->name, desc->flags, mType);
796 lStatus = BAD_VALUE;
797 goto Exit;
798 }
799
800 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
801
802 { // scope for mLock
803 Mutex::Autolock _l(mLock);
804
805 // check for existing effect chain with the requested audio session
806 chain = getEffectChain_l(sessionId);
807 if (chain == 0) {
808 // create a new chain for this session
809 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
810 chain = new EffectChain(this, sessionId);
811 addEffectChain_l(chain);
812 chain->setStrategy(getStrategyForSession_l(sessionId));
813 chainCreated = true;
814 } else {
815 effect = chain->getEffectFromDesc_l(desc);
816 }
817
818 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
819
820 if (effect == 0) {
821 int id = mAudioFlinger->nextUniqueId();
822 // Check CPU and memory usage
823 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
824 if (lStatus != NO_ERROR) {
825 goto Exit;
826 }
827 effectRegistered = true;
828 // create a new effect module if none present in the chain
829 effect = new EffectModule(this, chain, desc, id, sessionId);
830 lStatus = effect->status();
831 if (lStatus != NO_ERROR) {
832 goto Exit;
833 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700834 effect->setOffloaded(mType == OFFLOAD, mId);
835
Eric Laurent81784c32012-11-19 14:55:58 -0800836 lStatus = chain->addEffect_l(effect);
837 if (lStatus != NO_ERROR) {
838 goto Exit;
839 }
840 effectCreated = true;
841
842 effect->setDevice(mOutDevice);
843 effect->setDevice(mInDevice);
844 effect->setMode(mAudioFlinger->getMode());
845 effect->setAudioSource(mAudioSource);
846 }
847 // create effect handle and connect it to effect module
848 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800849 lStatus = handle->initCheck();
850 if (lStatus == OK) {
851 lStatus = effect->addHandle(handle.get());
852 }
Eric Laurent81784c32012-11-19 14:55:58 -0800853 if (enabled != NULL) {
854 *enabled = (int)effect->isEnabled();
855 }
856 }
857
858Exit:
859 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
860 Mutex::Autolock _l(mLock);
861 if (effectCreated) {
862 chain->removeEffect_l(effect);
863 }
864 if (effectRegistered) {
865 AudioSystem::unregisterEffect(effect->id());
866 }
867 if (chainCreated) {
868 removeEffectChain_l(chain);
869 }
870 handle.clear();
871 }
872
Glenn Kasten9156ef32013-08-06 15:39:08 -0700873 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800874 return handle;
875}
876
877sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
878{
879 Mutex::Autolock _l(mLock);
880 return getEffect_l(sessionId, effectId);
881}
882
883sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
884{
885 sp<EffectChain> chain = getEffectChain_l(sessionId);
886 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
887}
888
889// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
890// PlaybackThread::mLock held
891status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
892{
893 // check for existing effect chain with the requested audio session
894 int sessionId = effect->sessionId();
895 sp<EffectChain> chain = getEffectChain_l(sessionId);
896 bool chainCreated = false;
897
Eric Laurent5baf2af2013-09-12 17:37:00 -0700898 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
899 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
900 this, effect->desc().name, effect->desc().flags);
901
Eric Laurent81784c32012-11-19 14:55:58 -0800902 if (chain == 0) {
903 // create a new chain for this session
904 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
905 chain = new EffectChain(this, sessionId);
906 addEffectChain_l(chain);
907 chain->setStrategy(getStrategyForSession_l(sessionId));
908 chainCreated = true;
909 }
910 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
911
912 if (chain->getEffectFromId_l(effect->id()) != 0) {
913 ALOGW("addEffect_l() %p effect %s already present in chain %p",
914 this, effect->desc().name, chain.get());
915 return BAD_VALUE;
916 }
917
Eric Laurent5baf2af2013-09-12 17:37:00 -0700918 effect->setOffloaded(mType == OFFLOAD, mId);
919
Eric Laurent81784c32012-11-19 14:55:58 -0800920 status_t status = chain->addEffect_l(effect);
921 if (status != NO_ERROR) {
922 if (chainCreated) {
923 removeEffectChain_l(chain);
924 }
925 return status;
926 }
927
928 effect->setDevice(mOutDevice);
929 effect->setDevice(mInDevice);
930 effect->setMode(mAudioFlinger->getMode());
931 effect->setAudioSource(mAudioSource);
932 return NO_ERROR;
933}
934
935void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
936
937 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
938 effect_descriptor_t desc = effect->desc();
939 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
940 detachAuxEffect_l(effect->id());
941 }
942
943 sp<EffectChain> chain = effect->chain().promote();
944 if (chain != 0) {
945 // remove effect chain if removing last effect
946 if (chain->removeEffect_l(effect) == 0) {
947 removeEffectChain_l(chain);
948 }
949 } else {
950 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
951 }
952}
953
954void AudioFlinger::ThreadBase::lockEffectChains_l(
955 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
956{
957 effectChains = mEffectChains;
958 for (size_t i = 0; i < mEffectChains.size(); i++) {
959 mEffectChains[i]->lock();
960 }
961}
962
963void AudioFlinger::ThreadBase::unlockEffectChains(
964 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
965{
966 for (size_t i = 0; i < effectChains.size(); i++) {
967 effectChains[i]->unlock();
968 }
969}
970
971sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
972{
973 Mutex::Autolock _l(mLock);
974 return getEffectChain_l(sessionId);
975}
976
977sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
978{
979 size_t size = mEffectChains.size();
980 for (size_t i = 0; i < size; i++) {
981 if (mEffectChains[i]->sessionId() == sessionId) {
982 return mEffectChains[i];
983 }
984 }
985 return 0;
986}
987
988void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
989{
990 Mutex::Autolock _l(mLock);
991 size_t size = mEffectChains.size();
992 for (size_t i = 0; i < size; i++) {
993 mEffectChains[i]->setMode_l(mode);
994 }
995}
996
997void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
998 EffectHandle *handle,
999 bool unpinIfLast) {
1000
1001 Mutex::Autolock _l(mLock);
1002 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1003 // delete the effect module if removing last handle on it
1004 if (effect->removeHandle(handle) == 0) {
1005 if (!effect->isPinned() || unpinIfLast) {
1006 removeEffect_l(effect);
1007 AudioSystem::unregisterEffect(effect->id());
1008 }
1009 }
1010}
1011
1012// ----------------------------------------------------------------------------
1013// Playback
1014// ----------------------------------------------------------------------------
1015
1016AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1017 AudioStreamOut* output,
1018 audio_io_handle_t id,
1019 audio_devices_t device,
1020 type_t type)
1021 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001022 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001023 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001024 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001025 // mStreamTypes[] initialized in constructor body
1026 mOutput(output),
1027 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1028 mMixerStatus(MIXER_IDLE),
1029 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1030 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001031 mBytesRemaining(0),
1032 mCurrentWriteLength(0),
1033 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001034 mWriteAckSequence(0),
1035 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001036 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001037 mScreenState(AudioFlinger::mScreenState),
1038 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001039 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1040 // mLatchD, mLatchQ,
1041 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
1043 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001044 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001045
1046 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1047 // it would be safer to explicitly pass initial masterVolume/masterMute as
1048 // parameter.
1049 //
1050 // If the HAL we are using has support for master volume or master mute,
1051 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1052 // and the mute set to false).
1053 mMasterVolume = audioFlinger->masterVolume_l();
1054 mMasterMute = audioFlinger->masterMute_l();
1055 if (mOutput && mOutput->audioHwDev) {
1056 if (mOutput->audioHwDev->canSetMasterVolume()) {
1057 mMasterVolume = 1.0;
1058 }
1059
1060 if (mOutput->audioHwDev->canSetMasterMute()) {
1061 mMasterMute = false;
1062 }
1063 }
1064
1065 readOutputParameters();
1066
1067 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1068 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1069 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1070 stream = (audio_stream_type_t) (stream + 1)) {
1071 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1072 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1073 }
1074 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1075 // because mAudioFlinger doesn't have one to copy from
1076}
1077
1078AudioFlinger::PlaybackThread::~PlaybackThread()
1079{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001080 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001081 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001082}
1083
1084void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1085{
1086 dumpInternals(fd, args);
1087 dumpTracks(fd, args);
1088 dumpEffectChains(fd, args);
1089}
1090
1091void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1092{
1093 const size_t SIZE = 256;
1094 char buffer[SIZE];
1095 String8 result;
1096
1097 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1098 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1099 const stream_type_t *st = &mStreamTypes[i];
1100 if (i > 0) {
1101 result.appendFormat(", ");
1102 }
1103 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1104 if (st->mute) {
1105 result.append("M");
1106 }
1107 }
1108 result.append("\n");
1109 write(fd, result.string(), result.length());
1110 result.clear();
1111
1112 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1113 result.append(buffer);
1114 Track::appendDumpHeader(result);
1115 for (size_t i = 0; i < mTracks.size(); ++i) {
1116 sp<Track> track = mTracks[i];
1117 if (track != 0) {
1118 track->dump(buffer, SIZE);
1119 result.append(buffer);
1120 }
1121 }
1122
1123 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1124 result.append(buffer);
1125 Track::appendDumpHeader(result);
1126 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1127 sp<Track> track = mActiveTracks[i].promote();
1128 if (track != 0) {
1129 track->dump(buffer, SIZE);
1130 result.append(buffer);
1131 }
1132 }
1133 write(fd, result.string(), result.size());
1134
1135 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1136 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1137 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1138 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1139}
1140
1141void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1142{
1143 const size_t SIZE = 256;
1144 char buffer[SIZE];
1145 String8 result;
1146
1147 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1148 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001149 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1150 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001151 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1152 ns2ms(systemTime() - mLastWriteTime));
1153 result.append(buffer);
1154 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1155 result.append(buffer);
1156 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1157 result.append(buffer);
1158 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1159 result.append(buffer);
1160 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1161 result.append(buffer);
1162 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1163 result.append(buffer);
1164 write(fd, result.string(), result.size());
1165 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1166
1167 dumpBase(fd, args);
1168}
1169
1170// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001171
1172void AudioFlinger::PlaybackThread::onFirstRef()
1173{
1174 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1175}
1176
1177// ThreadBase virtuals
1178void AudioFlinger::PlaybackThread::preExit()
1179{
1180 ALOGV(" preExit()");
1181 // FIXME this is using hard-coded strings but in the future, this functionality will be
1182 // converted to use audio HAL extensions required to support tunneling
1183 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1184}
1185
1186// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1187sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1188 const sp<AudioFlinger::Client>& client,
1189 audio_stream_type_t streamType,
1190 uint32_t sampleRate,
1191 audio_format_t format,
1192 audio_channel_mask_t channelMask,
1193 size_t frameCount,
1194 const sp<IMemory>& sharedBuffer,
1195 int sessionId,
1196 IAudioFlinger::track_flags_t *flags,
1197 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001198 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001199 status_t *status)
1200{
1201 sp<Track> track;
1202 status_t lStatus;
1203
1204 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1205
1206 // client expresses a preference for FAST, but we get the final say
1207 if (*flags & IAudioFlinger::TRACK_FAST) {
1208 if (
1209 // not timed
1210 (!isTimed) &&
1211 // either of these use cases:
1212 (
1213 // use case 1: shared buffer with any frame count
1214 (
1215 (sharedBuffer != 0)
1216 ) ||
1217 // use case 2: callback handler and frame count is default or at least as large as HAL
1218 (
1219 (tid != -1) &&
1220 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001221 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001222 )
1223 ) &&
1224 // PCM data
1225 audio_is_linear_pcm(format) &&
1226 // mono or stereo
1227 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1228 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1229#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1230 // hardware sample rate
1231 (sampleRate == mSampleRate) &&
1232#endif
1233 // normal mixer has an associated fast mixer
1234 hasFastMixer() &&
1235 // there are sufficient fast track slots available
1236 (mFastTrackAvailMask != 0)
1237 // FIXME test that MixerThread for this fast track has a capable output HAL
1238 // FIXME add a permission test also?
1239 ) {
1240 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1241 if (frameCount == 0) {
1242 frameCount = mFrameCount * kFastTrackMultiplier;
1243 }
1244 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1245 frameCount, mFrameCount);
1246 } else {
1247 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1248 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1249 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1250 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1251 audio_is_linear_pcm(format),
1252 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1253 *flags &= ~IAudioFlinger::TRACK_FAST;
1254 // For compatibility with AudioTrack calculation, buffer depth is forced
1255 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1256 // This is probably too conservative, but legacy application code may depend on it.
1257 // If you change this calculation, also review the start threshold which is related.
1258 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1259 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1260 if (minBufCount < 2) {
1261 minBufCount = 2;
1262 }
1263 size_t minFrameCount = mNormalFrameCount * minBufCount;
1264 if (frameCount < minFrameCount) {
1265 frameCount = minFrameCount;
1266 }
1267 }
1268 }
1269
1270 if (mType == DIRECT) {
1271 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1272 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1273 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1274 "for output %p with format %d",
1275 sampleRate, format, channelMask, mOutput, mFormat);
1276 lStatus = BAD_VALUE;
1277 goto Exit;
1278 }
1279 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001280 } else if (mType == OFFLOAD) {
1281 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1282 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1283 "for output %p with format %d",
1284 sampleRate, format, channelMask, mOutput, mFormat);
1285 lStatus = BAD_VALUE;
1286 goto Exit;
1287 }
Eric Laurent81784c32012-11-19 14:55:58 -08001288 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001289 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1290 ALOGE("createTrack_l() Bad parameter: format %d \""
1291 "for output %p with format %d",
1292 format, mOutput, mFormat);
1293 lStatus = BAD_VALUE;
1294 goto Exit;
1295 }
Eric Laurent81784c32012-11-19 14:55:58 -08001296 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1297 if (sampleRate > mSampleRate*2) {
1298 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1299 lStatus = BAD_VALUE;
1300 goto Exit;
1301 }
1302 }
1303
1304 lStatus = initCheck();
1305 if (lStatus != NO_ERROR) {
1306 ALOGE("Audio driver not initialized.");
1307 goto Exit;
1308 }
1309
1310 { // scope for mLock
1311 Mutex::Autolock _l(mLock);
1312
1313 // all tracks in same audio session must share the same routing strategy otherwise
1314 // conflicts will happen when tracks are moved from one output to another by audio policy
1315 // manager
1316 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1317 for (size_t i = 0; i < mTracks.size(); ++i) {
1318 sp<Track> t = mTracks[i];
1319 if (t != 0 && !t->isOutputTrack()) {
1320 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1321 if (sessionId == t->sessionId() && strategy != actual) {
1322 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1323 strategy, actual);
1324 lStatus = BAD_VALUE;
1325 goto Exit;
1326 }
1327 }
1328 }
1329
1330 if (!isTimed) {
1331 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001332 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001333 } else {
1334 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001335 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001336 }
Glenn Kasten03003332013-08-06 15:40:54 -07001337
1338 // new Track always returns non-NULL,
1339 // but TimedTrack::create() is a factory that could fail by returning NULL
1340 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1341 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001342 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07001343 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001344 goto Exit;
1345 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001346
Eric Laurent81784c32012-11-19 14:55:58 -08001347 mTracks.add(track);
1348
1349 sp<EffectChain> chain = getEffectChain_l(sessionId);
1350 if (chain != 0) {
1351 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1352 track->setMainBuffer(chain->inBuffer());
1353 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1354 chain->incTrackCnt();
1355 }
1356
1357 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1358 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1359 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1360 // so ask activity manager to do this on our behalf
1361 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1362 }
1363 }
1364
1365 lStatus = NO_ERROR;
1366
1367Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001368 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001369 return track;
1370}
1371
1372uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1373{
1374 return latency;
1375}
1376
1377uint32_t AudioFlinger::PlaybackThread::latency() const
1378{
1379 Mutex::Autolock _l(mLock);
1380 return latency_l();
1381}
1382uint32_t AudioFlinger::PlaybackThread::latency_l() const
1383{
1384 if (initCheck() == NO_ERROR) {
1385 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1386 } else {
1387 return 0;
1388 }
1389}
1390
1391void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1392{
1393 Mutex::Autolock _l(mLock);
1394 // Don't apply master volume in SW if our HAL can do it for us.
1395 if (mOutput && mOutput->audioHwDev &&
1396 mOutput->audioHwDev->canSetMasterVolume()) {
1397 mMasterVolume = 1.0;
1398 } else {
1399 mMasterVolume = value;
1400 }
1401}
1402
1403void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1404{
1405 Mutex::Autolock _l(mLock);
1406 // Don't apply master mute in SW if our HAL can do it for us.
1407 if (mOutput && mOutput->audioHwDev &&
1408 mOutput->audioHwDev->canSetMasterMute()) {
1409 mMasterMute = false;
1410 } else {
1411 mMasterMute = muted;
1412 }
1413}
1414
1415void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1416{
1417 Mutex::Autolock _l(mLock);
1418 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001419 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001420}
1421
1422void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1423{
1424 Mutex::Autolock _l(mLock);
1425 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001426 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001427}
1428
1429float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1430{
1431 Mutex::Autolock _l(mLock);
1432 return mStreamTypes[stream].volume;
1433}
1434
1435// addTrack_l() must be called with ThreadBase::mLock held
1436status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1437{
1438 status_t status = ALREADY_EXISTS;
1439
1440 // set retry count for buffer fill
1441 track->mRetryCount = kMaxTrackStartupRetries;
1442 if (mActiveTracks.indexOf(track) < 0) {
1443 // the track is newly added, make sure it fills up all its
1444 // buffers before playing. This is to ensure the client will
1445 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001446 if (!track->isOutputTrack()) {
1447 TrackBase::track_state state = track->mState;
1448 mLock.unlock();
1449 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1450 mLock.lock();
1451 // abort track was stopped/paused while we released the lock
1452 if (state != track->mState) {
1453 if (status == NO_ERROR) {
1454 mLock.unlock();
1455 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1456 mLock.lock();
1457 }
1458 return INVALID_OPERATION;
1459 }
1460 // abort if start is rejected by audio policy manager
1461 if (status != NO_ERROR) {
1462 return PERMISSION_DENIED;
1463 }
1464#ifdef ADD_BATTERY_DATA
1465 // to track the speaker usage
1466 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1467#endif
1468 }
1469
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001470 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001471 track->mResetDone = false;
1472 track->mPresentationCompleteFrames = 0;
1473 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001474 mWakeLockUids.add(track->uid());
1475 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001476 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001477 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1478 if (chain != 0) {
1479 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1480 track->sessionId());
1481 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001482 }
1483
1484 status = NO_ERROR;
1485 }
1486
Eric Laurentede6c3b2013-09-19 14:37:46 -07001487 ALOGV("signal playback thread");
1488 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001489
1490 return status;
1491}
1492
Eric Laurentbfb1b832013-01-07 09:53:42 -08001493bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001494{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001496 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001497 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1498 track->mState = TrackBase::STOPPED;
1499 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001501 } else if (track->isFastTrack() || track->isOffloaded()) {
1502 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001503 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001504
1505 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001506}
1507
1508void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1509{
1510 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1511 mTracks.remove(track);
1512 deleteTrackName_l(track->name());
1513 // redundant as track is about to be destroyed, for dumpsys only
1514 track->mName = -1;
1515 if (track->isFastTrack()) {
1516 int index = track->mFastIndex;
1517 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1518 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1519 mFastTrackAvailMask |= 1 << index;
1520 // redundant as track is about to be destroyed, for dumpsys only
1521 track->mFastIndex = -1;
1522 }
1523 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1524 if (chain != 0) {
1525 chain->decTrackCnt();
1526 }
1527}
1528
Eric Laurentede6c3b2013-09-19 14:37:46 -07001529void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001530{
1531 // Thread could be blocked waiting for async
1532 // so signal it to handle state changes immediately
1533 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1534 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1535 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001536 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001537}
1538
Eric Laurent81784c32012-11-19 14:55:58 -08001539String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1540{
Eric Laurent81784c32012-11-19 14:55:58 -08001541 Mutex::Autolock _l(mLock);
1542 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001543 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001544 }
1545
Glenn Kastend8ea6992013-07-16 14:17:15 -07001546 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1547 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001548 free(s);
1549 return out_s8;
1550}
1551
1552// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1553void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1554 AudioSystem::OutputDescriptor desc;
1555 void *param2 = NULL;
1556
1557 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1558 param);
1559
1560 switch (event) {
1561 case AudioSystem::OUTPUT_OPENED:
1562 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001563 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001564 desc.samplingRate = mSampleRate;
1565 desc.format = mFormat;
1566 desc.frameCount = mNormalFrameCount; // FIXME see
1567 // AudioFlinger::frameCount(audio_io_handle_t)
1568 desc.latency = latency();
1569 param2 = &desc;
1570 break;
1571
1572 case AudioSystem::STREAM_CONFIG_CHANGED:
1573 param2 = &param;
1574 case AudioSystem::OUTPUT_CLOSED:
1575 default:
1576 break;
1577 }
1578 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1579}
1580
Eric Laurentbfb1b832013-01-07 09:53:42 -08001581void AudioFlinger::PlaybackThread::writeCallback()
1582{
1583 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001584 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585}
1586
1587void AudioFlinger::PlaybackThread::drainCallback()
1588{
1589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001590 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001591}
1592
Eric Laurent3b4529e2013-09-05 18:09:19 -07001593void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001594{
1595 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001596 // reject out of sequence requests
1597 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1598 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001599 mWaitWorkCV.signal();
1600 }
1601}
1602
Eric Laurent3b4529e2013-09-05 18:09:19 -07001603void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001604{
1605 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001606 // reject out of sequence requests
1607 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1608 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001609 mWaitWorkCV.signal();
1610 }
1611}
1612
1613// static
1614int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1615 void *param,
1616 void *cookie)
1617{
1618 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1619 ALOGV("asyncCallback() event %d", event);
1620 switch (event) {
1621 case STREAM_CBK_EVENT_WRITE_READY:
1622 me->writeCallback();
1623 break;
1624 case STREAM_CBK_EVENT_DRAIN_READY:
1625 me->drainCallback();
1626 break;
1627 default:
1628 ALOGW("asyncCallback() unknown event %d", event);
1629 break;
1630 }
1631 return 0;
1632}
1633
Eric Laurent81784c32012-11-19 14:55:58 -08001634void AudioFlinger::PlaybackThread::readOutputParameters()
1635{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001636 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001637 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1638 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001639 if (!audio_is_output_channel(mChannelMask)) {
1640 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1641 }
1642 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1643 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1644 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1645 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001646 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001647 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001648 if (!audio_is_valid_format(mFormat)) {
1649 LOG_FATAL("HAL format %d not valid for output", mFormat);
1650 }
1651 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1652 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1653 mFormat);
1654 }
Eric Laurent81784c32012-11-19 14:55:58 -08001655 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001656 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1657 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001658 if (mFrameCount & 15) {
1659 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1660 mFrameCount);
1661 }
1662
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1664 (mOutput->stream->set_callback != NULL)) {
1665 if (mOutput->stream->set_callback(mOutput->stream,
1666 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1667 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001668 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669 }
1670 }
1671
Eric Laurent81784c32012-11-19 14:55:58 -08001672 // Calculate size of normal mix buffer relative to the HAL output buffer size
1673 double multiplier = 1.0;
1674 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1675 kUseFastMixer == FastMixer_Dynamic)) {
1676 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1677 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1678 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1679 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1680 maxNormalFrameCount = maxNormalFrameCount & ~15;
1681 if (maxNormalFrameCount < minNormalFrameCount) {
1682 maxNormalFrameCount = minNormalFrameCount;
1683 }
1684 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1685 if (multiplier <= 1.0) {
1686 multiplier = 1.0;
1687 } else if (multiplier <= 2.0) {
1688 if (2 * mFrameCount <= maxNormalFrameCount) {
1689 multiplier = 2.0;
1690 } else {
1691 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1692 }
1693 } else {
1694 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1695 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1696 // track, but we sometimes have to do this to satisfy the maximum frame count
1697 // constraint)
1698 // FIXME this rounding up should not be done if no HAL SRC
1699 uint32_t truncMult = (uint32_t) multiplier;
1700 if ((truncMult & 1)) {
1701 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1702 ++truncMult;
1703 }
1704 }
1705 multiplier = (double) truncMult;
1706 }
1707 }
1708 mNormalFrameCount = multiplier * mFrameCount;
1709 // round up to nearest 16 frames to satisfy AudioMixer
1710 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1711 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1712 mNormalFrameCount);
1713
Glenn Kastenc1fac192013-08-06 07:41:36 -07001714 delete[] mMixBuffer;
1715 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1716 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1717 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1718 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001719
1720 // force reconfiguration of effect chains and engines to take new buffer size and audio
1721 // parameters into account
1722 // Note that mLock is not held when readOutputParameters() is called from the constructor
1723 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1724 // matter.
1725 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1726 Vector< sp<EffectChain> > effectChains = mEffectChains;
1727 for (size_t i = 0; i < effectChains.size(); i ++) {
1728 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1729 }
1730}
1731
1732
1733status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1734{
1735 if (halFrames == NULL || dspFrames == NULL) {
1736 return BAD_VALUE;
1737 }
1738 Mutex::Autolock _l(mLock);
1739 if (initCheck() != NO_ERROR) {
1740 return INVALID_OPERATION;
1741 }
1742 size_t framesWritten = mBytesWritten / mFrameSize;
1743 *halFrames = framesWritten;
1744
1745 if (isSuspended()) {
1746 // return an estimation of rendered frames when the output is suspended
1747 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1748 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1749 return NO_ERROR;
1750 } else {
1751 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1752 }
1753}
1754
1755uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1756{
1757 Mutex::Autolock _l(mLock);
1758 uint32_t result = 0;
1759 if (getEffectChain_l(sessionId) != 0) {
1760 result = EFFECT_SESSION;
1761 }
1762
1763 for (size_t i = 0; i < mTracks.size(); ++i) {
1764 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001765 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001766 result |= TRACK_SESSION;
1767 break;
1768 }
1769 }
1770
1771 return result;
1772}
1773
1774uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1775{
1776 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1777 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1778 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1779 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1780 }
1781 for (size_t i = 0; i < mTracks.size(); i++) {
1782 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001783 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001784 return AudioSystem::getStrategyForStream(track->streamType());
1785 }
1786 }
1787 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1788}
1789
1790
1791AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1792{
1793 Mutex::Autolock _l(mLock);
1794 return mOutput;
1795}
1796
1797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1798{
1799 Mutex::Autolock _l(mLock);
1800 AudioStreamOut *output = mOutput;
1801 mOutput = NULL;
1802 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1803 // must push a NULL and wait for ack
1804 mOutputSink.clear();
1805 mPipeSink.clear();
1806 mNormalSink.clear();
1807 return output;
1808}
1809
1810// this method must always be called either with ThreadBase mLock held or inside the thread loop
1811audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1812{
1813 if (mOutput == NULL) {
1814 return NULL;
1815 }
1816 return &mOutput->stream->common;
1817}
1818
1819uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1820{
1821 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1822}
1823
1824status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1825{
1826 if (!isValidSyncEvent(event)) {
1827 return BAD_VALUE;
1828 }
1829
1830 Mutex::Autolock _l(mLock);
1831
1832 for (size_t i = 0; i < mTracks.size(); ++i) {
1833 sp<Track> track = mTracks[i];
1834 if (event->triggerSession() == track->sessionId()) {
1835 (void) track->setSyncEvent(event);
1836 return NO_ERROR;
1837 }
1838 }
1839
1840 return NAME_NOT_FOUND;
1841}
1842
1843bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1844{
1845 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1846}
1847
1848void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1849 const Vector< sp<Track> >& tracksToRemove)
1850{
1851 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001852 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001853 for (size_t i = 0 ; i < count ; i++) {
1854 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001856 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857#ifdef ADD_BATTERY_DATA
1858 // to track the speaker usage
1859 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1860#endif
1861 if (track->isTerminated()) {
1862 AudioSystem::releaseOutput(mId);
1863 }
Eric Laurent81784c32012-11-19 14:55:58 -08001864 }
1865 }
1866 }
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869void AudioFlinger::PlaybackThread::checkSilentMode_l()
1870{
1871 if (!mMasterMute) {
1872 char value[PROPERTY_VALUE_MAX];
1873 if (property_get("ro.audio.silent", value, "0") > 0) {
1874 char *endptr;
1875 unsigned long ul = strtoul(value, &endptr, 0);
1876 if (*endptr == '\0' && ul != 0) {
1877 ALOGD("Silence is golden");
1878 // The setprop command will not allow a property to be changed after
1879 // the first time it is set, so we don't have to worry about un-muting.
1880 setMasterMute_l(true);
1881 }
1882 }
1883 }
1884}
1885
1886// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001887ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
1889 // FIXME rewrite to reduce number of system calls
1890 mLastWriteTime = systemTime();
1891 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001893
1894 // If an NBAIO sink is present, use it to write the normal mixer's submix
1895 if (mNormalSink != 0) {
1896#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001897 size_t count = mBytesRemaining >> mBitShift;
1898 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001899 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001900 // update the setpoint when AudioFlinger::mScreenState changes
1901 uint32_t screenState = AudioFlinger::mScreenState;
1902 if (screenState != mScreenState) {
1903 mScreenState = screenState;
1904 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1905 if (pipe != NULL) {
1906 pipe->setAvgFrames((mScreenState & 1) ?
1907 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1908 }
1909 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001910 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001911 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001912 if (framesWritten > 0) {
1913 bytesWritten = framesWritten << mBitShift;
1914 } else {
1915 bytesWritten = framesWritten;
1916 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001917 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001918 if (status == NO_ERROR) {
1919 size_t totalFramesWritten = mNormalSink->framesWritten();
1920 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1921 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1922 mLatchDValid = true;
1923 }
1924 }
Eric Laurent81784c32012-11-19 14:55:58 -08001925 // otherwise use the HAL / AudioStreamOut directly
1926 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001927 // Direct output and offload threads
Eric Laurent04733db2013-11-22 09:29:56 -08001928 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001929 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001930 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1931 mWriteAckSequence += 2;
1932 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001933 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001934 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001936 // FIXME We should have an implementation of timestamps for direct output threads.
1937 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent04733db2013-11-22 09:29:56 -08001939 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940 if (mUseAsyncWrite &&
1941 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1942 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001943 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001945 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001946 }
Eric Laurent81784c32012-11-19 14:55:58 -08001947 }
1948
Eric Laurent81784c32012-11-19 14:55:58 -08001949 mNumWrites++;
1950 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001951 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 return bytesWritten;
1953}
1954
1955void AudioFlinger::PlaybackThread::threadLoop_drain()
1956{
1957 if (mOutput->stream->drain) {
1958 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1959 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001960 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1961 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001962 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001963 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001964 }
1965 mOutput->stream->drain(mOutput->stream,
1966 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1967 : AUDIO_DRAIN_ALL);
1968 }
1969}
1970
1971void AudioFlinger::PlaybackThread::threadLoop_exit()
1972{
1973 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001974}
1975
1976/*
1977The derived values that are cached:
1978 - mixBufferSize from frame count * frame size
1979 - activeSleepTime from activeSleepTimeUs()
1980 - idleSleepTime from idleSleepTimeUs()
1981 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1982 - maxPeriod from frame count and sample rate (MIXER only)
1983
1984The parameters that affect these derived values are:
1985 - frame count
1986 - frame size
1987 - sample rate
1988 - device type: A2DP or not
1989 - device latency
1990 - format: PCM or not
1991 - active sleep time
1992 - idle sleep time
1993*/
1994
1995void AudioFlinger::PlaybackThread::cacheParameters_l()
1996{
1997 mixBufferSize = mNormalFrameCount * mFrameSize;
1998 activeSleepTime = activeSleepTimeUs();
1999 idleSleepTime = idleSleepTimeUs();
2000}
2001
2002void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2003{
Glenn Kasten7c027242012-12-26 14:43:16 -08002004 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002005 this, streamType, mTracks.size());
2006 Mutex::Autolock _l(mLock);
2007
2008 size_t size = mTracks.size();
2009 for (size_t i = 0; i < size; i++) {
2010 sp<Track> t = mTracks[i];
2011 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002012 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002013 }
2014 }
2015}
2016
2017status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2018{
2019 int session = chain->sessionId();
2020 int16_t *buffer = mMixBuffer;
2021 bool ownsBuffer = false;
2022
2023 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2024 if (session > 0) {
2025 // Only one effect chain can be present in direct output thread and it uses
2026 // the mix buffer as input
2027 if (mType != DIRECT) {
2028 size_t numSamples = mNormalFrameCount * mChannelCount;
2029 buffer = new int16_t[numSamples];
2030 memset(buffer, 0, numSamples * sizeof(int16_t));
2031 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2032 ownsBuffer = true;
2033 }
2034
2035 // Attach all tracks with same session ID to this chain.
2036 for (size_t i = 0; i < mTracks.size(); ++i) {
2037 sp<Track> track = mTracks[i];
2038 if (session == track->sessionId()) {
2039 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2040 buffer);
2041 track->setMainBuffer(buffer);
2042 chain->incTrackCnt();
2043 }
2044 }
2045
2046 // indicate all active tracks in the chain
2047 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2048 sp<Track> track = mActiveTracks[i].promote();
2049 if (track == 0) {
2050 continue;
2051 }
2052 if (session == track->sessionId()) {
2053 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2054 chain->incActiveTrackCnt();
2055 }
2056 }
2057 }
2058
2059 chain->setInBuffer(buffer, ownsBuffer);
2060 chain->setOutBuffer(mMixBuffer);
2061 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2062 // chains list in order to be processed last as it contains output stage effects
2063 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2064 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2065 // after track specific effects and before output stage
2066 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2067 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2068 // Effect chain for other sessions are inserted at beginning of effect
2069 // chains list to be processed before output mix effects. Relative order between other
2070 // sessions is not important
2071 size_t size = mEffectChains.size();
2072 size_t i = 0;
2073 for (i = 0; i < size; i++) {
2074 if (mEffectChains[i]->sessionId() < session) {
2075 break;
2076 }
2077 }
2078 mEffectChains.insertAt(chain, i);
2079 checkSuspendOnAddEffectChain_l(chain);
2080
2081 return NO_ERROR;
2082}
2083
2084size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2085{
2086 int session = chain->sessionId();
2087
2088 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2089
2090 for (size_t i = 0; i < mEffectChains.size(); i++) {
2091 if (chain == mEffectChains[i]) {
2092 mEffectChains.removeAt(i);
2093 // detach all active tracks from the chain
2094 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2095 sp<Track> track = mActiveTracks[i].promote();
2096 if (track == 0) {
2097 continue;
2098 }
2099 if (session == track->sessionId()) {
2100 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2101 chain.get(), session);
2102 chain->decActiveTrackCnt();
2103 }
2104 }
2105
2106 // detach all tracks with same session ID from this chain
2107 for (size_t i = 0; i < mTracks.size(); ++i) {
2108 sp<Track> track = mTracks[i];
2109 if (session == track->sessionId()) {
2110 track->setMainBuffer(mMixBuffer);
2111 chain->decTrackCnt();
2112 }
2113 }
2114 break;
2115 }
2116 }
2117 return mEffectChains.size();
2118}
2119
2120status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2121 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2122{
2123 Mutex::Autolock _l(mLock);
2124 return attachAuxEffect_l(track, EffectId);
2125}
2126
2127status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2128 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2129{
2130 status_t status = NO_ERROR;
2131
2132 if (EffectId == 0) {
2133 track->setAuxBuffer(0, NULL);
2134 } else {
2135 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2136 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2137 if (effect != 0) {
2138 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2139 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2140 } else {
2141 status = INVALID_OPERATION;
2142 }
2143 } else {
2144 status = BAD_VALUE;
2145 }
2146 }
2147 return status;
2148}
2149
2150void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2151{
2152 for (size_t i = 0; i < mTracks.size(); ++i) {
2153 sp<Track> track = mTracks[i];
2154 if (track->auxEffectId() == effectId) {
2155 attachAuxEffect_l(track, 0);
2156 }
2157 }
2158}
2159
2160bool AudioFlinger::PlaybackThread::threadLoop()
2161{
2162 Vector< sp<Track> > tracksToRemove;
2163
2164 standbyTime = systemTime();
2165
2166 // MIXER
2167 nsecs_t lastWarning = 0;
2168
2169 // DUPLICATING
2170 // FIXME could this be made local to while loop?
2171 writeFrames = 0;
2172
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002173 int lastGeneration = 0;
2174
Eric Laurent81784c32012-11-19 14:55:58 -08002175 cacheParameters_l();
2176 sleepTime = idleSleepTime;
2177
2178 if (mType == MIXER) {
2179 sleepTimeShift = 0;
2180 }
2181
2182 CpuStats cpuStats;
2183 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2184
2185 acquireWakeLock();
2186
Glenn Kasten9e58b552013-01-18 15:09:48 -08002187 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2188 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2189 // and then that string will be logged at the next convenient opportunity.
2190 const char *logString = NULL;
2191
Eric Laurent664539d2013-09-23 18:24:31 -07002192 checkSilentMode_l();
2193
Eric Laurent81784c32012-11-19 14:55:58 -08002194 while (!exitPending())
2195 {
2196 cpuStats.sample(myName);
2197
2198 Vector< sp<EffectChain> > effectChains;
2199
2200 processConfigEvents();
2201
2202 { // scope for mLock
2203
2204 Mutex::Autolock _l(mLock);
2205
Glenn Kasten9e58b552013-01-18 15:09:48 -08002206 if (logString != NULL) {
2207 mNBLogWriter->logTimestamp();
2208 mNBLogWriter->log(logString);
2209 logString = NULL;
2210 }
2211
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002212 if (mLatchDValid) {
2213 mLatchQ = mLatchD;
2214 mLatchDValid = false;
2215 mLatchQValid = true;
2216 }
2217
Eric Laurent81784c32012-11-19 14:55:58 -08002218 if (checkForNewParameters_l()) {
2219 cacheParameters_l();
2220 }
2221
2222 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002223 if (mSignalPending) {
2224 // A signal was raised while we were unlocked
2225 mSignalPending = false;
2226 } else if (waitingAsyncCallback_l()) {
2227 if (exitPending()) {
2228 break;
2229 }
2230 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002231 mWakeLockUids.clear();
2232 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 ALOGV("wait async completion");
2234 mWaitWorkCV.wait(mLock);
2235 ALOGV("async completion/wake");
2236 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002237 standbyTime = systemTime() + standbyDelay;
2238 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002239
2240 continue;
2241 }
2242 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243 isSuspended()) {
2244 // put audio hardware into standby after short delay
2245 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002246
2247 threadLoop_standby();
2248
2249 mStandby = true;
2250 }
2251
2252 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2253 // we're about to wait, flush the binder command buffer
2254 IPCThreadState::self()->flushCommands();
2255
2256 clearOutputTracks();
2257
2258 if (exitPending()) {
2259 break;
2260 }
2261
2262 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002263 mWakeLockUids.clear();
2264 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002265 // wait until we have something to do...
2266 ALOGV("%s going to sleep", myName.string());
2267 mWaitWorkCV.wait(mLock);
2268 ALOGV("%s waking up", myName.string());
2269 acquireWakeLock_l();
2270
2271 mMixerStatus = MIXER_IDLE;
2272 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2273 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002275 checkSilentMode_l();
2276
2277 standbyTime = systemTime() + standbyDelay;
2278 sleepTime = idleSleepTime;
2279 if (mType == MIXER) {
2280 sleepTimeShift = 0;
2281 }
2282
2283 continue;
2284 }
2285 }
Eric Laurent81784c32012-11-19 14:55:58 -08002286 // mMixerStatusIgnoringFastTracks is also updated internally
2287 mMixerStatus = prepareTracks_l(&tracksToRemove);
2288
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002289 // compare with previously applied list
2290 if (lastGeneration != mActiveTracksGeneration) {
2291 // update wakelock
2292 updateWakeLockUids_l(mWakeLockUids);
2293 lastGeneration = mActiveTracksGeneration;
2294 }
2295
Eric Laurent81784c32012-11-19 14:55:58 -08002296 // prevent any changes in effect chain list and in each effect chain
2297 // during mixing and effect process as the audio buffers could be deleted
2298 // or modified if an effect is created or deleted
2299 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002300 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002301
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302 if (mBytesRemaining == 0) {
2303 mCurrentWriteLength = 0;
2304 if (mMixerStatus == MIXER_TRACKS_READY) {
2305 // threadLoop_mix() sets mCurrentWriteLength
2306 threadLoop_mix();
2307 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2308 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2309 // threadLoop_sleepTime sets sleepTime to 0 if data
2310 // must be written to HAL
2311 threadLoop_sleepTime();
2312 if (sleepTime == 0) {
2313 mCurrentWriteLength = mixBufferSize;
2314 }
2315 }
2316 mBytesRemaining = mCurrentWriteLength;
2317 if (isSuspended()) {
2318 sleepTime = suspendSleepTimeUs();
2319 // simulate write to HAL when suspended
2320 mBytesWritten += mixBufferSize;
2321 mBytesRemaining = 0;
2322 }
Eric Laurent81784c32012-11-19 14:55:58 -08002323
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002325 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326 for (size_t i = 0; i < effectChains.size(); i ++) {
2327 effectChains[i]->process_l();
2328 }
Eric Laurent81784c32012-11-19 14:55:58 -08002329 }
2330 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002331 // Process effect chains for offloaded thread even if no audio
2332 // was read from audio track: process only updates effect state
2333 // and thus does have to be synchronized with audio writes but may have
2334 // to be called while waiting for async write callback
2335 if (mType == OFFLOAD) {
2336 for (size_t i = 0; i < effectChains.size(); i ++) {
2337 effectChains[i]->process_l();
2338 }
2339 }
Eric Laurent81784c32012-11-19 14:55:58 -08002340
2341 // enable changes in effect chain
2342 unlockEffectChains(effectChains);
2343
Eric Laurentbfb1b832013-01-07 09:53:42 -08002344 if (!waitingAsyncCallback()) {
2345 // sleepTime == 0 means we must write to audio hardware
2346 if (sleepTime == 0) {
2347 if (mBytesRemaining) {
2348 ssize_t ret = threadLoop_write();
2349 if (ret < 0) {
2350 mBytesRemaining = 0;
2351 } else {
2352 mBytesWritten += ret;
2353 mBytesRemaining -= ret;
2354 }
2355 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2356 (mMixerStatus == MIXER_DRAIN_ALL)) {
2357 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002358 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002359if (mType == MIXER) {
2360 // write blocked detection
2361 nsecs_t now = systemTime();
2362 nsecs_t delta = now - mLastWriteTime;
2363 if (!mStandby && delta > maxPeriod) {
2364 mNumDelayedWrites++;
2365 if ((now - lastWarning) > kWarningThrottleNs) {
2366 ATRACE_NAME("underrun");
2367 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2368 ns2ms(delta), mNumDelayedWrites, this);
2369 lastWarning = now;
2370 }
2371 }
Eric Laurent81784c32012-11-19 14:55:58 -08002372}
2373
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 } else {
2375 usleep(sleepTime);
2376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377 }
2378
2379 // Finally let go of removed track(s), without the lock held
2380 // since we can't guarantee the destructors won't acquire that
2381 // same lock. This will also mutate and push a new fast mixer state.
2382 threadLoop_removeTracks(tracksToRemove);
2383 tracksToRemove.clear();
2384
2385 // FIXME I don't understand the need for this here;
2386 // it was in the original code but maybe the
2387 // assignment in saveOutputTracks() makes this unnecessary?
2388 clearOutputTracks();
2389
2390 // Effect chains will be actually deleted here if they were removed from
2391 // mEffectChains list during mixing or effects processing
2392 effectChains.clear();
2393
2394 // FIXME Note that the above .clear() is no longer necessary since effectChains
2395 // is now local to this block, but will keep it for now (at least until merge done).
2396 }
2397
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398 threadLoop_exit();
2399
Eric Laurent81784c32012-11-19 14:55:58 -08002400 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002401 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002402 // put output stream into standby mode
2403 if (!mStandby) {
2404 mOutput->stream->common.standby(&mOutput->stream->common);
2405 }
2406 }
2407
2408 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002409 mWakeLockUids.clear();
2410 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002411
2412 ALOGV("Thread %p type %d exiting", this, mType);
2413 return false;
2414}
2415
Eric Laurentbfb1b832013-01-07 09:53:42 -08002416// removeTracks_l() must be called with ThreadBase::mLock held
2417void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2418{
2419 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002420 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002421 for (size_t i=0 ; i<count ; i++) {
2422 const sp<Track>& track = tracksToRemove.itemAt(i);
2423 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002424 mWakeLockUids.remove(track->uid());
2425 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2427 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2428 if (chain != 0) {
2429 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2430 track->sessionId());
2431 chain->decActiveTrackCnt();
2432 }
2433 if (track->isTerminated()) {
2434 removeTrack_l(track);
2435 }
2436 }
2437 }
2438
2439}
Eric Laurent81784c32012-11-19 14:55:58 -08002440
Eric Laurentaccc1472013-09-20 09:36:34 -07002441status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2442{
2443 if (mNormalSink != 0) {
2444 return mNormalSink->getTimestamp(timestamp);
2445 }
2446 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2447 uint64_t position64;
2448 int ret = mOutput->stream->get_presentation_position(
2449 mOutput->stream, &position64, &timestamp.mTime);
2450 if (ret == 0) {
2451 timestamp.mPosition = (uint32_t)position64;
2452 return NO_ERROR;
2453 }
2454 }
2455 return INVALID_OPERATION;
2456}
Eric Laurent81784c32012-11-19 14:55:58 -08002457// ----------------------------------------------------------------------------
2458
2459AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2460 audio_io_handle_t id, audio_devices_t device, type_t type)
2461 : PlaybackThread(audioFlinger, output, id, device, type),
2462 // mAudioMixer below
2463 // mFastMixer below
2464 mFastMixerFutex(0)
2465 // mOutputSink below
2466 // mPipeSink below
2467 // mNormalSink below
2468{
2469 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002470 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002471 "mFrameCount=%d, mNormalFrameCount=%d",
2472 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2473 mNormalFrameCount);
2474 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2475
2476 // FIXME - Current mixer implementation only supports stereo output
2477 if (mChannelCount != FCC_2) {
2478 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2479 }
2480
2481 // create an NBAIO sink for the HAL output stream, and negotiate
2482 mOutputSink = new AudioStreamOutSink(output->stream);
2483 size_t numCounterOffers = 0;
2484 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2485 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2486 ALOG_ASSERT(index == 0);
2487
2488 // initialize fast mixer depending on configuration
2489 bool initFastMixer;
2490 switch (kUseFastMixer) {
2491 case FastMixer_Never:
2492 initFastMixer = false;
2493 break;
2494 case FastMixer_Always:
2495 initFastMixer = true;
2496 break;
2497 case FastMixer_Static:
2498 case FastMixer_Dynamic:
2499 initFastMixer = mFrameCount < mNormalFrameCount;
2500 break;
2501 }
2502 if (initFastMixer) {
2503
2504 // create a MonoPipe to connect our submix to FastMixer
2505 NBAIO_Format format = mOutputSink->format();
2506 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2507 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2508 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2509 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2510 const NBAIO_Format offers[1] = {format};
2511 size_t numCounterOffers = 0;
2512 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2513 ALOG_ASSERT(index == 0);
2514 monoPipe->setAvgFrames((mScreenState & 1) ?
2515 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2516 mPipeSink = monoPipe;
2517
Glenn Kasten46909e72013-02-26 09:20:22 -08002518#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002519 if (mTeeSinkOutputEnabled) {
2520 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2521 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2522 numCounterOffers = 0;
2523 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2524 ALOG_ASSERT(index == 0);
2525 mTeeSink = teeSink;
2526 PipeReader *teeSource = new PipeReader(*teeSink);
2527 numCounterOffers = 0;
2528 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2529 ALOG_ASSERT(index == 0);
2530 mTeeSource = teeSource;
2531 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002532#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002533
2534 // create fast mixer and configure it initially with just one fast track for our submix
2535 mFastMixer = new FastMixer();
2536 FastMixerStateQueue *sq = mFastMixer->sq();
2537#ifdef STATE_QUEUE_DUMP
2538 sq->setObserverDump(&mStateQueueObserverDump);
2539 sq->setMutatorDump(&mStateQueueMutatorDump);
2540#endif
2541 FastMixerState *state = sq->begin();
2542 FastTrack *fastTrack = &state->mFastTracks[0];
2543 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2544 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2545 fastTrack->mVolumeProvider = NULL;
2546 fastTrack->mGeneration++;
2547 state->mFastTracksGen++;
2548 state->mTrackMask = 1;
2549 // fast mixer will use the HAL output sink
2550 state->mOutputSink = mOutputSink.get();
2551 state->mOutputSinkGen++;
2552 state->mFrameCount = mFrameCount;
2553 state->mCommand = FastMixerState::COLD_IDLE;
2554 // already done in constructor initialization list
2555 //mFastMixerFutex = 0;
2556 state->mColdFutexAddr = &mFastMixerFutex;
2557 state->mColdGen++;
2558 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002559#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002560 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002561#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002562 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2563 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002564 sq->end();
2565 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2566
2567 // start the fast mixer
2568 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2569 pid_t tid = mFastMixer->getTid();
2570 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2571 if (err != 0) {
2572 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2573 kPriorityFastMixer, getpid_cached, tid, err);
2574 }
2575
2576#ifdef AUDIO_WATCHDOG
2577 // create and start the watchdog
2578 mAudioWatchdog = new AudioWatchdog();
2579 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2580 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2581 tid = mAudioWatchdog->getTid();
2582 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2583 if (err != 0) {
2584 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2585 kPriorityFastMixer, getpid_cached, tid, err);
2586 }
2587#endif
2588
2589 } else {
2590 mFastMixer = NULL;
2591 }
2592
2593 switch (kUseFastMixer) {
2594 case FastMixer_Never:
2595 case FastMixer_Dynamic:
2596 mNormalSink = mOutputSink;
2597 break;
2598 case FastMixer_Always:
2599 mNormalSink = mPipeSink;
2600 break;
2601 case FastMixer_Static:
2602 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2603 break;
2604 }
2605}
2606
2607AudioFlinger::MixerThread::~MixerThread()
2608{
2609 if (mFastMixer != NULL) {
2610 FastMixerStateQueue *sq = mFastMixer->sq();
2611 FastMixerState *state = sq->begin();
2612 if (state->mCommand == FastMixerState::COLD_IDLE) {
2613 int32_t old = android_atomic_inc(&mFastMixerFutex);
2614 if (old == -1) {
2615 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2616 }
2617 }
2618 state->mCommand = FastMixerState::EXIT;
2619 sq->end();
2620 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2621 mFastMixer->join();
2622 // Though the fast mixer thread has exited, it's state queue is still valid.
2623 // We'll use that extract the final state which contains one remaining fast track
2624 // corresponding to our sub-mix.
2625 state = sq->begin();
2626 ALOG_ASSERT(state->mTrackMask == 1);
2627 FastTrack *fastTrack = &state->mFastTracks[0];
2628 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2629 delete fastTrack->mBufferProvider;
2630 sq->end(false /*didModify*/);
2631 delete mFastMixer;
2632#ifdef AUDIO_WATCHDOG
2633 if (mAudioWatchdog != 0) {
2634 mAudioWatchdog->requestExit();
2635 mAudioWatchdog->requestExitAndWait();
2636 mAudioWatchdog.clear();
2637 }
2638#endif
2639 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002640 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002641 delete mAudioMixer;
2642}
2643
2644
2645uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2646{
2647 if (mFastMixer != NULL) {
2648 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2649 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2650 }
2651 return latency;
2652}
2653
2654
2655void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2656{
2657 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2658}
2659
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002661{
2662 // FIXME we should only do one push per cycle; confirm this is true
2663 // Start the fast mixer if it's not already running
2664 if (mFastMixer != NULL) {
2665 FastMixerStateQueue *sq = mFastMixer->sq();
2666 FastMixerState *state = sq->begin();
2667 if (state->mCommand != FastMixerState::MIX_WRITE &&
2668 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2669 if (state->mCommand == FastMixerState::COLD_IDLE) {
2670 int32_t old = android_atomic_inc(&mFastMixerFutex);
2671 if (old == -1) {
2672 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2673 }
2674#ifdef AUDIO_WATCHDOG
2675 if (mAudioWatchdog != 0) {
2676 mAudioWatchdog->resume();
2677 }
2678#endif
2679 }
2680 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002681 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2682 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002683 sq->end();
2684 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2685 if (kUseFastMixer == FastMixer_Dynamic) {
2686 mNormalSink = mPipeSink;
2687 }
2688 } else {
2689 sq->end(false /*didModify*/);
2690 }
2691 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002693}
2694
2695void AudioFlinger::MixerThread::threadLoop_standby()
2696{
2697 // Idle the fast mixer if it's currently running
2698 if (mFastMixer != NULL) {
2699 FastMixerStateQueue *sq = mFastMixer->sq();
2700 FastMixerState *state = sq->begin();
2701 if (!(state->mCommand & FastMixerState::IDLE)) {
2702 state->mCommand = FastMixerState::COLD_IDLE;
2703 state->mColdFutexAddr = &mFastMixerFutex;
2704 state->mColdGen++;
2705 mFastMixerFutex = 0;
2706 sq->end();
2707 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2708 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2709 if (kUseFastMixer == FastMixer_Dynamic) {
2710 mNormalSink = mOutputSink;
2711 }
2712#ifdef AUDIO_WATCHDOG
2713 if (mAudioWatchdog != 0) {
2714 mAudioWatchdog->pause();
2715 }
2716#endif
2717 } else {
2718 sq->end(false /*didModify*/);
2719 }
2720 }
2721 PlaybackThread::threadLoop_standby();
2722}
2723
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724// Empty implementation for standard mixer
2725// Overridden for offloaded playback
2726void AudioFlinger::PlaybackThread::flushOutput_l()
2727{
2728}
2729
2730bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2731{
2732 return false;
2733}
2734
2735bool AudioFlinger::PlaybackThread::shouldStandby_l()
2736{
2737 return !mStandby;
2738}
2739
2740bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2741{
2742 Mutex::Autolock _l(mLock);
2743 return waitingAsyncCallback_l();
2744}
2745
Eric Laurent81784c32012-11-19 14:55:58 -08002746// shared by MIXER and DIRECT, overridden by DUPLICATING
2747void AudioFlinger::PlaybackThread::threadLoop_standby()
2748{
2749 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2750 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002751 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002752 // discard any pending drain or write ack by incrementing sequence
2753 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2754 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002756 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2757 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758 }
Eric Laurent81784c32012-11-19 14:55:58 -08002759}
2760
2761void AudioFlinger::MixerThread::threadLoop_mix()
2762{
2763 // obtain the presentation timestamp of the next output buffer
2764 int64_t pts;
2765 status_t status = INVALID_OPERATION;
2766
2767 if (mNormalSink != 0) {
2768 status = mNormalSink->getNextWriteTimestamp(&pts);
2769 } else {
2770 status = mOutputSink->getNextWriteTimestamp(&pts);
2771 }
2772
2773 if (status != NO_ERROR) {
2774 pts = AudioBufferProvider::kInvalidPTS;
2775 }
2776
2777 // mix buffers...
2778 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002780 // increase sleep time progressively when application underrun condition clears.
2781 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2782 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2783 // such that we would underrun the audio HAL.
2784 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2785 sleepTimeShift--;
2786 }
2787 sleepTime = 0;
2788 standbyTime = systemTime() + standbyDelay;
2789 //TODO: delay standby when effects have a tail
2790}
2791
2792void AudioFlinger::MixerThread::threadLoop_sleepTime()
2793{
2794 // If no tracks are ready, sleep once for the duration of an output
2795 // buffer size, then write 0s to the output
2796 if (sleepTime == 0) {
2797 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2798 sleepTime = activeSleepTime >> sleepTimeShift;
2799 if (sleepTime < kMinThreadSleepTimeUs) {
2800 sleepTime = kMinThreadSleepTimeUs;
2801 }
2802 // reduce sleep time in case of consecutive application underruns to avoid
2803 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2804 // duration we would end up writing less data than needed by the audio HAL if
2805 // the condition persists.
2806 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2807 sleepTimeShift++;
2808 }
2809 } else {
2810 sleepTime = idleSleepTime;
2811 }
2812 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002813 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 sleepTime = 0;
2815 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2816 "anticipated start");
2817 }
2818 // TODO add standby time extension fct of effect tail
2819}
2820
2821// prepareTracks_l() must be called with ThreadBase::mLock held
2822AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2823 Vector< sp<Track> > *tracksToRemove)
2824{
2825
2826 mixer_state mixerStatus = MIXER_IDLE;
2827 // find out which tracks need to be processed
2828 size_t count = mActiveTracks.size();
2829 size_t mixedTracks = 0;
2830 size_t tracksWithEffect = 0;
2831 // counts only _active_ fast tracks
2832 size_t fastTracks = 0;
2833 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2834
2835 float masterVolume = mMasterVolume;
2836 bool masterMute = mMasterMute;
2837
2838 if (masterMute) {
2839 masterVolume = 0;
2840 }
2841 // Delegate master volume control to effect in output mix effect chain if needed
2842 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2843 if (chain != 0) {
2844 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2845 chain->setVolume_l(&v, &v);
2846 masterVolume = (float)((v + (1 << 23)) >> 24);
2847 chain.clear();
2848 }
2849
2850 // prepare a new state to push
2851 FastMixerStateQueue *sq = NULL;
2852 FastMixerState *state = NULL;
2853 bool didModify = false;
2854 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2855 if (mFastMixer != NULL) {
2856 sq = mFastMixer->sq();
2857 state = sq->begin();
2858 }
2859
2860 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002861 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002862 if (t == 0) {
2863 continue;
2864 }
2865
2866 // this const just means the local variable doesn't change
2867 Track* const track = t.get();
2868
2869 // process fast tracks
2870 if (track->isFastTrack()) {
2871
2872 // It's theoretically possible (though unlikely) for a fast track to be created
2873 // and then removed within the same normal mix cycle. This is not a problem, as
2874 // the track never becomes active so it's fast mixer slot is never touched.
2875 // The converse, of removing an (active) track and then creating a new track
2876 // at the identical fast mixer slot within the same normal mix cycle,
2877 // is impossible because the slot isn't marked available until the end of each cycle.
2878 int j = track->mFastIndex;
2879 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2880 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2881 FastTrack *fastTrack = &state->mFastTracks[j];
2882
2883 // Determine whether the track is currently in underrun condition,
2884 // and whether it had a recent underrun.
2885 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2886 FastTrackUnderruns underruns = ftDump->mUnderruns;
2887 uint32_t recentFull = (underruns.mBitFields.mFull -
2888 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2889 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2890 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2891 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2892 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2893 uint32_t recentUnderruns = recentPartial + recentEmpty;
2894 track->mObservedUnderruns = underruns;
2895 // don't count underruns that occur while stopping or pausing
2896 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002897 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2898 recentUnderruns > 0) {
2899 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2900 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
2902
2903 // This is similar to the state machine for normal tracks,
2904 // with a few modifications for fast tracks.
2905 bool isActive = true;
2906 switch (track->mState) {
2907 case TrackBase::STOPPING_1:
2908 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002910 track->mState = TrackBase::STOPPING_2;
2911 }
2912 break;
2913 case TrackBase::PAUSING:
2914 // ramp down is not yet implemented
2915 track->setPaused();
2916 break;
2917 case TrackBase::RESUMING:
2918 // ramp up is not yet implemented
2919 track->mState = TrackBase::ACTIVE;
2920 break;
2921 case TrackBase::ACTIVE:
2922 if (recentFull > 0 || recentPartial > 0) {
2923 // track has provided at least some frames recently: reset retry count
2924 track->mRetryCount = kMaxTrackRetries;
2925 }
2926 if (recentUnderruns == 0) {
2927 // no recent underruns: stay active
2928 break;
2929 }
2930 // there has recently been an underrun of some kind
2931 if (track->sharedBuffer() == 0) {
2932 // were any of the recent underruns "empty" (no frames available)?
2933 if (recentEmpty == 0) {
2934 // no, then ignore the partial underruns as they are allowed indefinitely
2935 break;
2936 }
2937 // there has recently been an "empty" underrun: decrement the retry counter
2938 if (--(track->mRetryCount) > 0) {
2939 break;
2940 }
2941 // indicate to client process that the track was disabled because of underrun;
2942 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002943 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002944 // remove from active list, but state remains ACTIVE [confusing but true]
2945 isActive = false;
2946 break;
2947 }
2948 // fall through
2949 case TrackBase::STOPPING_2:
2950 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002951 case TrackBase::STOPPED:
2952 case TrackBase::FLUSHED: // flush() while active
2953 // Check for presentation complete if track is inactive
2954 // We have consumed all the buffers of this track.
2955 // This would be incomplete if we auto-paused on underrun
2956 {
2957 size_t audioHALFrames =
2958 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2959 size_t framesWritten = mBytesWritten / mFrameSize;
2960 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2961 // track stays in active list until presentation is complete
2962 break;
2963 }
2964 }
2965 if (track->isStopping_2()) {
2966 track->mState = TrackBase::STOPPED;
2967 }
2968 if (track->isStopped()) {
2969 // Can't reset directly, as fast mixer is still polling this track
2970 // track->reset();
2971 // So instead mark this track as needing to be reset after push with ack
2972 resetMask |= 1 << i;
2973 }
2974 isActive = false;
2975 break;
2976 case TrackBase::IDLE:
2977 default:
2978 LOG_FATAL("unexpected track state %d", track->mState);
2979 }
2980
2981 if (isActive) {
2982 // was it previously inactive?
2983 if (!(state->mTrackMask & (1 << j))) {
2984 ExtendedAudioBufferProvider *eabp = track;
2985 VolumeProvider *vp = track;
2986 fastTrack->mBufferProvider = eabp;
2987 fastTrack->mVolumeProvider = vp;
2988 fastTrack->mSampleRate = track->mSampleRate;
2989 fastTrack->mChannelMask = track->mChannelMask;
2990 fastTrack->mGeneration++;
2991 state->mTrackMask |= 1 << j;
2992 didModify = true;
2993 // no acknowledgement required for newly active tracks
2994 }
2995 // cache the combined master volume and stream type volume for fast mixer; this
2996 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002997 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 ++fastTracks;
2999 } else {
3000 // was it previously active?
3001 if (state->mTrackMask & (1 << j)) {
3002 fastTrack->mBufferProvider = NULL;
3003 fastTrack->mGeneration++;
3004 state->mTrackMask &= ~(1 << j);
3005 didModify = true;
3006 // If any fast tracks were removed, we must wait for acknowledgement
3007 // because we're about to decrement the last sp<> on those tracks.
3008 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3009 } else {
3010 LOG_FATAL("fast track %d should have been active", j);
3011 }
3012 tracksToRemove->add(track);
3013 // Avoids a misleading display in dumpsys
3014 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3015 }
3016 continue;
3017 }
3018
3019 { // local variable scope to avoid goto warning
3020
3021 audio_track_cblk_t* cblk = track->cblk();
3022
3023 // The first time a track is added we wait
3024 // for all its buffers to be filled before processing it
3025 int name = track->name();
3026 // make sure that we have enough frames to mix one full buffer.
3027 // enforce this condition only once to enable draining the buffer in case the client
3028 // app does not call stop() and relies on underrun to stop:
3029 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3030 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003031 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003032 uint32_t sr = track->sampleRate();
3033 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003034 desiredFrames = mNormalFrameCount;
3035 } else {
3036 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003037 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003038 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003039 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003040 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3041 // the minimum track buffer size is normally twice the number of frames necessary
3042 // to fill one buffer and the resampler should not leave more than one buffer worth
3043 // of unreleased frames after each pass, but just in case...
3044 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3045 }
Eric Laurent81784c32012-11-19 14:55:58 -08003046 uint32_t minFrames = 1;
3047 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3048 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003049 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003050 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003051
3052 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003053 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003054 !track->isPaused() && !track->isTerminated())
3055 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003056 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003057
3058 mixedTracks++;
3059
3060 // track->mainBuffer() != mMixBuffer means there is an effect chain
3061 // connected to the track
3062 chain.clear();
3063 if (track->mainBuffer() != mMixBuffer) {
3064 chain = getEffectChain_l(track->sessionId());
3065 // Delegate volume control to effect in track effect chain if needed
3066 if (chain != 0) {
3067 tracksWithEffect++;
3068 } else {
3069 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3070 "session %d",
3071 name, track->sessionId());
3072 }
3073 }
3074
3075
3076 int param = AudioMixer::VOLUME;
3077 if (track->mFillingUpStatus == Track::FS_FILLED) {
3078 // no ramp for the first volume setting
3079 track->mFillingUpStatus = Track::FS_ACTIVE;
3080 if (track->mState == TrackBase::RESUMING) {
3081 track->mState = TrackBase::ACTIVE;
3082 param = AudioMixer::RAMP_VOLUME;
3083 }
3084 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003085 // FIXME should not make a decision based on mServer
3086 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003087 // If the track is stopped before the first frame was mixed,
3088 // do not apply ramp
3089 param = AudioMixer::RAMP_VOLUME;
3090 }
3091
3092 // compute volume for this track
3093 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003094 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003095 vl = vr = va = 0;
3096 if (track->isPausing()) {
3097 track->setPaused();
3098 }
3099 } else {
3100
3101 // read original volumes with volume control
3102 float typeVolume = mStreamTypes[track->streamType()].volume;
3103 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003104 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003105 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003106 vl = vlr & 0xFFFF;
3107 vr = vlr >> 16;
3108 // track volumes come from shared memory, so can't be trusted and must be clamped
3109 if (vl > MAX_GAIN_INT) {
3110 ALOGV("Track left volume out of range: %04X", vl);
3111 vl = MAX_GAIN_INT;
3112 }
3113 if (vr > MAX_GAIN_INT) {
3114 ALOGV("Track right volume out of range: %04X", vr);
3115 vr = MAX_GAIN_INT;
3116 }
3117 // now apply the master volume and stream type volume
3118 vl = (uint32_t)(v * vl) << 12;
3119 vr = (uint32_t)(v * vr) << 12;
3120 // assuming master volume and stream type volume each go up to 1.0,
3121 // vl and vr are now in 8.24 format
3122
Glenn Kastene3aa6592012-12-04 12:22:46 -08003123 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // send level comes from shared memory and so may be corrupt
3125 if (sendLevel > MAX_GAIN_INT) {
3126 ALOGV("Track send level out of range: %04X", sendLevel);
3127 sendLevel = MAX_GAIN_INT;
3128 }
3129 va = (uint32_t)(v * sendLevel);
3130 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003131
Eric Laurent81784c32012-11-19 14:55:58 -08003132 // Delegate volume control to effect in track effect chain if needed
3133 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3134 // Do not ramp volume if volume is controlled by effect
3135 param = AudioMixer::VOLUME;
3136 track->mHasVolumeController = true;
3137 } else {
3138 // force no volume ramp when volume controller was just disabled or removed
3139 // from effect chain to avoid volume spike
3140 if (track->mHasVolumeController) {
3141 param = AudioMixer::VOLUME;
3142 }
3143 track->mHasVolumeController = false;
3144 }
3145
3146 // Convert volumes from 8.24 to 4.12 format
3147 // This additional clamping is needed in case chain->setVolume_l() overshot
3148 vl = (vl + (1 << 11)) >> 12;
3149 if (vl > MAX_GAIN_INT) {
3150 vl = MAX_GAIN_INT;
3151 }
3152 vr = (vr + (1 << 11)) >> 12;
3153 if (vr > MAX_GAIN_INT) {
3154 vr = MAX_GAIN_INT;
3155 }
3156
3157 if (va > MAX_GAIN_INT) {
3158 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3159 }
3160
3161 // XXX: these things DON'T need to be done each time
3162 mAudioMixer->setBufferProvider(name, track);
3163 mAudioMixer->enable(name);
3164
3165 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3166 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3167 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3168 mAudioMixer->setParameter(
3169 name,
3170 AudioMixer::TRACK,
3171 AudioMixer::FORMAT, (void *)track->format());
3172 mAudioMixer->setParameter(
3173 name,
3174 AudioMixer::TRACK,
3175 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003176 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3177 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003178 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003179 if (reqSampleRate == 0) {
3180 reqSampleRate = mSampleRate;
3181 } else if (reqSampleRate > maxSampleRate) {
3182 reqSampleRate = maxSampleRate;
3183 }
Eric Laurent81784c32012-11-19 14:55:58 -08003184 mAudioMixer->setParameter(
3185 name,
3186 AudioMixer::RESAMPLE,
3187 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003188 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003189 mAudioMixer->setParameter(
3190 name,
3191 AudioMixer::TRACK,
3192 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3193 mAudioMixer->setParameter(
3194 name,
3195 AudioMixer::TRACK,
3196 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3197
3198 // reset retry count
3199 track->mRetryCount = kMaxTrackRetries;
3200
3201 // If one track is ready, set the mixer ready if:
3202 // - the mixer was not ready during previous round OR
3203 // - no other track is not ready
3204 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3205 mixerStatus != MIXER_TRACKS_ENABLED) {
3206 mixerStatus = MIXER_TRACKS_READY;
3207 }
3208 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003209 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003210 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003211 }
Eric Laurent81784c32012-11-19 14:55:58 -08003212 // clear effect chain input buffer if an active track underruns to avoid sending
3213 // previous audio buffer again to effects
3214 chain = getEffectChain_l(track->sessionId());
3215 if (chain != 0) {
3216 chain->clearInputBuffer();
3217 }
3218
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003219 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003220 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3221 track->isStopped() || track->isPaused()) {
3222 // We have consumed all the buffers of this track.
3223 // Remove it from the list of active tracks.
3224 // TODO: use actual buffer filling status instead of latency when available from
3225 // audio HAL
3226 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3227 size_t framesWritten = mBytesWritten / mFrameSize;
3228 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3229 if (track->isStopped()) {
3230 track->reset();
3231 }
3232 tracksToRemove->add(track);
3233 }
3234 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003235 // No buffers for this track. Give it a few chances to
3236 // fill a buffer, then remove it from active list.
3237 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003238 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003239 tracksToRemove->add(track);
3240 // indicate to client process that the track was disabled because of underrun;
3241 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003242 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003243 // If one track is not ready, mark the mixer also not ready if:
3244 // - the mixer was ready during previous round OR
3245 // - no other track is ready
3246 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3247 mixerStatus != MIXER_TRACKS_READY) {
3248 mixerStatus = MIXER_TRACKS_ENABLED;
3249 }
3250 }
3251 mAudioMixer->disable(name);
3252 }
3253
3254 } // local variable scope to avoid goto warning
3255track_is_ready: ;
3256
3257 }
3258
3259 // Push the new FastMixer state if necessary
3260 bool pauseAudioWatchdog = false;
3261 if (didModify) {
3262 state->mFastTracksGen++;
3263 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3264 if (kUseFastMixer == FastMixer_Dynamic &&
3265 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3266 state->mCommand = FastMixerState::COLD_IDLE;
3267 state->mColdFutexAddr = &mFastMixerFutex;
3268 state->mColdGen++;
3269 mFastMixerFutex = 0;
3270 if (kUseFastMixer == FastMixer_Dynamic) {
3271 mNormalSink = mOutputSink;
3272 }
3273 // If we go into cold idle, need to wait for acknowledgement
3274 // so that fast mixer stops doing I/O.
3275 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3276 pauseAudioWatchdog = true;
3277 }
Eric Laurent81784c32012-11-19 14:55:58 -08003278 }
3279 if (sq != NULL) {
3280 sq->end(didModify);
3281 sq->push(block);
3282 }
3283#ifdef AUDIO_WATCHDOG
3284 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3285 mAudioWatchdog->pause();
3286 }
3287#endif
3288
3289 // Now perform the deferred reset on fast tracks that have stopped
3290 while (resetMask != 0) {
3291 size_t i = __builtin_ctz(resetMask);
3292 ALOG_ASSERT(i < count);
3293 resetMask &= ~(1 << i);
3294 sp<Track> t = mActiveTracks[i].promote();
3295 if (t == 0) {
3296 continue;
3297 }
3298 Track* track = t.get();
3299 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3300 track->reset();
3301 }
3302
3303 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003305
3306 // mix buffer must be cleared if all tracks are connected to an
3307 // effect chain as in this case the mixer will not write to
3308 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003309 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3310 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003311 // FIXME as a performance optimization, should remember previous zero status
3312 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3313 }
3314
3315 // if any fast tracks, then status is ready
3316 mMixerStatusIgnoringFastTracks = mixerStatus;
3317 if (fastTracks > 0) {
3318 mixerStatus = MIXER_TRACKS_READY;
3319 }
3320 return mixerStatus;
3321}
3322
3323// getTrackName_l() must be called with ThreadBase::mLock held
3324int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3325{
3326 return mAudioMixer->getTrackName(channelMask, sessionId);
3327}
3328
3329// deleteTrackName_l() must be called with ThreadBase::mLock held
3330void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3331{
3332 ALOGV("remove track (%d) and delete from mixer", name);
3333 mAudioMixer->deleteTrackName(name);
3334}
3335
3336// checkForNewParameters_l() must be called with ThreadBase::mLock held
3337bool AudioFlinger::MixerThread::checkForNewParameters_l()
3338{
3339 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3340 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3341 bool reconfig = false;
3342
3343 while (!mNewParameters.isEmpty()) {
3344
3345 if (mFastMixer != NULL) {
3346 FastMixerStateQueue *sq = mFastMixer->sq();
3347 FastMixerState *state = sq->begin();
3348 if (!(state->mCommand & FastMixerState::IDLE)) {
3349 previousCommand = state->mCommand;
3350 state->mCommand = FastMixerState::HOT_IDLE;
3351 sq->end();
3352 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3353 } else {
3354 sq->end(false /*didModify*/);
3355 }
3356 }
3357
3358 status_t status = NO_ERROR;
3359 String8 keyValuePair = mNewParameters[0];
3360 AudioParameter param = AudioParameter(keyValuePair);
3361 int value;
3362
3363 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3364 reconfig = true;
3365 }
3366 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3367 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3368 status = BAD_VALUE;
3369 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003370 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003371 reconfig = true;
3372 }
3373 }
3374 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003375 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003376 status = BAD_VALUE;
3377 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003378 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003379 reconfig = true;
3380 }
3381 }
3382 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3383 // do not accept frame count changes if tracks are open as the track buffer
3384 // size depends on frame count and correct behavior would not be guaranteed
3385 // if frame count is changed after track creation
3386 if (!mTracks.isEmpty()) {
3387 status = INVALID_OPERATION;
3388 } else {
3389 reconfig = true;
3390 }
3391 }
3392 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3393#ifdef ADD_BATTERY_DATA
3394 // when changing the audio output device, call addBatteryData to notify
3395 // the change
3396 if (mOutDevice != value) {
3397 uint32_t params = 0;
3398 // check whether speaker is on
3399 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3400 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3401 }
3402
3403 audio_devices_t deviceWithoutSpeaker
3404 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3405 // check if any other device (except speaker) is on
3406 if (value & deviceWithoutSpeaker ) {
3407 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3408 }
3409
3410 if (params != 0) {
3411 addBatteryData(params);
3412 }
3413 }
3414#endif
3415
3416 // forward device change to effects that have requested to be
3417 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003418 if (value != AUDIO_DEVICE_NONE) {
3419 mOutDevice = value;
3420 for (size_t i = 0; i < mEffectChains.size(); i++) {
3421 mEffectChains[i]->setDevice_l(mOutDevice);
3422 }
Eric Laurent81784c32012-11-19 14:55:58 -08003423 }
3424 }
3425
3426 if (status == NO_ERROR) {
3427 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3428 keyValuePair.string());
3429 if (!mStandby && status == INVALID_OPERATION) {
3430 mOutput->stream->common.standby(&mOutput->stream->common);
3431 mStandby = true;
3432 mBytesWritten = 0;
3433 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3434 keyValuePair.string());
3435 }
3436 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003437 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003438 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003439 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3440 for (size_t i = 0; i < mTracks.size() ; i++) {
3441 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3442 if (name < 0) {
3443 break;
3444 }
3445 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003446 }
3447 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3448 }
3449 }
3450
3451 mNewParameters.removeAt(0);
3452
3453 mParamStatus = status;
3454 mParamCond.signal();
3455 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3456 // already timed out waiting for the status and will never signal the condition.
3457 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3458 }
3459
3460 if (!(previousCommand & FastMixerState::IDLE)) {
3461 ALOG_ASSERT(mFastMixer != NULL);
3462 FastMixerStateQueue *sq = mFastMixer->sq();
3463 FastMixerState *state = sq->begin();
3464 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3465 state->mCommand = previousCommand;
3466 sq->end();
3467 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3468 }
3469
3470 return reconfig;
3471}
3472
3473
3474void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3475{
3476 const size_t SIZE = 256;
3477 char buffer[SIZE];
3478 String8 result;
3479
3480 PlaybackThread::dumpInternals(fd, args);
3481
3482 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3483 result.append(buffer);
3484 write(fd, result.string(), result.size());
3485
3486 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003487 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003488 copy.dump(fd);
3489
3490#ifdef STATE_QUEUE_DUMP
3491 // Similar for state queue
3492 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3493 observerCopy.dump(fd);
3494 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3495 mutatorCopy.dump(fd);
3496#endif
3497
Glenn Kasten46909e72013-02-26 09:20:22 -08003498#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003499 // Write the tee output to a .wav file
3500 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003501#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003502
3503#ifdef AUDIO_WATCHDOG
3504 if (mAudioWatchdog != 0) {
3505 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3506 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3507 wdCopy.dump(fd);
3508 }
3509#endif
3510}
3511
3512uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3513{
3514 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3515}
3516
3517uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3518{
3519 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3520}
3521
3522void AudioFlinger::MixerThread::cacheParameters_l()
3523{
3524 PlaybackThread::cacheParameters_l();
3525
3526 // FIXME: Relaxed timing because of a certain device that can't meet latency
3527 // Should be reduced to 2x after the vendor fixes the driver issue
3528 // increase threshold again due to low power audio mode. The way this warning
3529 // threshold is calculated and its usefulness should be reconsidered anyway.
3530 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3531}
3532
3533// ----------------------------------------------------------------------------
3534
3535AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3536 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3537 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3538 // mLeftVolFloat, mRightVolFloat
3539{
3540}
3541
Eric Laurentbfb1b832013-01-07 09:53:42 -08003542AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3543 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3544 ThreadBase::type_t type)
3545 : PlaybackThread(audioFlinger, output, id, device, type)
3546 // mLeftVolFloat, mRightVolFloat
3547{
3548}
3549
Eric Laurent81784c32012-11-19 14:55:58 -08003550AudioFlinger::DirectOutputThread::~DirectOutputThread()
3551{
3552}
3553
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3555{
3556 audio_track_cblk_t* cblk = track->cblk();
3557 float left, right;
3558
3559 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3560 left = right = 0;
3561 } else {
3562 float typeVolume = mStreamTypes[track->streamType()].volume;
3563 float v = mMasterVolume * typeVolume;
3564 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3565 uint32_t vlr = proxy->getVolumeLR();
3566 float v_clamped = v * (vlr & 0xFFFF);
3567 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3568 left = v_clamped/MAX_GAIN;
3569 v_clamped = v * (vlr >> 16);
3570 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3571 right = v_clamped/MAX_GAIN;
3572 }
3573
3574 if (lastTrack) {
3575 if (left != mLeftVolFloat || right != mRightVolFloat) {
3576 mLeftVolFloat = left;
3577 mRightVolFloat = right;
3578
3579 // Convert volumes from float to 8.24
3580 uint32_t vl = (uint32_t)(left * (1 << 24));
3581 uint32_t vr = (uint32_t)(right * (1 << 24));
3582
3583 // Delegate volume control to effect in track effect chain if needed
3584 // only one effect chain can be present on DirectOutputThread, so if
3585 // there is one, the track is connected to it
3586 if (!mEffectChains.isEmpty()) {
3587 mEffectChains[0]->setVolume_l(&vl, &vr);
3588 left = (float)vl / (1 << 24);
3589 right = (float)vr / (1 << 24);
3590 }
3591 if (mOutput->stream->set_volume) {
3592 mOutput->stream->set_volume(mOutput->stream, left, right);
3593 }
3594 }
3595 }
3596}
3597
3598
Eric Laurent81784c32012-11-19 14:55:58 -08003599AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3600 Vector< sp<Track> > *tracksToRemove
3601)
3602{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003603 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003604 mixer_state mixerStatus = MIXER_IDLE;
3605
3606 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003607 for (size_t i = 0; i < count; i++) {
3608 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003609 // The track died recently
3610 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003611 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003612 }
3613
3614 Track* const track = t.get();
3615 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003616 // Only consider last track started for volume and mixer state control.
3617 // In theory an older track could underrun and restart after the new one starts
3618 // but as we only care about the transition phase between two tracks on a
3619 // direct output, it is not a problem to ignore the underrun case.
3620 sp<Track> l = mLatestActiveTrack.promote();
3621 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003622
3623 // The first time a track is added we wait
3624 // for all its buffers to be filled before processing it
3625 uint32_t minFrames;
3626 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3627 minFrames = mNormalFrameCount;
3628 } else {
3629 minFrames = 1;
3630 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631
Eric Laurent81784c32012-11-19 14:55:58 -08003632 if ((track->framesReady() >= minFrames) && track->isReady() &&
3633 !track->isPaused() && !track->isTerminated())
3634 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003635 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003636
3637 if (track->mFillingUpStatus == Track::FS_FILLED) {
3638 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003639 // make sure processVolume_l() will apply new volume even if 0
3640 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 if (track->mState == TrackBase::RESUMING) {
3642 track->mState = TrackBase::ACTIVE;
3643 }
3644 }
3645
3646 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647 processVolume_l(track, last);
3648 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003649 // reset retry count
3650 track->mRetryCount = kMaxTrackRetriesDirect;
3651 mActiveTrack = t;
3652 mixerStatus = MIXER_TRACKS_READY;
3653 }
Eric Laurent81784c32012-11-19 14:55:58 -08003654 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003655 // clear effect chain input buffer if the last active track started underruns
3656 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003657 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003658 mEffectChains[0]->clearInputBuffer();
3659 }
3660
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003661 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003662 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3663 track->isStopped() || track->isPaused()) {
3664 // We have consumed all the buffers of this track.
3665 // Remove it from the list of active tracks.
3666 // TODO: implement behavior for compressed audio
3667 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3668 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003669 if (mStandby || !last ||
3670 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003671 if (track->isStopped()) {
3672 track->reset();
3673 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003674 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003675 }
3676 } else {
3677 // No buffers for this track. Give it a few chances to
3678 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003679 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003680 if (--(track->mRetryCount) <= 0) {
3681 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003682 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003683 // indicate to client process that the track was disabled because of underrun;
3684 // it will then automatically call start() when data is available
3685 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003686 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003687 mixerStatus = MIXER_TRACKS_ENABLED;
3688 }
3689 }
3690 }
3691 }
3692
Eric Laurent81784c32012-11-19 14:55:58 -08003693 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003694 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003695
3696 return mixerStatus;
3697}
3698
3699void AudioFlinger::DirectOutputThread::threadLoop_mix()
3700{
Eric Laurent81784c32012-11-19 14:55:58 -08003701 size_t frameCount = mFrameCount;
3702 int8_t *curBuf = (int8_t *)mMixBuffer;
3703 // output audio to hardware
3704 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003705 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003706 buffer.frameCount = frameCount;
3707 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003708 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003709 memset(curBuf, 0, frameCount * mFrameSize);
3710 break;
3711 }
3712 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3713 frameCount -= buffer.frameCount;
3714 curBuf += buffer.frameCount * mFrameSize;
3715 mActiveTrack->releaseBuffer(&buffer);
3716 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003718 sleepTime = 0;
3719 standbyTime = systemTime() + standbyDelay;
3720 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003721}
3722
3723void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3724{
3725 if (sleepTime == 0) {
3726 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3727 sleepTime = activeSleepTime;
3728 } else {
3729 sleepTime = idleSleepTime;
3730 }
3731 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3732 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3733 sleepTime = 0;
3734 }
3735}
3736
3737// getTrackName_l() must be called with ThreadBase::mLock held
3738int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3739 int sessionId)
3740{
3741 return 0;
3742}
3743
3744// deleteTrackName_l() must be called with ThreadBase::mLock held
3745void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3746{
3747}
3748
3749// checkForNewParameters_l() must be called with ThreadBase::mLock held
3750bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3751{
3752 bool reconfig = false;
3753
3754 while (!mNewParameters.isEmpty()) {
3755 status_t status = NO_ERROR;
3756 String8 keyValuePair = mNewParameters[0];
3757 AudioParameter param = AudioParameter(keyValuePair);
3758 int value;
3759
3760 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3761 // do not accept frame count changes if tracks are open as the track buffer
3762 // size depends on frame count and correct behavior would not be garantied
3763 // if frame count is changed after track creation
3764 if (!mTracks.isEmpty()) {
3765 status = INVALID_OPERATION;
3766 } else {
3767 reconfig = true;
3768 }
3769 }
3770 if (status == NO_ERROR) {
3771 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3772 keyValuePair.string());
3773 if (!mStandby && status == INVALID_OPERATION) {
3774 mOutput->stream->common.standby(&mOutput->stream->common);
3775 mStandby = true;
3776 mBytesWritten = 0;
3777 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3778 keyValuePair.string());
3779 }
3780 if (status == NO_ERROR && reconfig) {
3781 readOutputParameters();
3782 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3783 }
3784 }
3785
3786 mNewParameters.removeAt(0);
3787
3788 mParamStatus = status;
3789 mParamCond.signal();
3790 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3791 // already timed out waiting for the status and will never signal the condition.
3792 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3793 }
3794 return reconfig;
3795}
3796
3797uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3798{
3799 uint32_t time;
3800 if (audio_is_linear_pcm(mFormat)) {
3801 time = PlaybackThread::activeSleepTimeUs();
3802 } else {
3803 time = 10000;
3804 }
3805 return time;
3806}
3807
3808uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3809{
3810 uint32_t time;
3811 if (audio_is_linear_pcm(mFormat)) {
3812 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3813 } else {
3814 time = 10000;
3815 }
3816 return time;
3817}
3818
3819uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3820{
3821 uint32_t time;
3822 if (audio_is_linear_pcm(mFormat)) {
3823 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3824 } else {
3825 time = 10000;
3826 }
3827 return time;
3828}
3829
3830void AudioFlinger::DirectOutputThread::cacheParameters_l()
3831{
3832 PlaybackThread::cacheParameters_l();
3833
3834 // use shorter standby delay as on normal output to release
3835 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003836 if (audio_is_linear_pcm(mFormat)) {
3837 standbyDelay = microseconds(activeSleepTime*2);
3838 } else {
3839 standbyDelay = kOffloadStandbyDelayNs;
3840 }
Eric Laurent81784c32012-11-19 14:55:58 -08003841}
3842
3843// ----------------------------------------------------------------------------
3844
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003846 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003848 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003849 mWriteAckSequence(0),
3850 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003851{
3852}
3853
3854AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3855{
3856}
3857
3858void AudioFlinger::AsyncCallbackThread::onFirstRef()
3859{
3860 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3861}
3862
3863bool AudioFlinger::AsyncCallbackThread::threadLoop()
3864{
3865 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003866 uint32_t writeAckSequence;
3867 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003868
3869 {
3870 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003871 while (!((mWriteAckSequence & 1) ||
3872 (mDrainSequence & 1) ||
3873 exitPending())) {
3874 mWaitWorkCV.wait(mLock);
3875 }
3876
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877 if (exitPending()) {
3878 break;
3879 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003880 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3881 mWriteAckSequence, mDrainSequence);
3882 writeAckSequence = mWriteAckSequence;
3883 mWriteAckSequence &= ~1;
3884 drainSequence = mDrainSequence;
3885 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 }
3887 {
Eric Laurent4de95592013-09-26 15:28:21 -07003888 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3889 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003890 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003891 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003892 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003893 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003894 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895 }
3896 }
3897 }
3898 }
3899 return false;
3900}
3901
3902void AudioFlinger::AsyncCallbackThread::exit()
3903{
3904 ALOGV("AsyncCallbackThread::exit");
3905 Mutex::Autolock _l(mLock);
3906 requestExit();
3907 mWaitWorkCV.broadcast();
3908}
3909
Eric Laurent3b4529e2013-09-05 18:09:19 -07003910void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003911{
3912 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003913 // bit 0 is cleared
3914 mWriteAckSequence = sequence << 1;
3915}
3916
3917void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3918{
3919 Mutex::Autolock _l(mLock);
3920 // ignore unexpected callbacks
3921 if (mWriteAckSequence & 2) {
3922 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003923 mWaitWorkCV.signal();
3924 }
3925}
3926
Eric Laurent3b4529e2013-09-05 18:09:19 -07003927void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928{
3929 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003930 // bit 0 is cleared
3931 mDrainSequence = sequence << 1;
3932}
3933
3934void AudioFlinger::AsyncCallbackThread::resetDraining()
3935{
3936 Mutex::Autolock _l(mLock);
3937 // ignore unexpected callbacks
3938 if (mDrainSequence & 2) {
3939 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003940 mWaitWorkCV.signal();
3941 }
3942}
3943
3944
3945// ----------------------------------------------------------------------------
3946AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3947 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3948 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3949 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003950 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003951 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003952{
Eric Laurentfd477972013-10-25 18:10:40 -07003953 //FIXME: mStandby should be set to true by ThreadBase constructor
3954 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003955}
3956
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957void AudioFlinger::OffloadThread::threadLoop_exit()
3958{
3959 if (mFlushPending || mHwPaused) {
3960 // If a flush is pending or track was paused, just discard buffered data
3961 flushHw_l();
3962 } else {
3963 mMixerStatus = MIXER_DRAIN_ALL;
3964 threadLoop_drain();
3965 }
3966 mCallbackThread->exit();
3967 PlaybackThread::threadLoop_exit();
3968}
3969
3970AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3971 Vector< sp<Track> > *tracksToRemove
3972)
3973{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003974 size_t count = mActiveTracks.size();
3975
3976 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003977 bool doHwPause = false;
3978 bool doHwResume = false;
3979
Eric Laurentede6c3b2013-09-19 14:37:46 -07003980 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3981
Eric Laurentbfb1b832013-01-07 09:53:42 -08003982 // find out which tracks need to be processed
3983 for (size_t i = 0; i < count; i++) {
3984 sp<Track> t = mActiveTracks[i].promote();
3985 // The track died recently
3986 if (t == 0) {
3987 continue;
3988 }
3989 Track* const track = t.get();
3990 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003991 // Only consider last track started for volume and mixer state control.
3992 // In theory an older track could underrun and restart after the new one starts
3993 // but as we only care about the transition phase between two tracks on a
3994 // direct output, it is not a problem to ignore the underrun case.
3995 sp<Track> l = mLatestActiveTrack.promote();
3996 bool last = l.get() == track;
3997
Eric Laurentbfb1b832013-01-07 09:53:42 -08003998 if (track->isPausing()) {
3999 track->setPaused();
4000 if (last) {
4001 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004002 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004003 mHwPaused = true;
4004 }
4005 // If we were part way through writing the mixbuffer to
4006 // the HAL we must save this until we resume
4007 // BUG - this will be wrong if a different track is made active,
4008 // in that case we want to discard the pending data in the
4009 // mixbuffer and tell the client to present it again when the
4010 // track is resumed
4011 mPausedWriteLength = mCurrentWriteLength;
4012 mPausedBytesRemaining = mBytesRemaining;
4013 mBytesRemaining = 0; // stop writing
4014 }
4015 tracksToRemove->add(track);
4016 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004017 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004018 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004019 if (track->mFillingUpStatus == Track::FS_FILLED) {
4020 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004021 // make sure processVolume_l() will apply new volume even if 0
4022 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004023 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004025 if (last) {
4026 if (mPausedBytesRemaining) {
4027 // Need to continue write that was interrupted
4028 mCurrentWriteLength = mPausedWriteLength;
4029 mBytesRemaining = mPausedBytesRemaining;
4030 mPausedBytesRemaining = 0;
4031 }
4032 if (mHwPaused) {
4033 doHwResume = true;
4034 mHwPaused = false;
4035 // threadLoop_mix() will handle the case that we need to
4036 // resume an interrupted write
4037 }
4038 // enable write to audio HAL
4039 sleepTime = 0;
4040 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 }
4042 }
4043
4044 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004045 sp<Track> previousTrack = mPreviousTrack.promote();
4046 if (previousTrack != 0) {
4047 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004048 // Flush any data still being written from last track
4049 mBytesRemaining = 0;
4050 if (mPausedBytesRemaining) {
4051 // Last track was paused so we also need to flush saved
4052 // mixbuffer state and invalidate track so that it will
4053 // re-submit that unwritten data when it is next resumed
4054 mPausedBytesRemaining = 0;
4055 // Invalidate is a bit drastic - would be more efficient
4056 // to have a flag to tell client that some of the
4057 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004058 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004059 }
4060 // flush data already sent to the DSP if changing audio session as audio
4061 // comes from a different source. Also invalidate previous track to force a
4062 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004063 if (previousTrack->sessionId() != track->sessionId()) {
4064 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004065 mFlushPending = true;
4066 }
4067 }
4068 }
4069 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 // reset retry count
4071 track->mRetryCount = kMaxTrackRetriesOffload;
4072 mActiveTrack = t;
4073 mixerStatus = MIXER_TRACKS_READY;
4074 }
4075 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004076 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 if (track->isStopping_1()) {
4078 // Hardware buffer can hold a large amount of audio so we must
4079 // wait for all current track's data to drain before we say
4080 // that the track is stopped.
4081 if (mBytesRemaining == 0) {
4082 // Only start draining when all data in mixbuffer
4083 // has been written
4084 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4085 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004086 // do not drain if no data was ever sent to HAL (mStandby == true)
4087 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004088 // do not modify drain sequence if we are already draining. This happens
4089 // when resuming from pause after drain.
4090 if ((mDrainSequence & 1) == 0) {
4091 sleepTime = 0;
4092 standbyTime = systemTime() + standbyDelay;
4093 mixerStatus = MIXER_DRAIN_TRACK;
4094 mDrainSequence += 2;
4095 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 if (mHwPaused) {
4097 // It is possible to move from PAUSED to STOPPING_1 without
4098 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004099 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 mHwPaused = false;
4101 }
4102 }
4103 }
4104 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004105 // Drain has completed or we are in standby, signal presentation complete
4106 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 track->mState = TrackBase::STOPPED;
4108 size_t audioHALFrames =
4109 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4110 size_t framesWritten =
4111 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4112 track->presentationComplete(framesWritten, audioHALFrames);
4113 track->reset();
4114 tracksToRemove->add(track);
4115 }
4116 } else {
4117 // No buffers for this track. Give it a few chances to
4118 // fill a buffer, then remove it from active list.
4119 if (--(track->mRetryCount) <= 0) {
4120 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4121 track->name());
4122 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004123 // indicate to client process that the track was disabled because of underrun;
4124 // it will then automatically call start() when data is available
4125 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126 } else if (last){
4127 mixerStatus = MIXER_TRACKS_ENABLED;
4128 }
4129 }
4130 }
4131 // compute volume for this track
4132 processVolume_l(track, last);
4133 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004134
Eric Laurentea0fade2013-10-04 16:23:48 -07004135 // make sure the pause/flush/resume sequence is executed in the right order.
4136 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4137 // before flush and then resume HW. This can happen in case of pause/flush/resume
4138 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004139 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004140 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004141 if (!doHwPause) {
4142 doHwResume = true;
4143 }
Eric Laurent972a1732013-09-04 09:42:59 -07004144 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004145 if (mFlushPending) {
4146 flushHw_l();
4147 mFlushPending = false;
4148 }
Eric Laurentfd477972013-10-25 18:10:40 -07004149 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004150 mOutput->stream->resume(mOutput->stream);
4151 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004152
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153 // remove all the tracks that need to be...
4154 removeTracks_l(*tracksToRemove);
4155
4156 return mixerStatus;
4157}
4158
4159void AudioFlinger::OffloadThread::flushOutput_l()
4160{
4161 mFlushPending = true;
4162}
4163
4164// must be called with thread mutex locked
4165bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4166{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004167 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4168 mWriteAckSequence, mDrainSequence);
4169 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 return true;
4171 }
4172 return false;
4173}
4174
4175// must be called with thread mutex locked
4176bool AudioFlinger::OffloadThread::shouldStandby_l()
4177{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004178 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004179
4180 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4181 // after a timeout and we will enter standby then.
4182 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004183 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 }
4185
Glenn Kastene6f35b12013-08-19 09:58:50 -07004186 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187}
4188
4189
4190bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4191{
4192 Mutex::Autolock _l(mLock);
4193 return waitingAsyncCallback_l();
4194}
4195
4196void AudioFlinger::OffloadThread::flushHw_l()
4197{
4198 mOutput->stream->flush(mOutput->stream);
4199 // Flush anything still waiting in the mixbuffer
4200 mCurrentWriteLength = 0;
4201 mBytesRemaining = 0;
4202 mPausedWriteLength = 0;
4203 mPausedBytesRemaining = 0;
4204 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004205 // discard any pending drain or write ack by incrementing sequence
4206 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4207 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004208 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004209 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4210 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004211 }
4212}
4213
4214// ----------------------------------------------------------------------------
4215
Eric Laurent81784c32012-11-19 14:55:58 -08004216AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4217 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4218 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4219 DUPLICATING),
4220 mWaitTimeMs(UINT_MAX)
4221{
4222 addOutputTrack(mainThread);
4223}
4224
4225AudioFlinger::DuplicatingThread::~DuplicatingThread()
4226{
4227 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4228 mOutputTracks[i]->destroy();
4229 }
4230}
4231
4232void AudioFlinger::DuplicatingThread::threadLoop_mix()
4233{
4234 // mix buffers...
4235 if (outputsReady(outputTracks)) {
4236 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4237 } else {
4238 memset(mMixBuffer, 0, mixBufferSize);
4239 }
4240 sleepTime = 0;
4241 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004242 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004243 standbyTime = systemTime() + standbyDelay;
4244}
4245
4246void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4247{
4248 if (sleepTime == 0) {
4249 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4250 sleepTime = activeSleepTime;
4251 } else {
4252 sleepTime = idleSleepTime;
4253 }
4254 } else if (mBytesWritten != 0) {
4255 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4256 writeFrames = mNormalFrameCount;
4257 memset(mMixBuffer, 0, mixBufferSize);
4258 } else {
4259 // flush remaining overflow buffers in output tracks
4260 writeFrames = 0;
4261 }
4262 sleepTime = 0;
4263 }
4264}
4265
Eric Laurentbfb1b832013-01-07 09:53:42 -08004266ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004267{
4268 for (size_t i = 0; i < outputTracks.size(); i++) {
4269 outputTracks[i]->write(mMixBuffer, writeFrames);
4270 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004271 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004273}
4274
4275void AudioFlinger::DuplicatingThread::threadLoop_standby()
4276{
4277 // DuplicatingThread implements standby by stopping all tracks
4278 for (size_t i = 0; i < outputTracks.size(); i++) {
4279 outputTracks[i]->stop();
4280 }
4281}
4282
4283void AudioFlinger::DuplicatingThread::saveOutputTracks()
4284{
4285 outputTracks = mOutputTracks;
4286}
4287
4288void AudioFlinger::DuplicatingThread::clearOutputTracks()
4289{
4290 outputTracks.clear();
4291}
4292
4293void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4294{
4295 Mutex::Autolock _l(mLock);
4296 // FIXME explain this formula
4297 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4298 OutputTrack *outputTrack = new OutputTrack(thread,
4299 this,
4300 mSampleRate,
4301 mFormat,
4302 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004303 frameCount,
4304 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004305 if (outputTrack->cblk() != NULL) {
4306 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4307 mOutputTracks.add(outputTrack);
4308 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4309 updateWaitTime_l();
4310 }
4311}
4312
4313void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4314{
4315 Mutex::Autolock _l(mLock);
4316 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4317 if (mOutputTracks[i]->thread() == thread) {
4318 mOutputTracks[i]->destroy();
4319 mOutputTracks.removeAt(i);
4320 updateWaitTime_l();
4321 return;
4322 }
4323 }
4324 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4325}
4326
4327// caller must hold mLock
4328void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4329{
4330 mWaitTimeMs = UINT_MAX;
4331 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4332 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4333 if (strong != 0) {
4334 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4335 if (waitTimeMs < mWaitTimeMs) {
4336 mWaitTimeMs = waitTimeMs;
4337 }
4338 }
4339 }
4340}
4341
4342
4343bool AudioFlinger::DuplicatingThread::outputsReady(
4344 const SortedVector< sp<OutputTrack> > &outputTracks)
4345{
4346 for (size_t i = 0; i < outputTracks.size(); i++) {
4347 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4348 if (thread == 0) {
4349 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4350 outputTracks[i].get());
4351 return false;
4352 }
4353 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4354 // see note at standby() declaration
4355 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4356 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4357 thread.get());
4358 return false;
4359 }
4360 }
4361 return true;
4362}
4363
4364uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4365{
4366 return (mWaitTimeMs * 1000) / 2;
4367}
4368
4369void AudioFlinger::DuplicatingThread::cacheParameters_l()
4370{
4371 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4372 updateWaitTime_l();
4373
4374 MixerThread::cacheParameters_l();
4375}
4376
4377// ----------------------------------------------------------------------------
4378// Record
4379// ----------------------------------------------------------------------------
4380
4381AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4382 AudioStreamIn *input,
4383 uint32_t sampleRate,
4384 audio_channel_mask_t channelMask,
4385 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004386 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004387 audio_devices_t inDevice
4388#ifdef TEE_SINK
4389 , const sp<NBAIO_Sink>& teeSink
4390#endif
4391 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004392 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten2b806402013-11-20 16:37:38 -08004393 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten85948432013-08-19 12:09:05 -07004394 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear
4395 // are set by readInputParameters()
4396 // mRsmpInIndex LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004397 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004398 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004399 // mBytesRead is only meaningful while active, and so is cleared in start()
4400 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004401#ifdef TEE_SINK
4402 , mTeeSink(teeSink)
4403#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004404{
4405 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004406 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004407
4408 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004409}
4410
4411
4412AudioFlinger::RecordThread::~RecordThread()
4413{
Glenn Kasten481fb672013-09-30 14:39:28 -07004414 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004415 delete[] mRsmpInBuffer;
4416 delete mResampler;
4417 delete[] mRsmpOutBuffer;
4418}
4419
4420void AudioFlinger::RecordThread::onFirstRef()
4421{
4422 run(mName, PRIORITY_URGENT_AUDIO);
4423}
4424
Eric Laurent81784c32012-11-19 14:55:58 -08004425bool AudioFlinger::RecordThread::threadLoop()
4426{
Eric Laurent81784c32012-11-19 14:55:58 -08004427 nsecs_t lastWarning = 0;
4428
4429 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004430
4431 // used to verify we've read at least once before evaluating how many bytes were read
4432 bool readOnce = false;
4433
Glenn Kasten5edadd42013-08-14 16:30:49 -07004434 // used to request a deferred sleep, to be executed later while mutex is unlocked
4435 bool doSleep = false;
4436
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004437reacquire_wakelock:
4438 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004439 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004440 {
4441 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004442 size_t size = mActiveTracks.size();
4443 activeTracksGen = mActiveTracksGen;
4444 if (size > 0) {
4445 // FIXME an arbitrary choice
4446 activeTrack = mActiveTracks[0];
4447 acquireWakeLock_l(activeTrack->uid());
4448 if (size > 1) {
4449 SortedVector<int> tmp;
4450 for (size_t i = 0; i < size; i++) {
4451 tmp.add(mActiveTracks[i]->uid());
4452 }
4453 updateWakeLockUids_l(tmp);
4454 }
4455 } else {
4456 acquireWakeLock_l(-1);
4457 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004458 }
4459
Eric Laurent81784c32012-11-19 14:55:58 -08004460 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004461 for (;;) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004462 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004463 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004464
Glenn Kasten5edadd42013-08-14 16:30:49 -07004465 // sleep with mutex unlocked
4466 if (doSleep) {
4467 doSleep = false;
4468 usleep(kRecordThreadSleepUs);
4469 }
4470
Eric Laurent81784c32012-11-19 14:55:58 -08004471 { // scope for mLock
4472 Mutex::Autolock _l(mLock);
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004473 if (exitPending()) {
4474 break;
4475 }
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004476 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004477 // return value 'reconfig' is currently unused
4478 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004479
Glenn Kasten2b806402013-11-20 16:37:38 -08004480 // if no active track(s), then standby and release wakelock
4481 size_t size = mActiveTracks.size();
4482 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004483 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004484 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004485 releaseWakeLock_l();
4486 ALOGV("RecordThread: loop stopping");
4487 // go to sleep
4488 mWaitWorkCV.wait(mLock);
4489 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004490 goto reacquire_wakelock;
4491 }
4492
Glenn Kasten2b806402013-11-20 16:37:38 -08004493 if (mActiveTracksGen != activeTracksGen) {
4494 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004495 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004496 for (size_t i = 0; i < size; i++) {
4497 tmp.add(mActiveTracks[i]->uid());
4498 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004499 updateWakeLockUids_l(tmp);
Glenn Kasten2b806402013-11-20 16:37:38 -08004500 // FIXME an arbitrary choice
4501 activeTrack = mActiveTracks[0];
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004503
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004504 if (activeTrack->isTerminated()) {
4505 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004506 mActiveTracks.remove(activeTrack);
4507 mActiveTracksGen++;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004508 continue;
4509 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004510
Glenn Kastenb86432b2013-08-14 15:08:12 -07004511 activeTrackState = activeTrack->mState;
4512 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004513 case TrackBase::PAUSING:
Glenn Kasten93e471f2013-08-19 08:40:07 -07004514 standbyIfNotAlreadyInStandby();
Glenn Kasten2b806402013-11-20 16:37:38 -08004515 mActiveTracks.remove(activeTrack);
4516 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004517 mStartStopCond.broadcast();
4518 doSleep = true;
4519 continue;
4520
4521 case TrackBase::RESUMING:
4522 mStandby = false;
4523 if (mReqChannelCount != activeTrack->channelCount()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004524 mActiveTracks.remove(activeTrack);
4525 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004526 mStartStopCond.broadcast();
4527 continue;
4528 }
4529 if (readOnce) {
4530 mStartStopCond.broadcast();
4531 // record start succeeds only if first read from audio input succeeds
4532 if (mBytesRead < 0) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004533 mActiveTracks.remove(activeTrack);
4534 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004535 continue;
4536 }
4537 activeTrack->mState = TrackBase::ACTIVE;
4538 }
4539 break;
4540
4541 case TrackBase::ACTIVE:
4542 break;
4543
4544 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004545 doSleep = true;
4546 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004547
4548 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004549 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004550 }
4551
Eric Laurent81784c32012-11-19 14:55:58 -08004552 lockEffectChains_l(effectChains);
4553 }
4554
Glenn Kasten2b806402013-11-20 16:37:38 -08004555 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004556 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4557
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004558 for (size_t i = 0; i < effectChains.size(); i ++) {
4559 // thread mutex is not locked, but effect chain is locked
4560 effectChains[i]->process_l();
4561 }
4562
Glenn Kastenb91aa632013-08-19 08:40:21 -07004563 AudioBufferProvider::Buffer buffer;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004564 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004565 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004566 if (status == NO_ERROR) {
4567 readOnce = true;
4568 size_t framesOut = buffer.frameCount;
4569 if (mResampler == NULL) {
4570 // no resampling
4571 while (framesOut) {
4572 size_t framesIn = mFrameCount - mRsmpInIndex;
4573 if (framesIn > 0) {
4574 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4575 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004576 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004577 if (framesIn > framesOut) {
4578 framesIn = framesOut;
4579 }
4580 mRsmpInIndex += framesIn;
4581 framesOut -= framesIn;
4582 if (mChannelCount == mReqChannelCount) {
4583 memcpy(dst, src, framesIn * mFrameSize);
4584 } else {
4585 if (mChannelCount == 1) {
4586 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4587 (int16_t *)src, framesIn);
4588 } else {
4589 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4590 (int16_t *)src, framesIn);
4591 }
4592 }
4593 }
4594 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4595 void *readInto;
4596 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4597 readInto = buffer.raw;
4598 framesOut = 0;
4599 } else {
4600 readInto = mRsmpInBuffer;
4601 mRsmpInIndex = 0;
4602 }
4603 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4604 mBufferSize);
4605 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004606 // TODO: verify that it's benign to use a stale track state
4607 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004608 {
4609 ALOGE("Error reading audio input");
4610 // Force input into standby so that it tries to
4611 // recover at next read attempt
4612 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004613 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004614 }
4615 mRsmpInIndex = mFrameCount;
4616 framesOut = 0;
4617 buffer.frameCount = 0;
4618 }
4619#ifdef TEE_SINK
4620 else if (mTeeSink != 0) {
4621 (void) mTeeSink->write(readInto,
4622 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4623 }
4624#endif
4625 }
4626 }
4627 } else {
4628 // resampling
4629
Glenn Kasten85948432013-08-19 12:09:05 -07004630 // avoid busy-waiting if client doesn't keep up
4631 bool madeProgress = false;
4632
4633 // keep mRsmpInBuffer full so resampler always has sufficient input
4634 for (;;) {
4635 int32_t rear = mRsmpInRear;
4636 ssize_t filled = rear - mRsmpInFront;
4637 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
4638 // exit once there is enough data in buffer for resampler
4639 if ((size_t) filled >= mRsmpInFrames) {
4640 break;
4641 }
4642 size_t avail = mRsmpInFramesP2 - filled;
4643 // Only try to read full HAL buffers.
4644 // But if the HAL read returns a partial buffer, use it.
4645 if (avail < mFrameCount) {
4646 ALOGE("insufficient space to read: avail %d < mFrameCount %d",
4647 avail, mFrameCount);
4648 break;
4649 }
4650 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then
4651 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
4652 rear &= mRsmpInFramesP2 - 1;
4653 mBytesRead = mInput->stream->read(mInput->stream,
4654 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4655 if (mBytesRead <= 0) {
4656 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize);
4657 break;
4658 }
4659 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize);
4660 size_t framesRead = mBytesRead / mFrameSize;
4661 ALOG_ASSERT(framesRead > 0);
4662 madeProgress = true;
4663 // If 'avail' was non-contiguous, we now correct for reading past end of buffer.
4664 size_t part1 = mRsmpInFramesP2 - rear;
4665 if (framesRead > part1) {
4666 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4667 (framesRead - part1) * mFrameSize);
4668 }
4669 mRsmpInRear += framesRead;
4670 }
4671
4672 if (!madeProgress) {
4673 ALOGV("Did not make progress");
4674 usleep(((mFrameCount * 1000) / mSampleRate) * 1000);
4675 }
4676
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004677 // resampler accumulates, but we only have one source track
4678 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004679 mResampler->resample(mRsmpOutBuffer, framesOut,
4680 this /* AudioBufferProvider* */);
4681 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004682 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten85948432013-08-19 12:09:05 -07004683 if (mReqChannelCount == 1) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004684 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4685 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4686 // the resampler always outputs stereo samples:
4687 // do post stereo to mono conversion
4688 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4689 framesOut);
4690 } else {
4691 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4692 }
4693 // now done with mRsmpOutBuffer
4694
4695 }
4696 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004697 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004698 } else {
4699 if (mFramestoDrop > 0) {
4700 mFramestoDrop -= buffer.frameCount;
4701 if (mFramestoDrop <= 0) {
4702 clearSyncStartEvent();
4703 }
4704 } else {
4705 mFramestoDrop += buffer.frameCount;
4706 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4707 mSyncStartEvent->isCancelled()) {
4708 ALOGW("Synced record %s, session %d, trigger session %d",
4709 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004710 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004711 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4712 clearSyncStartEvent();
4713 }
4714 }
4715 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004716 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004717 }
4718 // client isn't retrieving buffers fast enough
4719 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004720 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004721 nsecs_t now = systemTime();
4722 if ((now - lastWarning) > kWarningThrottleNs) {
4723 ALOGW("RecordThread: buffer overflow");
4724 lastWarning = now;
4725 }
4726 }
4727 // Release the processor for a while before asking for a new buffer.
4728 // This will give the application more chance to read from the buffer and
4729 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004730 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004731 }
4732
Eric Laurent81784c32012-11-19 14:55:58 -08004733 // enable changes in effect chain
4734 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004735 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004736 }
4737
Glenn Kasten93e471f2013-08-19 08:40:07 -07004738 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004739
4740 {
4741 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004742 for (size_t i = 0; i < mTracks.size(); i++) {
4743 sp<RecordTrack> track = mTracks[i];
4744 track->invalidate();
4745 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004746 mActiveTracks.clear();
4747 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004748 mStartStopCond.broadcast();
4749 }
4750
4751 releaseWakeLock();
4752
4753 ALOGV("RecordThread %p exiting", this);
4754 return false;
4755}
4756
Glenn Kasten93e471f2013-08-19 08:40:07 -07004757void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004758{
4759 if (!mStandby) {
4760 inputStandBy();
4761 mStandby = true;
4762 }
4763}
4764
4765void AudioFlinger::RecordThread::inputStandBy()
4766{
4767 mInput->stream->common.standby(&mInput->stream->common);
4768}
4769
Glenn Kastene198c362013-08-13 09:13:36 -07004770sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004771 const sp<AudioFlinger::Client>& client,
4772 uint32_t sampleRate,
4773 audio_format_t format,
4774 audio_channel_mask_t channelMask,
4775 size_t frameCount,
4776 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004777 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004778 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004779 pid_t tid,
4780 status_t *status)
4781{
4782 sp<RecordTrack> track;
4783 status_t lStatus;
4784
4785 lStatus = initCheck();
4786 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004787 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004788 goto Exit;
4789 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004790 // client expresses a preference for FAST, but we get the final say
4791 if (*flags & IAudioFlinger::TRACK_FAST) {
4792 if (
4793 // use case: callback handler and frame count is default or at least as large as HAL
4794 (
4795 (tid != -1) &&
4796 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004797 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004798 ) &&
4799 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4800 // mono or stereo
4801 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4802 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4803 // hardware sample rate
4804 (sampleRate == mSampleRate) &&
4805 // record thread has an associated fast recorder
4806 hasFastRecorder()
4807 // FIXME test that RecordThread for this fast track has a capable output HAL
4808 // FIXME add a permission test also?
4809 ) {
4810 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4811 if (frameCount == 0) {
4812 frameCount = mFrameCount * kFastTrackMultiplier;
4813 }
4814 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4815 frameCount, mFrameCount);
4816 } else {
4817 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4818 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4819 "hasFastRecorder=%d tid=%d",
4820 frameCount, mFrameCount, format,
4821 audio_is_linear_pcm(format),
4822 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4823 *flags &= ~IAudioFlinger::TRACK_FAST;
4824 // For compatibility with AudioRecord calculation, buffer depth is forced
4825 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4826 // This is probably too conservative, but legacy application code may depend on it.
4827 // If you change this calculation, also review the start threshold which is related.
4828 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4829 size_t mNormalFrameCount = 2048; // FIXME
4830 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4831 if (minBufCount < 2) {
4832 minBufCount = 2;
4833 }
4834 size_t minFrameCount = mNormalFrameCount * minBufCount;
4835 if (frameCount < minFrameCount) {
4836 frameCount = minFrameCount;
4837 }
4838 }
4839 }
4840
Eric Laurent81784c32012-11-19 14:55:58 -08004841 // FIXME use flags and tid similar to createTrack_l()
4842
4843 { // scope for mLock
4844 Mutex::Autolock _l(mLock);
4845
4846 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004847 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004848
Glenn Kasten03003332013-08-06 15:40:54 -07004849 lStatus = track->initCheck();
4850 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004851 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07004852 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004853 goto Exit;
4854 }
4855 mTracks.add(track);
4856
4857 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4858 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4859 mAudioFlinger->btNrecIsOff();
4860 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4861 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004862
4863 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4864 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4865 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4866 // so ask activity manager to do this on our behalf
4867 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4868 }
Eric Laurent81784c32012-11-19 14:55:58 -08004869 }
4870 lStatus = NO_ERROR;
4871
4872Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004873 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004874 return track;
4875}
4876
4877status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4878 AudioSystem::sync_event_t event,
4879 int triggerSession)
4880{
4881 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4882 sp<ThreadBase> strongMe = this;
4883 status_t status = NO_ERROR;
4884
4885 if (event == AudioSystem::SYNC_EVENT_NONE) {
4886 clearSyncStartEvent();
4887 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4888 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4889 triggerSession,
4890 recordTrack->sessionId(),
4891 syncStartEventCallback,
4892 this);
4893 // Sync event can be cancelled by the trigger session if the track is not in a
4894 // compatible state in which case we start record immediately
4895 if (mSyncStartEvent->isCancelled()) {
4896 clearSyncStartEvent();
4897 } else {
4898 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4899 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4900 }
4901 }
4902
4903 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004904 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004905 AutoMutex lock(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004906 if (mActiveTracks.size() > 0) {
4907 // FIXME does not work for multiple active tracks
4908 if (mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004909 status = -EBUSY;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004910 } else if (recordTrack->mState == TrackBase::PAUSING) {
4911 recordTrack->mState = TrackBase::ACTIVE;
Eric Laurent81784c32012-11-19 14:55:58 -08004912 }
4913 return status;
4914 }
4915
Glenn Kasten47c20702013-08-13 15:37:35 -07004916 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004917 recordTrack->mState = TrackBase::IDLE;
Glenn Kasten2b806402013-11-20 16:37:38 -08004918 mActiveTracks.add(recordTrack);
4919 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004920 mLock.unlock();
4921 status_t status = AudioSystem::startInput(mId);
4922 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004923 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004924 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004925 mActiveTracks.remove(recordTrack);
4926 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004927 clearSyncStartEvent();
4928 return status;
4929 }
Glenn Kasten85948432013-08-19 12:09:05 -07004930 // FIXME LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004931 mRsmpInIndex = mFrameCount;
Glenn Kasten85948432013-08-19 12:09:05 -07004932 mRsmpInFront = 0;
4933 mRsmpInRear = 0;
4934 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004935 mBytesRead = 0;
4936 if (mResampler != NULL) {
4937 mResampler->reset();
4938 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004939 // FIXME hijacking a playback track state name which was intended for start after pause;
4940 // here 'STARTING_2' would be more accurate
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004941 recordTrack->mState = TrackBase::RESUMING;
Eric Laurent81784c32012-11-19 14:55:58 -08004942 // signal thread to start
4943 ALOGV("Signal record thread");
4944 mWaitWorkCV.broadcast();
4945 // do not wait for mStartStopCond if exiting
4946 if (exitPending()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004947 mActiveTracks.remove(recordTrack);
4948 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004949 status = INVALID_OPERATION;
4950 goto startError;
4951 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004952 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004953 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004954 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004955 ALOGV("Record failed to start");
4956 status = BAD_VALUE;
4957 goto startError;
4958 }
4959 ALOGV("Record started OK");
4960 return status;
4961 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004962
Eric Laurent81784c32012-11-19 14:55:58 -08004963startError:
4964 AudioSystem::stopInput(mId);
4965 clearSyncStartEvent();
4966 return status;
4967}
4968
4969void AudioFlinger::RecordThread::clearSyncStartEvent()
4970{
4971 if (mSyncStartEvent != 0) {
4972 mSyncStartEvent->cancel();
4973 }
4974 mSyncStartEvent.clear();
4975 mFramestoDrop = 0;
4976}
4977
4978void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4979{
4980 sp<SyncEvent> strongEvent = event.promote();
4981
4982 if (strongEvent != 0) {
4983 RecordThread *me = (RecordThread *)strongEvent->cookie();
4984 me->handleSyncStartEvent(strongEvent);
4985 }
4986}
4987
4988void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4989{
4990 if (event == mSyncStartEvent) {
4991 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4992 // from audio HAL
4993 mFramestoDrop = mFrameCount * 2;
4994 }
4995}
4996
Glenn Kastena8356f62013-07-25 14:37:52 -07004997bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004998 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004999 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005000 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005001 return false;
5002 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005003 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005004 recordTrack->mState = TrackBase::PAUSING;
5005 // do not wait for mStartStopCond if exiting
5006 if (exitPending()) {
5007 return true;
5008 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005009 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005010 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005011 // if we have been restarted, recordTrack is in mActiveTracks here
5012 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013 ALOGV("Record stopped OK");
5014 return true;
5015 }
5016 return false;
5017}
5018
5019bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
5020{
5021 return false;
5022}
5023
5024status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5025{
5026#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5027 if (!isValidSyncEvent(event)) {
5028 return BAD_VALUE;
5029 }
5030
5031 int eventSession = event->triggerSession();
5032 status_t ret = NAME_NOT_FOUND;
5033
5034 Mutex::Autolock _l(mLock);
5035
5036 for (size_t i = 0; i < mTracks.size(); i++) {
5037 sp<RecordTrack> track = mTracks[i];
5038 if (eventSession == track->sessionId()) {
5039 (void) track->setSyncEvent(event);
5040 ret = NO_ERROR;
5041 }
5042 }
5043 return ret;
5044#else
5045 return BAD_VALUE;
5046#endif
5047}
5048
5049// destroyTrack_l() must be called with ThreadBase::mLock held
5050void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5051{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005052 track->terminate();
5053 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005055 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005056 removeTrack_l(track);
5057 }
5058}
5059
5060void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5061{
5062 mTracks.remove(track);
5063 // need anything related to effects here?
5064}
5065
5066void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5067{
5068 dumpInternals(fd, args);
5069 dumpTracks(fd, args);
5070 dumpEffectChains(fd, args);
5071}
5072
5073void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5074{
5075 const size_t SIZE = 256;
5076 char buffer[SIZE];
5077 String8 result;
5078
5079 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5080 result.append(buffer);
5081
Glenn Kasten2b806402013-11-20 16:37:38 -08005082 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005083 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5084 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08005085 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005086 result.append(buffer);
5087 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5088 result.append(buffer);
5089 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
5090 result.append(buffer);
5091 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
5092 result.append(buffer);
5093 } else {
5094 result.append("No active record client\n");
5095 }
5096
5097 write(fd, result.string(), result.size());
5098
5099 dumpBase(fd, args);
5100}
5101
5102void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
5103{
5104 const size_t SIZE = 256;
5105 char buffer[SIZE];
5106 String8 result;
5107
5108 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5109 result.append(buffer);
5110 RecordTrack::appendDumpHeader(result);
5111 for (size_t i = 0; i < mTracks.size(); ++i) {
5112 sp<RecordTrack> track = mTracks[i];
5113 if (track != 0) {
5114 track->dump(buffer, SIZE);
5115 result.append(buffer);
5116 }
5117 }
5118
Glenn Kasten2b806402013-11-20 16:37:38 -08005119 size_t size = mActiveTracks.size();
5120 if (size > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005121 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5122 result.append(buffer);
5123 RecordTrack::appendDumpHeader(result);
Glenn Kasten2b806402013-11-20 16:37:38 -08005124 for (size_t i = 0; i < size; ++i) {
5125 sp<RecordTrack> track = mActiveTracks[i];
5126 track->dump(buffer, SIZE);
5127 result.append(buffer);
5128 }
Eric Laurent81784c32012-11-19 14:55:58 -08005129
5130 }
5131 write(fd, result.string(), result.size());
5132}
5133
5134// AudioBufferProvider interface
5135status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5136{
Glenn Kasten85948432013-08-19 12:09:05 -07005137 int32_t rear = mRsmpInRear;
5138 int32_t front = mRsmpInFront;
5139 ssize_t filled = rear - front;
5140 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
5141 // 'filled' may be non-contiguous, so return only the first contiguous chunk
5142 front &= mRsmpInFramesP2 - 1;
5143 size_t part1 = mRsmpInFramesP2 - front;
5144 if (part1 > (size_t) filled) {
5145 part1 = filled;
5146 }
5147 size_t ask = buffer->frameCount;
5148 ALOG_ASSERT(ask > 0);
5149 if (part1 > ask) {
5150 part1 = ask;
5151 }
5152 if (part1 == 0) {
5153 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5154 ALOGE("RecordThread::getNextBuffer() starved");
5155 buffer->raw = NULL;
5156 buffer->frameCount = 0;
5157 mRsmpInUnrel = 0;
5158 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005159 }
5160
Glenn Kasten85948432013-08-19 12:09:05 -07005161 buffer->raw = mRsmpInBuffer + front * mChannelCount;
5162 buffer->frameCount = part1;
5163 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005164 return NO_ERROR;
5165}
5166
5167// AudioBufferProvider interface
5168void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5169{
Glenn Kasten85948432013-08-19 12:09:05 -07005170 size_t stepCount = buffer->frameCount;
5171 if (stepCount == 0) {
5172 return;
5173 }
5174 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
5175 mRsmpInUnrel -= stepCount;
5176 mRsmpInFront += stepCount;
5177 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005178 buffer->frameCount = 0;
5179}
5180
5181bool AudioFlinger::RecordThread::checkForNewParameters_l()
5182{
5183 bool reconfig = false;
5184
5185 while (!mNewParameters.isEmpty()) {
5186 status_t status = NO_ERROR;
5187 String8 keyValuePair = mNewParameters[0];
5188 AudioParameter param = AudioParameter(keyValuePair);
5189 int value;
5190 audio_format_t reqFormat = mFormat;
5191 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005192 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005193
5194 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5195 reqSamplingRate = value;
5196 reconfig = true;
5197 }
5198 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005199 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5200 status = BAD_VALUE;
5201 } else {
5202 reqFormat = (audio_format_t) value;
5203 reconfig = true;
5204 }
Eric Laurent81784c32012-11-19 14:55:58 -08005205 }
5206 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005207 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5208 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5209 status = BAD_VALUE;
5210 } else {
5211 reqChannelMask = mask;
5212 reconfig = true;
5213 }
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
5215 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5216 // do not accept frame count changes if tracks are open as the track buffer
5217 // size depends on frame count and correct behavior would not be guaranteed
5218 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005219 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005220 status = INVALID_OPERATION;
5221 } else {
5222 reconfig = true;
5223 }
5224 }
5225 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5226 // forward device change to effects that have requested to be
5227 // aware of attached audio device.
5228 for (size_t i = 0; i < mEffectChains.size(); i++) {
5229 mEffectChains[i]->setDevice_l(value);
5230 }
5231
5232 // store input device and output device but do not forward output device to audio HAL.
5233 // Note that status is ignored by the caller for output device
5234 // (see AudioFlinger::setParameters()
5235 if (audio_is_output_devices(value)) {
5236 mOutDevice = value;
5237 status = BAD_VALUE;
5238 } else {
5239 mInDevice = value;
5240 // disable AEC and NS if the device is a BT SCO headset supporting those
5241 // pre processings
5242 if (mTracks.size() > 0) {
5243 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5244 mAudioFlinger->btNrecIsOff();
5245 for (size_t i = 0; i < mTracks.size(); i++) {
5246 sp<RecordTrack> track = mTracks[i];
5247 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5248 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5249 }
5250 }
5251 }
5252 }
5253 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5254 mAudioSource != (audio_source_t)value) {
5255 // forward device change to effects that have requested to be
5256 // aware of attached audio device.
5257 for (size_t i = 0; i < mEffectChains.size(); i++) {
5258 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5259 }
5260 mAudioSource = (audio_source_t)value;
5261 }
Glenn Kastene198c362013-08-13 09:13:36 -07005262
Eric Laurent81784c32012-11-19 14:55:58 -08005263 if (status == NO_ERROR) {
5264 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5265 keyValuePair.string());
5266 if (status == INVALID_OPERATION) {
5267 inputStandBy();
5268 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5269 keyValuePair.string());
5270 }
5271 if (reconfig) {
5272 if (status == BAD_VALUE &&
5273 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5274 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005275 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005276 <= (2 * reqSamplingRate)) &&
5277 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5278 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005279 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5280 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005281 status = NO_ERROR;
5282 }
5283 if (status == NO_ERROR) {
5284 readInputParameters();
5285 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5286 }
5287 }
5288 }
5289
5290 mNewParameters.removeAt(0);
5291
5292 mParamStatus = status;
5293 mParamCond.signal();
5294 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5295 // already timed out waiting for the status and will never signal the condition.
5296 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5297 }
5298 return reconfig;
5299}
5300
5301String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5302{
Eric Laurent81784c32012-11-19 14:55:58 -08005303 Mutex::Autolock _l(mLock);
5304 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005305 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
5307
Glenn Kastend8ea6992013-07-16 14:17:15 -07005308 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5309 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005310 free(s);
5311 return out_s8;
5312}
5313
5314void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5315 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005316 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005317
5318 switch (event) {
5319 case AudioSystem::INPUT_OPENED:
5320 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005321 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005322 desc.samplingRate = mSampleRate;
5323 desc.format = mFormat;
5324 desc.frameCount = mFrameCount;
5325 desc.latency = 0;
5326 param2 = &desc;
5327 break;
5328
5329 case AudioSystem::INPUT_CLOSED:
5330 default:
5331 break;
5332 }
5333 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5334}
5335
5336void AudioFlinger::RecordThread::readInputParameters()
5337{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005338 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005339 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005340 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005341 mRsmpOutBuffer = NULL;
5342 delete mResampler;
5343 mResampler = NULL;
5344
5345 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5346 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005347 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005348 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005349 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5350 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5351 }
Eric Laurent81784c32012-11-19 14:55:58 -08005352 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005353 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5354 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07005355 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5356 // 1 full output buffer, regardless of the alignment of the available input.
5357 mRsmpInFrames = mFrameCount * 3;
5358 mRsmpInFramesP2 = roundup(mRsmpInFrames);
5359 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5360 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5361 mRsmpInFront = 0;
5362 mRsmpInRear = 0;
5363 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005364
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005365 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Glenn Kasten579dd272013-11-08 14:26:14 -08005366 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005367 mResampler->setSampleRate(mSampleRate);
5368 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten85948432013-08-19 12:09:05 -07005369 // resampler always outputs stereo
Glenn Kasten34af0262013-07-30 11:52:39 -07005370 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005371 }
5372 mRsmpInIndex = mFrameCount;
5373}
5374
Glenn Kasten5f972c02014-01-13 09:59:31 -08005375uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005376{
5377 Mutex::Autolock _l(mLock);
5378 if (initCheck() != NO_ERROR) {
5379 return 0;
5380 }
5381
5382 return mInput->stream->get_input_frames_lost(mInput->stream);
5383}
5384
5385uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5386{
5387 Mutex::Autolock _l(mLock);
5388 uint32_t result = 0;
5389 if (getEffectChain_l(sessionId) != 0) {
5390 result = EFFECT_SESSION;
5391 }
5392
5393 for (size_t i = 0; i < mTracks.size(); ++i) {
5394 if (sessionId == mTracks[i]->sessionId()) {
5395 result |= TRACK_SESSION;
5396 break;
5397 }
5398 }
5399
5400 return result;
5401}
5402
5403KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5404{
5405 KeyedVector<int, bool> ids;
5406 Mutex::Autolock _l(mLock);
5407 for (size_t j = 0; j < mTracks.size(); ++j) {
5408 sp<RecordThread::RecordTrack> track = mTracks[j];
5409 int sessionId = track->sessionId();
5410 if (ids.indexOfKey(sessionId) < 0) {
5411 ids.add(sessionId, true);
5412 }
5413 }
5414 return ids;
5415}
5416
5417AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5418{
5419 Mutex::Autolock _l(mLock);
5420 AudioStreamIn *input = mInput;
5421 mInput = NULL;
5422 return input;
5423}
5424
5425// this method must always be called either with ThreadBase mLock held or inside the thread loop
5426audio_stream_t* AudioFlinger::RecordThread::stream() const
5427{
5428 if (mInput == NULL) {
5429 return NULL;
5430 }
5431 return &mInput->stream->common;
5432}
5433
5434status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5435{
5436 // only one chain per input thread
5437 if (mEffectChains.size() != 0) {
5438 return INVALID_OPERATION;
5439 }
5440 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5441
5442 chain->setInBuffer(NULL);
5443 chain->setOutBuffer(NULL);
5444
5445 checkSuspendOnAddEffectChain_l(chain);
5446
5447 mEffectChains.add(chain);
5448
5449 return NO_ERROR;
5450}
5451
5452size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5453{
5454 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5455 ALOGW_IF(mEffectChains.size() != 1,
5456 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5457 chain.get(), mEffectChains.size(), this);
5458 if (mEffectChains.size() == 1) {
5459 mEffectChains.removeAt(0);
5460 }
5461 return 0;
5462}
5463
5464}; // namespace android