blob: 44384b8913108177e44a2b81c8e794d8710e31f7 [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.
138// Currently the client uses double-buffering by default, but doesn't tell us about that.
139// So for now we just assume that client is double-buffered.
140// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
141// N-buffering, so AudioFlinger could allocate the right amount of memory.
142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143static const int kFastTrackMultiplier = 1;
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),
275 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
276 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
277 // mName will be set by concrete (non-virtual) subclass
278 mDeathRecipient(new PMDeathRecipient(this))
279{
280}
281
282AudioFlinger::ThreadBase::~ThreadBase()
283{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700284 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
285 for (size_t i = 0; i < mConfigEvents.size(); i++) {
286 delete mConfigEvents[i];
287 }
288 mConfigEvents.clear();
289
Eric Laurent81784c32012-11-19 14:55:58 -0800290 mParamCond.broadcast();
291 // do not lock the mutex in destructor
292 releaseWakeLock_l();
293 if (mPowerManager != 0) {
294 sp<IBinder> binder = mPowerManager->asBinder();
295 binder->unlinkToDeath(mDeathRecipient);
296 }
297}
298
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700299status_t AudioFlinger::ThreadBase::readyToRun()
300{
301 status_t status = initCheck();
302 if (status == NO_ERROR) {
303 ALOGI("AudioFlinger's thread %p ready to run", this);
304 } else {
305 ALOGE("No working audio driver found.");
306 }
307 return status;
308}
309
Eric Laurent81784c32012-11-19 14:55:58 -0800310void AudioFlinger::ThreadBase::exit()
311{
312 ALOGV("ThreadBase::exit");
313 // do any cleanup required for exit to succeed
314 preExit();
315 {
316 // This lock prevents the following race in thread (uniprocessor for illustration):
317 // if (!exitPending()) {
318 // // context switch from here to exit()
319 // // exit() calls requestExit(), what exitPending() observes
320 // // exit() calls signal(), which is dropped since no waiters
321 // // context switch back from exit() to here
322 // mWaitWorkCV.wait(...);
323 // // now thread is hung
324 // }
325 AutoMutex lock(mLock);
326 requestExit();
327 mWaitWorkCV.broadcast();
328 }
329 // When Thread::requestExitAndWait is made virtual and this method is renamed to
330 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
331 requestExitAndWait();
332}
333
334status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
335{
336 status_t status;
337
338 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
339 Mutex::Autolock _l(mLock);
340
341 mNewParameters.add(keyValuePairs);
342 mWaitWorkCV.signal();
343 // wait condition with timeout in case the thread loop has exited
344 // before the request could be processed
345 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
346 status = mParamStatus;
347 mWaitWorkCV.signal();
348 } else {
349 status = TIMED_OUT;
350 }
351 return status;
352}
353
354void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
355{
356 Mutex::Autolock _l(mLock);
357 sendIoConfigEvent_l(event, param);
358}
359
360// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
361void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
362{
363 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
364 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
365 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
366 param);
367 mWaitWorkCV.signal();
368}
369
370// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
371void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
372{
373 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
374 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
375 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
376 mConfigEvents.size(), pid, tid, prio);
377 mWaitWorkCV.signal();
378}
379
380void AudioFlinger::ThreadBase::processConfigEvents()
381{
Glenn Kastenf7773312013-08-13 16:00:42 -0700382 Mutex::Autolock _l(mLock);
383 processConfigEvents_l();
384}
385
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700386// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700387void AudioFlinger::ThreadBase::processConfigEvents_l()
388{
Eric Laurent81784c32012-11-19 14:55:58 -0800389 while (!mConfigEvents.isEmpty()) {
390 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
391 ConfigEvent *event = mConfigEvents[0];
392 mConfigEvents.removeAt(0);
393 // release mLock before locking AudioFlinger mLock: lock order is always
394 // AudioFlinger then ThreadBase to avoid cross deadlock
395 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700396 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700397 case CFG_EVENT_PRIO: {
398 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
399 // FIXME Need to understand why this has be done asynchronously
400 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
401 true /*asynchronous*/);
402 if (err != 0) {
403 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
404 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
405 }
406 } break;
407 case CFG_EVENT_IO: {
408 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700409 {
410 Mutex::Autolock _l(mAudioFlinger->mLock);
411 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
412 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700413 } break;
414 default:
415 ALOGE("processConfigEvents() unknown event type %d", event->type());
416 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800417 }
418 delete event;
419 mLock.lock();
420 }
Eric Laurent81784c32012-11-19 14:55:58 -0800421}
422
423void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
428
429 bool locked = AudioFlinger::dumpTryLock(mLock);
430 if (!locked) {
431 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
432 write(fd, buffer, strlen(buffer));
433 }
434
435 snprintf(buffer, SIZE, "io handle: %d\n", mId);
436 result.append(buffer);
437 snprintf(buffer, SIZE, "TID: %d\n", getTid());
438 result.append(buffer);
439 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
440 result.append(buffer);
441 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
442 result.append(buffer);
443 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
444 result.append(buffer);
Glenn Kasten70949c42013-08-06 07:40:12 -0700445 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
446 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700447 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800448 result.append(buffer);
449 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
450 result.append(buffer);
451 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
452 result.append(buffer);
453 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
454 result.append(buffer);
455
456 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
457 result.append(buffer);
458 result.append(" Index Command");
459 for (size_t i = 0; i < mNewParameters.size(); ++i) {
460 snprintf(buffer, SIZE, "\n %02d ", i);
461 result.append(buffer);
462 result.append(mNewParameters[i]);
463 }
464
465 snprintf(buffer, SIZE, "\n\nPending config events: \n");
466 result.append(buffer);
467 for (size_t i = 0; i < mConfigEvents.size(); i++) {
468 mConfigEvents[i]->dump(buffer, SIZE);
469 result.append(buffer);
470 }
471 result.append("\n");
472
473 write(fd, result.string(), result.size());
474
475 if (locked) {
476 mLock.unlock();
477 }
478}
479
480void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
481{
482 const size_t SIZE = 256;
483 char buffer[SIZE];
484 String8 result;
485
486 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
487 write(fd, buffer, strlen(buffer));
488
489 for (size_t i = 0; i < mEffectChains.size(); ++i) {
490 sp<EffectChain> chain = mEffectChains[i];
491 if (chain != 0) {
492 chain->dump(fd, args);
493 }
494 }
495}
496
Marco Nelissene14a5d62013-10-03 08:51:24 -0700497void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800498{
499 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700500 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800501}
502
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100503String16 AudioFlinger::ThreadBase::getWakeLockTag()
504{
505 switch (mType) {
506 case MIXER:
507 return String16("AudioMix");
508 case DIRECT:
509 return String16("AudioDirectOut");
510 case DUPLICATING:
511 return String16("AudioDup");
512 case RECORD:
513 return String16("AudioIn");
514 case OFFLOAD:
515 return String16("AudioOffload");
516 default:
517 ALOG_ASSERT(false);
518 return String16("AudioUnknown");
519 }
520}
521
Marco Nelissene14a5d62013-10-03 08:51:24 -0700522void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800523{
524 if (mPowerManager == 0) {
525 // use checkService() to avoid blocking if power service is not up yet
526 sp<IBinder> binder =
527 defaultServiceManager()->checkService(String16("power"));
528 if (binder == 0) {
529 ALOGW("Thread %s cannot connect to the power manager service", mName);
530 } else {
531 mPowerManager = interface_cast<IPowerManager>(binder);
532 binder->linkToDeath(mDeathRecipient);
533 }
534 }
535 if (mPowerManager != 0) {
536 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700537 status_t status;
538 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700539 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700540 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100541 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700542 String16("media"),
543 uid);
544 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700545 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700546 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100547 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700548 String16("media"));
549 }
Eric Laurent81784c32012-11-19 14:55:58 -0800550 if (status == NO_ERROR) {
551 mWakeLockToken = binder;
552 }
553 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
554 }
555}
556
557void AudioFlinger::ThreadBase::releaseWakeLock()
558{
559 Mutex::Autolock _l(mLock);
560 releaseWakeLock_l();
561}
562
563void AudioFlinger::ThreadBase::releaseWakeLock_l()
564{
565 if (mWakeLockToken != 0) {
566 ALOGV("releaseWakeLock_l() %s", mName);
567 if (mPowerManager != 0) {
568 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
569 }
570 mWakeLockToken.clear();
571 }
572}
573
574void AudioFlinger::ThreadBase::clearPowerManager()
575{
576 Mutex::Autolock _l(mLock);
577 releaseWakeLock_l();
578 mPowerManager.clear();
579}
580
581void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
582{
583 sp<ThreadBase> thread = mThread.promote();
584 if (thread != 0) {
585 thread->clearPowerManager();
586 }
587 ALOGW("power manager service died !!!");
588}
589
590void AudioFlinger::ThreadBase::setEffectSuspended(
591 const effect_uuid_t *type, bool suspend, int sessionId)
592{
593 Mutex::Autolock _l(mLock);
594 setEffectSuspended_l(type, suspend, sessionId);
595}
596
597void AudioFlinger::ThreadBase::setEffectSuspended_l(
598 const effect_uuid_t *type, bool suspend, int sessionId)
599{
600 sp<EffectChain> chain = getEffectChain_l(sessionId);
601 if (chain != 0) {
602 if (type != NULL) {
603 chain->setEffectSuspended_l(type, suspend);
604 } else {
605 chain->setEffectSuspendedAll_l(suspend);
606 }
607 }
608
609 updateSuspendedSessions_l(type, suspend, sessionId);
610}
611
612void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
613{
614 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
615 if (index < 0) {
616 return;
617 }
618
619 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
620 mSuspendedSessions.valueAt(index);
621
622 for (size_t i = 0; i < sessionEffects.size(); i++) {
623 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
624 for (int j = 0; j < desc->mRefCount; j++) {
625 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
626 chain->setEffectSuspendedAll_l(true);
627 } else {
628 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
629 desc->mType.timeLow);
630 chain->setEffectSuspended_l(&desc->mType, true);
631 }
632 }
633 }
634}
635
636void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
637 bool suspend,
638 int sessionId)
639{
640 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
641
642 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
643
644 if (suspend) {
645 if (index >= 0) {
646 sessionEffects = mSuspendedSessions.valueAt(index);
647 } else {
648 mSuspendedSessions.add(sessionId, sessionEffects);
649 }
650 } else {
651 if (index < 0) {
652 return;
653 }
654 sessionEffects = mSuspendedSessions.valueAt(index);
655 }
656
657
658 int key = EffectChain::kKeyForSuspendAll;
659 if (type != NULL) {
660 key = type->timeLow;
661 }
662 index = sessionEffects.indexOfKey(key);
663
664 sp<SuspendedSessionDesc> desc;
665 if (suspend) {
666 if (index >= 0) {
667 desc = sessionEffects.valueAt(index);
668 } else {
669 desc = new SuspendedSessionDesc();
670 if (type != NULL) {
671 desc->mType = *type;
672 }
673 sessionEffects.add(key, desc);
674 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
675 }
676 desc->mRefCount++;
677 } else {
678 if (index < 0) {
679 return;
680 }
681 desc = sessionEffects.valueAt(index);
682 if (--desc->mRefCount == 0) {
683 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
684 sessionEffects.removeItemsAt(index);
685 if (sessionEffects.isEmpty()) {
686 ALOGV("updateSuspendedSessions_l() restore removing session %d",
687 sessionId);
688 mSuspendedSessions.removeItem(sessionId);
689 }
690 }
691 }
692 if (!sessionEffects.isEmpty()) {
693 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
694 }
695}
696
697void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
698 bool enabled,
699 int sessionId)
700{
701 Mutex::Autolock _l(mLock);
702 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
703}
704
705void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
706 bool enabled,
707 int sessionId)
708{
709 if (mType != RECORD) {
710 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
711 // another session. This gives the priority to well behaved effect control panels
712 // and applications not using global effects.
713 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
714 // global effects
715 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
716 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
717 }
718 }
719
720 sp<EffectChain> chain = getEffectChain_l(sessionId);
721 if (chain != 0) {
722 chain->checkSuspendOnEffectEnabled(effect, enabled);
723 }
724}
725
726// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
727sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
728 const sp<AudioFlinger::Client>& client,
729 const sp<IEffectClient>& effectClient,
730 int32_t priority,
731 int sessionId,
732 effect_descriptor_t *desc,
733 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700734 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800735{
736 sp<EffectModule> effect;
737 sp<EffectHandle> handle;
738 status_t lStatus;
739 sp<EffectChain> chain;
740 bool chainCreated = false;
741 bool effectCreated = false;
742 bool effectRegistered = false;
743
744 lStatus = initCheck();
745 if (lStatus != NO_ERROR) {
746 ALOGW("createEffect_l() Audio driver not initialized.");
747 goto Exit;
748 }
749
Eric Laurent5baf2af2013-09-12 17:37:00 -0700750 // Allow global effects only on offloaded and mixer threads
751 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
752 switch (mType) {
753 case MIXER:
754 case OFFLOAD:
755 break;
756 case DIRECT:
757 case DUPLICATING:
758 case RECORD:
759 default:
760 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
761 lStatus = BAD_VALUE;
762 goto Exit;
763 }
Eric Laurent81784c32012-11-19 14:55:58 -0800764 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700765
Eric Laurent81784c32012-11-19 14:55:58 -0800766 // Only Pre processor effects are allowed on input threads and only on input threads
767 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
768 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
769 desc->name, desc->flags, mType);
770 lStatus = BAD_VALUE;
771 goto Exit;
772 }
773
774 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
775
776 { // scope for mLock
777 Mutex::Autolock _l(mLock);
778
779 // check for existing effect chain with the requested audio session
780 chain = getEffectChain_l(sessionId);
781 if (chain == 0) {
782 // create a new chain for this session
783 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
784 chain = new EffectChain(this, sessionId);
785 addEffectChain_l(chain);
786 chain->setStrategy(getStrategyForSession_l(sessionId));
787 chainCreated = true;
788 } else {
789 effect = chain->getEffectFromDesc_l(desc);
790 }
791
792 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
793
794 if (effect == 0) {
795 int id = mAudioFlinger->nextUniqueId();
796 // Check CPU and memory usage
797 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
798 if (lStatus != NO_ERROR) {
799 goto Exit;
800 }
801 effectRegistered = true;
802 // create a new effect module if none present in the chain
803 effect = new EffectModule(this, chain, desc, id, sessionId);
804 lStatus = effect->status();
805 if (lStatus != NO_ERROR) {
806 goto Exit;
807 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700808 effect->setOffloaded(mType == OFFLOAD, mId);
809
Eric Laurent81784c32012-11-19 14:55:58 -0800810 lStatus = chain->addEffect_l(effect);
811 if (lStatus != NO_ERROR) {
812 goto Exit;
813 }
814 effectCreated = true;
815
816 effect->setDevice(mOutDevice);
817 effect->setDevice(mInDevice);
818 effect->setMode(mAudioFlinger->getMode());
819 effect->setAudioSource(mAudioSource);
820 }
821 // create effect handle and connect it to effect module
822 handle = new EffectHandle(effect, client, effectClient, priority);
823 lStatus = effect->addHandle(handle.get());
824 if (enabled != NULL) {
825 *enabled = (int)effect->isEnabled();
826 }
827 }
828
829Exit:
830 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
831 Mutex::Autolock _l(mLock);
832 if (effectCreated) {
833 chain->removeEffect_l(effect);
834 }
835 if (effectRegistered) {
836 AudioSystem::unregisterEffect(effect->id());
837 }
838 if (chainCreated) {
839 removeEffectChain_l(chain);
840 }
841 handle.clear();
842 }
843
Glenn Kasten9156ef32013-08-06 15:39:08 -0700844 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800845 return handle;
846}
847
848sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
849{
850 Mutex::Autolock _l(mLock);
851 return getEffect_l(sessionId, effectId);
852}
853
854sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
855{
856 sp<EffectChain> chain = getEffectChain_l(sessionId);
857 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
858}
859
860// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
861// PlaybackThread::mLock held
862status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
863{
864 // check for existing effect chain with the requested audio session
865 int sessionId = effect->sessionId();
866 sp<EffectChain> chain = getEffectChain_l(sessionId);
867 bool chainCreated = false;
868
Eric Laurent5baf2af2013-09-12 17:37:00 -0700869 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
870 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
871 this, effect->desc().name, effect->desc().flags);
872
Eric Laurent81784c32012-11-19 14:55:58 -0800873 if (chain == 0) {
874 // create a new chain for this session
875 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
876 chain = new EffectChain(this, sessionId);
877 addEffectChain_l(chain);
878 chain->setStrategy(getStrategyForSession_l(sessionId));
879 chainCreated = true;
880 }
881 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
882
883 if (chain->getEffectFromId_l(effect->id()) != 0) {
884 ALOGW("addEffect_l() %p effect %s already present in chain %p",
885 this, effect->desc().name, chain.get());
886 return BAD_VALUE;
887 }
888
Eric Laurent5baf2af2013-09-12 17:37:00 -0700889 effect->setOffloaded(mType == OFFLOAD, mId);
890
Eric Laurent81784c32012-11-19 14:55:58 -0800891 status_t status = chain->addEffect_l(effect);
892 if (status != NO_ERROR) {
893 if (chainCreated) {
894 removeEffectChain_l(chain);
895 }
896 return status;
897 }
898
899 effect->setDevice(mOutDevice);
900 effect->setDevice(mInDevice);
901 effect->setMode(mAudioFlinger->getMode());
902 effect->setAudioSource(mAudioSource);
903 return NO_ERROR;
904}
905
906void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
907
908 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
909 effect_descriptor_t desc = effect->desc();
910 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
911 detachAuxEffect_l(effect->id());
912 }
913
914 sp<EffectChain> chain = effect->chain().promote();
915 if (chain != 0) {
916 // remove effect chain if removing last effect
917 if (chain->removeEffect_l(effect) == 0) {
918 removeEffectChain_l(chain);
919 }
920 } else {
921 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
922 }
923}
924
925void AudioFlinger::ThreadBase::lockEffectChains_l(
926 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
927{
928 effectChains = mEffectChains;
929 for (size_t i = 0; i < mEffectChains.size(); i++) {
930 mEffectChains[i]->lock();
931 }
932}
933
934void AudioFlinger::ThreadBase::unlockEffectChains(
935 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
936{
937 for (size_t i = 0; i < effectChains.size(); i++) {
938 effectChains[i]->unlock();
939 }
940}
941
942sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
943{
944 Mutex::Autolock _l(mLock);
945 return getEffectChain_l(sessionId);
946}
947
948sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
949{
950 size_t size = mEffectChains.size();
951 for (size_t i = 0; i < size; i++) {
952 if (mEffectChains[i]->sessionId() == sessionId) {
953 return mEffectChains[i];
954 }
955 }
956 return 0;
957}
958
959void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
960{
961 Mutex::Autolock _l(mLock);
962 size_t size = mEffectChains.size();
963 for (size_t i = 0; i < size; i++) {
964 mEffectChains[i]->setMode_l(mode);
965 }
966}
967
968void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
969 EffectHandle *handle,
970 bool unpinIfLast) {
971
972 Mutex::Autolock _l(mLock);
973 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
974 // delete the effect module if removing last handle on it
975 if (effect->removeHandle(handle) == 0) {
976 if (!effect->isPinned() || unpinIfLast) {
977 removeEffect_l(effect);
978 AudioSystem::unregisterEffect(effect->id());
979 }
980 }
981}
982
983// ----------------------------------------------------------------------------
984// Playback
985// ----------------------------------------------------------------------------
986
987AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
988 AudioStreamOut* output,
989 audio_io_handle_t id,
990 audio_devices_t device,
991 type_t type)
992 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700993 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -0700994 mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800995 // mStreamTypes[] initialized in constructor body
996 mOutput(output),
997 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
998 mMixerStatus(MIXER_IDLE),
999 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1000 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001001 mBytesRemaining(0),
1002 mCurrentWriteLength(0),
1003 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001004 mWriteAckSequence(0),
1005 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001006 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001007 mScreenState(AudioFlinger::mScreenState),
1008 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001009 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1010 // mLatchD, mLatchQ,
1011 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001012{
1013 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001014 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001015
1016 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1017 // it would be safer to explicitly pass initial masterVolume/masterMute as
1018 // parameter.
1019 //
1020 // If the HAL we are using has support for master volume or master mute,
1021 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1022 // and the mute set to false).
1023 mMasterVolume = audioFlinger->masterVolume_l();
1024 mMasterMute = audioFlinger->masterMute_l();
1025 if (mOutput && mOutput->audioHwDev) {
1026 if (mOutput->audioHwDev->canSetMasterVolume()) {
1027 mMasterVolume = 1.0;
1028 }
1029
1030 if (mOutput->audioHwDev->canSetMasterMute()) {
1031 mMasterMute = false;
1032 }
1033 }
1034
1035 readOutputParameters();
1036
1037 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1038 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1039 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1040 stream = (audio_stream_type_t) (stream + 1)) {
1041 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1042 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1043 }
1044 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1045 // because mAudioFlinger doesn't have one to copy from
1046}
1047
1048AudioFlinger::PlaybackThread::~PlaybackThread()
1049{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001050 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001051 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001052}
1053
1054void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1055{
1056 dumpInternals(fd, args);
1057 dumpTracks(fd, args);
1058 dumpEffectChains(fd, args);
1059}
1060
1061void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1062{
1063 const size_t SIZE = 256;
1064 char buffer[SIZE];
1065 String8 result;
1066
1067 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1068 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1069 const stream_type_t *st = &mStreamTypes[i];
1070 if (i > 0) {
1071 result.appendFormat(", ");
1072 }
1073 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1074 if (st->mute) {
1075 result.append("M");
1076 }
1077 }
1078 result.append("\n");
1079 write(fd, result.string(), result.length());
1080 result.clear();
1081
1082 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1083 result.append(buffer);
1084 Track::appendDumpHeader(result);
1085 for (size_t i = 0; i < mTracks.size(); ++i) {
1086 sp<Track> track = mTracks[i];
1087 if (track != 0) {
1088 track->dump(buffer, SIZE);
1089 result.append(buffer);
1090 }
1091 }
1092
1093 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1094 result.append(buffer);
1095 Track::appendDumpHeader(result);
1096 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1097 sp<Track> track = mActiveTracks[i].promote();
1098 if (track != 0) {
1099 track->dump(buffer, SIZE);
1100 result.append(buffer);
1101 }
1102 }
1103 write(fd, result.string(), result.size());
1104
1105 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1106 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1107 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1108 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1109}
1110
1111void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1112{
1113 const size_t SIZE = 256;
1114 char buffer[SIZE];
1115 String8 result;
1116
1117 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1118 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001119 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1120 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001121 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1122 ns2ms(systemTime() - mLastWriteTime));
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1125 result.append(buffer);
1126 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1127 result.append(buffer);
1128 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1129 result.append(buffer);
1130 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1133 result.append(buffer);
1134 write(fd, result.string(), result.size());
1135 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1136
1137 dumpBase(fd, args);
1138}
1139
1140// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001141
1142void AudioFlinger::PlaybackThread::onFirstRef()
1143{
1144 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1145}
1146
1147// ThreadBase virtuals
1148void AudioFlinger::PlaybackThread::preExit()
1149{
1150 ALOGV(" preExit()");
1151 // FIXME this is using hard-coded strings but in the future, this functionality will be
1152 // converted to use audio HAL extensions required to support tunneling
1153 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1154}
1155
1156// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1157sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1158 const sp<AudioFlinger::Client>& client,
1159 audio_stream_type_t streamType,
1160 uint32_t sampleRate,
1161 audio_format_t format,
1162 audio_channel_mask_t channelMask,
1163 size_t frameCount,
1164 const sp<IMemory>& sharedBuffer,
1165 int sessionId,
1166 IAudioFlinger::track_flags_t *flags,
1167 pid_t tid,
1168 status_t *status)
1169{
1170 sp<Track> track;
1171 status_t lStatus;
1172
1173 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1174
1175 // client expresses a preference for FAST, but we get the final say
1176 if (*flags & IAudioFlinger::TRACK_FAST) {
1177 if (
1178 // not timed
1179 (!isTimed) &&
1180 // either of these use cases:
1181 (
1182 // use case 1: shared buffer with any frame count
1183 (
1184 (sharedBuffer != 0)
1185 ) ||
1186 // use case 2: callback handler and frame count is default or at least as large as HAL
1187 (
1188 (tid != -1) &&
1189 ((frameCount == 0) ||
1190 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1191 )
1192 ) &&
1193 // PCM data
1194 audio_is_linear_pcm(format) &&
1195 // mono or stereo
1196 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1197 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1198#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1199 // hardware sample rate
1200 (sampleRate == mSampleRate) &&
1201#endif
1202 // normal mixer has an associated fast mixer
1203 hasFastMixer() &&
1204 // there are sufficient fast track slots available
1205 (mFastTrackAvailMask != 0)
1206 // FIXME test that MixerThread for this fast track has a capable output HAL
1207 // FIXME add a permission test also?
1208 ) {
1209 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1210 if (frameCount == 0) {
1211 frameCount = mFrameCount * kFastTrackMultiplier;
1212 }
1213 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1214 frameCount, mFrameCount);
1215 } else {
1216 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1217 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1218 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1219 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1220 audio_is_linear_pcm(format),
1221 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1222 *flags &= ~IAudioFlinger::TRACK_FAST;
1223 // For compatibility with AudioTrack calculation, buffer depth is forced
1224 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1225 // This is probably too conservative, but legacy application code may depend on it.
1226 // If you change this calculation, also review the start threshold which is related.
1227 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1228 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1229 if (minBufCount < 2) {
1230 minBufCount = 2;
1231 }
1232 size_t minFrameCount = mNormalFrameCount * minBufCount;
1233 if (frameCount < minFrameCount) {
1234 frameCount = minFrameCount;
1235 }
1236 }
1237 }
1238
1239 if (mType == DIRECT) {
1240 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1241 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1242 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1243 "for output %p with format %d",
1244 sampleRate, format, channelMask, mOutput, mFormat);
1245 lStatus = BAD_VALUE;
1246 goto Exit;
1247 }
1248 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001249 } else if (mType == OFFLOAD) {
1250 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1251 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1252 "for output %p with format %d",
1253 sampleRate, format, channelMask, mOutput, mFormat);
1254 lStatus = BAD_VALUE;
1255 goto Exit;
1256 }
Eric Laurent81784c32012-11-19 14:55:58 -08001257 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001258 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1259 ALOGE("createTrack_l() Bad parameter: format %d \""
1260 "for output %p with format %d",
1261 format, mOutput, mFormat);
1262 lStatus = BAD_VALUE;
1263 goto Exit;
1264 }
Eric Laurent81784c32012-11-19 14:55:58 -08001265 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1266 if (sampleRate > mSampleRate*2) {
1267 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1268 lStatus = BAD_VALUE;
1269 goto Exit;
1270 }
1271 }
1272
1273 lStatus = initCheck();
1274 if (lStatus != NO_ERROR) {
1275 ALOGE("Audio driver not initialized.");
1276 goto Exit;
1277 }
1278
1279 { // scope for mLock
1280 Mutex::Autolock _l(mLock);
1281
1282 // all tracks in same audio session must share the same routing strategy otherwise
1283 // conflicts will happen when tracks are moved from one output to another by audio policy
1284 // manager
1285 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1286 for (size_t i = 0; i < mTracks.size(); ++i) {
1287 sp<Track> t = mTracks[i];
1288 if (t != 0 && !t->isOutputTrack()) {
1289 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1290 if (sessionId == t->sessionId() && strategy != actual) {
1291 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1292 strategy, actual);
1293 lStatus = BAD_VALUE;
1294 goto Exit;
1295 }
1296 }
1297 }
1298
1299 if (!isTimed) {
1300 track = new Track(this, client, streamType, sampleRate, format,
1301 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1302 } else {
1303 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1304 channelMask, frameCount, sharedBuffer, sessionId);
1305 }
Glenn Kasten03003332013-08-06 15:40:54 -07001306
1307 // new Track always returns non-NULL,
1308 // but TimedTrack::create() is a factory that could fail by returning NULL
1309 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1310 if (lStatus != NO_ERROR) {
1311 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08001312 goto Exit;
1313 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001314
Eric Laurent81784c32012-11-19 14:55:58 -08001315 mTracks.add(track);
1316
1317 sp<EffectChain> chain = getEffectChain_l(sessionId);
1318 if (chain != 0) {
1319 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1320 track->setMainBuffer(chain->inBuffer());
1321 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1322 chain->incTrackCnt();
1323 }
1324
1325 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1326 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1327 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1328 // so ask activity manager to do this on our behalf
1329 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1330 }
1331 }
1332
1333 lStatus = NO_ERROR;
1334
1335Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001336 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001337 return track;
1338}
1339
1340uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1341{
1342 return latency;
1343}
1344
1345uint32_t AudioFlinger::PlaybackThread::latency() const
1346{
1347 Mutex::Autolock _l(mLock);
1348 return latency_l();
1349}
1350uint32_t AudioFlinger::PlaybackThread::latency_l() const
1351{
1352 if (initCheck() == NO_ERROR) {
1353 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1354 } else {
1355 return 0;
1356 }
1357}
1358
1359void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1360{
1361 Mutex::Autolock _l(mLock);
1362 // Don't apply master volume in SW if our HAL can do it for us.
1363 if (mOutput && mOutput->audioHwDev &&
1364 mOutput->audioHwDev->canSetMasterVolume()) {
1365 mMasterVolume = 1.0;
1366 } else {
1367 mMasterVolume = value;
1368 }
1369}
1370
1371void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1372{
1373 Mutex::Autolock _l(mLock);
1374 // Don't apply master mute in SW if our HAL can do it for us.
1375 if (mOutput && mOutput->audioHwDev &&
1376 mOutput->audioHwDev->canSetMasterMute()) {
1377 mMasterMute = false;
1378 } else {
1379 mMasterMute = muted;
1380 }
1381}
1382
1383void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1384{
1385 Mutex::Autolock _l(mLock);
1386 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001387 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001388}
1389
1390void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1391{
1392 Mutex::Autolock _l(mLock);
1393 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001394 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001395}
1396
1397float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1398{
1399 Mutex::Autolock _l(mLock);
1400 return mStreamTypes[stream].volume;
1401}
1402
1403// addTrack_l() must be called with ThreadBase::mLock held
1404status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1405{
1406 status_t status = ALREADY_EXISTS;
1407
1408 // set retry count for buffer fill
1409 track->mRetryCount = kMaxTrackStartupRetries;
1410 if (mActiveTracks.indexOf(track) < 0) {
1411 // the track is newly added, make sure it fills up all its
1412 // buffers before playing. This is to ensure the client will
1413 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001414 if (!track->isOutputTrack()) {
1415 TrackBase::track_state state = track->mState;
1416 mLock.unlock();
1417 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1418 mLock.lock();
1419 // abort track was stopped/paused while we released the lock
1420 if (state != track->mState) {
1421 if (status == NO_ERROR) {
1422 mLock.unlock();
1423 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1424 mLock.lock();
1425 }
1426 return INVALID_OPERATION;
1427 }
1428 // abort if start is rejected by audio policy manager
1429 if (status != NO_ERROR) {
1430 return PERMISSION_DENIED;
1431 }
1432#ifdef ADD_BATTERY_DATA
1433 // to track the speaker usage
1434 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1435#endif
1436 }
1437
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001438 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001439 track->mResetDone = false;
1440 track->mPresentationCompleteFrames = 0;
1441 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001442 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1443 if (chain != 0) {
1444 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1445 track->sessionId());
1446 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001447 }
1448
1449 status = NO_ERROR;
1450 }
1451
Eric Laurentede6c3b2013-09-19 14:37:46 -07001452 ALOGV("signal playback thread");
1453 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001454
1455 return status;
1456}
1457
Eric Laurentbfb1b832013-01-07 09:53:42 -08001458bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001459{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001460 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001461 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001462 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1463 track->mState = TrackBase::STOPPED;
1464 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001465 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001466 } else if (track->isFastTrack() || track->isOffloaded()) {
1467 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001468 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001469
1470 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001471}
1472
1473void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1474{
1475 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1476 mTracks.remove(track);
1477 deleteTrackName_l(track->name());
1478 // redundant as track is about to be destroyed, for dumpsys only
1479 track->mName = -1;
1480 if (track->isFastTrack()) {
1481 int index = track->mFastIndex;
1482 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1483 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1484 mFastTrackAvailMask |= 1 << index;
1485 // redundant as track is about to be destroyed, for dumpsys only
1486 track->mFastIndex = -1;
1487 }
1488 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1489 if (chain != 0) {
1490 chain->decTrackCnt();
1491 }
1492}
1493
Eric Laurentede6c3b2013-09-19 14:37:46 -07001494void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495{
1496 // Thread could be blocked waiting for async
1497 // so signal it to handle state changes immediately
1498 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1499 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1500 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001501 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001502}
1503
Eric Laurent81784c32012-11-19 14:55:58 -08001504String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1505{
Eric Laurent81784c32012-11-19 14:55:58 -08001506 Mutex::Autolock _l(mLock);
1507 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001508 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001509 }
1510
Glenn Kastend8ea6992013-07-16 14:17:15 -07001511 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1512 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001513 free(s);
1514 return out_s8;
1515}
1516
1517// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1518void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1519 AudioSystem::OutputDescriptor desc;
1520 void *param2 = NULL;
1521
1522 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1523 param);
1524
1525 switch (event) {
1526 case AudioSystem::OUTPUT_OPENED:
1527 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001528 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001529 desc.samplingRate = mSampleRate;
1530 desc.format = mFormat;
1531 desc.frameCount = mNormalFrameCount; // FIXME see
1532 // AudioFlinger::frameCount(audio_io_handle_t)
1533 desc.latency = latency();
1534 param2 = &desc;
1535 break;
1536
1537 case AudioSystem::STREAM_CONFIG_CHANGED:
1538 param2 = &param;
1539 case AudioSystem::OUTPUT_CLOSED:
1540 default:
1541 break;
1542 }
1543 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1544}
1545
Eric Laurentbfb1b832013-01-07 09:53:42 -08001546void AudioFlinger::PlaybackThread::writeCallback()
1547{
1548 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001549 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001550}
1551
1552void AudioFlinger::PlaybackThread::drainCallback()
1553{
1554 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001555 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001556}
1557
Eric Laurent3b4529e2013-09-05 18:09:19 -07001558void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001559{
1560 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001561 // reject out of sequence requests
1562 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1563 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001564 mWaitWorkCV.signal();
1565 }
1566}
1567
Eric Laurent3b4529e2013-09-05 18:09:19 -07001568void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001569{
1570 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001571 // reject out of sequence requests
1572 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1573 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001574 mWaitWorkCV.signal();
1575 }
1576}
1577
1578// static
1579int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1580 void *param,
1581 void *cookie)
1582{
1583 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1584 ALOGV("asyncCallback() event %d", event);
1585 switch (event) {
1586 case STREAM_CBK_EVENT_WRITE_READY:
1587 me->writeCallback();
1588 break;
1589 case STREAM_CBK_EVENT_DRAIN_READY:
1590 me->drainCallback();
1591 break;
1592 default:
1593 ALOGW("asyncCallback() unknown event %d", event);
1594 break;
1595 }
1596 return 0;
1597}
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599void AudioFlinger::PlaybackThread::readOutputParameters()
1600{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001601 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001602 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1603 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001604 if (!audio_is_output_channel(mChannelMask)) {
1605 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1606 }
1607 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1608 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1609 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1610 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001611 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001612 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001613 if (!audio_is_valid_format(mFormat)) {
1614 LOG_FATAL("HAL format %d not valid for output", mFormat);
1615 }
1616 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1617 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1618 mFormat);
1619 }
Eric Laurent81784c32012-11-19 14:55:58 -08001620 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001621 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1622 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001623 if (mFrameCount & 15) {
1624 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1625 mFrameCount);
1626 }
1627
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1629 (mOutput->stream->set_callback != NULL)) {
1630 if (mOutput->stream->set_callback(mOutput->stream,
1631 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1632 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001633 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001634 }
1635 }
1636
Eric Laurent81784c32012-11-19 14:55:58 -08001637 // Calculate size of normal mix buffer relative to the HAL output buffer size
1638 double multiplier = 1.0;
1639 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1640 kUseFastMixer == FastMixer_Dynamic)) {
1641 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1642 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1643 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1644 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1645 maxNormalFrameCount = maxNormalFrameCount & ~15;
1646 if (maxNormalFrameCount < minNormalFrameCount) {
1647 maxNormalFrameCount = minNormalFrameCount;
1648 }
1649 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1650 if (multiplier <= 1.0) {
1651 multiplier = 1.0;
1652 } else if (multiplier <= 2.0) {
1653 if (2 * mFrameCount <= maxNormalFrameCount) {
1654 multiplier = 2.0;
1655 } else {
1656 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1657 }
1658 } else {
1659 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1660 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1661 // track, but we sometimes have to do this to satisfy the maximum frame count
1662 // constraint)
1663 // FIXME this rounding up should not be done if no HAL SRC
1664 uint32_t truncMult = (uint32_t) multiplier;
1665 if ((truncMult & 1)) {
1666 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1667 ++truncMult;
1668 }
1669 }
1670 multiplier = (double) truncMult;
1671 }
1672 }
1673 mNormalFrameCount = multiplier * mFrameCount;
1674 // round up to nearest 16 frames to satisfy AudioMixer
1675 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1676 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1677 mNormalFrameCount);
1678
Glenn Kastenc1fac192013-08-06 07:41:36 -07001679 delete[] mMixBuffer;
1680 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1681 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1682 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1683 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001684
1685 // force reconfiguration of effect chains and engines to take new buffer size and audio
1686 // parameters into account
1687 // Note that mLock is not held when readOutputParameters() is called from the constructor
1688 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1689 // matter.
1690 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1691 Vector< sp<EffectChain> > effectChains = mEffectChains;
1692 for (size_t i = 0; i < effectChains.size(); i ++) {
1693 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1694 }
1695}
1696
1697
1698status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1699{
1700 if (halFrames == NULL || dspFrames == NULL) {
1701 return BAD_VALUE;
1702 }
1703 Mutex::Autolock _l(mLock);
1704 if (initCheck() != NO_ERROR) {
1705 return INVALID_OPERATION;
1706 }
1707 size_t framesWritten = mBytesWritten / mFrameSize;
1708 *halFrames = framesWritten;
1709
1710 if (isSuspended()) {
1711 // return an estimation of rendered frames when the output is suspended
1712 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1713 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1714 return NO_ERROR;
1715 } else {
1716 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1717 }
1718}
1719
1720uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1721{
1722 Mutex::Autolock _l(mLock);
1723 uint32_t result = 0;
1724 if (getEffectChain_l(sessionId) != 0) {
1725 result = EFFECT_SESSION;
1726 }
1727
1728 for (size_t i = 0; i < mTracks.size(); ++i) {
1729 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001730 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001731 result |= TRACK_SESSION;
1732 break;
1733 }
1734 }
1735
1736 return result;
1737}
1738
1739uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1740{
1741 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1742 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1743 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1744 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1745 }
1746 for (size_t i = 0; i < mTracks.size(); i++) {
1747 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001748 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001749 return AudioSystem::getStrategyForStream(track->streamType());
1750 }
1751 }
1752 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1753}
1754
1755
1756AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1757{
1758 Mutex::Autolock _l(mLock);
1759 return mOutput;
1760}
1761
1762AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1763{
1764 Mutex::Autolock _l(mLock);
1765 AudioStreamOut *output = mOutput;
1766 mOutput = NULL;
1767 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1768 // must push a NULL and wait for ack
1769 mOutputSink.clear();
1770 mPipeSink.clear();
1771 mNormalSink.clear();
1772 return output;
1773}
1774
1775// this method must always be called either with ThreadBase mLock held or inside the thread loop
1776audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1777{
1778 if (mOutput == NULL) {
1779 return NULL;
1780 }
1781 return &mOutput->stream->common;
1782}
1783
1784uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1785{
1786 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1787}
1788
1789status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1790{
1791 if (!isValidSyncEvent(event)) {
1792 return BAD_VALUE;
1793 }
1794
1795 Mutex::Autolock _l(mLock);
1796
1797 for (size_t i = 0; i < mTracks.size(); ++i) {
1798 sp<Track> track = mTracks[i];
1799 if (event->triggerSession() == track->sessionId()) {
1800 (void) track->setSyncEvent(event);
1801 return NO_ERROR;
1802 }
1803 }
1804
1805 return NAME_NOT_FOUND;
1806}
1807
1808bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1809{
1810 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1811}
1812
1813void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1814 const Vector< sp<Track> >& tracksToRemove)
1815{
1816 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001817 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001818 for (size_t i = 0 ; i < count ; i++) {
1819 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001820 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001821 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001822#ifdef ADD_BATTERY_DATA
1823 // to track the speaker usage
1824 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1825#endif
1826 if (track->isTerminated()) {
1827 AudioSystem::releaseOutput(mId);
1828 }
Eric Laurent81784c32012-11-19 14:55:58 -08001829 }
1830 }
1831 }
Eric Laurent81784c32012-11-19 14:55:58 -08001832}
1833
1834void AudioFlinger::PlaybackThread::checkSilentMode_l()
1835{
1836 if (!mMasterMute) {
1837 char value[PROPERTY_VALUE_MAX];
1838 if (property_get("ro.audio.silent", value, "0") > 0) {
1839 char *endptr;
1840 unsigned long ul = strtoul(value, &endptr, 0);
1841 if (*endptr == '\0' && ul != 0) {
1842 ALOGD("Silence is golden");
1843 // The setprop command will not allow a property to be changed after
1844 // the first time it is set, so we don't have to worry about un-muting.
1845 setMasterMute_l(true);
1846 }
1847 }
1848 }
1849}
1850
1851// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001853{
1854 // FIXME rewrite to reduce number of system calls
1855 mLastWriteTime = systemTime();
1856 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001858
1859 // If an NBAIO sink is present, use it to write the normal mixer's submix
1860 if (mNormalSink != 0) {
1861#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 size_t count = mBytesRemaining >> mBitShift;
1863 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001864 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001865 // update the setpoint when AudioFlinger::mScreenState changes
1866 uint32_t screenState = AudioFlinger::mScreenState;
1867 if (screenState != mScreenState) {
1868 mScreenState = screenState;
1869 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1870 if (pipe != NULL) {
1871 pipe->setAvgFrames((mScreenState & 1) ?
1872 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1873 }
1874 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001875 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001876 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001877 if (framesWritten > 0) {
1878 bytesWritten = framesWritten << mBitShift;
1879 } else {
1880 bytesWritten = framesWritten;
1881 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001882 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001883 if (status == NO_ERROR) {
1884 size_t totalFramesWritten = mNormalSink->framesWritten();
1885 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1886 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1887 mLatchDValid = true;
1888 }
1889 }
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // otherwise use the HAL / AudioStreamOut directly
1891 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892 // Direct output and offload threads
1893 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1894 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001895 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1896 mWriteAckSequence += 2;
1897 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001899 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001900 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001901 // FIXME We should have an implementation of timestamps for direct output threads.
1902 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001903 bytesWritten = mOutput->stream->write(mOutput->stream,
1904 mMixBuffer + offset, mBytesRemaining);
1905 if (mUseAsyncWrite &&
1906 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1907 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001908 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001909 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001910 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001911 }
Eric Laurent81784c32012-11-19 14:55:58 -08001912 }
1913
Eric Laurent81784c32012-11-19 14:55:58 -08001914 mNumWrites++;
1915 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001916
1917 return bytesWritten;
1918}
1919
1920void AudioFlinger::PlaybackThread::threadLoop_drain()
1921{
1922 if (mOutput->stream->drain) {
1923 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1924 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001925 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1926 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001927 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001928 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001929 }
1930 mOutput->stream->drain(mOutput->stream,
1931 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1932 : AUDIO_DRAIN_ALL);
1933 }
1934}
1935
1936void AudioFlinger::PlaybackThread::threadLoop_exit()
1937{
1938 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001939}
1940
1941/*
1942The derived values that are cached:
1943 - mixBufferSize from frame count * frame size
1944 - activeSleepTime from activeSleepTimeUs()
1945 - idleSleepTime from idleSleepTimeUs()
1946 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1947 - maxPeriod from frame count and sample rate (MIXER only)
1948
1949The parameters that affect these derived values are:
1950 - frame count
1951 - frame size
1952 - sample rate
1953 - device type: A2DP or not
1954 - device latency
1955 - format: PCM or not
1956 - active sleep time
1957 - idle sleep time
1958*/
1959
1960void AudioFlinger::PlaybackThread::cacheParameters_l()
1961{
1962 mixBufferSize = mNormalFrameCount * mFrameSize;
1963 activeSleepTime = activeSleepTimeUs();
1964 idleSleepTime = idleSleepTimeUs();
1965}
1966
1967void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1968{
Glenn Kasten7c027242012-12-26 14:43:16 -08001969 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001970 this, streamType, mTracks.size());
1971 Mutex::Autolock _l(mLock);
1972
1973 size_t size = mTracks.size();
1974 for (size_t i = 0; i < size; i++) {
1975 sp<Track> t = mTracks[i];
1976 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001977 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001978 }
1979 }
1980}
1981
1982status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1983{
1984 int session = chain->sessionId();
1985 int16_t *buffer = mMixBuffer;
1986 bool ownsBuffer = false;
1987
1988 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1989 if (session > 0) {
1990 // Only one effect chain can be present in direct output thread and it uses
1991 // the mix buffer as input
1992 if (mType != DIRECT) {
1993 size_t numSamples = mNormalFrameCount * mChannelCount;
1994 buffer = new int16_t[numSamples];
1995 memset(buffer, 0, numSamples * sizeof(int16_t));
1996 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1997 ownsBuffer = true;
1998 }
1999
2000 // Attach all tracks with same session ID to this chain.
2001 for (size_t i = 0; i < mTracks.size(); ++i) {
2002 sp<Track> track = mTracks[i];
2003 if (session == track->sessionId()) {
2004 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2005 buffer);
2006 track->setMainBuffer(buffer);
2007 chain->incTrackCnt();
2008 }
2009 }
2010
2011 // indicate all active tracks in the chain
2012 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2013 sp<Track> track = mActiveTracks[i].promote();
2014 if (track == 0) {
2015 continue;
2016 }
2017 if (session == track->sessionId()) {
2018 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2019 chain->incActiveTrackCnt();
2020 }
2021 }
2022 }
2023
2024 chain->setInBuffer(buffer, ownsBuffer);
2025 chain->setOutBuffer(mMixBuffer);
2026 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2027 // chains list in order to be processed last as it contains output stage effects
2028 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2029 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2030 // after track specific effects and before output stage
2031 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2032 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2033 // Effect chain for other sessions are inserted at beginning of effect
2034 // chains list to be processed before output mix effects. Relative order between other
2035 // sessions is not important
2036 size_t size = mEffectChains.size();
2037 size_t i = 0;
2038 for (i = 0; i < size; i++) {
2039 if (mEffectChains[i]->sessionId() < session) {
2040 break;
2041 }
2042 }
2043 mEffectChains.insertAt(chain, i);
2044 checkSuspendOnAddEffectChain_l(chain);
2045
2046 return NO_ERROR;
2047}
2048
2049size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2050{
2051 int session = chain->sessionId();
2052
2053 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2054
2055 for (size_t i = 0; i < mEffectChains.size(); i++) {
2056 if (chain == mEffectChains[i]) {
2057 mEffectChains.removeAt(i);
2058 // detach all active tracks from the chain
2059 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2060 sp<Track> track = mActiveTracks[i].promote();
2061 if (track == 0) {
2062 continue;
2063 }
2064 if (session == track->sessionId()) {
2065 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2066 chain.get(), session);
2067 chain->decActiveTrackCnt();
2068 }
2069 }
2070
2071 // detach all tracks with same session ID from this chain
2072 for (size_t i = 0; i < mTracks.size(); ++i) {
2073 sp<Track> track = mTracks[i];
2074 if (session == track->sessionId()) {
2075 track->setMainBuffer(mMixBuffer);
2076 chain->decTrackCnt();
2077 }
2078 }
2079 break;
2080 }
2081 }
2082 return mEffectChains.size();
2083}
2084
2085status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2086 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2087{
2088 Mutex::Autolock _l(mLock);
2089 return attachAuxEffect_l(track, EffectId);
2090}
2091
2092status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2093 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2094{
2095 status_t status = NO_ERROR;
2096
2097 if (EffectId == 0) {
2098 track->setAuxBuffer(0, NULL);
2099 } else {
2100 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2101 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2102 if (effect != 0) {
2103 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2104 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2105 } else {
2106 status = INVALID_OPERATION;
2107 }
2108 } else {
2109 status = BAD_VALUE;
2110 }
2111 }
2112 return status;
2113}
2114
2115void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2116{
2117 for (size_t i = 0; i < mTracks.size(); ++i) {
2118 sp<Track> track = mTracks[i];
2119 if (track->auxEffectId() == effectId) {
2120 attachAuxEffect_l(track, 0);
2121 }
2122 }
2123}
2124
2125bool AudioFlinger::PlaybackThread::threadLoop()
2126{
2127 Vector< sp<Track> > tracksToRemove;
2128
2129 standbyTime = systemTime();
2130
2131 // MIXER
2132 nsecs_t lastWarning = 0;
2133
2134 // DUPLICATING
2135 // FIXME could this be made local to while loop?
2136 writeFrames = 0;
2137
2138 cacheParameters_l();
2139 sleepTime = idleSleepTime;
2140
2141 if (mType == MIXER) {
2142 sleepTimeShift = 0;
2143 }
2144
2145 CpuStats cpuStats;
2146 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2147
2148 acquireWakeLock();
2149
Glenn Kasten9e58b552013-01-18 15:09:48 -08002150 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2151 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2152 // and then that string will be logged at the next convenient opportunity.
2153 const char *logString = NULL;
2154
Eric Laurent664539d2013-09-23 18:24:31 -07002155 checkSilentMode_l();
2156
Eric Laurent81784c32012-11-19 14:55:58 -08002157 while (!exitPending())
2158 {
2159 cpuStats.sample(myName);
2160
2161 Vector< sp<EffectChain> > effectChains;
2162
2163 processConfigEvents();
2164
2165 { // scope for mLock
2166
2167 Mutex::Autolock _l(mLock);
2168
Glenn Kasten9e58b552013-01-18 15:09:48 -08002169 if (logString != NULL) {
2170 mNBLogWriter->logTimestamp();
2171 mNBLogWriter->log(logString);
2172 logString = NULL;
2173 }
2174
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002175 if (mLatchDValid) {
2176 mLatchQ = mLatchD;
2177 mLatchDValid = false;
2178 mLatchQValid = true;
2179 }
2180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 if (checkForNewParameters_l()) {
2182 cacheParameters_l();
2183 }
2184
2185 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186 if (mSignalPending) {
2187 // A signal was raised while we were unlocked
2188 mSignalPending = false;
2189 } else if (waitingAsyncCallback_l()) {
2190 if (exitPending()) {
2191 break;
2192 }
2193 releaseWakeLock_l();
2194 ALOGV("wait async completion");
2195 mWaitWorkCV.wait(mLock);
2196 ALOGV("async completion/wake");
2197 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002198 standbyTime = systemTime() + standbyDelay;
2199 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002200
2201 continue;
2202 }
2203 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 isSuspended()) {
2205 // put audio hardware into standby after short delay
2206 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002207
2208 threadLoop_standby();
2209
2210 mStandby = true;
2211 }
2212
2213 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2214 // we're about to wait, flush the binder command buffer
2215 IPCThreadState::self()->flushCommands();
2216
2217 clearOutputTracks();
2218
2219 if (exitPending()) {
2220 break;
2221 }
2222
2223 releaseWakeLock_l();
2224 // wait until we have something to do...
2225 ALOGV("%s going to sleep", myName.string());
2226 mWaitWorkCV.wait(mLock);
2227 ALOGV("%s waking up", myName.string());
2228 acquireWakeLock_l();
2229
2230 mMixerStatus = MIXER_IDLE;
2231 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2232 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002234 checkSilentMode_l();
2235
2236 standbyTime = systemTime() + standbyDelay;
2237 sleepTime = idleSleepTime;
2238 if (mType == MIXER) {
2239 sleepTimeShift = 0;
2240 }
2241
2242 continue;
2243 }
2244 }
Eric Laurent81784c32012-11-19 14:55:58 -08002245 // mMixerStatusIgnoringFastTracks is also updated internally
2246 mMixerStatus = prepareTracks_l(&tracksToRemove);
2247
2248 // prevent any changes in effect chain list and in each effect chain
2249 // during mixing and effect process as the audio buffers could be deleted
2250 // or modified if an effect is created or deleted
2251 lockEffectChains_l(effectChains);
2252 }
2253
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254 if (mBytesRemaining == 0) {
2255 mCurrentWriteLength = 0;
2256 if (mMixerStatus == MIXER_TRACKS_READY) {
2257 // threadLoop_mix() sets mCurrentWriteLength
2258 threadLoop_mix();
2259 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2260 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2261 // threadLoop_sleepTime sets sleepTime to 0 if data
2262 // must be written to HAL
2263 threadLoop_sleepTime();
2264 if (sleepTime == 0) {
2265 mCurrentWriteLength = mixBufferSize;
2266 }
2267 }
2268 mBytesRemaining = mCurrentWriteLength;
2269 if (isSuspended()) {
2270 sleepTime = suspendSleepTimeUs();
2271 // simulate write to HAL when suspended
2272 mBytesWritten += mixBufferSize;
2273 mBytesRemaining = 0;
2274 }
Eric Laurent81784c32012-11-19 14:55:58 -08002275
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002277 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 for (size_t i = 0; i < effectChains.size(); i ++) {
2279 effectChains[i]->process_l();
2280 }
Eric Laurent81784c32012-11-19 14:55:58 -08002281 }
2282 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002283 // Process effect chains for offloaded thread even if no audio
2284 // was read from audio track: process only updates effect state
2285 // and thus does have to be synchronized with audio writes but may have
2286 // to be called while waiting for async write callback
2287 if (mType == OFFLOAD) {
2288 for (size_t i = 0; i < effectChains.size(); i ++) {
2289 effectChains[i]->process_l();
2290 }
2291 }
Eric Laurent81784c32012-11-19 14:55:58 -08002292
2293 // enable changes in effect chain
2294 unlockEffectChains(effectChains);
2295
Eric Laurentbfb1b832013-01-07 09:53:42 -08002296 if (!waitingAsyncCallback()) {
2297 // sleepTime == 0 means we must write to audio hardware
2298 if (sleepTime == 0) {
2299 if (mBytesRemaining) {
2300 ssize_t ret = threadLoop_write();
2301 if (ret < 0) {
2302 mBytesRemaining = 0;
2303 } else {
2304 mBytesWritten += ret;
2305 mBytesRemaining -= ret;
2306 }
2307 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2308 (mMixerStatus == MIXER_DRAIN_ALL)) {
2309 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002310 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311if (mType == MIXER) {
2312 // write blocked detection
2313 nsecs_t now = systemTime();
2314 nsecs_t delta = now - mLastWriteTime;
2315 if (!mStandby && delta > maxPeriod) {
2316 mNumDelayedWrites++;
2317 if ((now - lastWarning) > kWarningThrottleNs) {
2318 ATRACE_NAME("underrun");
2319 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2320 ns2ms(delta), mNumDelayedWrites, this);
2321 lastWarning = now;
2322 }
2323 }
Eric Laurent81784c32012-11-19 14:55:58 -08002324}
2325
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326 mStandby = false;
2327 } else {
2328 usleep(sleepTime);
2329 }
Eric Laurent81784c32012-11-19 14:55:58 -08002330 }
2331
2332 // Finally let go of removed track(s), without the lock held
2333 // since we can't guarantee the destructors won't acquire that
2334 // same lock. This will also mutate and push a new fast mixer state.
2335 threadLoop_removeTracks(tracksToRemove);
2336 tracksToRemove.clear();
2337
2338 // FIXME I don't understand the need for this here;
2339 // it was in the original code but maybe the
2340 // assignment in saveOutputTracks() makes this unnecessary?
2341 clearOutputTracks();
2342
2343 // Effect chains will be actually deleted here if they were removed from
2344 // mEffectChains list during mixing or effects processing
2345 effectChains.clear();
2346
2347 // FIXME Note that the above .clear() is no longer necessary since effectChains
2348 // is now local to this block, but will keep it for now (at least until merge done).
2349 }
2350
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 threadLoop_exit();
2352
Eric Laurent81784c32012-11-19 14:55:58 -08002353 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002355 // put output stream into standby mode
2356 if (!mStandby) {
2357 mOutput->stream->common.standby(&mOutput->stream->common);
2358 }
2359 }
2360
2361 releaseWakeLock();
2362
2363 ALOGV("Thread %p type %d exiting", this, mType);
2364 return false;
2365}
2366
Eric Laurentbfb1b832013-01-07 09:53:42 -08002367// removeTracks_l() must be called with ThreadBase::mLock held
2368void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2369{
2370 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002371 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 for (size_t i=0 ; i<count ; i++) {
2373 const sp<Track>& track = tracksToRemove.itemAt(i);
2374 mActiveTracks.remove(track);
2375 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2376 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2377 if (chain != 0) {
2378 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2379 track->sessionId());
2380 chain->decActiveTrackCnt();
2381 }
2382 if (track->isTerminated()) {
2383 removeTrack_l(track);
2384 }
2385 }
2386 }
2387
2388}
Eric Laurent81784c32012-11-19 14:55:58 -08002389
Eric Laurentaccc1472013-09-20 09:36:34 -07002390status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2391{
2392 if (mNormalSink != 0) {
2393 return mNormalSink->getTimestamp(timestamp);
2394 }
2395 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2396 uint64_t position64;
2397 int ret = mOutput->stream->get_presentation_position(
2398 mOutput->stream, &position64, &timestamp.mTime);
2399 if (ret == 0) {
2400 timestamp.mPosition = (uint32_t)position64;
2401 return NO_ERROR;
2402 }
2403 }
2404 return INVALID_OPERATION;
2405}
Eric Laurent81784c32012-11-19 14:55:58 -08002406// ----------------------------------------------------------------------------
2407
2408AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2409 audio_io_handle_t id, audio_devices_t device, type_t type)
2410 : PlaybackThread(audioFlinger, output, id, device, type),
2411 // mAudioMixer below
2412 // mFastMixer below
2413 mFastMixerFutex(0)
2414 // mOutputSink below
2415 // mPipeSink below
2416 // mNormalSink below
2417{
2418 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002419 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002420 "mFrameCount=%d, mNormalFrameCount=%d",
2421 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2422 mNormalFrameCount);
2423 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2424
2425 // FIXME - Current mixer implementation only supports stereo output
2426 if (mChannelCount != FCC_2) {
2427 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2428 }
2429
2430 // create an NBAIO sink for the HAL output stream, and negotiate
2431 mOutputSink = new AudioStreamOutSink(output->stream);
2432 size_t numCounterOffers = 0;
2433 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2434 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2435 ALOG_ASSERT(index == 0);
2436
2437 // initialize fast mixer depending on configuration
2438 bool initFastMixer;
2439 switch (kUseFastMixer) {
2440 case FastMixer_Never:
2441 initFastMixer = false;
2442 break;
2443 case FastMixer_Always:
2444 initFastMixer = true;
2445 break;
2446 case FastMixer_Static:
2447 case FastMixer_Dynamic:
2448 initFastMixer = mFrameCount < mNormalFrameCount;
2449 break;
2450 }
2451 if (initFastMixer) {
2452
2453 // create a MonoPipe to connect our submix to FastMixer
2454 NBAIO_Format format = mOutputSink->format();
2455 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2456 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2457 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2458 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2459 const NBAIO_Format offers[1] = {format};
2460 size_t numCounterOffers = 0;
2461 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2462 ALOG_ASSERT(index == 0);
2463 monoPipe->setAvgFrames((mScreenState & 1) ?
2464 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2465 mPipeSink = monoPipe;
2466
Glenn Kasten46909e72013-02-26 09:20:22 -08002467#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002468 if (mTeeSinkOutputEnabled) {
2469 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2470 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2471 numCounterOffers = 0;
2472 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2473 ALOG_ASSERT(index == 0);
2474 mTeeSink = teeSink;
2475 PipeReader *teeSource = new PipeReader(*teeSink);
2476 numCounterOffers = 0;
2477 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2478 ALOG_ASSERT(index == 0);
2479 mTeeSource = teeSource;
2480 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002481#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002482
2483 // create fast mixer and configure it initially with just one fast track for our submix
2484 mFastMixer = new FastMixer();
2485 FastMixerStateQueue *sq = mFastMixer->sq();
2486#ifdef STATE_QUEUE_DUMP
2487 sq->setObserverDump(&mStateQueueObserverDump);
2488 sq->setMutatorDump(&mStateQueueMutatorDump);
2489#endif
2490 FastMixerState *state = sq->begin();
2491 FastTrack *fastTrack = &state->mFastTracks[0];
2492 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2493 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2494 fastTrack->mVolumeProvider = NULL;
2495 fastTrack->mGeneration++;
2496 state->mFastTracksGen++;
2497 state->mTrackMask = 1;
2498 // fast mixer will use the HAL output sink
2499 state->mOutputSink = mOutputSink.get();
2500 state->mOutputSinkGen++;
2501 state->mFrameCount = mFrameCount;
2502 state->mCommand = FastMixerState::COLD_IDLE;
2503 // already done in constructor initialization list
2504 //mFastMixerFutex = 0;
2505 state->mColdFutexAddr = &mFastMixerFutex;
2506 state->mColdGen++;
2507 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002508#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002509 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002510#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002511 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2512 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002513 sq->end();
2514 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2515
2516 // start the fast mixer
2517 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2518 pid_t tid = mFastMixer->getTid();
2519 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2520 if (err != 0) {
2521 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2522 kPriorityFastMixer, getpid_cached, tid, err);
2523 }
2524
2525#ifdef AUDIO_WATCHDOG
2526 // create and start the watchdog
2527 mAudioWatchdog = new AudioWatchdog();
2528 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2529 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2530 tid = mAudioWatchdog->getTid();
2531 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2532 if (err != 0) {
2533 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2534 kPriorityFastMixer, getpid_cached, tid, err);
2535 }
2536#endif
2537
2538 } else {
2539 mFastMixer = NULL;
2540 }
2541
2542 switch (kUseFastMixer) {
2543 case FastMixer_Never:
2544 case FastMixer_Dynamic:
2545 mNormalSink = mOutputSink;
2546 break;
2547 case FastMixer_Always:
2548 mNormalSink = mPipeSink;
2549 break;
2550 case FastMixer_Static:
2551 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2552 break;
2553 }
2554}
2555
2556AudioFlinger::MixerThread::~MixerThread()
2557{
2558 if (mFastMixer != NULL) {
2559 FastMixerStateQueue *sq = mFastMixer->sq();
2560 FastMixerState *state = sq->begin();
2561 if (state->mCommand == FastMixerState::COLD_IDLE) {
2562 int32_t old = android_atomic_inc(&mFastMixerFutex);
2563 if (old == -1) {
2564 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2565 }
2566 }
2567 state->mCommand = FastMixerState::EXIT;
2568 sq->end();
2569 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2570 mFastMixer->join();
2571 // Though the fast mixer thread has exited, it's state queue is still valid.
2572 // We'll use that extract the final state which contains one remaining fast track
2573 // corresponding to our sub-mix.
2574 state = sq->begin();
2575 ALOG_ASSERT(state->mTrackMask == 1);
2576 FastTrack *fastTrack = &state->mFastTracks[0];
2577 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2578 delete fastTrack->mBufferProvider;
2579 sq->end(false /*didModify*/);
2580 delete mFastMixer;
2581#ifdef AUDIO_WATCHDOG
2582 if (mAudioWatchdog != 0) {
2583 mAudioWatchdog->requestExit();
2584 mAudioWatchdog->requestExitAndWait();
2585 mAudioWatchdog.clear();
2586 }
2587#endif
2588 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002589 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002590 delete mAudioMixer;
2591}
2592
2593
2594uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2595{
2596 if (mFastMixer != NULL) {
2597 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2598 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2599 }
2600 return latency;
2601}
2602
2603
2604void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2605{
2606 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2607}
2608
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002610{
2611 // FIXME we should only do one push per cycle; confirm this is true
2612 // Start the fast mixer if it's not already running
2613 if (mFastMixer != NULL) {
2614 FastMixerStateQueue *sq = mFastMixer->sq();
2615 FastMixerState *state = sq->begin();
2616 if (state->mCommand != FastMixerState::MIX_WRITE &&
2617 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2618 if (state->mCommand == FastMixerState::COLD_IDLE) {
2619 int32_t old = android_atomic_inc(&mFastMixerFutex);
2620 if (old == -1) {
2621 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2622 }
2623#ifdef AUDIO_WATCHDOG
2624 if (mAudioWatchdog != 0) {
2625 mAudioWatchdog->resume();
2626 }
2627#endif
2628 }
2629 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002630 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2631 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002632 sq->end();
2633 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2634 if (kUseFastMixer == FastMixer_Dynamic) {
2635 mNormalSink = mPipeSink;
2636 }
2637 } else {
2638 sq->end(false /*didModify*/);
2639 }
2640 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002642}
2643
2644void AudioFlinger::MixerThread::threadLoop_standby()
2645{
2646 // Idle the fast mixer if it's currently running
2647 if (mFastMixer != NULL) {
2648 FastMixerStateQueue *sq = mFastMixer->sq();
2649 FastMixerState *state = sq->begin();
2650 if (!(state->mCommand & FastMixerState::IDLE)) {
2651 state->mCommand = FastMixerState::COLD_IDLE;
2652 state->mColdFutexAddr = &mFastMixerFutex;
2653 state->mColdGen++;
2654 mFastMixerFutex = 0;
2655 sq->end();
2656 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2657 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2658 if (kUseFastMixer == FastMixer_Dynamic) {
2659 mNormalSink = mOutputSink;
2660 }
2661#ifdef AUDIO_WATCHDOG
2662 if (mAudioWatchdog != 0) {
2663 mAudioWatchdog->pause();
2664 }
2665#endif
2666 } else {
2667 sq->end(false /*didModify*/);
2668 }
2669 }
2670 PlaybackThread::threadLoop_standby();
2671}
2672
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673// Empty implementation for standard mixer
2674// Overridden for offloaded playback
2675void AudioFlinger::PlaybackThread::flushOutput_l()
2676{
2677}
2678
2679bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2680{
2681 return false;
2682}
2683
2684bool AudioFlinger::PlaybackThread::shouldStandby_l()
2685{
2686 return !mStandby;
2687}
2688
2689bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2690{
2691 Mutex::Autolock _l(mLock);
2692 return waitingAsyncCallback_l();
2693}
2694
Eric Laurent81784c32012-11-19 14:55:58 -08002695// shared by MIXER and DIRECT, overridden by DUPLICATING
2696void AudioFlinger::PlaybackThread::threadLoop_standby()
2697{
2698 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2699 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002701 // discard any pending drain or write ack by incrementing sequence
2702 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2703 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002705 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2706 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 }
Eric Laurent81784c32012-11-19 14:55:58 -08002708}
2709
2710void AudioFlinger::MixerThread::threadLoop_mix()
2711{
2712 // obtain the presentation timestamp of the next output buffer
2713 int64_t pts;
2714 status_t status = INVALID_OPERATION;
2715
2716 if (mNormalSink != 0) {
2717 status = mNormalSink->getNextWriteTimestamp(&pts);
2718 } else {
2719 status = mOutputSink->getNextWriteTimestamp(&pts);
2720 }
2721
2722 if (status != NO_ERROR) {
2723 pts = AudioBufferProvider::kInvalidPTS;
2724 }
2725
2726 // mix buffers...
2727 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002728 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002729 // increase sleep time progressively when application underrun condition clears.
2730 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2731 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2732 // such that we would underrun the audio HAL.
2733 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2734 sleepTimeShift--;
2735 }
2736 sleepTime = 0;
2737 standbyTime = systemTime() + standbyDelay;
2738 //TODO: delay standby when effects have a tail
2739}
2740
2741void AudioFlinger::MixerThread::threadLoop_sleepTime()
2742{
2743 // If no tracks are ready, sleep once for the duration of an output
2744 // buffer size, then write 0s to the output
2745 if (sleepTime == 0) {
2746 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2747 sleepTime = activeSleepTime >> sleepTimeShift;
2748 if (sleepTime < kMinThreadSleepTimeUs) {
2749 sleepTime = kMinThreadSleepTimeUs;
2750 }
2751 // reduce sleep time in case of consecutive application underruns to avoid
2752 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2753 // duration we would end up writing less data than needed by the audio HAL if
2754 // the condition persists.
2755 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2756 sleepTimeShift++;
2757 }
2758 } else {
2759 sleepTime = idleSleepTime;
2760 }
2761 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002762 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002763 sleepTime = 0;
2764 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2765 "anticipated start");
2766 }
2767 // TODO add standby time extension fct of effect tail
2768}
2769
2770// prepareTracks_l() must be called with ThreadBase::mLock held
2771AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2772 Vector< sp<Track> > *tracksToRemove)
2773{
2774
2775 mixer_state mixerStatus = MIXER_IDLE;
2776 // find out which tracks need to be processed
2777 size_t count = mActiveTracks.size();
2778 size_t mixedTracks = 0;
2779 size_t tracksWithEffect = 0;
2780 // counts only _active_ fast tracks
2781 size_t fastTracks = 0;
2782 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2783
2784 float masterVolume = mMasterVolume;
2785 bool masterMute = mMasterMute;
2786
2787 if (masterMute) {
2788 masterVolume = 0;
2789 }
2790 // Delegate master volume control to effect in output mix effect chain if needed
2791 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2792 if (chain != 0) {
2793 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2794 chain->setVolume_l(&v, &v);
2795 masterVolume = (float)((v + (1 << 23)) >> 24);
2796 chain.clear();
2797 }
2798
2799 // prepare a new state to push
2800 FastMixerStateQueue *sq = NULL;
2801 FastMixerState *state = NULL;
2802 bool didModify = false;
2803 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2804 if (mFastMixer != NULL) {
2805 sq = mFastMixer->sq();
2806 state = sq->begin();
2807 }
2808
2809 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002810 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002811 if (t == 0) {
2812 continue;
2813 }
2814
2815 // this const just means the local variable doesn't change
2816 Track* const track = t.get();
2817
2818 // process fast tracks
2819 if (track->isFastTrack()) {
2820
2821 // It's theoretically possible (though unlikely) for a fast track to be created
2822 // and then removed within the same normal mix cycle. This is not a problem, as
2823 // the track never becomes active so it's fast mixer slot is never touched.
2824 // The converse, of removing an (active) track and then creating a new track
2825 // at the identical fast mixer slot within the same normal mix cycle,
2826 // is impossible because the slot isn't marked available until the end of each cycle.
2827 int j = track->mFastIndex;
2828 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2829 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2830 FastTrack *fastTrack = &state->mFastTracks[j];
2831
2832 // Determine whether the track is currently in underrun condition,
2833 // and whether it had a recent underrun.
2834 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2835 FastTrackUnderruns underruns = ftDump->mUnderruns;
2836 uint32_t recentFull = (underruns.mBitFields.mFull -
2837 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2838 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2839 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2840 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2841 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2842 uint32_t recentUnderruns = recentPartial + recentEmpty;
2843 track->mObservedUnderruns = underruns;
2844 // don't count underruns that occur while stopping or pausing
2845 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002846 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2847 recentUnderruns > 0) {
2848 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2849 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002850 }
2851
2852 // This is similar to the state machine for normal tracks,
2853 // with a few modifications for fast tracks.
2854 bool isActive = true;
2855 switch (track->mState) {
2856 case TrackBase::STOPPING_1:
2857 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002859 track->mState = TrackBase::STOPPING_2;
2860 }
2861 break;
2862 case TrackBase::PAUSING:
2863 // ramp down is not yet implemented
2864 track->setPaused();
2865 break;
2866 case TrackBase::RESUMING:
2867 // ramp up is not yet implemented
2868 track->mState = TrackBase::ACTIVE;
2869 break;
2870 case TrackBase::ACTIVE:
2871 if (recentFull > 0 || recentPartial > 0) {
2872 // track has provided at least some frames recently: reset retry count
2873 track->mRetryCount = kMaxTrackRetries;
2874 }
2875 if (recentUnderruns == 0) {
2876 // no recent underruns: stay active
2877 break;
2878 }
2879 // there has recently been an underrun of some kind
2880 if (track->sharedBuffer() == 0) {
2881 // were any of the recent underruns "empty" (no frames available)?
2882 if (recentEmpty == 0) {
2883 // no, then ignore the partial underruns as they are allowed indefinitely
2884 break;
2885 }
2886 // there has recently been an "empty" underrun: decrement the retry counter
2887 if (--(track->mRetryCount) > 0) {
2888 break;
2889 }
2890 // indicate to client process that the track was disabled because of underrun;
2891 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002892 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002893 // remove from active list, but state remains ACTIVE [confusing but true]
2894 isActive = false;
2895 break;
2896 }
2897 // fall through
2898 case TrackBase::STOPPING_2:
2899 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002900 case TrackBase::STOPPED:
2901 case TrackBase::FLUSHED: // flush() while active
2902 // Check for presentation complete if track is inactive
2903 // We have consumed all the buffers of this track.
2904 // This would be incomplete if we auto-paused on underrun
2905 {
2906 size_t audioHALFrames =
2907 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2908 size_t framesWritten = mBytesWritten / mFrameSize;
2909 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2910 // track stays in active list until presentation is complete
2911 break;
2912 }
2913 }
2914 if (track->isStopping_2()) {
2915 track->mState = TrackBase::STOPPED;
2916 }
2917 if (track->isStopped()) {
2918 // Can't reset directly, as fast mixer is still polling this track
2919 // track->reset();
2920 // So instead mark this track as needing to be reset after push with ack
2921 resetMask |= 1 << i;
2922 }
2923 isActive = false;
2924 break;
2925 case TrackBase::IDLE:
2926 default:
2927 LOG_FATAL("unexpected track state %d", track->mState);
2928 }
2929
2930 if (isActive) {
2931 // was it previously inactive?
2932 if (!(state->mTrackMask & (1 << j))) {
2933 ExtendedAudioBufferProvider *eabp = track;
2934 VolumeProvider *vp = track;
2935 fastTrack->mBufferProvider = eabp;
2936 fastTrack->mVolumeProvider = vp;
2937 fastTrack->mSampleRate = track->mSampleRate;
2938 fastTrack->mChannelMask = track->mChannelMask;
2939 fastTrack->mGeneration++;
2940 state->mTrackMask |= 1 << j;
2941 didModify = true;
2942 // no acknowledgement required for newly active tracks
2943 }
2944 // cache the combined master volume and stream type volume for fast mixer; this
2945 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002946 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002947 ++fastTracks;
2948 } else {
2949 // was it previously active?
2950 if (state->mTrackMask & (1 << j)) {
2951 fastTrack->mBufferProvider = NULL;
2952 fastTrack->mGeneration++;
2953 state->mTrackMask &= ~(1 << j);
2954 didModify = true;
2955 // If any fast tracks were removed, we must wait for acknowledgement
2956 // because we're about to decrement the last sp<> on those tracks.
2957 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2958 } else {
2959 LOG_FATAL("fast track %d should have been active", j);
2960 }
2961 tracksToRemove->add(track);
2962 // Avoids a misleading display in dumpsys
2963 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2964 }
2965 continue;
2966 }
2967
2968 { // local variable scope to avoid goto warning
2969
2970 audio_track_cblk_t* cblk = track->cblk();
2971
2972 // The first time a track is added we wait
2973 // for all its buffers to be filled before processing it
2974 int name = track->name();
2975 // make sure that we have enough frames to mix one full buffer.
2976 // enforce this condition only once to enable draining the buffer in case the client
2977 // app does not call stop() and relies on underrun to stop:
2978 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2979 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002980 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002981 uint32_t sr = track->sampleRate();
2982 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002983 desiredFrames = mNormalFrameCount;
2984 } else {
2985 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002986 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002987 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07002988 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002989 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2990 // the minimum track buffer size is normally twice the number of frames necessary
2991 // to fill one buffer and the resampler should not leave more than one buffer worth
2992 // of unreleased frames after each pass, but just in case...
2993 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2994 }
Eric Laurent81784c32012-11-19 14:55:58 -08002995 uint32_t minFrames = 1;
2996 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2997 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002998 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002999 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003000 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
3001 size_t framesReady;
3002 if (track->sharedBuffer() == 0) {
3003 framesReady = track->framesReady();
3004 } else if (track->isStopped()) {
3005 framesReady = 0;
3006 } else {
3007 framesReady = 1;
3008 }
3009 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003010 !track->isPaused() && !track->isTerminated())
3011 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003012 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003013
3014 mixedTracks++;
3015
3016 // track->mainBuffer() != mMixBuffer means there is an effect chain
3017 // connected to the track
3018 chain.clear();
3019 if (track->mainBuffer() != mMixBuffer) {
3020 chain = getEffectChain_l(track->sessionId());
3021 // Delegate volume control to effect in track effect chain if needed
3022 if (chain != 0) {
3023 tracksWithEffect++;
3024 } else {
3025 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3026 "session %d",
3027 name, track->sessionId());
3028 }
3029 }
3030
3031
3032 int param = AudioMixer::VOLUME;
3033 if (track->mFillingUpStatus == Track::FS_FILLED) {
3034 // no ramp for the first volume setting
3035 track->mFillingUpStatus = Track::FS_ACTIVE;
3036 if (track->mState == TrackBase::RESUMING) {
3037 track->mState = TrackBase::ACTIVE;
3038 param = AudioMixer::RAMP_VOLUME;
3039 }
3040 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003041 // FIXME should not make a decision based on mServer
3042 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003043 // If the track is stopped before the first frame was mixed,
3044 // do not apply ramp
3045 param = AudioMixer::RAMP_VOLUME;
3046 }
3047
3048 // compute volume for this track
3049 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003050 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003051 vl = vr = va = 0;
3052 if (track->isPausing()) {
3053 track->setPaused();
3054 }
3055 } else {
3056
3057 // read original volumes with volume control
3058 float typeVolume = mStreamTypes[track->streamType()].volume;
3059 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003060 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003061 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003062 vl = vlr & 0xFFFF;
3063 vr = vlr >> 16;
3064 // track volumes come from shared memory, so can't be trusted and must be clamped
3065 if (vl > MAX_GAIN_INT) {
3066 ALOGV("Track left volume out of range: %04X", vl);
3067 vl = MAX_GAIN_INT;
3068 }
3069 if (vr > MAX_GAIN_INT) {
3070 ALOGV("Track right volume out of range: %04X", vr);
3071 vr = MAX_GAIN_INT;
3072 }
3073 // now apply the master volume and stream type volume
3074 vl = (uint32_t)(v * vl) << 12;
3075 vr = (uint32_t)(v * vr) << 12;
3076 // assuming master volume and stream type volume each go up to 1.0,
3077 // vl and vr are now in 8.24 format
3078
Glenn Kastene3aa6592012-12-04 12:22:46 -08003079 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003080 // send level comes from shared memory and so may be corrupt
3081 if (sendLevel > MAX_GAIN_INT) {
3082 ALOGV("Track send level out of range: %04X", sendLevel);
3083 sendLevel = MAX_GAIN_INT;
3084 }
3085 va = (uint32_t)(v * sendLevel);
3086 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087
Eric Laurent81784c32012-11-19 14:55:58 -08003088 // Delegate volume control to effect in track effect chain if needed
3089 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3090 // Do not ramp volume if volume is controlled by effect
3091 param = AudioMixer::VOLUME;
3092 track->mHasVolumeController = true;
3093 } else {
3094 // force no volume ramp when volume controller was just disabled or removed
3095 // from effect chain to avoid volume spike
3096 if (track->mHasVolumeController) {
3097 param = AudioMixer::VOLUME;
3098 }
3099 track->mHasVolumeController = false;
3100 }
3101
3102 // Convert volumes from 8.24 to 4.12 format
3103 // This additional clamping is needed in case chain->setVolume_l() overshot
3104 vl = (vl + (1 << 11)) >> 12;
3105 if (vl > MAX_GAIN_INT) {
3106 vl = MAX_GAIN_INT;
3107 }
3108 vr = (vr + (1 << 11)) >> 12;
3109 if (vr > MAX_GAIN_INT) {
3110 vr = MAX_GAIN_INT;
3111 }
3112
3113 if (va > MAX_GAIN_INT) {
3114 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3115 }
3116
3117 // XXX: these things DON'T need to be done each time
3118 mAudioMixer->setBufferProvider(name, track);
3119 mAudioMixer->enable(name);
3120
3121 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3122 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3123 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3124 mAudioMixer->setParameter(
3125 name,
3126 AudioMixer::TRACK,
3127 AudioMixer::FORMAT, (void *)track->format());
3128 mAudioMixer->setParameter(
3129 name,
3130 AudioMixer::TRACK,
3131 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003132 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3133 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003134 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003135 if (reqSampleRate == 0) {
3136 reqSampleRate = mSampleRate;
3137 } else if (reqSampleRate > maxSampleRate) {
3138 reqSampleRate = maxSampleRate;
3139 }
Eric Laurent81784c32012-11-19 14:55:58 -08003140 mAudioMixer->setParameter(
3141 name,
3142 AudioMixer::RESAMPLE,
3143 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003144 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003145 mAudioMixer->setParameter(
3146 name,
3147 AudioMixer::TRACK,
3148 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3149 mAudioMixer->setParameter(
3150 name,
3151 AudioMixer::TRACK,
3152 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3153
3154 // reset retry count
3155 track->mRetryCount = kMaxTrackRetries;
3156
3157 // If one track is ready, set the mixer ready if:
3158 // - the mixer was not ready during previous round OR
3159 // - no other track is not ready
3160 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3161 mixerStatus != MIXER_TRACKS_ENABLED) {
3162 mixerStatus = MIXER_TRACKS_READY;
3163 }
3164 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003165 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003166 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003167 }
Eric Laurent81784c32012-11-19 14:55:58 -08003168 // clear effect chain input buffer if an active track underruns to avoid sending
3169 // previous audio buffer again to effects
3170 chain = getEffectChain_l(track->sessionId());
3171 if (chain != 0) {
3172 chain->clearInputBuffer();
3173 }
3174
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003175 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003176 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3177 track->isStopped() || track->isPaused()) {
3178 // We have consumed all the buffers of this track.
3179 // Remove it from the list of active tracks.
3180 // TODO: use actual buffer filling status instead of latency when available from
3181 // audio HAL
3182 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3183 size_t framesWritten = mBytesWritten / mFrameSize;
3184 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3185 if (track->isStopped()) {
3186 track->reset();
3187 }
3188 tracksToRemove->add(track);
3189 }
3190 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003191 // No buffers for this track. Give it a few chances to
3192 // fill a buffer, then remove it from active list.
3193 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003194 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003195 tracksToRemove->add(track);
3196 // indicate to client process that the track was disabled because of underrun;
3197 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003198 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003199 // If one track is not ready, mark the mixer also not ready if:
3200 // - the mixer was ready during previous round OR
3201 // - no other track is ready
3202 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3203 mixerStatus != MIXER_TRACKS_READY) {
3204 mixerStatus = MIXER_TRACKS_ENABLED;
3205 }
3206 }
3207 mAudioMixer->disable(name);
3208 }
3209
3210 } // local variable scope to avoid goto warning
3211track_is_ready: ;
3212
3213 }
3214
3215 // Push the new FastMixer state if necessary
3216 bool pauseAudioWatchdog = false;
3217 if (didModify) {
3218 state->mFastTracksGen++;
3219 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3220 if (kUseFastMixer == FastMixer_Dynamic &&
3221 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3222 state->mCommand = FastMixerState::COLD_IDLE;
3223 state->mColdFutexAddr = &mFastMixerFutex;
3224 state->mColdGen++;
3225 mFastMixerFutex = 0;
3226 if (kUseFastMixer == FastMixer_Dynamic) {
3227 mNormalSink = mOutputSink;
3228 }
3229 // If we go into cold idle, need to wait for acknowledgement
3230 // so that fast mixer stops doing I/O.
3231 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3232 pauseAudioWatchdog = true;
3233 }
Eric Laurent81784c32012-11-19 14:55:58 -08003234 }
3235 if (sq != NULL) {
3236 sq->end(didModify);
3237 sq->push(block);
3238 }
3239#ifdef AUDIO_WATCHDOG
3240 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3241 mAudioWatchdog->pause();
3242 }
3243#endif
3244
3245 // Now perform the deferred reset on fast tracks that have stopped
3246 while (resetMask != 0) {
3247 size_t i = __builtin_ctz(resetMask);
3248 ALOG_ASSERT(i < count);
3249 resetMask &= ~(1 << i);
3250 sp<Track> t = mActiveTracks[i].promote();
3251 if (t == 0) {
3252 continue;
3253 }
3254 Track* track = t.get();
3255 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3256 track->reset();
3257 }
3258
3259 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003261
3262 // mix buffer must be cleared if all tracks are connected to an
3263 // effect chain as in this case the mixer will not write to
3264 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3266 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003267 // FIXME as a performance optimization, should remember previous zero status
3268 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3269 }
3270
3271 // if any fast tracks, then status is ready
3272 mMixerStatusIgnoringFastTracks = mixerStatus;
3273 if (fastTracks > 0) {
3274 mixerStatus = MIXER_TRACKS_READY;
3275 }
3276 return mixerStatus;
3277}
3278
3279// getTrackName_l() must be called with ThreadBase::mLock held
3280int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3281{
3282 return mAudioMixer->getTrackName(channelMask, sessionId);
3283}
3284
3285// deleteTrackName_l() must be called with ThreadBase::mLock held
3286void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3287{
3288 ALOGV("remove track (%d) and delete from mixer", name);
3289 mAudioMixer->deleteTrackName(name);
3290}
3291
3292// checkForNewParameters_l() must be called with ThreadBase::mLock held
3293bool AudioFlinger::MixerThread::checkForNewParameters_l()
3294{
3295 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3296 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3297 bool reconfig = false;
3298
3299 while (!mNewParameters.isEmpty()) {
3300
3301 if (mFastMixer != NULL) {
3302 FastMixerStateQueue *sq = mFastMixer->sq();
3303 FastMixerState *state = sq->begin();
3304 if (!(state->mCommand & FastMixerState::IDLE)) {
3305 previousCommand = state->mCommand;
3306 state->mCommand = FastMixerState::HOT_IDLE;
3307 sq->end();
3308 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3309 } else {
3310 sq->end(false /*didModify*/);
3311 }
3312 }
3313
3314 status_t status = NO_ERROR;
3315 String8 keyValuePair = mNewParameters[0];
3316 AudioParameter param = AudioParameter(keyValuePair);
3317 int value;
3318
3319 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3320 reconfig = true;
3321 }
3322 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3323 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3324 status = BAD_VALUE;
3325 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003326 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003327 reconfig = true;
3328 }
3329 }
3330 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003331 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003332 status = BAD_VALUE;
3333 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003334 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003335 reconfig = true;
3336 }
3337 }
3338 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3339 // do not accept frame count changes if tracks are open as the track buffer
3340 // size depends on frame count and correct behavior would not be guaranteed
3341 // if frame count is changed after track creation
3342 if (!mTracks.isEmpty()) {
3343 status = INVALID_OPERATION;
3344 } else {
3345 reconfig = true;
3346 }
3347 }
3348 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3349#ifdef ADD_BATTERY_DATA
3350 // when changing the audio output device, call addBatteryData to notify
3351 // the change
3352 if (mOutDevice != value) {
3353 uint32_t params = 0;
3354 // check whether speaker is on
3355 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3356 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3357 }
3358
3359 audio_devices_t deviceWithoutSpeaker
3360 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3361 // check if any other device (except speaker) is on
3362 if (value & deviceWithoutSpeaker ) {
3363 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3364 }
3365
3366 if (params != 0) {
3367 addBatteryData(params);
3368 }
3369 }
3370#endif
3371
3372 // forward device change to effects that have requested to be
3373 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003374 if (value != AUDIO_DEVICE_NONE) {
3375 mOutDevice = value;
3376 for (size_t i = 0; i < mEffectChains.size(); i++) {
3377 mEffectChains[i]->setDevice_l(mOutDevice);
3378 }
Eric Laurent81784c32012-11-19 14:55:58 -08003379 }
3380 }
3381
3382 if (status == NO_ERROR) {
3383 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3384 keyValuePair.string());
3385 if (!mStandby && status == INVALID_OPERATION) {
3386 mOutput->stream->common.standby(&mOutput->stream->common);
3387 mStandby = true;
3388 mBytesWritten = 0;
3389 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3390 keyValuePair.string());
3391 }
3392 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003393 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003394 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003395 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3396 for (size_t i = 0; i < mTracks.size() ; i++) {
3397 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3398 if (name < 0) {
3399 break;
3400 }
3401 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003402 }
3403 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3404 }
3405 }
3406
3407 mNewParameters.removeAt(0);
3408
3409 mParamStatus = status;
3410 mParamCond.signal();
3411 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3412 // already timed out waiting for the status and will never signal the condition.
3413 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3414 }
3415
3416 if (!(previousCommand & FastMixerState::IDLE)) {
3417 ALOG_ASSERT(mFastMixer != NULL);
3418 FastMixerStateQueue *sq = mFastMixer->sq();
3419 FastMixerState *state = sq->begin();
3420 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3421 state->mCommand = previousCommand;
3422 sq->end();
3423 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3424 }
3425
3426 return reconfig;
3427}
3428
3429
3430void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3431{
3432 const size_t SIZE = 256;
3433 char buffer[SIZE];
3434 String8 result;
3435
3436 PlaybackThread::dumpInternals(fd, args);
3437
3438 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3439 result.append(buffer);
3440 write(fd, result.string(), result.size());
3441
3442 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003443 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003444 copy.dump(fd);
3445
3446#ifdef STATE_QUEUE_DUMP
3447 // Similar for state queue
3448 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3449 observerCopy.dump(fd);
3450 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3451 mutatorCopy.dump(fd);
3452#endif
3453
Glenn Kasten46909e72013-02-26 09:20:22 -08003454#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003455 // Write the tee output to a .wav file
3456 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003457#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003458
3459#ifdef AUDIO_WATCHDOG
3460 if (mAudioWatchdog != 0) {
3461 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3462 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3463 wdCopy.dump(fd);
3464 }
3465#endif
3466}
3467
3468uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3469{
3470 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3471}
3472
3473uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3474{
3475 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3476}
3477
3478void AudioFlinger::MixerThread::cacheParameters_l()
3479{
3480 PlaybackThread::cacheParameters_l();
3481
3482 // FIXME: Relaxed timing because of a certain device that can't meet latency
3483 // Should be reduced to 2x after the vendor fixes the driver issue
3484 // increase threshold again due to low power audio mode. The way this warning
3485 // threshold is calculated and its usefulness should be reconsidered anyway.
3486 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3487}
3488
3489// ----------------------------------------------------------------------------
3490
3491AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3492 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3493 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3494 // mLeftVolFloat, mRightVolFloat
3495{
3496}
3497
Eric Laurentbfb1b832013-01-07 09:53:42 -08003498AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3499 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3500 ThreadBase::type_t type)
3501 : PlaybackThread(audioFlinger, output, id, device, type)
3502 // mLeftVolFloat, mRightVolFloat
3503{
3504}
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506AudioFlinger::DirectOutputThread::~DirectOutputThread()
3507{
3508}
3509
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3511{
3512 audio_track_cblk_t* cblk = track->cblk();
3513 float left, right;
3514
3515 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3516 left = right = 0;
3517 } else {
3518 float typeVolume = mStreamTypes[track->streamType()].volume;
3519 float v = mMasterVolume * typeVolume;
3520 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3521 uint32_t vlr = proxy->getVolumeLR();
3522 float v_clamped = v * (vlr & 0xFFFF);
3523 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3524 left = v_clamped/MAX_GAIN;
3525 v_clamped = v * (vlr >> 16);
3526 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3527 right = v_clamped/MAX_GAIN;
3528 }
3529
3530 if (lastTrack) {
3531 if (left != mLeftVolFloat || right != mRightVolFloat) {
3532 mLeftVolFloat = left;
3533 mRightVolFloat = right;
3534
3535 // Convert volumes from float to 8.24
3536 uint32_t vl = (uint32_t)(left * (1 << 24));
3537 uint32_t vr = (uint32_t)(right * (1 << 24));
3538
3539 // Delegate volume control to effect in track effect chain if needed
3540 // only one effect chain can be present on DirectOutputThread, so if
3541 // there is one, the track is connected to it
3542 if (!mEffectChains.isEmpty()) {
3543 mEffectChains[0]->setVolume_l(&vl, &vr);
3544 left = (float)vl / (1 << 24);
3545 right = (float)vr / (1 << 24);
3546 }
3547 if (mOutput->stream->set_volume) {
3548 mOutput->stream->set_volume(mOutput->stream, left, right);
3549 }
3550 }
3551 }
3552}
3553
3554
Eric Laurent81784c32012-11-19 14:55:58 -08003555AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3556 Vector< sp<Track> > *tracksToRemove
3557)
3558{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003559 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003560 mixer_state mixerStatus = MIXER_IDLE;
3561
3562 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003563 for (size_t i = 0; i < count; i++) {
3564 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003565 // The track died recently
3566 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003567 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003568 }
3569
3570 Track* const track = t.get();
3571 audio_track_cblk_t* cblk = track->cblk();
3572
3573 // The first time a track is added we wait
3574 // for all its buffers to be filled before processing it
3575 uint32_t minFrames;
3576 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3577 minFrames = mNormalFrameCount;
3578 } else {
3579 minFrames = 1;
3580 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 // Only consider last track started for volume and mixer state control.
3582 // This is the last entry in mActiveTracks unless a track underruns.
3583 // As we only care about the transition phase between two tracks on a
3584 // direct output, it is not a problem to ignore the underrun case.
3585 bool last = (i == (count - 1));
3586
Eric Laurent81784c32012-11-19 14:55:58 -08003587 if ((track->framesReady() >= minFrames) && track->isReady() &&
3588 !track->isPaused() && !track->isTerminated())
3589 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003590 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003591
3592 if (track->mFillingUpStatus == Track::FS_FILLED) {
3593 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003594 // make sure processVolume_l() will apply new volume even if 0
3595 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003596 if (track->mState == TrackBase::RESUMING) {
3597 track->mState = TrackBase::ACTIVE;
3598 }
3599 }
3600
3601 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003602 processVolume_l(track, last);
3603 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003604 // reset retry count
3605 track->mRetryCount = kMaxTrackRetriesDirect;
3606 mActiveTrack = t;
3607 mixerStatus = MIXER_TRACKS_READY;
3608 }
Eric Laurent81784c32012-11-19 14:55:58 -08003609 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003610 // clear effect chain input buffer if the last active track started underruns
3611 // to avoid sending previous audio buffer again to effects
3612 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003613 mEffectChains[0]->clearInputBuffer();
3614 }
3615
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003616 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003617 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3618 track->isStopped() || track->isPaused()) {
3619 // We have consumed all the buffers of this track.
3620 // Remove it from the list of active tracks.
3621 // TODO: implement behavior for compressed audio
3622 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3623 size_t framesWritten = mBytesWritten / mFrameSize;
3624 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3625 if (track->isStopped()) {
3626 track->reset();
3627 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003628 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003629 }
3630 } else {
3631 // No buffers for this track. Give it a few chances to
3632 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003633 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003634 if (--(track->mRetryCount) <= 0) {
3635 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003636 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003637 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003638 mixerStatus = MIXER_TRACKS_ENABLED;
3639 }
3640 }
3641 }
3642 }
3643
Eric Laurent81784c32012-11-19 14:55:58 -08003644 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003646
3647 return mixerStatus;
3648}
3649
3650void AudioFlinger::DirectOutputThread::threadLoop_mix()
3651{
Eric Laurent81784c32012-11-19 14:55:58 -08003652 size_t frameCount = mFrameCount;
3653 int8_t *curBuf = (int8_t *)mMixBuffer;
3654 // output audio to hardware
3655 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003656 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003657 buffer.frameCount = frameCount;
3658 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003659 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003660 memset(curBuf, 0, frameCount * mFrameSize);
3661 break;
3662 }
3663 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3664 frameCount -= buffer.frameCount;
3665 curBuf += buffer.frameCount * mFrameSize;
3666 mActiveTrack->releaseBuffer(&buffer);
3667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003669 sleepTime = 0;
3670 standbyTime = systemTime() + standbyDelay;
3671 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003672}
3673
3674void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3675{
3676 if (sleepTime == 0) {
3677 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3678 sleepTime = activeSleepTime;
3679 } else {
3680 sleepTime = idleSleepTime;
3681 }
3682 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3683 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3684 sleepTime = 0;
3685 }
3686}
3687
3688// getTrackName_l() must be called with ThreadBase::mLock held
3689int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3690 int sessionId)
3691{
3692 return 0;
3693}
3694
3695// deleteTrackName_l() must be called with ThreadBase::mLock held
3696void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3697{
3698}
3699
3700// checkForNewParameters_l() must be called with ThreadBase::mLock held
3701bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3702{
3703 bool reconfig = false;
3704
3705 while (!mNewParameters.isEmpty()) {
3706 status_t status = NO_ERROR;
3707 String8 keyValuePair = mNewParameters[0];
3708 AudioParameter param = AudioParameter(keyValuePair);
3709 int value;
3710
3711 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3712 // do not accept frame count changes if tracks are open as the track buffer
3713 // size depends on frame count and correct behavior would not be garantied
3714 // if frame count is changed after track creation
3715 if (!mTracks.isEmpty()) {
3716 status = INVALID_OPERATION;
3717 } else {
3718 reconfig = true;
3719 }
3720 }
3721 if (status == NO_ERROR) {
3722 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3723 keyValuePair.string());
3724 if (!mStandby && status == INVALID_OPERATION) {
3725 mOutput->stream->common.standby(&mOutput->stream->common);
3726 mStandby = true;
3727 mBytesWritten = 0;
3728 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3729 keyValuePair.string());
3730 }
3731 if (status == NO_ERROR && reconfig) {
3732 readOutputParameters();
3733 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3734 }
3735 }
3736
3737 mNewParameters.removeAt(0);
3738
3739 mParamStatus = status;
3740 mParamCond.signal();
3741 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3742 // already timed out waiting for the status and will never signal the condition.
3743 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3744 }
3745 return reconfig;
3746}
3747
3748uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3749{
3750 uint32_t time;
3751 if (audio_is_linear_pcm(mFormat)) {
3752 time = PlaybackThread::activeSleepTimeUs();
3753 } else {
3754 time = 10000;
3755 }
3756 return time;
3757}
3758
3759uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3760{
3761 uint32_t time;
3762 if (audio_is_linear_pcm(mFormat)) {
3763 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3764 } else {
3765 time = 10000;
3766 }
3767 return time;
3768}
3769
3770uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3771{
3772 uint32_t time;
3773 if (audio_is_linear_pcm(mFormat)) {
3774 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3775 } else {
3776 time = 10000;
3777 }
3778 return time;
3779}
3780
3781void AudioFlinger::DirectOutputThread::cacheParameters_l()
3782{
3783 PlaybackThread::cacheParameters_l();
3784
3785 // use shorter standby delay as on normal output to release
3786 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003787 if (audio_is_linear_pcm(mFormat)) {
3788 standbyDelay = microseconds(activeSleepTime*2);
3789 } else {
3790 standbyDelay = kOffloadStandbyDelayNs;
3791 }
Eric Laurent81784c32012-11-19 14:55:58 -08003792}
3793
3794// ----------------------------------------------------------------------------
3795
Eric Laurentbfb1b832013-01-07 09:53:42 -08003796AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003797 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003798 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003799 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003800 mWriteAckSequence(0),
3801 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802{
3803}
3804
3805AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3806{
3807}
3808
3809void AudioFlinger::AsyncCallbackThread::onFirstRef()
3810{
3811 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3812}
3813
3814bool AudioFlinger::AsyncCallbackThread::threadLoop()
3815{
3816 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003817 uint32_t writeAckSequence;
3818 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819
3820 {
3821 Mutex::Autolock _l(mLock);
3822 mWaitWorkCV.wait(mLock);
3823 if (exitPending()) {
3824 break;
3825 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003826 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3827 mWriteAckSequence, mDrainSequence);
3828 writeAckSequence = mWriteAckSequence;
3829 mWriteAckSequence &= ~1;
3830 drainSequence = mDrainSequence;
3831 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003832 }
3833 {
Eric Laurent4de95592013-09-26 15:28:21 -07003834 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3835 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003836 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003837 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003839 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003840 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003841 }
3842 }
3843 }
3844 }
3845 return false;
3846}
3847
3848void AudioFlinger::AsyncCallbackThread::exit()
3849{
3850 ALOGV("AsyncCallbackThread::exit");
3851 Mutex::Autolock _l(mLock);
3852 requestExit();
3853 mWaitWorkCV.broadcast();
3854}
3855
Eric Laurent3b4529e2013-09-05 18:09:19 -07003856void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857{
3858 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003859 // bit 0 is cleared
3860 mWriteAckSequence = sequence << 1;
3861}
3862
3863void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3864{
3865 Mutex::Autolock _l(mLock);
3866 // ignore unexpected callbacks
3867 if (mWriteAckSequence & 2) {
3868 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869 mWaitWorkCV.signal();
3870 }
3871}
3872
Eric Laurent3b4529e2013-09-05 18:09:19 -07003873void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874{
3875 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003876 // bit 0 is cleared
3877 mDrainSequence = sequence << 1;
3878}
3879
3880void AudioFlinger::AsyncCallbackThread::resetDraining()
3881{
3882 Mutex::Autolock _l(mLock);
3883 // ignore unexpected callbacks
3884 if (mDrainSequence & 2) {
3885 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 mWaitWorkCV.signal();
3887 }
3888}
3889
3890
3891// ----------------------------------------------------------------------------
3892AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3893 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3894 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3895 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003896 mFlushPending(false),
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003897 mPausedBytesRemaining(0),
3898 mPreviousTrack(NULL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900}
3901
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902void AudioFlinger::OffloadThread::threadLoop_exit()
3903{
3904 if (mFlushPending || mHwPaused) {
3905 // If a flush is pending or track was paused, just discard buffered data
3906 flushHw_l();
3907 } else {
3908 mMixerStatus = MIXER_DRAIN_ALL;
3909 threadLoop_drain();
3910 }
3911 mCallbackThread->exit();
3912 PlaybackThread::threadLoop_exit();
3913}
3914
3915AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3916 Vector< sp<Track> > *tracksToRemove
3917)
3918{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919 size_t count = mActiveTracks.size();
3920
3921 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003922 bool doHwPause = false;
3923 bool doHwResume = false;
3924
Eric Laurentede6c3b2013-09-19 14:37:46 -07003925 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3926
Eric Laurentbfb1b832013-01-07 09:53:42 -08003927 // find out which tracks need to be processed
3928 for (size_t i = 0; i < count; i++) {
3929 sp<Track> t = mActiveTracks[i].promote();
3930 // The track died recently
3931 if (t == 0) {
3932 continue;
3933 }
3934 Track* const track = t.get();
3935 audio_track_cblk_t* cblk = track->cblk();
3936 if (mPreviousTrack != NULL) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003937 if (t.get() != mPreviousTrack) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003938 // Flush any data still being written from last track
3939 mBytesRemaining = 0;
3940 if (mPausedBytesRemaining) {
3941 // Last track was paused so we also need to flush saved
3942 // mixbuffer state and invalidate track so that it will
3943 // re-submit that unwritten data when it is next resumed
3944 mPausedBytesRemaining = 0;
3945 // Invalidate is a bit drastic - would be more efficient
3946 // to have a flag to tell client that some of the
3947 // previously written data was lost
3948 mPreviousTrack->invalidate();
3949 }
3950 }
3951 }
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003952 mPreviousTrack = t.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003953 bool last = (i == (count - 1));
3954 if (track->isPausing()) {
3955 track->setPaused();
3956 if (last) {
3957 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003958 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959 mHwPaused = true;
3960 }
3961 // If we were part way through writing the mixbuffer to
3962 // the HAL we must save this until we resume
3963 // BUG - this will be wrong if a different track is made active,
3964 // in that case we want to discard the pending data in the
3965 // mixbuffer and tell the client to present it again when the
3966 // track is resumed
3967 mPausedWriteLength = mCurrentWriteLength;
3968 mPausedBytesRemaining = mBytesRemaining;
3969 mBytesRemaining = 0; // stop writing
3970 }
3971 tracksToRemove->add(track);
3972 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003973 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003974 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003975 if (track->mFillingUpStatus == Track::FS_FILLED) {
3976 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003977 // make sure processVolume_l() will apply new volume even if 0
3978 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003979 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003980 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003981 if (last) {
3982 if (mPausedBytesRemaining) {
3983 // Need to continue write that was interrupted
3984 mCurrentWriteLength = mPausedWriteLength;
3985 mBytesRemaining = mPausedBytesRemaining;
3986 mPausedBytesRemaining = 0;
3987 }
3988 if (mHwPaused) {
3989 doHwResume = true;
3990 mHwPaused = false;
3991 // threadLoop_mix() will handle the case that we need to
3992 // resume an interrupted write
3993 }
3994 // enable write to audio HAL
3995 sleepTime = 0;
3996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003997 }
3998 }
3999
4000 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004001 // reset retry count
4002 track->mRetryCount = kMaxTrackRetriesOffload;
4003 mActiveTrack = t;
4004 mixerStatus = MIXER_TRACKS_READY;
4005 }
4006 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004007 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004008 if (track->isStopping_1()) {
4009 // Hardware buffer can hold a large amount of audio so we must
4010 // wait for all current track's data to drain before we say
4011 // that the track is stopped.
4012 if (mBytesRemaining == 0) {
4013 // Only start draining when all data in mixbuffer
4014 // has been written
4015 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4016 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004017 // do not drain if no data was ever sent to HAL (mStandby == true)
4018 if (last && !mStandby) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07004019 sleepTime = 0;
4020 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004021 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07004022 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004023 if (mHwPaused) {
4024 // It is possible to move from PAUSED to STOPPING_1 without
4025 // a resume so we must ensure hardware is running
4026 mOutput->stream->resume(mOutput->stream);
4027 mHwPaused = false;
4028 }
4029 }
4030 }
4031 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004032 // Drain has completed or we are in standby, signal presentation complete
4033 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034 track->mState = TrackBase::STOPPED;
4035 size_t audioHALFrames =
4036 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4037 size_t framesWritten =
4038 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4039 track->presentationComplete(framesWritten, audioHALFrames);
4040 track->reset();
4041 tracksToRemove->add(track);
4042 }
4043 } else {
4044 // No buffers for this track. Give it a few chances to
4045 // fill a buffer, then remove it from active list.
4046 if (--(track->mRetryCount) <= 0) {
4047 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4048 track->name());
4049 tracksToRemove->add(track);
4050 } else if (last){
4051 mixerStatus = MIXER_TRACKS_ENABLED;
4052 }
4053 }
4054 }
4055 // compute volume for this track
4056 processVolume_l(track, last);
4057 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004058
Eric Laurentea0fade2013-10-04 16:23:48 -07004059 // make sure the pause/flush/resume sequence is executed in the right order.
4060 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4061 // before flush and then resume HW. This can happen in case of pause/flush/resume
4062 // if resume is received before pause is executed.
4063 if (doHwPause || (mFlushPending && !mHwPaused && (count != 0))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004064 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004065 if (!doHwPause) {
4066 doHwResume = true;
4067 }
Eric Laurent972a1732013-09-04 09:42:59 -07004068 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004069 if (mFlushPending) {
4070 flushHw_l();
4071 mFlushPending = false;
4072 }
Eric Laurent972a1732013-09-04 09:42:59 -07004073 if (doHwResume) {
4074 mOutput->stream->resume(mOutput->stream);
4075 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004076
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 // remove all the tracks that need to be...
4078 removeTracks_l(*tracksToRemove);
4079
4080 return mixerStatus;
4081}
4082
4083void AudioFlinger::OffloadThread::flushOutput_l()
4084{
4085 mFlushPending = true;
4086}
4087
4088// must be called with thread mutex locked
4089bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4090{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004091 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4092 mWriteAckSequence, mDrainSequence);
4093 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004094 return true;
4095 }
4096 return false;
4097}
4098
4099// must be called with thread mutex locked
4100bool AudioFlinger::OffloadThread::shouldStandby_l()
4101{
4102 bool TrackPaused = false;
4103
4104 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4105 // after a timeout and we will enter standby then.
4106 if (mTracks.size() > 0) {
4107 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4108 }
4109
4110 return !mStandby && !TrackPaused;
4111}
4112
4113
4114bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4115{
4116 Mutex::Autolock _l(mLock);
4117 return waitingAsyncCallback_l();
4118}
4119
4120void AudioFlinger::OffloadThread::flushHw_l()
4121{
4122 mOutput->stream->flush(mOutput->stream);
4123 // Flush anything still waiting in the mixbuffer
4124 mCurrentWriteLength = 0;
4125 mBytesRemaining = 0;
4126 mPausedWriteLength = 0;
4127 mPausedBytesRemaining = 0;
4128 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004129 // discard any pending drain or write ack by incrementing sequence
4130 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4131 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004133 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4134 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 }
4136}
4137
4138// ----------------------------------------------------------------------------
4139
Eric Laurent81784c32012-11-19 14:55:58 -08004140AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4141 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4142 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4143 DUPLICATING),
4144 mWaitTimeMs(UINT_MAX)
4145{
4146 addOutputTrack(mainThread);
4147}
4148
4149AudioFlinger::DuplicatingThread::~DuplicatingThread()
4150{
4151 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4152 mOutputTracks[i]->destroy();
4153 }
4154}
4155
4156void AudioFlinger::DuplicatingThread::threadLoop_mix()
4157{
4158 // mix buffers...
4159 if (outputsReady(outputTracks)) {
4160 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4161 } else {
4162 memset(mMixBuffer, 0, mixBufferSize);
4163 }
4164 sleepTime = 0;
4165 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004166 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004167 standbyTime = systemTime() + standbyDelay;
4168}
4169
4170void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4171{
4172 if (sleepTime == 0) {
4173 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4174 sleepTime = activeSleepTime;
4175 } else {
4176 sleepTime = idleSleepTime;
4177 }
4178 } else if (mBytesWritten != 0) {
4179 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4180 writeFrames = mNormalFrameCount;
4181 memset(mMixBuffer, 0, mixBufferSize);
4182 } else {
4183 // flush remaining overflow buffers in output tracks
4184 writeFrames = 0;
4185 }
4186 sleepTime = 0;
4187 }
4188}
4189
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004191{
4192 for (size_t i = 0; i < outputTracks.size(); i++) {
4193 outputTracks[i]->write(mMixBuffer, writeFrames);
4194 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004196}
4197
4198void AudioFlinger::DuplicatingThread::threadLoop_standby()
4199{
4200 // DuplicatingThread implements standby by stopping all tracks
4201 for (size_t i = 0; i < outputTracks.size(); i++) {
4202 outputTracks[i]->stop();
4203 }
4204}
4205
4206void AudioFlinger::DuplicatingThread::saveOutputTracks()
4207{
4208 outputTracks = mOutputTracks;
4209}
4210
4211void AudioFlinger::DuplicatingThread::clearOutputTracks()
4212{
4213 outputTracks.clear();
4214}
4215
4216void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4217{
4218 Mutex::Autolock _l(mLock);
4219 // FIXME explain this formula
4220 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4221 OutputTrack *outputTrack = new OutputTrack(thread,
4222 this,
4223 mSampleRate,
4224 mFormat,
4225 mChannelMask,
4226 frameCount);
4227 if (outputTrack->cblk() != NULL) {
4228 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4229 mOutputTracks.add(outputTrack);
4230 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4231 updateWaitTime_l();
4232 }
4233}
4234
4235void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4236{
4237 Mutex::Autolock _l(mLock);
4238 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4239 if (mOutputTracks[i]->thread() == thread) {
4240 mOutputTracks[i]->destroy();
4241 mOutputTracks.removeAt(i);
4242 updateWaitTime_l();
4243 return;
4244 }
4245 }
4246 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4247}
4248
4249// caller must hold mLock
4250void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4251{
4252 mWaitTimeMs = UINT_MAX;
4253 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4254 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4255 if (strong != 0) {
4256 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4257 if (waitTimeMs < mWaitTimeMs) {
4258 mWaitTimeMs = waitTimeMs;
4259 }
4260 }
4261 }
4262}
4263
4264
4265bool AudioFlinger::DuplicatingThread::outputsReady(
4266 const SortedVector< sp<OutputTrack> > &outputTracks)
4267{
4268 for (size_t i = 0; i < outputTracks.size(); i++) {
4269 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4270 if (thread == 0) {
4271 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4272 outputTracks[i].get());
4273 return false;
4274 }
4275 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4276 // see note at standby() declaration
4277 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4278 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4279 thread.get());
4280 return false;
4281 }
4282 }
4283 return true;
4284}
4285
4286uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4287{
4288 return (mWaitTimeMs * 1000) / 2;
4289}
4290
4291void AudioFlinger::DuplicatingThread::cacheParameters_l()
4292{
4293 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4294 updateWaitTime_l();
4295
4296 MixerThread::cacheParameters_l();
4297}
4298
4299// ----------------------------------------------------------------------------
4300// Record
4301// ----------------------------------------------------------------------------
4302
4303AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4304 AudioStreamIn *input,
4305 uint32_t sampleRate,
4306 audio_channel_mask_t channelMask,
4307 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004308 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004309 audio_devices_t inDevice
4310#ifdef TEE_SINK
4311 , const sp<NBAIO_Sink>& teeSink
4312#endif
4313 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004314 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004315 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten70949c42013-08-06 07:40:12 -07004316 // mRsmpInIndex set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004317 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004318 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004319 // mBytesRead is only meaningful while active, and so is cleared in start()
4320 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004321#ifdef TEE_SINK
4322 , mTeeSink(teeSink)
4323#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004324{
4325 snprintf(mName, kNameLength, "AudioIn_%X", id);
4326
4327 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004328 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004329}
4330
4331
4332AudioFlinger::RecordThread::~RecordThread()
4333{
4334 delete[] mRsmpInBuffer;
4335 delete mResampler;
4336 delete[] mRsmpOutBuffer;
4337}
4338
4339void AudioFlinger::RecordThread::onFirstRef()
4340{
4341 run(mName, PRIORITY_URGENT_AUDIO);
4342}
4343
Eric Laurent81784c32012-11-19 14:55:58 -08004344bool AudioFlinger::RecordThread::threadLoop()
4345{
4346 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004347
4348 nsecs_t lastWarning = 0;
4349
4350 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004351 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004352
4353 // used to verify we've read at least once before evaluating how many bytes were read
4354 bool readOnce = false;
4355
Glenn Kasten5edadd42013-08-14 16:30:49 -07004356 // used to request a deferred sleep, to be executed later while mutex is unlocked
4357 bool doSleep = false;
4358
Eric Laurent81784c32012-11-19 14:55:58 -08004359 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004360 for (;;) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004361 sp<RecordTrack> activeTrack;
Glenn Kastenb86432b2013-08-14 15:08:12 -07004362 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004363 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004364
Glenn Kasten5edadd42013-08-14 16:30:49 -07004365 // sleep with mutex unlocked
4366 if (doSleep) {
4367 doSleep = false;
4368 usleep(kRecordThreadSleepUs);
4369 }
4370
Eric Laurent81784c32012-11-19 14:55:58 -08004371 { // scope for mLock
4372 Mutex::Autolock _l(mLock);
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004373 if (exitPending()) {
4374 break;
4375 }
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004376 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004377 // return value 'reconfig' is currently unused
4378 bool reconfig = checkForNewParameters_l();
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004379 // make a stable copy of mActiveTrack
4380 activeTrack = mActiveTrack;
4381 if (activeTrack == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004382 standby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004383 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004384 releaseWakeLock_l();
4385 ALOGV("RecordThread: loop stopping");
4386 // go to sleep
4387 mWaitWorkCV.wait(mLock);
4388 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004389 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004390 continue;
4391 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004392
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004393 if (activeTrack->isTerminated()) {
4394 removeTrack_l(activeTrack);
Glenn Kastend9fc34f2013-08-14 13:55:45 -07004395 mActiveTrack.clear();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004396 continue;
4397 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004398
Glenn Kastenb86432b2013-08-14 15:08:12 -07004399 activeTrackState = activeTrack->mState;
4400 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004401 case TrackBase::PAUSING:
4402 standby();
4403 mActiveTrack.clear();
4404 mStartStopCond.broadcast();
4405 doSleep = true;
4406 continue;
4407
4408 case TrackBase::RESUMING:
4409 mStandby = false;
4410 if (mReqChannelCount != activeTrack->channelCount()) {
4411 mActiveTrack.clear();
4412 mStartStopCond.broadcast();
4413 continue;
4414 }
4415 if (readOnce) {
4416 mStartStopCond.broadcast();
4417 // record start succeeds only if first read from audio input succeeds
4418 if (mBytesRead < 0) {
4419 mActiveTrack.clear();
4420 continue;
4421 }
4422 activeTrack->mState = TrackBase::ACTIVE;
4423 }
4424 break;
4425
4426 case TrackBase::ACTIVE:
4427 break;
4428
4429 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004430 doSleep = true;
4431 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004432
4433 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004434 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004435 }
4436
Eric Laurent81784c32012-11-19 14:55:58 -08004437 lockEffectChains_l(effectChains);
4438 }
4439
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004440 // thread mutex is now unlocked, mActiveTrack unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004441 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4442
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004443 for (size_t i = 0; i < effectChains.size(); i ++) {
4444 // thread mutex is not locked, but effect chain is locked
4445 effectChains[i]->process_l();
4446 }
4447
4448 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004449 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004450 if (status == NO_ERROR) {
4451 readOnce = true;
4452 size_t framesOut = buffer.frameCount;
4453 if (mResampler == NULL) {
4454 // no resampling
4455 while (framesOut) {
4456 size_t framesIn = mFrameCount - mRsmpInIndex;
4457 if (framesIn > 0) {
4458 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4459 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004460 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004461 if (framesIn > framesOut) {
4462 framesIn = framesOut;
4463 }
4464 mRsmpInIndex += framesIn;
4465 framesOut -= framesIn;
4466 if (mChannelCount == mReqChannelCount) {
4467 memcpy(dst, src, framesIn * mFrameSize);
4468 } else {
4469 if (mChannelCount == 1) {
4470 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4471 (int16_t *)src, framesIn);
4472 } else {
4473 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4474 (int16_t *)src, framesIn);
4475 }
4476 }
4477 }
4478 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4479 void *readInto;
4480 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4481 readInto = buffer.raw;
4482 framesOut = 0;
4483 } else {
4484 readInto = mRsmpInBuffer;
4485 mRsmpInIndex = 0;
4486 }
4487 mBytesRead = mInput->stream->read(mInput->stream, readInto,
4488 mBufferSize);
4489 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004490 // TODO: verify that it's benign to use a stale track state
4491 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004492 {
4493 ALOGE("Error reading audio input");
4494 // Force input into standby so that it tries to
4495 // recover at next read attempt
4496 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004497 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004498 }
4499 mRsmpInIndex = mFrameCount;
4500 framesOut = 0;
4501 buffer.frameCount = 0;
4502 }
4503#ifdef TEE_SINK
4504 else if (mTeeSink != 0) {
4505 (void) mTeeSink->write(readInto,
4506 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4507 }
4508#endif
4509 }
4510 }
4511 } else {
4512 // resampling
4513
4514 // resampler accumulates, but we only have one source track
4515 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4516 // alter output frame count as if we were expecting stereo samples
4517 if (mChannelCount == 1 && mReqChannelCount == 1) {
4518 framesOut >>= 1;
4519 }
4520 mResampler->resample(mRsmpOutBuffer, framesOut,
4521 this /* AudioBufferProvider* */);
4522 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004523 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004524 if (mChannelCount == 2 && mReqChannelCount == 1) {
4525 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4526 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4527 // the resampler always outputs stereo samples:
4528 // do post stereo to mono conversion
4529 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4530 framesOut);
4531 } else {
4532 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4533 }
4534 // now done with mRsmpOutBuffer
4535
4536 }
4537 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004538 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004539 } else {
4540 if (mFramestoDrop > 0) {
4541 mFramestoDrop -= buffer.frameCount;
4542 if (mFramestoDrop <= 0) {
4543 clearSyncStartEvent();
4544 }
4545 } else {
4546 mFramestoDrop += buffer.frameCount;
4547 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4548 mSyncStartEvent->isCancelled()) {
4549 ALOGW("Synced record %s, session %d, trigger session %d",
4550 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004551 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004552 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4553 clearSyncStartEvent();
4554 }
4555 }
4556 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004557 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004558 }
4559 // client isn't retrieving buffers fast enough
4560 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004561 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004562 nsecs_t now = systemTime();
4563 if ((now - lastWarning) > kWarningThrottleNs) {
4564 ALOGW("RecordThread: buffer overflow");
4565 lastWarning = now;
4566 }
4567 }
4568 // Release the processor for a while before asking for a new buffer.
4569 // This will give the application more chance to read from the buffer and
4570 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004571 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004572 }
4573
Eric Laurent81784c32012-11-19 14:55:58 -08004574 // enable changes in effect chain
4575 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004576 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004577 }
4578
4579 standby();
4580
4581 {
4582 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004583 for (size_t i = 0; i < mTracks.size(); i++) {
4584 sp<RecordTrack> track = mTracks[i];
4585 track->invalidate();
4586 }
Eric Laurent81784c32012-11-19 14:55:58 -08004587 mActiveTrack.clear();
4588 mStartStopCond.broadcast();
4589 }
4590
4591 releaseWakeLock();
4592
4593 ALOGV("RecordThread %p exiting", this);
4594 return false;
4595}
4596
4597void AudioFlinger::RecordThread::standby()
4598{
4599 if (!mStandby) {
4600 inputStandBy();
4601 mStandby = true;
4602 }
4603}
4604
4605void AudioFlinger::RecordThread::inputStandBy()
4606{
4607 mInput->stream->common.standby(&mInput->stream->common);
4608}
4609
Glenn Kastene198c362013-08-13 09:13:36 -07004610sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004611 const sp<AudioFlinger::Client>& client,
4612 uint32_t sampleRate,
4613 audio_format_t format,
4614 audio_channel_mask_t channelMask,
4615 size_t frameCount,
4616 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004617 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004618 pid_t tid,
4619 status_t *status)
4620{
4621 sp<RecordTrack> track;
4622 status_t lStatus;
4623
4624 lStatus = initCheck();
4625 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004626 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004627 goto Exit;
4628 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004629 // client expresses a preference for FAST, but we get the final say
4630 if (*flags & IAudioFlinger::TRACK_FAST) {
4631 if (
4632 // use case: callback handler and frame count is default or at least as large as HAL
4633 (
4634 (tid != -1) &&
4635 ((frameCount == 0) ||
4636 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4637 ) &&
4638 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4639 // mono or stereo
4640 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4641 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4642 // hardware sample rate
4643 (sampleRate == mSampleRate) &&
4644 // record thread has an associated fast recorder
4645 hasFastRecorder()
4646 // FIXME test that RecordThread for this fast track has a capable output HAL
4647 // FIXME add a permission test also?
4648 ) {
4649 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4650 if (frameCount == 0) {
4651 frameCount = mFrameCount * kFastTrackMultiplier;
4652 }
4653 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4654 frameCount, mFrameCount);
4655 } else {
4656 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4657 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4658 "hasFastRecorder=%d tid=%d",
4659 frameCount, mFrameCount, format,
4660 audio_is_linear_pcm(format),
4661 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4662 *flags &= ~IAudioFlinger::TRACK_FAST;
4663 // For compatibility with AudioRecord calculation, buffer depth is forced
4664 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4665 // This is probably too conservative, but legacy application code may depend on it.
4666 // If you change this calculation, also review the start threshold which is related.
4667 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4668 size_t mNormalFrameCount = 2048; // FIXME
4669 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4670 if (minBufCount < 2) {
4671 minBufCount = 2;
4672 }
4673 size_t minFrameCount = mNormalFrameCount * minBufCount;
4674 if (frameCount < minFrameCount) {
4675 frameCount = minFrameCount;
4676 }
4677 }
4678 }
4679
Eric Laurent81784c32012-11-19 14:55:58 -08004680 // FIXME use flags and tid similar to createTrack_l()
4681
4682 { // scope for mLock
4683 Mutex::Autolock _l(mLock);
4684
4685 track = new RecordTrack(this, client, sampleRate,
4686 format, channelMask, frameCount, sessionId);
4687
Glenn Kasten03003332013-08-06 15:40:54 -07004688 lStatus = track->initCheck();
4689 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004690 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Glenn Kasten03003332013-08-06 15:40:54 -07004691 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004692 goto Exit;
4693 }
4694 mTracks.add(track);
4695
4696 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4697 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4698 mAudioFlinger->btNrecIsOff();
4699 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4700 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004701
4702 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4703 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4704 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4705 // so ask activity manager to do this on our behalf
4706 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4707 }
Eric Laurent81784c32012-11-19 14:55:58 -08004708 }
4709 lStatus = NO_ERROR;
4710
4711Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004712 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004713 return track;
4714}
4715
4716status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4717 AudioSystem::sync_event_t event,
4718 int triggerSession)
4719{
4720 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4721 sp<ThreadBase> strongMe = this;
4722 status_t status = NO_ERROR;
4723
4724 if (event == AudioSystem::SYNC_EVENT_NONE) {
4725 clearSyncStartEvent();
4726 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4727 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4728 triggerSession,
4729 recordTrack->sessionId(),
4730 syncStartEventCallback,
4731 this);
4732 // Sync event can be cancelled by the trigger session if the track is not in a
4733 // compatible state in which case we start record immediately
4734 if (mSyncStartEvent->isCancelled()) {
4735 clearSyncStartEvent();
4736 } else {
4737 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4738 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4739 }
4740 }
4741
4742 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004743 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004744 AutoMutex lock(mLock);
4745 if (mActiveTrack != 0) {
4746 if (recordTrack != mActiveTrack.get()) {
4747 status = -EBUSY;
4748 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4749 mActiveTrack->mState = TrackBase::ACTIVE;
4750 }
4751 return status;
4752 }
4753
Glenn Kasten47c20702013-08-13 15:37:35 -07004754 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004755 recordTrack->mState = TrackBase::IDLE;
4756 mActiveTrack = recordTrack;
4757 mLock.unlock();
4758 status_t status = AudioSystem::startInput(mId);
4759 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004760 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004761 if (status != NO_ERROR) {
4762 mActiveTrack.clear();
4763 clearSyncStartEvent();
4764 return status;
4765 }
4766 mRsmpInIndex = mFrameCount;
4767 mBytesRead = 0;
4768 if (mResampler != NULL) {
4769 mResampler->reset();
4770 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004771 // FIXME hijacking a playback track state name which was intended for start after pause;
4772 // here 'STARTING_2' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004773 mActiveTrack->mState = TrackBase::RESUMING;
4774 // signal thread to start
4775 ALOGV("Signal record thread");
4776 mWaitWorkCV.broadcast();
4777 // do not wait for mStartStopCond if exiting
4778 if (exitPending()) {
4779 mActiveTrack.clear();
4780 status = INVALID_OPERATION;
4781 goto startError;
4782 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004783 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004784 mStartStopCond.wait(mLock);
4785 if (mActiveTrack == 0) {
4786 ALOGV("Record failed to start");
4787 status = BAD_VALUE;
4788 goto startError;
4789 }
4790 ALOGV("Record started OK");
4791 return status;
4792 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004793
Eric Laurent81784c32012-11-19 14:55:58 -08004794startError:
4795 AudioSystem::stopInput(mId);
4796 clearSyncStartEvent();
4797 return status;
4798}
4799
4800void AudioFlinger::RecordThread::clearSyncStartEvent()
4801{
4802 if (mSyncStartEvent != 0) {
4803 mSyncStartEvent->cancel();
4804 }
4805 mSyncStartEvent.clear();
4806 mFramestoDrop = 0;
4807}
4808
4809void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4810{
4811 sp<SyncEvent> strongEvent = event.promote();
4812
4813 if (strongEvent != 0) {
4814 RecordThread *me = (RecordThread *)strongEvent->cookie();
4815 me->handleSyncStartEvent(strongEvent);
4816 }
4817}
4818
4819void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4820{
4821 if (event == mSyncStartEvent) {
4822 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4823 // from audio HAL
4824 mFramestoDrop = mFrameCount * 2;
4825 }
4826}
4827
Glenn Kastena8356f62013-07-25 14:37:52 -07004828bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004829 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004830 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004831 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4832 return false;
4833 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004834 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08004835 recordTrack->mState = TrackBase::PAUSING;
4836 // do not wait for mStartStopCond if exiting
4837 if (exitPending()) {
4838 return true;
4839 }
Glenn Kasten47c20702013-08-13 15:37:35 -07004840 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08004841 mStartStopCond.wait(mLock);
4842 // if we have been restarted, recordTrack == mActiveTrack.get() here
4843 if (exitPending() || recordTrack != mActiveTrack.get()) {
4844 ALOGV("Record stopped OK");
4845 return true;
4846 }
4847 return false;
4848}
4849
4850bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4851{
4852 return false;
4853}
4854
4855status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4856{
4857#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4858 if (!isValidSyncEvent(event)) {
4859 return BAD_VALUE;
4860 }
4861
4862 int eventSession = event->triggerSession();
4863 status_t ret = NAME_NOT_FOUND;
4864
4865 Mutex::Autolock _l(mLock);
4866
4867 for (size_t i = 0; i < mTracks.size(); i++) {
4868 sp<RecordTrack> track = mTracks[i];
4869 if (eventSession == track->sessionId()) {
4870 (void) track->setSyncEvent(event);
4871 ret = NO_ERROR;
4872 }
4873 }
4874 return ret;
4875#else
4876 return BAD_VALUE;
4877#endif
4878}
4879
4880// destroyTrack_l() must be called with ThreadBase::mLock held
4881void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4882{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004883 track->terminate();
4884 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004885 // active tracks are removed by threadLoop()
4886 if (mActiveTrack != track) {
4887 removeTrack_l(track);
4888 }
4889}
4890
4891void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4892{
4893 mTracks.remove(track);
4894 // need anything related to effects here?
4895}
4896
4897void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4898{
4899 dumpInternals(fd, args);
4900 dumpTracks(fd, args);
4901 dumpEffectChains(fd, args);
4902}
4903
4904void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4905{
4906 const size_t SIZE = 256;
4907 char buffer[SIZE];
4908 String8 result;
4909
4910 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4911 result.append(buffer);
4912
4913 if (mActiveTrack != 0) {
4914 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4915 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004916 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004917 result.append(buffer);
4918 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4919 result.append(buffer);
4920 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4921 result.append(buffer);
4922 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4923 result.append(buffer);
4924 } else {
4925 result.append("No active record client\n");
4926 }
4927
4928 write(fd, result.string(), result.size());
4929
4930 dumpBase(fd, args);
4931}
4932
4933void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4934{
4935 const size_t SIZE = 256;
4936 char buffer[SIZE];
4937 String8 result;
4938
4939 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4940 result.append(buffer);
4941 RecordTrack::appendDumpHeader(result);
4942 for (size_t i = 0; i < mTracks.size(); ++i) {
4943 sp<RecordTrack> track = mTracks[i];
4944 if (track != 0) {
4945 track->dump(buffer, SIZE);
4946 result.append(buffer);
4947 }
4948 }
4949
4950 if (mActiveTrack != 0) {
4951 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4952 result.append(buffer);
4953 RecordTrack::appendDumpHeader(result);
4954 mActiveTrack->dump(buffer, SIZE);
4955 result.append(buffer);
4956
4957 }
4958 write(fd, result.string(), result.size());
4959}
4960
4961// AudioBufferProvider interface
4962status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4963{
4964 size_t framesReq = buffer->frameCount;
4965 size_t framesReady = mFrameCount - mRsmpInIndex;
4966 int channelCount;
4967
4968 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004969 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004970 if (mBytesRead <= 0) {
4971 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4972 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4973 // Force input into standby so that it tries to
4974 // recover at next read attempt
4975 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004976 // FIXME an awkward place to sleep, consider using doSleep when this is pulled up
Eric Laurent81784c32012-11-19 14:55:58 -08004977 usleep(kRecordThreadSleepUs);
4978 }
4979 buffer->raw = NULL;
4980 buffer->frameCount = 0;
4981 return NOT_ENOUGH_DATA;
4982 }
4983 mRsmpInIndex = 0;
4984 framesReady = mFrameCount;
4985 }
4986
4987 if (framesReq > framesReady) {
4988 framesReq = framesReady;
4989 }
4990
4991 if (mChannelCount == 1 && mReqChannelCount == 2) {
4992 channelCount = 1;
4993 } else {
4994 channelCount = 2;
4995 }
4996 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4997 buffer->frameCount = framesReq;
4998 return NO_ERROR;
4999}
5000
5001// AudioBufferProvider interface
5002void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5003{
5004 mRsmpInIndex += buffer->frameCount;
5005 buffer->frameCount = 0;
5006}
5007
5008bool AudioFlinger::RecordThread::checkForNewParameters_l()
5009{
5010 bool reconfig = false;
5011
5012 while (!mNewParameters.isEmpty()) {
5013 status_t status = NO_ERROR;
5014 String8 keyValuePair = mNewParameters[0];
5015 AudioParameter param = AudioParameter(keyValuePair);
5016 int value;
5017 audio_format_t reqFormat = mFormat;
5018 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005019 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005020
5021 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5022 reqSamplingRate = value;
5023 reconfig = true;
5024 }
5025 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005026 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5027 status = BAD_VALUE;
5028 } else {
5029 reqFormat = (audio_format_t) value;
5030 reconfig = true;
5031 }
Eric Laurent81784c32012-11-19 14:55:58 -08005032 }
5033 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005034 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5035 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5036 status = BAD_VALUE;
5037 } else {
5038 reqChannelMask = mask;
5039 reconfig = true;
5040 }
Eric Laurent81784c32012-11-19 14:55:58 -08005041 }
5042 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5043 // do not accept frame count changes if tracks are open as the track buffer
5044 // size depends on frame count and correct behavior would not be guaranteed
5045 // if frame count is changed after track creation
5046 if (mActiveTrack != 0) {
5047 status = INVALID_OPERATION;
5048 } else {
5049 reconfig = true;
5050 }
5051 }
5052 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5053 // forward device change to effects that have requested to be
5054 // aware of attached audio device.
5055 for (size_t i = 0; i < mEffectChains.size(); i++) {
5056 mEffectChains[i]->setDevice_l(value);
5057 }
5058
5059 // store input device and output device but do not forward output device to audio HAL.
5060 // Note that status is ignored by the caller for output device
5061 // (see AudioFlinger::setParameters()
5062 if (audio_is_output_devices(value)) {
5063 mOutDevice = value;
5064 status = BAD_VALUE;
5065 } else {
5066 mInDevice = value;
5067 // disable AEC and NS if the device is a BT SCO headset supporting those
5068 // pre processings
5069 if (mTracks.size() > 0) {
5070 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5071 mAudioFlinger->btNrecIsOff();
5072 for (size_t i = 0; i < mTracks.size(); i++) {
5073 sp<RecordTrack> track = mTracks[i];
5074 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5075 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5076 }
5077 }
5078 }
5079 }
5080 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5081 mAudioSource != (audio_source_t)value) {
5082 // forward device change to effects that have requested to be
5083 // aware of attached audio device.
5084 for (size_t i = 0; i < mEffectChains.size(); i++) {
5085 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5086 }
5087 mAudioSource = (audio_source_t)value;
5088 }
Glenn Kastene198c362013-08-13 09:13:36 -07005089
Eric Laurent81784c32012-11-19 14:55:58 -08005090 if (status == NO_ERROR) {
5091 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5092 keyValuePair.string());
5093 if (status == INVALID_OPERATION) {
5094 inputStandBy();
5095 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5096 keyValuePair.string());
5097 }
5098 if (reconfig) {
5099 if (status == BAD_VALUE &&
5100 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5101 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005102 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005103 <= (2 * reqSamplingRate)) &&
5104 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5105 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005106 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5107 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005108 status = NO_ERROR;
5109 }
5110 if (status == NO_ERROR) {
5111 readInputParameters();
5112 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5113 }
5114 }
5115 }
5116
5117 mNewParameters.removeAt(0);
5118
5119 mParamStatus = status;
5120 mParamCond.signal();
5121 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5122 // already timed out waiting for the status and will never signal the condition.
5123 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5124 }
5125 return reconfig;
5126}
5127
5128String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5129{
Eric Laurent81784c32012-11-19 14:55:58 -08005130 Mutex::Autolock _l(mLock);
5131 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005132 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
5134
Glenn Kastend8ea6992013-07-16 14:17:15 -07005135 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5136 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005137 free(s);
5138 return out_s8;
5139}
5140
5141void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5142 AudioSystem::OutputDescriptor desc;
5143 void *param2 = NULL;
5144
5145 switch (event) {
5146 case AudioSystem::INPUT_OPENED:
5147 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005148 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005149 desc.samplingRate = mSampleRate;
5150 desc.format = mFormat;
5151 desc.frameCount = mFrameCount;
5152 desc.latency = 0;
5153 param2 = &desc;
5154 break;
5155
5156 case AudioSystem::INPUT_CLOSED:
5157 default:
5158 break;
5159 }
5160 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5161}
5162
5163void AudioFlinger::RecordThread::readInputParameters()
5164{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005165 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005166 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005167 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005168 mRsmpOutBuffer = NULL;
5169 delete mResampler;
5170 mResampler = NULL;
5171
5172 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5173 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005174 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005176 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5177 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005180 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5181 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005182 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5183
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005184 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Eric Laurent81784c32012-11-19 14:55:58 -08005185 int channelCount;
5186 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5187 // stereo to mono post process as the resampler always outputs stereo.
5188 if (mChannelCount == 1 && mReqChannelCount == 2) {
5189 channelCount = 1;
5190 } else {
5191 channelCount = 2;
5192 }
5193 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5194 mResampler->setSampleRate(mSampleRate);
5195 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005196 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005197
5198 // optmization: if mono to mono, alter input frame count as if we were inputing
5199 // stereo samples
5200 if (mChannelCount == 1 && mReqChannelCount == 1) {
5201 mFrameCount >>= 1;
5202 }
5203
5204 }
5205 mRsmpInIndex = mFrameCount;
5206}
5207
5208unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5209{
5210 Mutex::Autolock _l(mLock);
5211 if (initCheck() != NO_ERROR) {
5212 return 0;
5213 }
5214
5215 return mInput->stream->get_input_frames_lost(mInput->stream);
5216}
5217
5218uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5219{
5220 Mutex::Autolock _l(mLock);
5221 uint32_t result = 0;
5222 if (getEffectChain_l(sessionId) != 0) {
5223 result = EFFECT_SESSION;
5224 }
5225
5226 for (size_t i = 0; i < mTracks.size(); ++i) {
5227 if (sessionId == mTracks[i]->sessionId()) {
5228 result |= TRACK_SESSION;
5229 break;
5230 }
5231 }
5232
5233 return result;
5234}
5235
5236KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5237{
5238 KeyedVector<int, bool> ids;
5239 Mutex::Autolock _l(mLock);
5240 for (size_t j = 0; j < mTracks.size(); ++j) {
5241 sp<RecordThread::RecordTrack> track = mTracks[j];
5242 int sessionId = track->sessionId();
5243 if (ids.indexOfKey(sessionId) < 0) {
5244 ids.add(sessionId, true);
5245 }
5246 }
5247 return ids;
5248}
5249
5250AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5251{
5252 Mutex::Autolock _l(mLock);
5253 AudioStreamIn *input = mInput;
5254 mInput = NULL;
5255 return input;
5256}
5257
5258// this method must always be called either with ThreadBase mLock held or inside the thread loop
5259audio_stream_t* AudioFlinger::RecordThread::stream() const
5260{
5261 if (mInput == NULL) {
5262 return NULL;
5263 }
5264 return &mInput->stream->common;
5265}
5266
5267status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5268{
5269 // only one chain per input thread
5270 if (mEffectChains.size() != 0) {
5271 return INVALID_OPERATION;
5272 }
5273 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5274
5275 chain->setInBuffer(NULL);
5276 chain->setOutBuffer(NULL);
5277
5278 checkSuspendOnAddEffectChain_l(chain);
5279
5280 mEffectChains.add(chain);
5281
5282 return NO_ERROR;
5283}
5284
5285size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5286{
5287 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5288 ALOGW_IF(mEffectChains.size() != 1,
5289 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5290 chain.get(), mEffectChains.size(), this);
5291 if (mEffectChains.size() == 1) {
5292 mEffectChains.removeAt(0);
5293 }
5294 return 0;
5295}
5296
5297}; // namespace android