blob: 7559d4c8ec3cd275da2d63f6d54e8a221b9b2dd1 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
Alok Kediya601e9b52013-09-27 11:55:10 +05302** Copyright (c) 2013, The Linux Foundation. All rights reserved.
3** Not a Contribution.
Eric Laurent81784c32012-11-19 14:55:58 -08004** Copyright 2012, The Android Open Source Project
5**
6** Licensed under the Apache License, Version 2.0 (the "License");
7** you may not use this file except in compliance with the License.
8** You may obtain a copy of the License at
9**
10** http://www.apache.org/licenses/LICENSE-2.0
11**
12** Unless required by applicable law or agreed to in writing, software
13** distributed under the License is distributed on an "AS IS" BASIS,
14** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15** See the License for the specific language governing permissions and
16** limitations under the License.
17*/
18
19
20#define LOG_TAG "AudioFlinger"
21//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080022#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080023
Glenn Kasten153b9fe2013-07-15 11:23:36 -070024#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <math.h>
26#include <fcntl.h>
27#include <sys/stat.h>
28#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070029#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
38
39// NBAIO implementations
40#include <media/nbaio/AudioStreamOutSink.h>
41#include <media/nbaio/MonoPipe.h>
42#include <media/nbaio/MonoPipeReader.h>
43#include <media/nbaio/Pipe.h>
44#include <media/nbaio/PipeReader.h>
45#include <media/nbaio/SourceAudioBufferProvider.h>
46
47#include <powermanager/PowerManager.h>
48
49#include <common_time/cc_helper.h>
50#include <common_time/local_clock.h>
51
52#include "AudioFlinger.h"
53#include "AudioMixer.h"
54#include "FastMixer.h"
55#include "ServiceUtilities.h"
56#include "SchedulingPolicyService.h"
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62
Eric Laurent81784c32012-11-19 14:55:58 -080063#ifdef DEBUG_CPU_USAGE
64#include <cpustats/CentralTendencyStatistics.h>
65#include <cpustats/ThreadCpuUsage.h>
66#endif
67
Alok Kediya601e9b52013-09-27 11:55:10 +053068#ifdef SRS_PROCESSING
69#include "srs_processing.h"
70#include "postpro_patch_ics.h"
71#endif
72
Eric Laurent81784c32012-11-19 14:55:58 -080073// ----------------------------------------------------------------------------
74
75// Note: the following macro is used for extremely verbose logging message. In
76// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
77// 0; but one side effect of this is to turn all LOGV's as well. Some messages
78// are so verbose that we want to suppress them even when we have ALOG_ASSERT
79// turned on. Do not uncomment the #def below unless you really know what you
80// are doing and want to see all of the extremely verbose messages.
81//#define VERY_VERY_VERBOSE_LOGGING
82#ifdef VERY_VERY_VERBOSE_LOGGING
83#define ALOGVV ALOGV
84#else
85#define ALOGVV(a...) do { } while(0)
86#endif
87
Ethan Chen8d420ed2013-11-14 00:40:54 -080088#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +053089#define DIRECT_TRACK_EOS 1
90#define DIRECT_TRACK_HW_FAIL 6
91static const char lockName[] = "DirectTrack";
Ethan Chen8d420ed2013-11-14 00:40:54 -080092#endif
Eric Laurent81784c32012-11-19 14:55:58 -080093namespace android {
94
95// retry counts for buffer fill timeout
96// 50 * ~20msecs = 1 second
97static const int8_t kMaxTrackRetries = 50;
98static const int8_t kMaxTrackStartupRetries = 50;
99// allow less retry attempts on direct output thread.
100// direct outputs can be a scarce resource in audio hardware and should
101// be released as quickly as possible.
102static const int8_t kMaxTrackRetriesDirect = 2;
103
104// don't warn about blocked writes or record buffer overflows more often than this
105static const nsecs_t kWarningThrottleNs = seconds(5);
106
107// RecordThread loop sleep time upon application overrun or audio HAL read error
108static const int kRecordThreadSleepUs = 5000;
109
110// maximum time to wait for setParameters to complete
111static const nsecs_t kSetParametersTimeoutNs = seconds(2);
112
113// minimum sleep time for the mixer thread loop when tracks are active but in underrun
114static const uint32_t kMinThreadSleepTimeUs = 5000;
115// maximum divider applied to the active sleep time in the mixer thread loop
116static const uint32_t kMaxThreadSleepTimeShift = 2;
117
118// minimum normal mix buffer size, expressed in milliseconds rather than frames
119static const uint32_t kMinNormalMixBufferSizeMs = 20;
120// maximum normal mix buffer size
121static const uint32_t kMaxNormalMixBufferSizeMs = 24;
122
Eric Laurent972a1732013-09-04 09:42:59 -0700123// Offloaded output thread standby delay: allows track transition without going to standby
124static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126// Whether to use fast mixer
127static const enum {
128 FastMixer_Never, // never initialize or use: for debugging only
129 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
130 // normal mixer multiplier is 1
131 FastMixer_Static, // initialize if needed, then use all the time if initialized,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
134 // multiplier is calculated based on min & max normal mixer buffer size
135 // FIXME for FastMixer_Dynamic:
136 // Supporting this option will require fixing HALs that can't handle large writes.
137 // For example, one HAL implementation returns an error from a large write,
138 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
139 // We could either fix the HAL implementations, or provide a wrapper that breaks
140 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
141} kUseFastMixer = FastMixer_Static;
142
143// Priorities for requestPriority
144static const int kPriorityAudioApp = 2;
145static const int kPriorityFastMixer = 3;
146
147// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
148// for the track. The client then sub-divides this into smaller buffers for its use.
149// Currently the client uses double-buffering by default, but doesn't tell us about that.
150// So for now we just assume that client is double-buffered.
151// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
152// N-buffering, so AudioFlinger could allocate the right amount of memory.
153// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800154static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// ----------------------------------------------------------------------------
157
158#ifdef ADD_BATTERY_DATA
159// To collect the amplifier usage
160static void addBatteryData(uint32_t params) {
161 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
162 if (service == NULL) {
163 // it already logged
164 return;
165 }
166
167 service->addBatteryData(params);
168}
169#endif
170
171
172// ----------------------------------------------------------------------------
173// CPU Stats
174// ----------------------------------------------------------------------------
175
176class CpuStats {
177public:
178 CpuStats();
179 void sample(const String8 &title);
180#ifdef DEBUG_CPU_USAGE
181private:
182 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
183 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
184
185 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
186
187 int mCpuNum; // thread's current CPU number
188 int mCpukHz; // frequency of thread's current CPU in kHz
189#endif
190};
191
192CpuStats::CpuStats()
193#ifdef DEBUG_CPU_USAGE
194 : mCpuNum(-1), mCpukHz(-1)
195#endif
196{
197}
198
199void CpuStats::sample(const String8 &title) {
200#ifdef DEBUG_CPU_USAGE
201 // get current thread's delta CPU time in wall clock ns
202 double wcNs;
203 bool valid = mCpuUsage.sampleAndEnable(wcNs);
204
205 // record sample for wall clock statistics
206 if (valid) {
207 mWcStats.sample(wcNs);
208 }
209
210 // get the current CPU number
211 int cpuNum = sched_getcpu();
212
213 // get the current CPU frequency in kHz
214 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
215
216 // check if either CPU number or frequency changed
217 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
218 mCpuNum = cpuNum;
219 mCpukHz = cpukHz;
220 // ignore sample for purposes of cycles
221 valid = false;
222 }
223
224 // if no change in CPU number or frequency, then record sample for cycle statistics
225 if (valid && mCpukHz > 0) {
226 double cycles = wcNs * cpukHz * 0.000001;
227 mHzStats.sample(cycles);
228 }
229
230 unsigned n = mWcStats.n();
231 // mCpuUsage.elapsed() is expensive, so don't call it every loop
232 if ((n & 127) == 1) {
233 long long elapsed = mCpuUsage.elapsed();
234 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
235 double perLoop = elapsed / (double) n;
236 double perLoop100 = perLoop * 0.01;
237 double perLoop1k = perLoop * 0.001;
238 double mean = mWcStats.mean();
239 double stddev = mWcStats.stddev();
240 double minimum = mWcStats.minimum();
241 double maximum = mWcStats.maximum();
242 double meanCycles = mHzStats.mean();
243 double stddevCycles = mHzStats.stddev();
244 double minCycles = mHzStats.minimum();
245 double maxCycles = mHzStats.maximum();
246 mCpuUsage.resetElapsed();
247 mWcStats.reset();
248 mHzStats.reset();
249 ALOGD("CPU usage for %s over past %.1f secs\n"
250 " (%u mixer loops at %.1f mean ms per loop):\n"
251 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
252 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
253 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
254 title.string(),
255 elapsed * .000000001, n, perLoop * .000001,
256 mean * .001,
257 stddev * .001,
258 minimum * .001,
259 maximum * .001,
260 mean / perLoop100,
261 stddev / perLoop100,
262 minimum / perLoop100,
263 maximum / perLoop100,
264 meanCycles / perLoop1k,
265 stddevCycles / perLoop1k,
266 minCycles / perLoop1k,
267 maxCycles / perLoop1k);
268
269 }
270 }
271#endif
272};
273
274// ----------------------------------------------------------------------------
275// ThreadBase
276// ----------------------------------------------------------------------------
277
278AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
279 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
280 : Thread(false /*canCallJava*/),
281 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700282 mAudioFlinger(audioFlinger),
283 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, and mFormat are
284 // set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800285 mParamStatus(NO_ERROR),
286 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
287 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
288 // mName will be set by concrete (non-virtual) subclass
289 mDeathRecipient(new PMDeathRecipient(this))
290{
291}
292
293AudioFlinger::ThreadBase::~ThreadBase()
294{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700295 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
296 for (size_t i = 0; i < mConfigEvents.size(); i++) {
297 delete mConfigEvents[i];
298 }
299 mConfigEvents.clear();
300
Eric Laurent81784c32012-11-19 14:55:58 -0800301 mParamCond.broadcast();
302 // do not lock the mutex in destructor
303 releaseWakeLock_l();
304 if (mPowerManager != 0) {
305 sp<IBinder> binder = mPowerManager->asBinder();
306 binder->unlinkToDeath(mDeathRecipient);
307 }
308}
309
310void 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
Ethan Chen8d420ed2013-11-14 00:40:54 -0800354#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530355void AudioFlinger::ThreadBase::effectConfigChanged() {
356 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
357 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
358}
Ethan Chen8d420ed2013-11-14 00:40:54 -0800359#endif
Alok Kediya601e9b52013-09-27 11:55:10 +0530360
Eric Laurent81784c32012-11-19 14:55:58 -0800361void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
362{
363 Mutex::Autolock _l(mLock);
364 sendIoConfigEvent_l(event, param);
365}
366
367// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
368void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
369{
370 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
371 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
372 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
373 param);
374 mWaitWorkCV.signal();
375}
376
377// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
378void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
379{
380 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
381 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
382 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
383 mConfigEvents.size(), pid, tid, prio);
384 mWaitWorkCV.signal();
385}
386
387void AudioFlinger::ThreadBase::processConfigEvents()
388{
389 mLock.lock();
390 while (!mConfigEvents.isEmpty()) {
391 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
392 ConfigEvent *event = mConfigEvents[0];
393 mConfigEvents.removeAt(0);
394 // release mLock before locking AudioFlinger mLock: lock order is always
395 // AudioFlinger then ThreadBase to avoid cross deadlock
396 mLock.unlock();
397 switch(event->type()) {
398 case CFG_EVENT_PRIO: {
399 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700400 // FIXME Need to understand why this has be done asynchronously
401 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
402 true /*asynchronous*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800403 if (err != 0) {
404 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
405 "error %d",
406 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
407 }
408 } break;
409 case CFG_EVENT_IO: {
410 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
411 mAudioFlinger->mLock.lock();
412 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
413 mAudioFlinger->mLock.unlock();
414 } break;
415 default:
416 ALOGE("processConfigEvents() unknown event type %d", event->type());
417 break;
418 }
419 delete event;
420 mLock.lock();
421 }
422 mLock.unlock();
423}
424
425void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
426{
427 const size_t SIZE = 256;
428 char buffer[SIZE];
429 String8 result;
430
431 bool locked = AudioFlinger::dumpTryLock(mLock);
432 if (!locked) {
433 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
434 write(fd, buffer, strlen(buffer));
435 }
436
437 snprintf(buffer, SIZE, "io handle: %d\n", mId);
438 result.append(buffer);
439 snprintf(buffer, SIZE, "TID: %d\n", getTid());
440 result.append(buffer);
441 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
442 result.append(buffer);
443 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
444 result.append(buffer);
445 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
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,
734 status_t *status
735 )
736{
737 sp<EffectModule> effect;
738 sp<EffectHandle> handle;
739 status_t lStatus;
740 sp<EffectChain> chain;
741 bool chainCreated = false;
742 bool effectCreated = false;
743 bool effectRegistered = false;
744
745 lStatus = initCheck();
746 if (lStatus != NO_ERROR) {
747 ALOGW("createEffect_l() Audio driver not initialized.");
748 goto Exit;
749 }
750
Eric Laurent5baf2af2013-09-12 17:37:00 -0700751 // Allow global effects only on offloaded and mixer threads
752 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
753 switch (mType) {
754 case MIXER:
755 case OFFLOAD:
756 break;
757 case DIRECT:
758 case DUPLICATING:
759 case RECORD:
760 default:
761 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
762 lStatus = BAD_VALUE;
763 goto Exit;
764 }
Eric Laurent81784c32012-11-19 14:55:58 -0800765 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700766
Eric Laurent81784c32012-11-19 14:55:58 -0800767 // Only Pre processor effects are allowed on input threads and only on input threads
768 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
769 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
770 desc->name, desc->flags, mType);
771 lStatus = BAD_VALUE;
772 goto Exit;
773 }
774
775 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
776
777 { // scope for mLock
778 Mutex::Autolock _l(mLock);
779
780 // check for existing effect chain with the requested audio session
781 chain = getEffectChain_l(sessionId);
782 if (chain == 0) {
783 // create a new chain for this session
784 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
785 chain = new EffectChain(this, sessionId);
786 addEffectChain_l(chain);
787 chain->setStrategy(getStrategyForSession_l(sessionId));
788 chainCreated = true;
Ethan Chen8d420ed2013-11-14 00:40:54 -0800789#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530790 if(sessionId == mAudioFlinger->mLPASessionId) {
791 // Clear reference to previous effect chain if any
792 if(mAudioFlinger->mLPAEffectChain.get()) {
793 mAudioFlinger->mLPAEffectChain.clear();
794 }
795 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
796 mAudioFlinger->mLPAEffectChain = chain;
797 chain->setLPAFlag(true);
798 // For LPA, the volume will be applied in DSP. No need for volume
799 // control in the Effect chain, so setting it to unity.
800 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
801 chain->setVolume_l(&volume,&volume);
802 }
Ethan Chen8d420ed2013-11-14 00:40:54 -0800803#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800804 } else {
805 effect = chain->getEffectFromDesc_l(desc);
806 }
807
808 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
809
810 if (effect == 0) {
811 int id = mAudioFlinger->nextUniqueId();
812 // Check CPU and memory usage
813 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
814 if (lStatus != NO_ERROR) {
815 goto Exit;
816 }
817 effectRegistered = true;
818 // create a new effect module if none present in the chain
819 effect = new EffectModule(this, chain, desc, id, sessionId);
820 lStatus = effect->status();
821 if (lStatus != NO_ERROR) {
822 goto Exit;
823 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700824 effect->setOffloaded(mType == OFFLOAD, mId);
825
Eric Laurent81784c32012-11-19 14:55:58 -0800826 lStatus = chain->addEffect_l(effect);
827 if (lStatus != NO_ERROR) {
828 goto Exit;
829 }
830 effectCreated = true;
831
Ethan Chen8d420ed2013-11-14 00:40:54 -0800832#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530833 effect->setDevice(mAudioFlinger->mLPASessionId == sessionId ? mAudioFlinger->mDirectDevice:mOutDevice);
Ethan Chen8d420ed2013-11-14 00:40:54 -0800834#else
835 effect->setDevice(mOutDevice);
836#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800837 effect->setDevice(mInDevice);
838 effect->setMode(mAudioFlinger->getMode());
839 effect->setAudioSource(mAudioSource);
840 }
841 // create effect handle and connect it to effect module
842 handle = new EffectHandle(effect, client, effectClient, priority);
843 lStatus = effect->addHandle(handle.get());
844 if (enabled != NULL) {
845 *enabled = (int)effect->isEnabled();
846 }
847 }
848
849Exit:
850 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
851 Mutex::Autolock _l(mLock);
852 if (effectCreated) {
853 chain->removeEffect_l(effect);
854 }
855 if (effectRegistered) {
856 AudioSystem::unregisterEffect(effect->id());
857 }
858 if (chainCreated) {
859 removeEffectChain_l(chain);
860 }
861 handle.clear();
862 }
863
864 if (status != NULL) {
865 *status = lStatus;
866 }
867 return handle;
868}
869
870sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
871{
872 Mutex::Autolock _l(mLock);
873 return getEffect_l(sessionId, effectId);
874}
875
876sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
877{
878 sp<EffectChain> chain = getEffectChain_l(sessionId);
879 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
880}
881
882// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
883// PlaybackThread::mLock held
884status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
885{
886 // check for existing effect chain with the requested audio session
887 int sessionId = effect->sessionId();
888 sp<EffectChain> chain = getEffectChain_l(sessionId);
889 bool chainCreated = false;
890
Eric Laurent5baf2af2013-09-12 17:37:00 -0700891 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
892 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
893 this, effect->desc().name, effect->desc().flags);
894
Eric Laurent81784c32012-11-19 14:55:58 -0800895 if (chain == 0) {
896 // create a new chain for this session
897 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
898 chain = new EffectChain(this, sessionId);
899 addEffectChain_l(chain);
900 chain->setStrategy(getStrategyForSession_l(sessionId));
901 chainCreated = true;
902 }
903 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
904
905 if (chain->getEffectFromId_l(effect->id()) != 0) {
906 ALOGW("addEffect_l() %p effect %s already present in chain %p",
907 this, effect->desc().name, chain.get());
908 return BAD_VALUE;
909 }
910
Eric Laurent5baf2af2013-09-12 17:37:00 -0700911 effect->setOffloaded(mType == OFFLOAD, mId);
912
Eric Laurent81784c32012-11-19 14:55:58 -0800913 status_t status = chain->addEffect_l(effect);
914 if (status != NO_ERROR) {
915 if (chainCreated) {
916 removeEffectChain_l(chain);
917 }
918 return status;
919 }
920
921 effect->setDevice(mOutDevice);
922 effect->setDevice(mInDevice);
923 effect->setMode(mAudioFlinger->getMode());
924 effect->setAudioSource(mAudioSource);
925 return NO_ERROR;
926}
927
928void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
929
930 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
931 effect_descriptor_t desc = effect->desc();
932 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
933 detachAuxEffect_l(effect->id());
934 }
935
936 sp<EffectChain> chain = effect->chain().promote();
937 if (chain != 0) {
938 // remove effect chain if removing last effect
939 if (chain->removeEffect_l(effect) == 0) {
940 removeEffectChain_l(chain);
941 }
942 } else {
943 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
944 }
945}
946
947void AudioFlinger::ThreadBase::lockEffectChains_l(
948 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
949{
950 effectChains = mEffectChains;
Ethan Chen8d420ed2013-11-14 00:40:54 -0800951#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530952 mAudioFlinger->mAllChainsLocked = true;
Ethan Chen8d420ed2013-11-14 00:40:54 -0800953#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800954 for (size_t i = 0; i < mEffectChains.size(); i++) {
Ethan Chen8d420ed2013-11-14 00:40:54 -0800955#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530956 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain) {
Ethan Chen8d420ed2013-11-14 00:40:54 -0800957#else
Alok Kediya601e9b52013-09-27 11:55:10 +0530958 mEffectChains[i]->lock();
Ethan Chen8d420ed2013-11-14 00:40:54 -0800959#endif
960#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530961 } else {
962 mAudioFlinger-> mAllChainsLocked = false;
963 }
Ethan Chen8d420ed2013-11-14 00:40:54 -0800964#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800965 }
966}
967
968void AudioFlinger::ThreadBase::unlockEffectChains(
969 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
970{
971 for (size_t i = 0; i < effectChains.size(); i++) {
Ethan Chen8d420ed2013-11-14 00:40:54 -0800972#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530973 if (mAudioFlinger->mAllChainsLocked || effectChains[i] != mAudioFlinger->mLPAEffectChain)
Ethan Chen8d420ed2013-11-14 00:40:54 -0800974#endif
Alok Kediya601e9b52013-09-27 11:55:10 +0530975 effectChains[i]->unlock();
Eric Laurent81784c32012-11-19 14:55:58 -0800976 }
977}
978
979sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
980{
981 Mutex::Autolock _l(mLock);
982 return getEffectChain_l(sessionId);
983}
984
985sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
986{
987 size_t size = mEffectChains.size();
988 for (size_t i = 0; i < size; i++) {
989 if (mEffectChains[i]->sessionId() == sessionId) {
990 return mEffectChains[i];
991 }
992 }
993 return 0;
994}
995
996void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
997{
998 Mutex::Autolock _l(mLock);
999 size_t size = mEffectChains.size();
1000 for (size_t i = 0; i < size; i++) {
1001 mEffectChains[i]->setMode_l(mode);
1002 }
1003}
1004
1005void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1006 EffectHandle *handle,
1007 bool unpinIfLast) {
1008
1009 Mutex::Autolock _l(mLock);
1010 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1011 // delete the effect module if removing last handle on it
1012 if (effect->removeHandle(handle) == 0) {
1013 if (!effect->isPinned() || unpinIfLast) {
1014 removeEffect_l(effect);
1015 AudioSystem::unregisterEffect(effect->id());
1016 }
1017 }
1018}
1019
1020// ----------------------------------------------------------------------------
1021// Playback
1022// ----------------------------------------------------------------------------
1023
1024AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1025 AudioStreamOut* output,
1026 audio_io_handle_t id,
1027 audio_devices_t device,
1028 type_t type)
1029 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001030 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001031 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001032 // mStreamTypes[] initialized in constructor body
1033 mOutput(output),
1034 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1035 mMixerStatus(MIXER_IDLE),
1036 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1037 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001038 mBytesRemaining(0),
1039 mCurrentWriteLength(0),
1040 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001041 mWriteAckSequence(0),
1042 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001043 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001044 mScreenState(AudioFlinger::mScreenState),
1045 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001046 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1047 // mLatchD, mLatchQ,
1048 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
1050 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001051 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001052
1053 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1054 // it would be safer to explicitly pass initial masterVolume/masterMute as
1055 // parameter.
1056 //
1057 // If the HAL we are using has support for master volume or master mute,
1058 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1059 // and the mute set to false).
1060 mMasterVolume = audioFlinger->masterVolume_l();
1061 mMasterMute = audioFlinger->masterMute_l();
1062 if (mOutput && mOutput->audioHwDev) {
1063 if (mOutput->audioHwDev->canSetMasterVolume()) {
1064 mMasterVolume = 1.0;
1065 }
1066
1067 if (mOutput->audioHwDev->canSetMasterMute()) {
1068 mMasterMute = false;
1069 }
1070 }
1071
1072 readOutputParameters();
1073
1074 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1075 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1076 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1077 stream = (audio_stream_type_t) (stream + 1)) {
1078 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1079 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1080 }
1081 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1082 // because mAudioFlinger doesn't have one to copy from
1083}
1084
1085AudioFlinger::PlaybackThread::~PlaybackThread()
1086{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001087 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001088 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001089}
1090
1091void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1092{
1093 dumpInternals(fd, args);
1094 dumpTracks(fd, args);
1095 dumpEffectChains(fd, args);
1096}
1097
1098void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1099{
1100 const size_t SIZE = 256;
1101 char buffer[SIZE];
1102 String8 result;
1103
1104 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1105 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1106 const stream_type_t *st = &mStreamTypes[i];
1107 if (i > 0) {
1108 result.appendFormat(", ");
1109 }
1110 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1111 if (st->mute) {
1112 result.append("M");
1113 }
1114 }
1115 result.append("\n");
1116 write(fd, result.string(), result.length());
1117 result.clear();
1118
1119 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1120 result.append(buffer);
1121 Track::appendDumpHeader(result);
1122 for (size_t i = 0; i < mTracks.size(); ++i) {
1123 sp<Track> track = mTracks[i];
1124 if (track != 0) {
1125 track->dump(buffer, SIZE);
1126 result.append(buffer);
1127 }
1128 }
1129
1130 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1131 result.append(buffer);
1132 Track::appendDumpHeader(result);
1133 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1134 sp<Track> track = mActiveTracks[i].promote();
1135 if (track != 0) {
1136 track->dump(buffer, SIZE);
1137 result.append(buffer);
1138 }
1139 }
1140 write(fd, result.string(), result.size());
1141
1142 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1143 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1144 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1145 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1146}
1147
1148void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1149{
1150 const size_t SIZE = 256;
1151 char buffer[SIZE];
1152 String8 result;
1153
1154 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1155 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001156 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1157 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001158 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1159 ns2ms(systemTime() - mLastWriteTime));
1160 result.append(buffer);
1161 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1162 result.append(buffer);
1163 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1164 result.append(buffer);
1165 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1166 result.append(buffer);
1167 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1168 result.append(buffer);
1169 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1170 result.append(buffer);
1171 write(fd, result.string(), result.size());
1172 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1173
1174 dumpBase(fd, args);
1175}
1176
1177// Thread virtuals
1178status_t AudioFlinger::PlaybackThread::readyToRun()
1179{
1180 status_t status = initCheck();
1181 if (status == NO_ERROR) {
1182 ALOGI("AudioFlinger's thread %p ready to run", this);
1183 } else {
1184 ALOGE("No working audio driver found.");
1185 }
1186 return status;
1187}
1188
1189void AudioFlinger::PlaybackThread::onFirstRef()
1190{
1191 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1192}
1193
1194// ThreadBase virtuals
1195void AudioFlinger::PlaybackThread::preExit()
1196{
1197 ALOGV(" preExit()");
1198 // FIXME this is using hard-coded strings but in the future, this functionality will be
1199 // converted to use audio HAL extensions required to support tunneling
1200 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1201}
1202
1203// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1204sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1205 const sp<AudioFlinger::Client>& client,
1206 audio_stream_type_t streamType,
1207 uint32_t sampleRate,
1208 audio_format_t format,
1209 audio_channel_mask_t channelMask,
1210 size_t frameCount,
1211 const sp<IMemory>& sharedBuffer,
1212 int sessionId,
1213 IAudioFlinger::track_flags_t *flags,
1214 pid_t tid,
1215 status_t *status)
1216{
1217 sp<Track> track;
1218 status_t lStatus;
1219
1220 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1221
1222 // client expresses a preference for FAST, but we get the final say
1223 if (*flags & IAudioFlinger::TRACK_FAST) {
1224 if (
1225 // not timed
1226 (!isTimed) &&
1227 // either of these use cases:
1228 (
1229 // use case 1: shared buffer with any frame count
1230 (
1231 (sharedBuffer != 0)
1232 ) ||
1233 // use case 2: callback handler and frame count is default or at least as large as HAL
1234 (
1235 (tid != -1) &&
1236 ((frameCount == 0) ||
1237 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1238 )
1239 ) &&
1240 // PCM data
1241 audio_is_linear_pcm(format) &&
1242 // mono or stereo
1243 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1244 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1245#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1246 // hardware sample rate
1247 (sampleRate == mSampleRate) &&
1248#endif
1249 // normal mixer has an associated fast mixer
1250 hasFastMixer() &&
1251 // there are sufficient fast track slots available
1252 (mFastTrackAvailMask != 0)
1253 // FIXME test that MixerThread for this fast track has a capable output HAL
1254 // FIXME add a permission test also?
1255 ) {
1256 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1257 if (frameCount == 0) {
1258 frameCount = mFrameCount * kFastTrackMultiplier;
1259 }
1260 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1261 frameCount, mFrameCount);
1262 } else {
1263 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1264 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1265 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1266 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1267 audio_is_linear_pcm(format),
1268 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1269 *flags &= ~IAudioFlinger::TRACK_FAST;
1270 // For compatibility with AudioTrack calculation, buffer depth is forced
1271 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1272 // This is probably too conservative, but legacy application code may depend on it.
1273 // If you change this calculation, also review the start threshold which is related.
1274 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
Alok Kediya601e9b52013-09-27 11:55:10 +05301275 uint32_t minBufCount = 0;
1276 if (mSampleRate) {
1277 minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1278 }
Eric Laurent81784c32012-11-19 14:55:58 -08001279 if (minBufCount < 2) {
1280 minBufCount = 2;
1281 }
1282 size_t minFrameCount = mNormalFrameCount * minBufCount;
1283 if (frameCount < minFrameCount) {
1284 frameCount = minFrameCount;
1285 }
1286 }
1287 }
1288
1289 if (mType == DIRECT) {
Ethan Chen8d420ed2013-11-14 00:40:54 -08001290#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05301291 if (((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM)
1292 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AMR_NB)
1293 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AMR_WB)
1294 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRC)
1295 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCB)
1296 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCWB)
1297 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCNW)) {
Ethan Chen8d420ed2013-11-14 00:40:54 -08001298#else
1299 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1300#endif
Eric Laurent81784c32012-11-19 14:55:58 -08001301 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1302 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1303 "for output %p with format %d",
1304 sampleRate, format, channelMask, mOutput, mFormat);
1305 lStatus = BAD_VALUE;
1306 goto Exit;
1307 }
1308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001309 } else if (mType == OFFLOAD) {
1310 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1311 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1312 "for output %p with format %d",
1313 sampleRate, format, channelMask, mOutput, mFormat);
1314 lStatus = BAD_VALUE;
1315 goto Exit;
1316 }
Eric Laurent81784c32012-11-19 14:55:58 -08001317 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001318 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1319 ALOGE("createTrack_l() Bad parameter: format %d \""
1320 "for output %p with format %d",
1321 format, mOutput, mFormat);
1322 lStatus = BAD_VALUE;
1323 goto Exit;
1324 }
Eric Laurent81784c32012-11-19 14:55:58 -08001325 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1326 if (sampleRate > mSampleRate*2) {
1327 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1328 lStatus = BAD_VALUE;
1329 goto Exit;
1330 }
1331 }
1332
1333 lStatus = initCheck();
1334 if (lStatus != NO_ERROR) {
1335 ALOGE("Audio driver not initialized.");
1336 goto Exit;
1337 }
1338
1339 { // scope for mLock
1340 Mutex::Autolock _l(mLock);
1341
1342 // all tracks in same audio session must share the same routing strategy otherwise
1343 // conflicts will happen when tracks are moved from one output to another by audio policy
1344 // manager
1345 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1346 for (size_t i = 0; i < mTracks.size(); ++i) {
1347 sp<Track> t = mTracks[i];
1348 if (t != 0 && !t->isOutputTrack()) {
1349 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1350 if (sessionId == t->sessionId() && strategy != actual) {
1351 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1352 strategy, actual);
1353 lStatus = BAD_VALUE;
1354 goto Exit;
1355 }
1356 }
1357 }
1358
1359 if (!isTimed) {
1360 track = new Track(this, client, streamType, sampleRate, format,
1361 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1362 } else {
1363 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1364 channelMask, frameCount, sharedBuffer, sessionId);
1365 }
1366 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1367 lStatus = NO_MEMORY;
1368 goto Exit;
1369 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001370
Eric Laurent81784c32012-11-19 14:55:58 -08001371 mTracks.add(track);
1372
1373 sp<EffectChain> chain = getEffectChain_l(sessionId);
1374 if (chain != 0) {
1375 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1376 track->setMainBuffer(chain->inBuffer());
1377 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1378 chain->incTrackCnt();
1379 }
1380
1381 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1382 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1383 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1384 // so ask activity manager to do this on our behalf
1385 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1386 }
1387 }
1388
1389 lStatus = NO_ERROR;
1390
1391Exit:
1392 if (status) {
1393 *status = lStatus;
1394 }
1395 return track;
1396}
1397
1398uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1399{
1400 return latency;
1401}
1402
1403uint32_t AudioFlinger::PlaybackThread::latency() const
1404{
1405 Mutex::Autolock _l(mLock);
1406 return latency_l();
1407}
1408uint32_t AudioFlinger::PlaybackThread::latency_l() const
1409{
1410 if (initCheck() == NO_ERROR) {
1411 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1412 } else {
1413 return 0;
1414 }
1415}
1416
1417void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1418{
1419 Mutex::Autolock _l(mLock);
1420 // Don't apply master volume in SW if our HAL can do it for us.
1421 if (mOutput && mOutput->audioHwDev &&
1422 mOutput->audioHwDev->canSetMasterVolume()) {
1423 mMasterVolume = 1.0;
1424 } else {
1425 mMasterVolume = value;
1426 }
1427}
1428
1429void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1430{
1431 Mutex::Autolock _l(mLock);
1432 // Don't apply master mute in SW if our HAL can do it for us.
1433 if (mOutput && mOutput->audioHwDev &&
1434 mOutput->audioHwDev->canSetMasterMute()) {
1435 mMasterMute = false;
1436 } else {
1437 mMasterMute = muted;
1438 }
1439}
1440
1441void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1442{
1443 Mutex::Autolock _l(mLock);
1444 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001445 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001446}
1447
1448void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1449{
1450 Mutex::Autolock _l(mLock);
1451 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001452 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001453}
1454
1455float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1456{
1457 Mutex::Autolock _l(mLock);
1458 return mStreamTypes[stream].volume;
1459}
1460
1461// addTrack_l() must be called with ThreadBase::mLock held
1462status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1463{
1464 status_t status = ALREADY_EXISTS;
1465
1466 // set retry count for buffer fill
1467 track->mRetryCount = kMaxTrackStartupRetries;
1468 if (mActiveTracks.indexOf(track) < 0) {
1469 // the track is newly added, make sure it fills up all its
1470 // buffers before playing. This is to ensure the client will
1471 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001472 if (!track->isOutputTrack()) {
1473 TrackBase::track_state state = track->mState;
1474 mLock.unlock();
1475 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1476 mLock.lock();
1477 // abort track was stopped/paused while we released the lock
1478 if (state != track->mState) {
1479 if (status == NO_ERROR) {
1480 mLock.unlock();
1481 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1482 mLock.lock();
1483 }
1484 return INVALID_OPERATION;
1485 }
1486 // abort if start is rejected by audio policy manager
1487 if (status != NO_ERROR) {
1488 return PERMISSION_DENIED;
1489 }
1490#ifdef ADD_BATTERY_DATA
1491 // to track the speaker usage
1492 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1493#endif
1494 }
1495
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001496 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001497 track->mResetDone = false;
1498 track->mPresentationCompleteFrames = 0;
1499 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001500 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1501 if (chain != 0) {
1502 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1503 track->sessionId());
1504 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001505 }
1506
1507 status = NO_ERROR;
1508 }
1509
Eric Laurentede6c3b2013-09-19 14:37:46 -07001510 ALOGV("signal playback thread");
1511 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001512
1513 return status;
1514}
1515
Eric Laurentbfb1b832013-01-07 09:53:42 -08001516bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001519 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001520 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1521 track->mState = TrackBase::STOPPED;
1522 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001523 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001524 } else if (track->isFastTrack() || track->isOffloaded()) {
1525 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001526 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001527
1528 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001529}
1530
1531void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1532{
1533 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1534 mTracks.remove(track);
1535 deleteTrackName_l(track->name());
1536 // redundant as track is about to be destroyed, for dumpsys only
1537 track->mName = -1;
1538 if (track->isFastTrack()) {
1539 int index = track->mFastIndex;
1540 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1541 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1542 mFastTrackAvailMask |= 1 << index;
1543 // redundant as track is about to be destroyed, for dumpsys only
1544 track->mFastIndex = -1;
1545 }
1546 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1547 if (chain != 0) {
1548 chain->decTrackCnt();
1549 }
1550}
1551
Eric Laurentede6c3b2013-09-19 14:37:46 -07001552void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001553{
1554 // Thread could be blocked waiting for async
1555 // so signal it to handle state changes immediately
1556 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1557 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1558 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001559 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001560}
1561
Eric Laurent81784c32012-11-19 14:55:58 -08001562String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1563{
Eric Laurent81784c32012-11-19 14:55:58 -08001564 Mutex::Autolock _l(mLock);
1565 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001566 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001567 }
1568
Glenn Kastend8ea6992013-07-16 14:17:15 -07001569 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1570 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001571 free(s);
1572 return out_s8;
1573}
1574
1575// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1576void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1577 AudioSystem::OutputDescriptor desc;
1578 void *param2 = NULL;
1579
1580 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1581 param);
1582
1583 switch (event) {
1584 case AudioSystem::OUTPUT_OPENED:
1585 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001586 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001587 desc.samplingRate = mSampleRate;
1588 desc.format = mFormat;
1589 desc.frameCount = mNormalFrameCount; // FIXME see
1590 // AudioFlinger::frameCount(audio_io_handle_t)
1591 desc.latency = latency();
1592 param2 = &desc;
1593 break;
1594
1595 case AudioSystem::STREAM_CONFIG_CHANGED:
1596 param2 = &param;
1597 case AudioSystem::OUTPUT_CLOSED:
1598 default:
1599 break;
1600 }
1601 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1602}
1603
Eric Laurentbfb1b832013-01-07 09:53:42 -08001604void AudioFlinger::PlaybackThread::writeCallback()
1605{
1606 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001607 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001608}
1609
1610void AudioFlinger::PlaybackThread::drainCallback()
1611{
1612 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001613 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001614}
1615
Eric Laurent3b4529e2013-09-05 18:09:19 -07001616void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001617{
1618 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001619 // reject out of sequence requests
1620 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1621 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001622 mWaitWorkCV.signal();
1623 }
1624}
1625
Eric Laurent3b4529e2013-09-05 18:09:19 -07001626void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001627{
1628 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001629 // reject out of sequence requests
1630 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1631 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001632 mWaitWorkCV.signal();
1633 }
1634}
1635
1636// static
1637int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1638 void *param,
1639 void *cookie)
1640{
1641 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1642 ALOGV("asyncCallback() event %d", event);
1643 switch (event) {
1644 case STREAM_CBK_EVENT_WRITE_READY:
1645 me->writeCallback();
1646 break;
1647 case STREAM_CBK_EVENT_DRAIN_READY:
1648 me->drainCallback();
1649 break;
1650 default:
1651 ALOGW("asyncCallback() unknown event %d", event);
1652 break;
1653 }
1654 return 0;
1655}
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657void AudioFlinger::PlaybackThread::readOutputParameters()
1658{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001659 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1661 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001662 if (!audio_is_output_channel(mChannelMask)) {
1663 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1664 }
1665 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1666 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1667 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1668 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001669 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001670 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001671 if (!audio_is_valid_format(mFormat)) {
1672 LOG_FATAL("HAL format %d not valid for output", mFormat);
1673 }
1674 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1675 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1676 mFormat);
1677 }
Eric Laurent81784c32012-11-19 14:55:58 -08001678 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1679 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1680 if (mFrameCount & 15) {
1681 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1682 mFrameCount);
1683 }
1684
Eric Laurentbfb1b832013-01-07 09:53:42 -08001685 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1686 (mOutput->stream->set_callback != NULL)) {
1687 if (mOutput->stream->set_callback(mOutput->stream,
1688 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1689 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001690 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691 }
1692 }
1693
Eric Laurent81784c32012-11-19 14:55:58 -08001694 // Calculate size of normal mix buffer relative to the HAL output buffer size
1695 double multiplier = 1.0;
1696 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1697 kUseFastMixer == FastMixer_Dynamic)) {
1698 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1699 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1700 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1701 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1702 maxNormalFrameCount = maxNormalFrameCount & ~15;
1703 if (maxNormalFrameCount < minNormalFrameCount) {
1704 maxNormalFrameCount = minNormalFrameCount;
1705 }
1706 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1707 if (multiplier <= 1.0) {
1708 multiplier = 1.0;
1709 } else if (multiplier <= 2.0) {
1710 if (2 * mFrameCount <= maxNormalFrameCount) {
1711 multiplier = 2.0;
1712 } else {
1713 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1714 }
1715 } else {
1716 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1717 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1718 // track, but we sometimes have to do this to satisfy the maximum frame count
1719 // constraint)
1720 // FIXME this rounding up should not be done if no HAL SRC
1721 uint32_t truncMult = (uint32_t) multiplier;
1722 if ((truncMult & 1)) {
1723 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1724 ++truncMult;
1725 }
1726 }
1727 multiplier = (double) truncMult;
1728 }
1729 }
1730 mNormalFrameCount = multiplier * mFrameCount;
1731 // round up to nearest 16 frames to satisfy AudioMixer
1732 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1733 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1734 mNormalFrameCount);
1735
Eric Laurentbfb1b832013-01-07 09:53:42 -08001736 delete[] mAllocMixBuffer;
1737 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1738 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1739 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1740 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001741
1742 // force reconfiguration of effect chains and engines to take new buffer size and audio
1743 // parameters into account
1744 // Note that mLock is not held when readOutputParameters() is called from the constructor
1745 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1746 // matter.
1747 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1748 Vector< sp<EffectChain> > effectChains = mEffectChains;
1749 for (size_t i = 0; i < effectChains.size(); i ++) {
1750 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1751 }
1752}
1753
1754
1755status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1756{
1757 if (halFrames == NULL || dspFrames == NULL) {
1758 return BAD_VALUE;
1759 }
1760 Mutex::Autolock _l(mLock);
1761 if (initCheck() != NO_ERROR) {
1762 return INVALID_OPERATION;
1763 }
1764 size_t framesWritten = mBytesWritten / mFrameSize;
1765 *halFrames = framesWritten;
1766
1767 if (isSuspended()) {
1768 // return an estimation of rendered frames when the output is suspended
1769 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1770 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1771 return NO_ERROR;
1772 } else {
1773 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1774 }
1775}
1776
1777uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1778{
1779 Mutex::Autolock _l(mLock);
1780 uint32_t result = 0;
1781 if (getEffectChain_l(sessionId) != 0) {
1782 result = EFFECT_SESSION;
1783 }
1784
1785 for (size_t i = 0; i < mTracks.size(); ++i) {
1786 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001787 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001788 result |= TRACK_SESSION;
1789 break;
1790 }
1791 }
1792
1793 return result;
1794}
1795
1796uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1797{
1798 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1799 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1800 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1801 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1802 }
1803 for (size_t i = 0; i < mTracks.size(); i++) {
1804 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001805 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001806 return AudioSystem::getStrategyForStream(track->streamType());
1807 }
1808 }
1809 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1810}
1811
1812
1813AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1814{
1815 Mutex::Autolock _l(mLock);
1816 return mOutput;
1817}
1818
1819AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1820{
1821 Mutex::Autolock _l(mLock);
1822 AudioStreamOut *output = mOutput;
1823 mOutput = NULL;
1824 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1825 // must push a NULL and wait for ack
1826 mOutputSink.clear();
1827 mPipeSink.clear();
1828 mNormalSink.clear();
1829 return output;
1830}
1831
1832// this method must always be called either with ThreadBase mLock held or inside the thread loop
1833audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1834{
1835 if (mOutput == NULL) {
1836 return NULL;
1837 }
1838 return &mOutput->stream->common;
1839}
1840
1841uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1842{
1843 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1844}
1845
1846status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1847{
1848 if (!isValidSyncEvent(event)) {
1849 return BAD_VALUE;
1850 }
1851
1852 Mutex::Autolock _l(mLock);
1853
1854 for (size_t i = 0; i < mTracks.size(); ++i) {
1855 sp<Track> track = mTracks[i];
1856 if (event->triggerSession() == track->sessionId()) {
1857 (void) track->setSyncEvent(event);
1858 return NO_ERROR;
1859 }
1860 }
1861
1862 return NAME_NOT_FOUND;
1863}
1864
1865bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1866{
1867 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1868}
1869
1870void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1871 const Vector< sp<Track> >& tracksToRemove)
1872{
1873 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001874 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001875 for (size_t i = 0 ; i < count ; i++) {
1876 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001877 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001878 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001879#ifdef ADD_BATTERY_DATA
1880 // to track the speaker usage
1881 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1882#endif
1883 if (track->isTerminated()) {
1884 AudioSystem::releaseOutput(mId);
1885 }
Eric Laurent81784c32012-11-19 14:55:58 -08001886 }
1887 }
1888 }
Eric Laurent81784c32012-11-19 14:55:58 -08001889}
1890
1891void AudioFlinger::PlaybackThread::checkSilentMode_l()
1892{
1893 if (!mMasterMute) {
1894 char value[PROPERTY_VALUE_MAX];
1895 if (property_get("ro.audio.silent", value, "0") > 0) {
1896 char *endptr;
1897 unsigned long ul = strtoul(value, &endptr, 0);
1898 if (*endptr == '\0' && ul != 0) {
1899 ALOGD("Silence is golden");
1900 // The setprop command will not allow a property to be changed after
1901 // the first time it is set, so we don't have to worry about un-muting.
1902 setMasterMute_l(true);
1903 }
1904 }
1905 }
1906}
1907
1908// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001909ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001910{
1911 // FIXME rewrite to reduce number of system calls
1912 mLastWriteTime = systemTime();
1913 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001914 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001915
1916 // If an NBAIO sink is present, use it to write the normal mixer's submix
1917 if (mNormalSink != 0) {
1918#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 size_t count = mBytesRemaining >> mBitShift;
1920 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001921 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001922 // update the setpoint when AudioFlinger::mScreenState changes
1923 uint32_t screenState = AudioFlinger::mScreenState;
1924 if (screenState != mScreenState) {
1925 mScreenState = screenState;
1926 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1927 if (pipe != NULL) {
1928 pipe->setAvgFrames((mScreenState & 1) ?
1929 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1930 }
1931 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001933 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001934 if (framesWritten > 0) {
1935 bytesWritten = framesWritten << mBitShift;
1936 } else {
1937 bytesWritten = framesWritten;
1938 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001939 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001940 if (status == NO_ERROR) {
1941 size_t totalFramesWritten = mNormalSink->framesWritten();
1942 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1943 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1944 mLatchDValid = true;
1945 }
1946 }
Eric Laurent81784c32012-11-19 14:55:58 -08001947 // otherwise use the HAL / AudioStreamOut directly
1948 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001949 // Direct output and offload threads
1950 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1951 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001952 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1953 mWriteAckSequence += 2;
1954 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001955 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001956 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001958 // FIXME We should have an implementation of timestamps for direct output threads.
1959 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960 bytesWritten = mOutput->stream->write(mOutput->stream,
1961 mMixBuffer + offset, mBytesRemaining);
1962 if (mUseAsyncWrite &&
1963 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1964 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001965 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001967 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 }
Eric Laurent81784c32012-11-19 14:55:58 -08001969 }
1970
Eric Laurent81784c32012-11-19 14:55:58 -08001971 mNumWrites++;
1972 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973
1974 return bytesWritten;
1975}
1976
1977void AudioFlinger::PlaybackThread::threadLoop_drain()
1978{
1979 if (mOutput->stream->drain) {
1980 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1981 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001982 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1983 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001984 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001985 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001986 }
1987 mOutput->stream->drain(mOutput->stream,
1988 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1989 : AUDIO_DRAIN_ALL);
1990 }
1991}
1992
1993void AudioFlinger::PlaybackThread::threadLoop_exit()
1994{
1995 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
1998/*
1999The derived values that are cached:
2000 - mixBufferSize from frame count * frame size
2001 - activeSleepTime from activeSleepTimeUs()
2002 - idleSleepTime from idleSleepTimeUs()
2003 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2004 - maxPeriod from frame count and sample rate (MIXER only)
2005
2006The parameters that affect these derived values are:
2007 - frame count
2008 - frame size
2009 - sample rate
2010 - device type: A2DP or not
2011 - device latency
2012 - format: PCM or not
2013 - active sleep time
2014 - idle sleep time
2015*/
2016
2017void AudioFlinger::PlaybackThread::cacheParameters_l()
2018{
2019 mixBufferSize = mNormalFrameCount * mFrameSize;
2020 activeSleepTime = activeSleepTimeUs();
2021 idleSleepTime = idleSleepTimeUs();
2022}
2023
2024void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2025{
Glenn Kasten7c027242012-12-26 14:43:16 -08002026 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002027 this, streamType, mTracks.size());
2028 Mutex::Autolock _l(mLock);
2029
2030 size_t size = mTracks.size();
2031 for (size_t i = 0; i < size; i++) {
2032 sp<Track> t = mTracks[i];
2033 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002034 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002035 }
2036 }
2037}
2038
2039status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2040{
2041 int session = chain->sessionId();
2042 int16_t *buffer = mMixBuffer;
2043 bool ownsBuffer = false;
2044
2045 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2046 if (session > 0) {
2047 // Only one effect chain can be present in direct output thread and it uses
2048 // the mix buffer as input
2049 if (mType != DIRECT) {
2050 size_t numSamples = mNormalFrameCount * mChannelCount;
2051 buffer = new int16_t[numSamples];
2052 memset(buffer, 0, numSamples * sizeof(int16_t));
2053 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2054 ownsBuffer = true;
2055 }
2056
2057 // Attach all tracks with same session ID to this chain.
2058 for (size_t i = 0; i < mTracks.size(); ++i) {
2059 sp<Track> track = mTracks[i];
2060 if (session == track->sessionId()) {
2061 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2062 buffer);
2063 track->setMainBuffer(buffer);
2064 chain->incTrackCnt();
2065 }
2066 }
2067
2068 // indicate all active tracks in the chain
2069 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2070 sp<Track> track = mActiveTracks[i].promote();
2071 if (track == 0) {
2072 continue;
2073 }
2074 if (session == track->sessionId()) {
2075 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2076 chain->incActiveTrackCnt();
2077 }
2078 }
2079 }
2080
2081 chain->setInBuffer(buffer, ownsBuffer);
2082 chain->setOutBuffer(mMixBuffer);
2083 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2084 // chains list in order to be processed last as it contains output stage effects
2085 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2086 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2087 // after track specific effects and before output stage
2088 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2089 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2090 // Effect chain for other sessions are inserted at beginning of effect
2091 // chains list to be processed before output mix effects. Relative order between other
2092 // sessions is not important
2093 size_t size = mEffectChains.size();
2094 size_t i = 0;
2095 for (i = 0; i < size; i++) {
2096 if (mEffectChains[i]->sessionId() < session) {
2097 break;
2098 }
2099 }
2100 mEffectChains.insertAt(chain, i);
2101 checkSuspendOnAddEffectChain_l(chain);
2102
2103 return NO_ERROR;
2104}
2105
2106size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2107{
2108 int session = chain->sessionId();
2109
2110 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2111
2112 for (size_t i = 0; i < mEffectChains.size(); i++) {
2113 if (chain == mEffectChains[i]) {
2114 mEffectChains.removeAt(i);
2115 // detach all active tracks from the chain
2116 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2117 sp<Track> track = mActiveTracks[i].promote();
2118 if (track == 0) {
2119 continue;
2120 }
2121 if (session == track->sessionId()) {
2122 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2123 chain.get(), session);
2124 chain->decActiveTrackCnt();
2125 }
2126 }
2127
2128 // detach all tracks with same session ID from this chain
2129 for (size_t i = 0; i < mTracks.size(); ++i) {
2130 sp<Track> track = mTracks[i];
2131 if (session == track->sessionId()) {
2132 track->setMainBuffer(mMixBuffer);
2133 chain->decTrackCnt();
2134 }
2135 }
2136 break;
2137 }
2138 }
2139 return mEffectChains.size();
2140}
2141
2142status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2143 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2144{
2145 Mutex::Autolock _l(mLock);
2146 return attachAuxEffect_l(track, EffectId);
2147}
2148
2149status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2150 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2151{
2152 status_t status = NO_ERROR;
2153
2154 if (EffectId == 0) {
2155 track->setAuxBuffer(0, NULL);
2156 } else {
2157 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2158 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2159 if (effect != 0) {
2160 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2161 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2162 } else {
2163 status = INVALID_OPERATION;
2164 }
2165 } else {
2166 status = BAD_VALUE;
2167 }
2168 }
2169 return status;
2170}
2171
2172void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2173{
2174 for (size_t i = 0; i < mTracks.size(); ++i) {
2175 sp<Track> track = mTracks[i];
2176 if (track->auxEffectId() == effectId) {
2177 attachAuxEffect_l(track, 0);
2178 }
2179 }
2180}
2181
2182bool AudioFlinger::PlaybackThread::threadLoop()
2183{
2184 Vector< sp<Track> > tracksToRemove;
2185
2186 standbyTime = systemTime();
2187
Alok Kediya601e9b52013-09-27 11:55:10 +05302188#ifdef SRS_PROCESSING
2189if (mType == MIXER) {
2190 POSTPRO_PATCH_ICS_OUTPROC_MIX_INIT(this, gettid());
2191 } else if (mType == DUPLICATING) {
2192 POSTPRO_PATCH_ICS_OUTPROC_DUPE_INIT(this, gettid());
2193 }
2194#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002195 // MIXER
2196 nsecs_t lastWarning = 0;
2197
2198 // DUPLICATING
2199 // FIXME could this be made local to while loop?
2200 writeFrames = 0;
2201
2202 cacheParameters_l();
2203 sleepTime = idleSleepTime;
2204
2205 if (mType == MIXER) {
2206 sleepTimeShift = 0;
2207 }
2208
2209 CpuStats cpuStats;
2210 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2211
2212 acquireWakeLock();
2213
Glenn Kasten9e58b552013-01-18 15:09:48 -08002214 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2215 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2216 // and then that string will be logged at the next convenient opportunity.
2217 const char *logString = NULL;
2218
Eric Laurent664539d2013-09-23 18:24:31 -07002219 checkSilentMode_l();
2220
Eric Laurent81784c32012-11-19 14:55:58 -08002221 while (!exitPending())
2222 {
2223 cpuStats.sample(myName);
2224
2225 Vector< sp<EffectChain> > effectChains;
2226
2227 processConfigEvents();
2228
2229 { // scope for mLock
2230
2231 Mutex::Autolock _l(mLock);
2232
Glenn Kasten9e58b552013-01-18 15:09:48 -08002233 if (logString != NULL) {
2234 mNBLogWriter->logTimestamp();
2235 mNBLogWriter->log(logString);
2236 logString = NULL;
2237 }
2238
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002239 if (mLatchDValid) {
2240 mLatchQ = mLatchD;
2241 mLatchDValid = false;
2242 mLatchQValid = true;
2243 }
2244
Eric Laurent81784c32012-11-19 14:55:58 -08002245 if (checkForNewParameters_l()) {
2246 cacheParameters_l();
2247 }
2248
2249 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250 if (mSignalPending) {
2251 // A signal was raised while we were unlocked
2252 mSignalPending = false;
2253 } else if (waitingAsyncCallback_l()) {
2254 if (exitPending()) {
2255 break;
2256 }
2257 releaseWakeLock_l();
2258 ALOGV("wait async completion");
2259 mWaitWorkCV.wait(mLock);
2260 ALOGV("async completion/wake");
2261 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002262 standbyTime = systemTime() + standbyDelay;
2263 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002264
2265 continue;
2266 }
2267 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268 isSuspended()) {
2269 // put audio hardware into standby after short delay
2270 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002271
2272 threadLoop_standby();
2273
2274 mStandby = true;
2275 }
2276
2277 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2278 // we're about to wait, flush the binder command buffer
2279 IPCThreadState::self()->flushCommands();
2280
2281 clearOutputTracks();
2282
2283 if (exitPending()) {
2284 break;
2285 }
2286
2287 releaseWakeLock_l();
2288 // wait until we have something to do...
2289 ALOGV("%s going to sleep", myName.string());
2290 mWaitWorkCV.wait(mLock);
2291 ALOGV("%s waking up", myName.string());
2292 acquireWakeLock_l();
2293
2294 mMixerStatus = MIXER_IDLE;
2295 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2296 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002298 checkSilentMode_l();
2299
2300 standbyTime = systemTime() + standbyDelay;
2301 sleepTime = idleSleepTime;
2302 if (mType == MIXER) {
2303 sleepTimeShift = 0;
2304 }
2305
2306 continue;
2307 }
2308 }
Eric Laurent81784c32012-11-19 14:55:58 -08002309 // mMixerStatusIgnoringFastTracks is also updated internally
2310 mMixerStatus = prepareTracks_l(&tracksToRemove);
2311
2312 // prevent any changes in effect chain list and in each effect chain
2313 // during mixing and effect process as the audio buffers could be deleted
2314 // or modified if an effect is created or deleted
2315 lockEffectChains_l(effectChains);
2316 }
2317
Eric Laurentbfb1b832013-01-07 09:53:42 -08002318 if (mBytesRemaining == 0) {
2319 mCurrentWriteLength = 0;
2320 if (mMixerStatus == MIXER_TRACKS_READY) {
2321 // threadLoop_mix() sets mCurrentWriteLength
2322 threadLoop_mix();
2323 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2324 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2325 // threadLoop_sleepTime sets sleepTime to 0 if data
2326 // must be written to HAL
2327 threadLoop_sleepTime();
2328 if (sleepTime == 0) {
2329 mCurrentWriteLength = mixBufferSize;
2330 }
2331 }
2332 mBytesRemaining = mCurrentWriteLength;
2333 if (isSuspended()) {
2334 sleepTime = suspendSleepTimeUs();
2335 // simulate write to HAL when suspended
2336 mBytesWritten += mixBufferSize;
2337 mBytesRemaining = 0;
2338 }
Eric Laurent81784c32012-11-19 14:55:58 -08002339
Eric Laurentbfb1b832013-01-07 09:53:42 -08002340 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002341 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002342 for (size_t i = 0; i < effectChains.size(); i ++) {
Ethan Chen8d420ed2013-11-14 00:40:54 -08002343#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05302344 if (effectChains[i] != mAudioFlinger->mLPAEffectChain) {
Ethan Chen8d420ed2013-11-14 00:40:54 -08002345#endif
Alok Kediya601e9b52013-09-27 11:55:10 +05302346 effectChains[i]->process_l();
Ethan Chen8d420ed2013-11-14 00:40:54 -08002347#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05302348 }
Ethan Chen8d420ed2013-11-14 00:40:54 -08002349#endif
Alok Kediya601e9b52013-09-27 11:55:10 +05302350 }
Eric Laurent81784c32012-11-19 14:55:58 -08002351 }
2352 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002353 // Process effect chains for offloaded thread even if no audio
2354 // was read from audio track: process only updates effect state
2355 // and thus does have to be synchronized with audio writes but may have
2356 // to be called while waiting for async write callback
2357 if (mType == OFFLOAD) {
2358 for (size_t i = 0; i < effectChains.size(); i ++) {
Ethan Chendbfb39e2013-11-06 01:23:02 -08002359 effectChains[i]->process_l();
Eric Laurent59fe0102013-09-27 18:48:26 -07002360 }
2361 }
Eric Laurent81784c32012-11-19 14:55:58 -08002362
2363 // enable changes in effect chain
2364 unlockEffectChains(effectChains);
2365
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 if (!waitingAsyncCallback()) {
2367 // sleepTime == 0 means we must write to audio hardware
2368 if (sleepTime == 0) {
Alok Kediya601e9b52013-09-27 11:55:10 +05302369#ifdef SRS_PROCESSING
2370 if (mType == MIXER) {
2371 POSTPRO_PATCH_ICS_OUTPROC_MIX_SAMPLES(this, mFormat, mMixBuffer,
2372 mixBufferSize, mSampleRate, mChannelCount);
2373 } else if (mType == DUPLICATING) {
2374 POSTPRO_PATCH_ICS_OUTPROC_DUPE_SAMPLES(this, mFormat, mMixBuffer,
2375 mixBufferSize, mSampleRate, mChannelCount);
2376 }
2377#endif
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 if (mBytesRemaining) {
2379 ssize_t ret = threadLoop_write();
2380 if (ret < 0) {
2381 mBytesRemaining = 0;
2382 } else {
2383 mBytesWritten += ret;
2384 mBytesRemaining -= ret;
2385 }
2386 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2387 (mMixerStatus == MIXER_DRAIN_ALL)) {
2388 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390if (mType == MIXER) {
2391 // write blocked detection
2392 nsecs_t now = systemTime();
2393 nsecs_t delta = now - mLastWriteTime;
2394 if (!mStandby && delta > maxPeriod) {
2395 mNumDelayedWrites++;
2396 if ((now - lastWarning) > kWarningThrottleNs) {
2397 ATRACE_NAME("underrun");
2398 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2399 ns2ms(delta), mNumDelayedWrites, this);
2400 lastWarning = now;
2401 }
2402 }
Eric Laurent81784c32012-11-19 14:55:58 -08002403}
2404
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 mStandby = false;
2406 } else {
2407 usleep(sleepTime);
2408 }
Eric Laurent81784c32012-11-19 14:55:58 -08002409 }
2410
2411 // Finally let go of removed track(s), without the lock held
2412 // since we can't guarantee the destructors won't acquire that
2413 // same lock. This will also mutate and push a new fast mixer state.
2414 threadLoop_removeTracks(tracksToRemove);
2415 tracksToRemove.clear();
2416
2417 // FIXME I don't understand the need for this here;
2418 // it was in the original code but maybe the
2419 // assignment in saveOutputTracks() makes this unnecessary?
2420 clearOutputTracks();
2421
2422 // Effect chains will be actually deleted here if they were removed from
2423 // mEffectChains list during mixing or effects processing
2424 effectChains.clear();
2425
2426 // FIXME Note that the above .clear() is no longer necessary since effectChains
2427 // is now local to this block, but will keep it for now (at least until merge done).
2428 }
2429
Eric Laurentbfb1b832013-01-07 09:53:42 -08002430 threadLoop_exit();
2431
Eric Laurent81784c32012-11-19 14:55:58 -08002432 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002433 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // put output stream into standby mode
2435 if (!mStandby) {
2436 mOutput->stream->common.standby(&mOutput->stream->common);
2437 }
2438 }
2439
Alok Kediya601e9b52013-09-27 11:55:10 +05302440#ifdef SRS_PROCESSING
2441 if (mType == MIXER) {
2442 POSTPRO_PATCH_ICS_OUTPROC_MIX_EXIT(this, gettid());
2443 } else if (mType == DUPLICATING) {
2444 POSTPRO_PATCH_ICS_OUTPROC_DUPE_EXIT(this, gettid());
2445 }
2446#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002447 releaseWakeLock();
2448
2449 ALOGV("Thread %p type %d exiting", this, mType);
2450 return false;
2451}
2452
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453// removeTracks_l() must be called with ThreadBase::mLock held
2454void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2455{
2456 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002457 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002458 for (size_t i=0 ; i<count ; i++) {
2459 const sp<Track>& track = tracksToRemove.itemAt(i);
2460 mActiveTracks.remove(track);
2461 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2462 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2463 if (chain != 0) {
2464 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2465 track->sessionId());
2466 chain->decActiveTrackCnt();
2467 }
2468 if (track->isTerminated()) {
2469 removeTrack_l(track);
2470 }
2471 }
2472 }
2473
2474}
Eric Laurent81784c32012-11-19 14:55:58 -08002475
Eric Laurentaccc1472013-09-20 09:36:34 -07002476status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2477{
2478 if (mNormalSink != 0) {
2479 return mNormalSink->getTimestamp(timestamp);
2480 }
2481 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2482 uint64_t position64;
2483 int ret = mOutput->stream->get_presentation_position(
2484 mOutput->stream, &position64, &timestamp.mTime);
2485 if (ret == 0) {
2486 timestamp.mPosition = (uint32_t)position64;
2487 return NO_ERROR;
2488 }
2489 }
2490 return INVALID_OPERATION;
2491}
Eric Laurent81784c32012-11-19 14:55:58 -08002492// ----------------------------------------------------------------------------
2493
2494AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2495 audio_io_handle_t id, audio_devices_t device, type_t type)
2496 : PlaybackThread(audioFlinger, output, id, device, type),
2497 // mAudioMixer below
2498 // mFastMixer below
2499 mFastMixerFutex(0)
2500 // mOutputSink below
2501 // mPipeSink below
2502 // mNormalSink below
2503{
2504 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002505 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002506 "mFrameCount=%d, mNormalFrameCount=%d",
2507 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2508 mNormalFrameCount);
2509 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2510
2511 // FIXME - Current mixer implementation only supports stereo output
2512 if (mChannelCount != FCC_2) {
2513 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2514 }
2515
2516 // create an NBAIO sink for the HAL output stream, and negotiate
2517 mOutputSink = new AudioStreamOutSink(output->stream);
2518 size_t numCounterOffers = 0;
2519 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2520 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2521 ALOG_ASSERT(index == 0);
2522
2523 // initialize fast mixer depending on configuration
2524 bool initFastMixer;
2525 switch (kUseFastMixer) {
2526 case FastMixer_Never:
2527 initFastMixer = false;
2528 break;
2529 case FastMixer_Always:
2530 initFastMixer = true;
2531 break;
2532 case FastMixer_Static:
2533 case FastMixer_Dynamic:
2534 initFastMixer = mFrameCount < mNormalFrameCount;
2535 break;
2536 }
2537 if (initFastMixer) {
2538
2539 // create a MonoPipe to connect our submix to FastMixer
2540 NBAIO_Format format = mOutputSink->format();
2541 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2542 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2543 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2544 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2545 const NBAIO_Format offers[1] = {format};
2546 size_t numCounterOffers = 0;
2547 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2548 ALOG_ASSERT(index == 0);
2549 monoPipe->setAvgFrames((mScreenState & 1) ?
2550 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2551 mPipeSink = monoPipe;
2552
Glenn Kasten46909e72013-02-26 09:20:22 -08002553#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002554 if (mTeeSinkOutputEnabled) {
2555 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2556 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2557 numCounterOffers = 0;
2558 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2559 ALOG_ASSERT(index == 0);
2560 mTeeSink = teeSink;
2561 PipeReader *teeSource = new PipeReader(*teeSink);
2562 numCounterOffers = 0;
2563 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2564 ALOG_ASSERT(index == 0);
2565 mTeeSource = teeSource;
2566 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002567#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002568
2569 // create fast mixer and configure it initially with just one fast track for our submix
2570 mFastMixer = new FastMixer();
2571 FastMixerStateQueue *sq = mFastMixer->sq();
2572#ifdef STATE_QUEUE_DUMP
2573 sq->setObserverDump(&mStateQueueObserverDump);
2574 sq->setMutatorDump(&mStateQueueMutatorDump);
2575#endif
2576 FastMixerState *state = sq->begin();
2577 FastTrack *fastTrack = &state->mFastTracks[0];
2578 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2579 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2580 fastTrack->mVolumeProvider = NULL;
2581 fastTrack->mGeneration++;
2582 state->mFastTracksGen++;
2583 state->mTrackMask = 1;
2584 // fast mixer will use the HAL output sink
2585 state->mOutputSink = mOutputSink.get();
2586 state->mOutputSinkGen++;
2587 state->mFrameCount = mFrameCount;
2588 state->mCommand = FastMixerState::COLD_IDLE;
2589 // already done in constructor initialization list
2590 //mFastMixerFutex = 0;
2591 state->mColdFutexAddr = &mFastMixerFutex;
2592 state->mColdGen++;
2593 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002594#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002595 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002596#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002597 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2598 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002599 sq->end();
2600 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2601
2602 // start the fast mixer
2603 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2604 pid_t tid = mFastMixer->getTid();
2605 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2606 if (err != 0) {
2607 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2608 kPriorityFastMixer, getpid_cached, tid, err);
2609 }
2610
2611#ifdef AUDIO_WATCHDOG
2612 // create and start the watchdog
2613 mAudioWatchdog = new AudioWatchdog();
2614 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2615 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2616 tid = mAudioWatchdog->getTid();
2617 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2618 if (err != 0) {
2619 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2620 kPriorityFastMixer, getpid_cached, tid, err);
2621 }
2622#endif
2623
2624 } else {
2625 mFastMixer = NULL;
2626 }
2627
2628 switch (kUseFastMixer) {
2629 case FastMixer_Never:
2630 case FastMixer_Dynamic:
2631 mNormalSink = mOutputSink;
2632 break;
2633 case FastMixer_Always:
2634 mNormalSink = mPipeSink;
2635 break;
2636 case FastMixer_Static:
2637 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2638 break;
2639 }
2640}
2641
2642AudioFlinger::MixerThread::~MixerThread()
2643{
2644 if (mFastMixer != NULL) {
2645 FastMixerStateQueue *sq = mFastMixer->sq();
2646 FastMixerState *state = sq->begin();
2647 if (state->mCommand == FastMixerState::COLD_IDLE) {
2648 int32_t old = android_atomic_inc(&mFastMixerFutex);
2649 if (old == -1) {
2650 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2651 }
2652 }
2653 state->mCommand = FastMixerState::EXIT;
2654 sq->end();
2655 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2656 mFastMixer->join();
2657 // Though the fast mixer thread has exited, it's state queue is still valid.
2658 // We'll use that extract the final state which contains one remaining fast track
2659 // corresponding to our sub-mix.
2660 state = sq->begin();
2661 ALOG_ASSERT(state->mTrackMask == 1);
2662 FastTrack *fastTrack = &state->mFastTracks[0];
2663 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2664 delete fastTrack->mBufferProvider;
2665 sq->end(false /*didModify*/);
2666 delete mFastMixer;
2667#ifdef AUDIO_WATCHDOG
2668 if (mAudioWatchdog != 0) {
2669 mAudioWatchdog->requestExit();
2670 mAudioWatchdog->requestExitAndWait();
2671 mAudioWatchdog.clear();
2672 }
2673#endif
2674 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002675 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002676 delete mAudioMixer;
2677}
2678
2679
2680uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2681{
2682 if (mFastMixer != NULL) {
2683 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
Alok Kediya601e9b52013-09-27 11:55:10 +05302684 if(mSampleRate)
2685 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2686 else
2687 ALOGW("SampleRate is 0");
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
2689 return latency;
2690}
2691
2692
2693void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2694{
2695 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2696}
2697
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002699{
2700 // FIXME we should only do one push per cycle; confirm this is true
2701 // Start the fast mixer if it's not already running
2702 if (mFastMixer != NULL) {
2703 FastMixerStateQueue *sq = mFastMixer->sq();
2704 FastMixerState *state = sq->begin();
2705 if (state->mCommand != FastMixerState::MIX_WRITE &&
2706 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2707 if (state->mCommand == FastMixerState::COLD_IDLE) {
2708 int32_t old = android_atomic_inc(&mFastMixerFutex);
2709 if (old == -1) {
2710 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2711 }
2712#ifdef AUDIO_WATCHDOG
2713 if (mAudioWatchdog != 0) {
2714 mAudioWatchdog->resume();
2715 }
2716#endif
2717 }
2718 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002719 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2720 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002721 sq->end();
2722 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2723 if (kUseFastMixer == FastMixer_Dynamic) {
2724 mNormalSink = mPipeSink;
2725 }
2726 } else {
2727 sq->end(false /*didModify*/);
2728 }
2729 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002731}
2732
2733void AudioFlinger::MixerThread::threadLoop_standby()
2734{
2735 // Idle the fast mixer if it's currently running
2736 if (mFastMixer != NULL) {
2737 FastMixerStateQueue *sq = mFastMixer->sq();
2738 FastMixerState *state = sq->begin();
2739 if (!(state->mCommand & FastMixerState::IDLE)) {
2740 state->mCommand = FastMixerState::COLD_IDLE;
2741 state->mColdFutexAddr = &mFastMixerFutex;
2742 state->mColdGen++;
2743 mFastMixerFutex = 0;
2744 sq->end();
2745 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2746 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2747 if (kUseFastMixer == FastMixer_Dynamic) {
2748 mNormalSink = mOutputSink;
2749 }
2750#ifdef AUDIO_WATCHDOG
2751 if (mAudioWatchdog != 0) {
2752 mAudioWatchdog->pause();
2753 }
2754#endif
2755 } else {
2756 sq->end(false /*didModify*/);
2757 }
2758 }
2759 PlaybackThread::threadLoop_standby();
2760}
2761
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762// Empty implementation for standard mixer
2763// Overridden for offloaded playback
2764void AudioFlinger::PlaybackThread::flushOutput_l()
2765{
2766}
2767
2768bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2769{
2770 return false;
2771}
2772
2773bool AudioFlinger::PlaybackThread::shouldStandby_l()
2774{
2775 return !mStandby;
2776}
2777
2778bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2779{
2780 Mutex::Autolock _l(mLock);
2781 return waitingAsyncCallback_l();
2782}
2783
Eric Laurent81784c32012-11-19 14:55:58 -08002784// shared by MIXER and DIRECT, overridden by DUPLICATING
2785void AudioFlinger::PlaybackThread::threadLoop_standby()
2786{
2787 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2788 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002790 // discard any pending drain or write ack by incrementing sequence
2791 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2792 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002793 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002794 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2795 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 }
Eric Laurent81784c32012-11-19 14:55:58 -08002797}
2798
2799void AudioFlinger::MixerThread::threadLoop_mix()
2800{
2801 // obtain the presentation timestamp of the next output buffer
2802 int64_t pts;
2803 status_t status = INVALID_OPERATION;
2804
Ricardo Cerqueira0d44b5b2013-11-03 02:46:27 +00002805#ifndef ICS_AUDIO_BLOB
Eric Laurent81784c32012-11-19 14:55:58 -08002806 if (mNormalSink != 0) {
2807 status = mNormalSink->getNextWriteTimestamp(&pts);
2808 } else {
2809 status = mOutputSink->getNextWriteTimestamp(&pts);
2810 }
Ricardo Cerqueira0d44b5b2013-11-03 02:46:27 +00002811#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002812
2813 if (status != NO_ERROR) {
2814 pts = AudioBufferProvider::kInvalidPTS;
2815 }
2816
2817 // mix buffers...
2818 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // increase sleep time progressively when application underrun condition clears.
2821 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2822 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2823 // such that we would underrun the audio HAL.
2824 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2825 sleepTimeShift--;
2826 }
2827 sleepTime = 0;
2828 standbyTime = systemTime() + standbyDelay;
2829 //TODO: delay standby when effects have a tail
2830}
2831
2832void AudioFlinger::MixerThread::threadLoop_sleepTime()
2833{
2834 // If no tracks are ready, sleep once for the duration of an output
2835 // buffer size, then write 0s to the output
2836 if (sleepTime == 0) {
2837 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2838 sleepTime = activeSleepTime >> sleepTimeShift;
2839 if (sleepTime < kMinThreadSleepTimeUs) {
2840 sleepTime = kMinThreadSleepTimeUs;
2841 }
2842 // reduce sleep time in case of consecutive application underruns to avoid
2843 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2844 // duration we would end up writing less data than needed by the audio HAL if
2845 // the condition persists.
2846 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2847 sleepTimeShift++;
2848 }
2849 } else {
2850 sleepTime = idleSleepTime;
2851 }
2852 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2853 memset (mMixBuffer, 0, mixBufferSize);
2854 sleepTime = 0;
2855 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2856 "anticipated start");
2857 }
2858 // TODO add standby time extension fct of effect tail
2859}
2860
2861// prepareTracks_l() must be called with ThreadBase::mLock held
2862AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2863 Vector< sp<Track> > *tracksToRemove)
2864{
2865
2866 mixer_state mixerStatus = MIXER_IDLE;
2867 // find out which tracks need to be processed
2868 size_t count = mActiveTracks.size();
2869 size_t mixedTracks = 0;
2870 size_t tracksWithEffect = 0;
2871 // counts only _active_ fast tracks
2872 size_t fastTracks = 0;
2873 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2874
2875 float masterVolume = mMasterVolume;
2876 bool masterMute = mMasterMute;
2877
2878 if (masterMute) {
2879 masterVolume = 0;
2880 }
2881 // Delegate master volume control to effect in output mix effect chain if needed
2882 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2883 if (chain != 0) {
2884 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2885 chain->setVolume_l(&v, &v);
2886 masterVolume = (float)((v + (1 << 23)) >> 24);
2887 chain.clear();
2888 }
2889
2890 // prepare a new state to push
2891 FastMixerStateQueue *sq = NULL;
2892 FastMixerState *state = NULL;
2893 bool didModify = false;
2894 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2895 if (mFastMixer != NULL) {
2896 sq = mFastMixer->sq();
2897 state = sq->begin();
2898 }
2899
2900 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002901 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002902 if (t == 0) {
2903 continue;
2904 }
2905
2906 // this const just means the local variable doesn't change
2907 Track* const track = t.get();
2908
2909 // process fast tracks
2910 if (track->isFastTrack()) {
2911
2912 // It's theoretically possible (though unlikely) for a fast track to be created
2913 // and then removed within the same normal mix cycle. This is not a problem, as
2914 // the track never becomes active so it's fast mixer slot is never touched.
2915 // The converse, of removing an (active) track and then creating a new track
2916 // at the identical fast mixer slot within the same normal mix cycle,
2917 // is impossible because the slot isn't marked available until the end of each cycle.
2918 int j = track->mFastIndex;
2919 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2920 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2921 FastTrack *fastTrack = &state->mFastTracks[j];
2922
2923 // Determine whether the track is currently in underrun condition,
2924 // and whether it had a recent underrun.
2925 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2926 FastTrackUnderruns underruns = ftDump->mUnderruns;
2927 uint32_t recentFull = (underruns.mBitFields.mFull -
2928 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2929 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2930 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2931 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2932 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2933 uint32_t recentUnderruns = recentPartial + recentEmpty;
2934 track->mObservedUnderruns = underruns;
2935 // don't count underruns that occur while stopping or pausing
2936 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002937 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2938 recentUnderruns > 0) {
2939 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2940 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002941 }
2942
2943 // This is similar to the state machine for normal tracks,
2944 // with a few modifications for fast tracks.
2945 bool isActive = true;
2946 switch (track->mState) {
2947 case TrackBase::STOPPING_1:
2948 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002950 track->mState = TrackBase::STOPPING_2;
2951 }
2952 break;
2953 case TrackBase::PAUSING:
2954 // ramp down is not yet implemented
2955 track->setPaused();
2956 break;
2957 case TrackBase::RESUMING:
2958 // ramp up is not yet implemented
2959 track->mState = TrackBase::ACTIVE;
2960 break;
2961 case TrackBase::ACTIVE:
2962 if (recentFull > 0 || recentPartial > 0) {
2963 // track has provided at least some frames recently: reset retry count
2964 track->mRetryCount = kMaxTrackRetries;
2965 }
2966 if (recentUnderruns == 0) {
2967 // no recent underruns: stay active
2968 break;
2969 }
2970 // there has recently been an underrun of some kind
2971 if (track->sharedBuffer() == 0) {
2972 // were any of the recent underruns "empty" (no frames available)?
2973 if (recentEmpty == 0) {
2974 // no, then ignore the partial underruns as they are allowed indefinitely
2975 break;
2976 }
2977 // there has recently been an "empty" underrun: decrement the retry counter
2978 if (--(track->mRetryCount) > 0) {
2979 break;
2980 }
2981 // indicate to client process that the track was disabled because of underrun;
2982 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002983 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002984 // remove from active list, but state remains ACTIVE [confusing but true]
2985 isActive = false;
2986 break;
2987 }
2988 // fall through
2989 case TrackBase::STOPPING_2:
2990 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002991 case TrackBase::STOPPED:
2992 case TrackBase::FLUSHED: // flush() while active
2993 // Check for presentation complete if track is inactive
2994 // We have consumed all the buffers of this track.
2995 // This would be incomplete if we auto-paused on underrun
2996 {
2997 size_t audioHALFrames =
2998 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2999 size_t framesWritten = mBytesWritten / mFrameSize;
3000 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3001 // track stays in active list until presentation is complete
3002 break;
3003 }
3004 }
3005 if (track->isStopping_2()) {
3006 track->mState = TrackBase::STOPPED;
3007 }
3008 if (track->isStopped()) {
3009 // Can't reset directly, as fast mixer is still polling this track
3010 // track->reset();
3011 // So instead mark this track as needing to be reset after push with ack
3012 resetMask |= 1 << i;
3013 }
3014 isActive = false;
3015 break;
3016 case TrackBase::IDLE:
3017 default:
3018 LOG_FATAL("unexpected track state %d", track->mState);
3019 }
3020
3021 if (isActive) {
3022 // was it previously inactive?
3023 if (!(state->mTrackMask & (1 << j))) {
3024 ExtendedAudioBufferProvider *eabp = track;
3025 VolumeProvider *vp = track;
3026 fastTrack->mBufferProvider = eabp;
3027 fastTrack->mVolumeProvider = vp;
3028 fastTrack->mSampleRate = track->mSampleRate;
3029 fastTrack->mChannelMask = track->mChannelMask;
3030 fastTrack->mGeneration++;
3031 state->mTrackMask |= 1 << j;
3032 didModify = true;
3033 // no acknowledgement required for newly active tracks
3034 }
3035 // cache the combined master volume and stream type volume for fast mixer; this
3036 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003037 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003038 ++fastTracks;
3039 } else {
3040 // was it previously active?
3041 if (state->mTrackMask & (1 << j)) {
3042 fastTrack->mBufferProvider = NULL;
3043 fastTrack->mGeneration++;
3044 state->mTrackMask &= ~(1 << j);
3045 didModify = true;
3046 // If any fast tracks were removed, we must wait for acknowledgement
3047 // because we're about to decrement the last sp<> on those tracks.
3048 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3049 } else {
3050 LOG_FATAL("fast track %d should have been active", j);
3051 }
3052 tracksToRemove->add(track);
3053 // Avoids a misleading display in dumpsys
3054 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3055 }
3056 continue;
3057 }
3058
3059 { // local variable scope to avoid goto warning
3060
3061 audio_track_cblk_t* cblk = track->cblk();
3062
3063 // The first time a track is added we wait
3064 // for all its buffers to be filled before processing it
3065 int name = track->name();
3066 // make sure that we have enough frames to mix one full buffer.
3067 // enforce this condition only once to enable draining the buffer in case the client
3068 // app does not call stop() and relies on underrun to stop:
3069 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3070 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003071 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003072 uint32_t sr = track->sampleRate();
3073 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003074 desiredFrames = mNormalFrameCount;
3075 } else {
3076 // +1 for rounding and +1 for additional sample needed for interpolation
Alok Kediya601e9b52013-09-27 11:55:10 +05303077 if (mSampleRate) {
3078 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
3079 } else {
3080 desiredFrames = 2;
3081 ALOGW("SampleRate is 0");
3082 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003083 // add frames already consumed but not yet released by the resampler
3084 // because cblk->framesReady() will include these frames
3085 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3086 // the minimum track buffer size is normally twice the number of frames necessary
3087 // to fill one buffer and the resampler should not leave more than one buffer worth
3088 // of unreleased frames after each pass, but just in case...
3089 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3090 }
Eric Laurent81784c32012-11-19 14:55:58 -08003091 uint32_t minFrames = 1;
3092 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3093 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003094 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003095 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003096 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
3097 size_t framesReady;
3098 if (track->sharedBuffer() == 0) {
3099 framesReady = track->framesReady();
3100 } else if (track->isStopped()) {
3101 framesReady = 0;
3102 } else {
3103 framesReady = 1;
3104 }
3105 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003106 !track->isPaused() && !track->isTerminated())
3107 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003108 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003109
3110 mixedTracks++;
3111
3112 // track->mainBuffer() != mMixBuffer means there is an effect chain
3113 // connected to the track
3114 chain.clear();
3115 if (track->mainBuffer() != mMixBuffer) {
3116 chain = getEffectChain_l(track->sessionId());
3117 // Delegate volume control to effect in track effect chain if needed
3118 if (chain != 0) {
3119 tracksWithEffect++;
3120 } else {
3121 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3122 "session %d",
3123 name, track->sessionId());
3124 }
3125 }
3126
3127
3128 int param = AudioMixer::VOLUME;
3129 if (track->mFillingUpStatus == Track::FS_FILLED) {
3130 // no ramp for the first volume setting
3131 track->mFillingUpStatus = Track::FS_ACTIVE;
3132 if (track->mState == TrackBase::RESUMING) {
3133 track->mState = TrackBase::ACTIVE;
3134 param = AudioMixer::RAMP_VOLUME;
3135 }
3136 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003137 // FIXME should not make a decision based on mServer
3138 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003139 // If the track is stopped before the first frame was mixed,
3140 // do not apply ramp
3141 param = AudioMixer::RAMP_VOLUME;
3142 }
3143
3144 // compute volume for this track
3145 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003146 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003147 vl = vr = va = 0;
3148 if (track->isPausing()) {
3149 track->setPaused();
3150 }
3151 } else {
3152
3153 // read original volumes with volume control
3154 float typeVolume = mStreamTypes[track->streamType()].volume;
3155 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003156 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003157 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003158 vl = vlr & 0xFFFF;
3159 vr = vlr >> 16;
3160 // track volumes come from shared memory, so can't be trusted and must be clamped
3161 if (vl > MAX_GAIN_INT) {
3162 ALOGV("Track left volume out of range: %04X", vl);
3163 vl = MAX_GAIN_INT;
3164 }
3165 if (vr > MAX_GAIN_INT) {
3166 ALOGV("Track right volume out of range: %04X", vr);
3167 vr = MAX_GAIN_INT;
3168 }
3169 // now apply the master volume and stream type volume
3170 vl = (uint32_t)(v * vl) << 12;
3171 vr = (uint32_t)(v * vr) << 12;
3172 // assuming master volume and stream type volume each go up to 1.0,
3173 // vl and vr are now in 8.24 format
3174
Glenn Kastene3aa6592012-12-04 12:22:46 -08003175 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003176 // send level comes from shared memory and so may be corrupt
3177 if (sendLevel > MAX_GAIN_INT) {
3178 ALOGV("Track send level out of range: %04X", sendLevel);
3179 sendLevel = MAX_GAIN_INT;
3180 }
3181 va = (uint32_t)(v * sendLevel);
3182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183
Eric Laurent81784c32012-11-19 14:55:58 -08003184 // Delegate volume control to effect in track effect chain if needed
3185 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3186 // Do not ramp volume if volume is controlled by effect
3187 param = AudioMixer::VOLUME;
3188 track->mHasVolumeController = true;
3189 } else {
3190 // force no volume ramp when volume controller was just disabled or removed
3191 // from effect chain to avoid volume spike
3192 if (track->mHasVolumeController) {
3193 param = AudioMixer::VOLUME;
3194 }
3195 track->mHasVolumeController = false;
3196 }
3197
3198 // Convert volumes from 8.24 to 4.12 format
3199 // This additional clamping is needed in case chain->setVolume_l() overshot
3200 vl = (vl + (1 << 11)) >> 12;
3201 if (vl > MAX_GAIN_INT) {
3202 vl = MAX_GAIN_INT;
3203 }
3204 vr = (vr + (1 << 11)) >> 12;
3205 if (vr > MAX_GAIN_INT) {
3206 vr = MAX_GAIN_INT;
3207 }
3208
3209 if (va > MAX_GAIN_INT) {
3210 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3211 }
3212
3213 // XXX: these things DON'T need to be done each time
3214 mAudioMixer->setBufferProvider(name, track);
3215 mAudioMixer->enable(name);
3216
3217 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3218 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3219 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3220 mAudioMixer->setParameter(
3221 name,
3222 AudioMixer::TRACK,
3223 AudioMixer::FORMAT, (void *)track->format());
3224 mAudioMixer->setParameter(
3225 name,
3226 AudioMixer::TRACK,
3227 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003228 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3229 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003230 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003231 if (reqSampleRate == 0) {
3232 reqSampleRate = mSampleRate;
3233 } else if (reqSampleRate > maxSampleRate) {
3234 reqSampleRate = maxSampleRate;
3235 }
Eric Laurent81784c32012-11-19 14:55:58 -08003236 mAudioMixer->setParameter(
3237 name,
3238 AudioMixer::RESAMPLE,
3239 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003240 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003241 mAudioMixer->setParameter(
3242 name,
3243 AudioMixer::TRACK,
3244 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3245 mAudioMixer->setParameter(
3246 name,
3247 AudioMixer::TRACK,
3248 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3249
3250 // reset retry count
3251 track->mRetryCount = kMaxTrackRetries;
3252
3253 // If one track is ready, set the mixer ready if:
3254 // - the mixer was not ready during previous round OR
3255 // - no other track is not ready
3256 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3257 mixerStatus != MIXER_TRACKS_ENABLED) {
3258 mixerStatus = MIXER_TRACKS_READY;
3259 }
3260 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003261 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003262 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003263 }
Eric Laurent81784c32012-11-19 14:55:58 -08003264 // clear effect chain input buffer if an active track underruns to avoid sending
3265 // previous audio buffer again to effects
3266 chain = getEffectChain_l(track->sessionId());
3267 if (chain != 0) {
3268 chain->clearInputBuffer();
3269 }
3270
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003271 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003272 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3273 track->isStopped() || track->isPaused()) {
3274 // We have consumed all the buffers of this track.
3275 // Remove it from the list of active tracks.
3276 // TODO: use actual buffer filling status instead of latency when available from
3277 // audio HAL
3278 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3279 size_t framesWritten = mBytesWritten / mFrameSize;
3280 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3281 if (track->isStopped()) {
3282 track->reset();
3283 }
3284 tracksToRemove->add(track);
3285 }
3286 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003287 // No buffers for this track. Give it a few chances to
3288 // fill a buffer, then remove it from active list.
3289 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003290 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003291 tracksToRemove->add(track);
3292 // indicate to client process that the track was disabled because of underrun;
3293 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003294 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003295 // If one track is not ready, mark the mixer also not ready if:
3296 // - the mixer was ready during previous round OR
3297 // - no other track is ready
3298 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3299 mixerStatus != MIXER_TRACKS_READY) {
3300 mixerStatus = MIXER_TRACKS_ENABLED;
3301 }
3302 }
3303 mAudioMixer->disable(name);
3304 }
3305
3306 } // local variable scope to avoid goto warning
3307track_is_ready: ;
3308
3309 }
3310
3311 // Push the new FastMixer state if necessary
3312 bool pauseAudioWatchdog = false;
3313 if (didModify) {
3314 state->mFastTracksGen++;
3315 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3316 if (kUseFastMixer == FastMixer_Dynamic &&
3317 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3318 state->mCommand = FastMixerState::COLD_IDLE;
3319 state->mColdFutexAddr = &mFastMixerFutex;
3320 state->mColdGen++;
3321 mFastMixerFutex = 0;
3322 if (kUseFastMixer == FastMixer_Dynamic) {
3323 mNormalSink = mOutputSink;
3324 }
3325 // If we go into cold idle, need to wait for acknowledgement
3326 // so that fast mixer stops doing I/O.
3327 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3328 pauseAudioWatchdog = true;
3329 }
Eric Laurent81784c32012-11-19 14:55:58 -08003330 }
3331 if (sq != NULL) {
3332 sq->end(didModify);
3333 sq->push(block);
3334 }
3335#ifdef AUDIO_WATCHDOG
3336 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3337 mAudioWatchdog->pause();
3338 }
3339#endif
3340
3341 // Now perform the deferred reset on fast tracks that have stopped
3342 while (resetMask != 0) {
3343 size_t i = __builtin_ctz(resetMask);
3344 ALOG_ASSERT(i < count);
3345 resetMask &= ~(1 << i);
3346 sp<Track> t = mActiveTracks[i].promote();
3347 if (t == 0) {
3348 continue;
3349 }
3350 Track* track = t.get();
3351 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3352 track->reset();
3353 }
3354
3355 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003357
3358 // mix buffer must be cleared if all tracks are connected to an
3359 // effect chain as in this case the mixer will not write to
3360 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003361 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3362 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003363 // FIXME as a performance optimization, should remember previous zero status
3364 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3365 }
3366
3367 // if any fast tracks, then status is ready
3368 mMixerStatusIgnoringFastTracks = mixerStatus;
3369 if (fastTracks > 0) {
3370 mixerStatus = MIXER_TRACKS_READY;
3371 }
3372 return mixerStatus;
3373}
3374
3375// getTrackName_l() must be called with ThreadBase::mLock held
3376int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3377{
3378 return mAudioMixer->getTrackName(channelMask, sessionId);
3379}
3380
3381// deleteTrackName_l() must be called with ThreadBase::mLock held
3382void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3383{
3384 ALOGV("remove track (%d) and delete from mixer", name);
3385 mAudioMixer->deleteTrackName(name);
3386}
3387
3388// checkForNewParameters_l() must be called with ThreadBase::mLock held
3389bool AudioFlinger::MixerThread::checkForNewParameters_l()
3390{
3391 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3392 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3393 bool reconfig = false;
3394
3395 while (!mNewParameters.isEmpty()) {
3396
3397 if (mFastMixer != NULL) {
3398 FastMixerStateQueue *sq = mFastMixer->sq();
3399 FastMixerState *state = sq->begin();
3400 if (!(state->mCommand & FastMixerState::IDLE)) {
3401 previousCommand = state->mCommand;
3402 state->mCommand = FastMixerState::HOT_IDLE;
3403 sq->end();
3404 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3405 } else {
3406 sq->end(false /*didModify*/);
3407 }
3408 }
3409
3410 status_t status = NO_ERROR;
3411 String8 keyValuePair = mNewParameters[0];
3412 AudioParameter param = AudioParameter(keyValuePair);
3413 int value;
3414
Alok Kediya601e9b52013-09-27 11:55:10 +05303415#ifdef SRS_PROCESSING
3416 POSTPRO_PATCH_ICS_OUTPROC_MIX_ROUTE(this, param, value);
3417#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003418 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3419 reconfig = true;
3420 }
3421 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3422 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3423 status = BAD_VALUE;
3424 } else {
3425 reconfig = true;
3426 }
3427 }
3428 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003429 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003430 status = BAD_VALUE;
3431 } else {
3432 reconfig = true;
3433 }
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3436 // do not accept frame count changes if tracks are open as the track buffer
3437 // size depends on frame count and correct behavior would not be guaranteed
3438 // if frame count is changed after track creation
3439 if (!mTracks.isEmpty()) {
3440 status = INVALID_OPERATION;
3441 } else {
3442 reconfig = true;
3443 }
3444 }
3445 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3446#ifdef ADD_BATTERY_DATA
3447 // when changing the audio output device, call addBatteryData to notify
3448 // the change
3449 if (mOutDevice != value) {
3450 uint32_t params = 0;
3451 // check whether speaker is on
3452 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3453 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3454 }
3455
3456 audio_devices_t deviceWithoutSpeaker
3457 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3458 // check if any other device (except speaker) is on
3459 if (value & deviceWithoutSpeaker ) {
3460 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3461 }
3462
3463 if (params != 0) {
3464 addBatteryData(params);
3465 }
3466 }
3467#endif
3468
3469 // forward device change to effects that have requested to be
3470 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003471 if (value != AUDIO_DEVICE_NONE) {
3472 mOutDevice = value;
3473 for (size_t i = 0; i < mEffectChains.size(); i++) {
3474 mEffectChains[i]->setDevice_l(mOutDevice);
3475 }
Eric Laurent81784c32012-11-19 14:55:58 -08003476 }
3477 }
3478
3479 if (status == NO_ERROR) {
3480 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3481 keyValuePair.string());
3482 if (!mStandby && status == INVALID_OPERATION) {
3483 mOutput->stream->common.standby(&mOutput->stream->common);
3484 mStandby = true;
3485 mBytesWritten = 0;
3486 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3487 keyValuePair.string());
3488 }
3489 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003490 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003491 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003492 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3493 for (size_t i = 0; i < mTracks.size() ; i++) {
3494 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3495 if (name < 0) {
3496 break;
3497 }
3498 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003499 }
3500 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3501 }
3502 }
3503
3504 mNewParameters.removeAt(0);
3505
3506 mParamStatus = status;
3507 mParamCond.signal();
3508 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3509 // already timed out waiting for the status and will never signal the condition.
3510 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3511 }
3512
3513 if (!(previousCommand & FastMixerState::IDLE)) {
3514 ALOG_ASSERT(mFastMixer != NULL);
3515 FastMixerStateQueue *sq = mFastMixer->sq();
3516 FastMixerState *state = sq->begin();
3517 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3518 state->mCommand = previousCommand;
3519 sq->end();
3520 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3521 }
3522
3523 return reconfig;
3524}
3525
3526
3527void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3528{
3529 const size_t SIZE = 256;
3530 char buffer[SIZE];
3531 String8 result;
3532
3533 PlaybackThread::dumpInternals(fd, args);
3534
3535 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3536 result.append(buffer);
3537 write(fd, result.string(), result.size());
3538
3539 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003540 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003541 copy.dump(fd);
3542
3543#ifdef STATE_QUEUE_DUMP
3544 // Similar for state queue
3545 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3546 observerCopy.dump(fd);
3547 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3548 mutatorCopy.dump(fd);
3549#endif
3550
Glenn Kasten46909e72013-02-26 09:20:22 -08003551#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003552 // Write the tee output to a .wav file
3553 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003554#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003555
3556#ifdef AUDIO_WATCHDOG
3557 if (mAudioWatchdog != 0) {
3558 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3559 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3560 wdCopy.dump(fd);
3561 }
3562#endif
3563}
3564
3565uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3566{
3567 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3568}
3569
3570uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3571{
3572 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3573}
3574
3575void AudioFlinger::MixerThread::cacheParameters_l()
3576{
3577 PlaybackThread::cacheParameters_l();
3578
3579 // FIXME: Relaxed timing because of a certain device that can't meet latency
3580 // Should be reduced to 2x after the vendor fixes the driver issue
3581 // increase threshold again due to low power audio mode. The way this warning
3582 // threshold is calculated and its usefulness should be reconsidered anyway.
3583 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3584}
3585
3586// ----------------------------------------------------------------------------
3587
3588AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3589 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3590 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3591 // mLeftVolFloat, mRightVolFloat
3592{
3593}
3594
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3596 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3597 ThreadBase::type_t type)
3598 : PlaybackThread(audioFlinger, output, id, device, type)
3599 // mLeftVolFloat, mRightVolFloat
3600{
3601}
3602
Eric Laurent81784c32012-11-19 14:55:58 -08003603AudioFlinger::DirectOutputThread::~DirectOutputThread()
3604{
3605}
3606
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3608{
3609 audio_track_cblk_t* cblk = track->cblk();
3610 float left, right;
3611
3612 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3613 left = right = 0;
3614 } else {
3615 float typeVolume = mStreamTypes[track->streamType()].volume;
3616 float v = mMasterVolume * typeVolume;
3617 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3618 uint32_t vlr = proxy->getVolumeLR();
3619 float v_clamped = v * (vlr & 0xFFFF);
3620 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3621 left = v_clamped/MAX_GAIN;
3622 v_clamped = v * (vlr >> 16);
3623 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3624 right = v_clamped/MAX_GAIN;
3625 }
3626
3627 if (lastTrack) {
3628 if (left != mLeftVolFloat || right != mRightVolFloat) {
3629 mLeftVolFloat = left;
3630 mRightVolFloat = right;
3631
3632 // Convert volumes from float to 8.24
3633 uint32_t vl = (uint32_t)(left * (1 << 24));
3634 uint32_t vr = (uint32_t)(right * (1 << 24));
3635
3636 // Delegate volume control to effect in track effect chain if needed
3637 // only one effect chain can be present on DirectOutputThread, so if
3638 // there is one, the track is connected to it
3639 if (!mEffectChains.isEmpty()) {
3640 mEffectChains[0]->setVolume_l(&vl, &vr);
3641 left = (float)vl / (1 << 24);
3642 right = (float)vr / (1 << 24);
3643 }
3644 if (mOutput->stream->set_volume) {
3645 mOutput->stream->set_volume(mOutput->stream, left, right);
3646 }
3647 }
3648 }
3649}
3650
3651
Eric Laurent81784c32012-11-19 14:55:58 -08003652AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3653 Vector< sp<Track> > *tracksToRemove
3654)
3655{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003656 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003657 mixer_state mixerStatus = MIXER_IDLE;
3658
3659 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003660 for (size_t i = 0; i < count; i++) {
3661 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003662 // The track died recently
3663 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003664 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003665 }
3666
3667 Track* const track = t.get();
3668 audio_track_cblk_t* cblk = track->cblk();
3669
3670 // The first time a track is added we wait
3671 // for all its buffers to be filled before processing it
3672 uint32_t minFrames;
3673 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3674 minFrames = mNormalFrameCount;
3675 } else {
3676 minFrames = 1;
3677 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 // Only consider last track started for volume and mixer state control.
3679 // This is the last entry in mActiveTracks unless a track underruns.
3680 // As we only care about the transition phase between two tracks on a
3681 // direct output, it is not a problem to ignore the underrun case.
3682 bool last = (i == (count - 1));
3683
Eric Laurent81784c32012-11-19 14:55:58 -08003684 if ((track->framesReady() >= minFrames) && track->isReady() &&
3685 !track->isPaused() && !track->isTerminated())
3686 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003687 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003688
3689 if (track->mFillingUpStatus == Track::FS_FILLED) {
3690 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003691 // make sure processVolume_l() will apply new volume even if 0
3692 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003693 if (track->mState == TrackBase::RESUMING) {
3694 track->mState = TrackBase::ACTIVE;
3695 }
3696 }
3697
3698 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003699 processVolume_l(track, last);
3700 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003701 // reset retry count
3702 track->mRetryCount = kMaxTrackRetriesDirect;
3703 mActiveTrack = t;
3704 mixerStatus = MIXER_TRACKS_READY;
3705 }
Eric Laurent81784c32012-11-19 14:55:58 -08003706 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003707 // clear effect chain input buffer if the last active track started underruns
3708 // to avoid sending previous audio buffer again to effects
3709 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003710 mEffectChains[0]->clearInputBuffer();
3711 }
3712
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003713 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3715 track->isStopped() || track->isPaused()) {
3716 // We have consumed all the buffers of this track.
3717 // Remove it from the list of active tracks.
3718 // TODO: implement behavior for compressed audio
3719 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3720 size_t framesWritten = mBytesWritten / mFrameSize;
Santhosh Kumar Thimmanna Bhattar03fd1d52013-10-30 11:29:19 +05303721 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames) ||
3722 track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003723 if (track->isStopped()) {
3724 track->reset();
3725 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003726 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728 } else {
3729 // No buffers for this track. Give it a few chances to
3730 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003731 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003732 if (--(track->mRetryCount) <= 0) {
3733 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003734 tracksToRemove->add(track);
Alok Kediya601e9b52013-09-27 11:55:10 +05303735 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003737 mixerStatus = MIXER_TRACKS_ENABLED;
3738 }
3739 }
3740 }
3741 }
3742
Eric Laurent81784c32012-11-19 14:55:58 -08003743 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003744 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003745
3746 return mixerStatus;
3747}
3748
3749void AudioFlinger::DirectOutputThread::threadLoop_mix()
3750{
Eric Laurent81784c32012-11-19 14:55:58 -08003751 size_t frameCount = mFrameCount;
3752 int8_t *curBuf = (int8_t *)mMixBuffer;
3753 // output audio to hardware
3754 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003755 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003756 buffer.frameCount = frameCount;
3757 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003758 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759 memset(curBuf, 0, frameCount * mFrameSize);
3760 break;
3761 }
3762 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3763 frameCount -= buffer.frameCount;
3764 curBuf += buffer.frameCount * mFrameSize;
3765 mActiveTrack->releaseBuffer(&buffer);
3766 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003768 sleepTime = 0;
3769 standbyTime = systemTime() + standbyDelay;
3770 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003771}
3772
3773void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3774{
3775 if (sleepTime == 0) {
3776 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3777 sleepTime = activeSleepTime;
3778 } else {
3779 sleepTime = idleSleepTime;
3780 }
3781 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3782 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3783 sleepTime = 0;
3784 }
3785}
3786
3787// getTrackName_l() must be called with ThreadBase::mLock held
3788int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3789 int sessionId)
3790{
3791 return 0;
3792}
3793
3794// deleteTrackName_l() must be called with ThreadBase::mLock held
3795void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3796{
3797}
3798
3799// checkForNewParameters_l() must be called with ThreadBase::mLock held
3800bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3801{
3802 bool reconfig = false;
3803
3804 while (!mNewParameters.isEmpty()) {
3805 status_t status = NO_ERROR;
3806 String8 keyValuePair = mNewParameters[0];
3807 AudioParameter param = AudioParameter(keyValuePair);
3808 int value;
3809
3810 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3811 // do not accept frame count changes if tracks are open as the track buffer
3812 // size depends on frame count and correct behavior would not be garantied
3813 // if frame count is changed after track creation
3814 if (!mTracks.isEmpty()) {
3815 status = INVALID_OPERATION;
3816 } else {
3817 reconfig = true;
3818 }
3819 }
3820 if (status == NO_ERROR) {
3821 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3822 keyValuePair.string());
3823 if (!mStandby && status == INVALID_OPERATION) {
3824 mOutput->stream->common.standby(&mOutput->stream->common);
3825 mStandby = true;
3826 mBytesWritten = 0;
3827 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3828 keyValuePair.string());
3829 }
3830 if (status == NO_ERROR && reconfig) {
3831 readOutputParameters();
3832 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3833 }
3834 }
3835
3836 mNewParameters.removeAt(0);
3837
3838 mParamStatus = status;
3839 mParamCond.signal();
3840 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3841 // already timed out waiting for the status and will never signal the condition.
3842 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3843 }
3844 return reconfig;
3845}
3846
3847uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3848{
3849 uint32_t time;
3850 if (audio_is_linear_pcm(mFormat)) {
3851 time = PlaybackThread::activeSleepTimeUs();
3852 } else {
3853 time = 10000;
3854 }
3855 return time;
3856}
3857
3858uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3859{
3860 uint32_t time;
3861 if (audio_is_linear_pcm(mFormat)) {
3862 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3863 } else {
3864 time = 10000;
3865 }
3866 return time;
3867}
3868
3869uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3870{
3871 uint32_t time;
3872 if (audio_is_linear_pcm(mFormat)) {
3873 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3874 } else {
3875 time = 10000;
3876 }
3877 return time;
3878}
3879
3880void AudioFlinger::DirectOutputThread::cacheParameters_l()
3881{
3882 PlaybackThread::cacheParameters_l();
3883
3884 // use shorter standby delay as on normal output to release
3885 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003886 if (audio_is_linear_pcm(mFormat)) {
3887 standbyDelay = microseconds(activeSleepTime*2);
3888 } else {
3889 standbyDelay = kOffloadStandbyDelayNs;
3890 }
Eric Laurent81784c32012-11-19 14:55:58 -08003891}
3892
3893// ----------------------------------------------------------------------------
3894
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003896 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003898 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003899 mWriteAckSequence(0),
3900 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901{
3902}
3903
3904AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3905{
3906}
3907
3908void AudioFlinger::AsyncCallbackThread::onFirstRef()
3909{
3910 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3911}
3912
3913bool AudioFlinger::AsyncCallbackThread::threadLoop()
3914{
3915 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003916 uint32_t writeAckSequence;
3917 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918
3919 {
3920 Mutex::Autolock _l(mLock);
3921 mWaitWorkCV.wait(mLock);
3922 if (exitPending()) {
3923 break;
3924 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003925 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3926 mWriteAckSequence, mDrainSequence);
3927 writeAckSequence = mWriteAckSequence;
3928 mWriteAckSequence &= ~1;
3929 drainSequence = mDrainSequence;
3930 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 }
3932 {
Eric Laurent4de95592013-09-26 15:28:21 -07003933 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3934 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003935 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003936 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003937 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003938 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003939 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003940 }
3941 }
3942 }
3943 }
3944 return false;
3945}
3946
3947void AudioFlinger::AsyncCallbackThread::exit()
3948{
3949 ALOGV("AsyncCallbackThread::exit");
3950 Mutex::Autolock _l(mLock);
3951 requestExit();
3952 mWaitWorkCV.broadcast();
3953}
3954
Eric Laurent3b4529e2013-09-05 18:09:19 -07003955void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003956{
3957 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003958 // bit 0 is cleared
3959 mWriteAckSequence = sequence << 1;
3960}
3961
3962void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3963{
3964 Mutex::Autolock _l(mLock);
3965 // ignore unexpected callbacks
3966 if (mWriteAckSequence & 2) {
3967 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003968 mWaitWorkCV.signal();
3969 }
3970}
3971
Eric Laurent3b4529e2013-09-05 18:09:19 -07003972void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973{
3974 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003975 // bit 0 is cleared
3976 mDrainSequence = sequence << 1;
3977}
3978
3979void AudioFlinger::AsyncCallbackThread::resetDraining()
3980{
3981 Mutex::Autolock _l(mLock);
3982 // ignore unexpected callbacks
3983 if (mDrainSequence & 2) {
3984 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003985 mWaitWorkCV.signal();
3986 }
3987}
3988
3989
3990// ----------------------------------------------------------------------------
3991AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3992 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3993 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3994 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003995 mFlushPending(false),
Eric Laurent6a99d202013-10-17 18:59:26 -07003996 mPausedBytesRemaining(0),
3997 mPreviousTrack(NULL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003998{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003999}
4000
Eric Laurentbfb1b832013-01-07 09:53:42 -08004001void AudioFlinger::OffloadThread::threadLoop_exit()
4002{
4003 if (mFlushPending || mHwPaused) {
4004 // If a flush is pending or track was paused, just discard buffered data
4005 flushHw_l();
4006 } else {
4007 mMixerStatus = MIXER_DRAIN_ALL;
4008 threadLoop_drain();
4009 }
4010 mCallbackThread->exit();
4011 PlaybackThread::threadLoop_exit();
4012}
4013
4014AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4015 Vector< sp<Track> > *tracksToRemove
4016)
4017{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004018 size_t count = mActiveTracks.size();
4019
4020 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004021 bool doHwPause = false;
4022 bool doHwResume = false;
4023
Eric Laurentede6c3b2013-09-19 14:37:46 -07004024 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4025
Eric Laurentbfb1b832013-01-07 09:53:42 -08004026 // find out which tracks need to be processed
4027 for (size_t i = 0; i < count; i++) {
4028 sp<Track> t = mActiveTracks[i].promote();
4029 // The track died recently
4030 if (t == 0) {
4031 continue;
4032 }
4033 Track* const track = t.get();
4034 audio_track_cblk_t* cblk = track->cblk();
4035 if (mPreviousTrack != NULL) {
Eric Laurent6a99d202013-10-17 18:59:26 -07004036 if (t.get() != mPreviousTrack) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004037 // Flush any data still being written from last track
4038 mBytesRemaining = 0;
4039 if (mPausedBytesRemaining) {
4040 // Last track was paused so we also need to flush saved
4041 // mixbuffer state and invalidate track so that it will
4042 // re-submit that unwritten data when it is next resumed
4043 mPausedBytesRemaining = 0;
4044 // Invalidate is a bit drastic - would be more efficient
4045 // to have a flag to tell client that some of the
4046 // previously written data was lost
4047 mPreviousTrack->invalidate();
4048 }
4049 }
4050 }
Eric Laurent6a99d202013-10-17 18:59:26 -07004051 mPreviousTrack = t.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004052 bool last = (i == (count - 1));
4053 if (track->isPausing()) {
4054 track->setPaused();
4055 if (last) {
4056 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004057 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004058 mHwPaused = true;
4059 }
4060 // If we were part way through writing the mixbuffer to
4061 // the HAL we must save this until we resume
4062 // BUG - this will be wrong if a different track is made active,
4063 // in that case we want to discard the pending data in the
4064 // mixbuffer and tell the client to present it again when the
4065 // track is resumed
4066 mPausedWriteLength = mCurrentWriteLength;
4067 mPausedBytesRemaining = mBytesRemaining;
4068 mBytesRemaining = 0; // stop writing
4069 }
4070 tracksToRemove->add(track);
4071 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004072 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004073 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004074 if (track->mFillingUpStatus == Track::FS_FILLED) {
4075 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004076 // make sure processVolume_l() will apply new volume even if 0
4077 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004079 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004080 if (last) {
4081 if (mPausedBytesRemaining) {
4082 // Need to continue write that was interrupted
4083 mCurrentWriteLength = mPausedWriteLength;
4084 mBytesRemaining = mPausedBytesRemaining;
4085 mPausedBytesRemaining = 0;
4086 }
4087 if (mHwPaused) {
4088 doHwResume = true;
4089 mHwPaused = false;
4090 // threadLoop_mix() will handle the case that we need to
4091 // resume an interrupted write
4092 }
4093 // enable write to audio HAL
4094 sleepTime = 0;
4095 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 }
4097 }
4098
4099 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 // reset retry count
4101 track->mRetryCount = kMaxTrackRetriesOffload;
4102 mActiveTrack = t;
4103 mixerStatus = MIXER_TRACKS_READY;
4104 }
4105 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004106 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 if (track->isStopping_1()) {
4108 // Hardware buffer can hold a large amount of audio so we must
4109 // wait for all current track's data to drain before we say
4110 // that the track is stopped.
4111 if (mBytesRemaining == 0) {
4112 // Only start draining when all data in mixbuffer
4113 // has been written
4114 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4115 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a99d202013-10-17 18:59:26 -07004116 // do not drain if no data was ever sent to HAL (mStandby == true)
4117 if (last && !mStandby) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07004118 sleepTime = 0;
4119 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004120 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07004121 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004122 if (mHwPaused) {
4123 // It is possible to move from PAUSED to STOPPING_1 without
4124 // a resume so we must ensure hardware is running
4125 mOutput->stream->resume(mOutput->stream);
4126 mHwPaused = false;
4127 }
4128 }
4129 }
4130 } else if (track->isStopping_2()) {
Eric Laurent6a99d202013-10-17 18:59:26 -07004131 // Drain has completed or we are in standby, signal presentation complete
4132 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 track->mState = TrackBase::STOPPED;
4134 size_t audioHALFrames =
4135 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4136 size_t framesWritten =
4137 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4138 track->presentationComplete(framesWritten, audioHALFrames);
4139 track->reset();
4140 tracksToRemove->add(track);
4141 }
4142 } else {
4143 // No buffers for this track. Give it a few chances to
4144 // fill a buffer, then remove it from active list.
4145 if (--(track->mRetryCount) <= 0) {
4146 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4147 track->name());
4148 tracksToRemove->add(track);
4149 } else if (last){
4150 mixerStatus = MIXER_TRACKS_ENABLED;
4151 }
4152 }
4153 }
4154 // compute volume for this track
4155 processVolume_l(track, last);
4156 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004157
Eric Laurentea0fade2013-10-04 16:23:48 -07004158 // make sure the pause/flush/resume sequence is executed in the right order.
4159 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4160 // before flush and then resume HW. This can happen in case of pause/flush/resume
4161 // if resume is received before pause is executed.
4162 if (doHwPause || (mFlushPending && !mHwPaused && (count != 0))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004163 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004164 if (!doHwPause) {
4165 doHwResume = true;
4166 }
Eric Laurent972a1732013-09-04 09:42:59 -07004167 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004168 if (mFlushPending) {
4169 flushHw_l();
4170 mFlushPending = false;
4171 }
Eric Laurent972a1732013-09-04 09:42:59 -07004172 if (doHwResume) {
4173 mOutput->stream->resume(mOutput->stream);
4174 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004175
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176 // remove all the tracks that need to be...
4177 removeTracks_l(*tracksToRemove);
4178
4179 return mixerStatus;
4180}
4181
4182void AudioFlinger::OffloadThread::flushOutput_l()
4183{
4184 mFlushPending = true;
4185}
4186
4187// must be called with thread mutex locked
4188bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4189{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004190 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4191 mWriteAckSequence, mDrainSequence);
4192 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 return true;
4194 }
4195 return false;
4196}
4197
4198// must be called with thread mutex locked
4199bool AudioFlinger::OffloadThread::shouldStandby_l()
4200{
4201 bool TrackPaused = false;
4202
4203 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4204 // after a timeout and we will enter standby then.
4205 if (mTracks.size() > 0) {
4206 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4207 }
4208
4209 return !mStandby && !TrackPaused;
4210}
4211
4212
4213bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4214{
4215 Mutex::Autolock _l(mLock);
4216 return waitingAsyncCallback_l();
4217}
4218
4219void AudioFlinger::OffloadThread::flushHw_l()
4220{
4221 mOutput->stream->flush(mOutput->stream);
4222 // Flush anything still waiting in the mixbuffer
4223 mCurrentWriteLength = 0;
4224 mBytesRemaining = 0;
4225 mPausedWriteLength = 0;
4226 mPausedBytesRemaining = 0;
4227 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004228 // discard any pending drain or write ack by incrementing sequence
4229 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4230 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004231 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004232 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4233 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004234 }
4235}
4236
4237// ----------------------------------------------------------------------------
4238
Eric Laurent81784c32012-11-19 14:55:58 -08004239AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4240 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4241 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4242 DUPLICATING),
4243 mWaitTimeMs(UINT_MAX)
4244{
4245 addOutputTrack(mainThread);
4246}
4247
4248AudioFlinger::DuplicatingThread::~DuplicatingThread()
4249{
4250 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4251 mOutputTracks[i]->destroy();
4252 }
4253}
4254
4255void AudioFlinger::DuplicatingThread::threadLoop_mix()
4256{
4257 // mix buffers...
4258 if (outputsReady(outputTracks)) {
4259 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4260 } else {
4261 memset(mMixBuffer, 0, mixBufferSize);
4262 }
4263 sleepTime = 0;
4264 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004265 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004266 standbyTime = systemTime() + standbyDelay;
4267}
4268
4269void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4270{
4271 if (sleepTime == 0) {
4272 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4273 sleepTime = activeSleepTime;
4274 } else {
4275 sleepTime = idleSleepTime;
4276 }
4277 } else if (mBytesWritten != 0) {
4278 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4279 writeFrames = mNormalFrameCount;
4280 memset(mMixBuffer, 0, mixBufferSize);
4281 } else {
4282 // flush remaining overflow buffers in output tracks
4283 writeFrames = 0;
4284 }
4285 sleepTime = 0;
4286 }
4287}
4288
Eric Laurentbfb1b832013-01-07 09:53:42 -08004289ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004290{
4291 for (size_t i = 0; i < outputTracks.size(); i++) {
4292 outputTracks[i]->write(mMixBuffer, writeFrames);
4293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004295}
4296
4297void AudioFlinger::DuplicatingThread::threadLoop_standby()
4298{
4299 // DuplicatingThread implements standby by stopping all tracks
4300 for (size_t i = 0; i < outputTracks.size(); i++) {
4301 outputTracks[i]->stop();
4302 }
4303}
4304
4305void AudioFlinger::DuplicatingThread::saveOutputTracks()
4306{
4307 outputTracks = mOutputTracks;
4308}
4309
4310void AudioFlinger::DuplicatingThread::clearOutputTracks()
4311{
4312 outputTracks.clear();
4313}
4314
4315void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4316{
4317 Mutex::Autolock _l(mLock);
4318 // FIXME explain this formula
Alok Kediya601e9b52013-09-27 11:55:10 +05304319 int sampleRate = thread->sampleRate();
4320 size_t frameCount = 0;
4321 if (sampleRate)
4322 frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Eric Laurent81784c32012-11-19 14:55:58 -08004323 OutputTrack *outputTrack = new OutputTrack(thread,
4324 this,
4325 mSampleRate,
4326 mFormat,
4327 mChannelMask,
4328 frameCount);
4329 if (outputTrack->cblk() != NULL) {
4330 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4331 mOutputTracks.add(outputTrack);
4332 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4333 updateWaitTime_l();
4334 }
4335}
4336
4337void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4338{
4339 Mutex::Autolock _l(mLock);
4340 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4341 if (mOutputTracks[i]->thread() == thread) {
4342 mOutputTracks[i]->destroy();
4343 mOutputTracks.removeAt(i);
4344 updateWaitTime_l();
4345 return;
4346 }
4347 }
4348 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4349}
4350
4351// caller must hold mLock
4352void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4353{
4354 mWaitTimeMs = UINT_MAX;
4355 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4356 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4357 if (strong != 0) {
4358 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4359 if (waitTimeMs < mWaitTimeMs) {
4360 mWaitTimeMs = waitTimeMs;
4361 }
4362 }
4363 }
4364}
4365
4366
4367bool AudioFlinger::DuplicatingThread::outputsReady(
4368 const SortedVector< sp<OutputTrack> > &outputTracks)
4369{
4370 for (size_t i = 0; i < outputTracks.size(); i++) {
4371 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4372 if (thread == 0) {
4373 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4374 outputTracks[i].get());
4375 return false;
4376 }
4377 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4378 // see note at standby() declaration
4379 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4380 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4381 thread.get());
4382 return false;
4383 }
4384 }
4385 return true;
4386}
4387
4388uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4389{
4390 return (mWaitTimeMs * 1000) / 2;
4391}
4392
4393void AudioFlinger::DuplicatingThread::cacheParameters_l()
4394{
4395 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4396 updateWaitTime_l();
4397
4398 MixerThread::cacheParameters_l();
4399}
4400
4401// ----------------------------------------------------------------------------
4402// Record
4403// ----------------------------------------------------------------------------
4404
4405AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4406 AudioStreamIn *input,
4407 uint32_t sampleRate,
4408 audio_channel_mask_t channelMask,
4409 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004410 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004411 audio_devices_t inDevice
4412#ifdef TEE_SINK
4413 , const sp<NBAIO_Sink>& teeSink
4414#endif
4415 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004416 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004417 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004418 // mRsmpInIndex and mBufferSize set by readInputParameters()
Alok Kediya601e9b52013-09-27 11:55:10 +05304419 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004420 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004421 // mBytesRead is only meaningful while active, and so is cleared in start()
4422 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004423#ifdef TEE_SINK
4424 , mTeeSink(teeSink)
4425#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004426{
4427 snprintf(mName, kNameLength, "AudioIn_%X", id);
4428
4429 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004430 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004431}
4432
4433
4434AudioFlinger::RecordThread::~RecordThread()
4435{
4436 delete[] mRsmpInBuffer;
4437 delete mResampler;
4438 delete[] mRsmpOutBuffer;
4439}
4440
4441void AudioFlinger::RecordThread::onFirstRef()
4442{
4443 run(mName, PRIORITY_URGENT_AUDIO);
4444}
4445
4446status_t AudioFlinger::RecordThread::readyToRun()
4447{
4448 status_t status = initCheck();
4449 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4450 return status;
4451}
4452
4453bool AudioFlinger::RecordThread::threadLoop()
4454{
4455 AudioBufferProvider::Buffer buffer;
4456 sp<RecordTrack> activeTrack;
4457 Vector< sp<EffectChain> > effectChains;
4458
4459 nsecs_t lastWarning = 0;
4460
4461 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004462 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004463
4464 // used to verify we've read at least once before evaluating how many bytes were read
4465 bool readOnce = false;
4466
4467 // start recording
4468 while (!exitPending()) {
4469
4470 processConfigEvents();
4471
4472 { // scope for mLock
4473 Mutex::Autolock _l(mLock);
4474 checkForNewParameters_l();
4475 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4476 standby();
4477
4478 if (exitPending()) {
4479 break;
4480 }
4481
4482 releaseWakeLock_l();
4483 ALOGV("RecordThread: loop stopping");
4484 // go to sleep
4485 mWaitWorkCV.wait(mLock);
4486 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004487 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004488 continue;
4489 }
4490 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491 if (mActiveTrack->isTerminated()) {
4492 removeTrack_l(mActiveTrack);
4493 mActiveTrack.clear();
4494 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004495 standby();
4496 mActiveTrack.clear();
4497 mStartStopCond.broadcast();
4498 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4499 if (mReqChannelCount != mActiveTrack->channelCount()) {
4500 mActiveTrack.clear();
4501 mStartStopCond.broadcast();
4502 } else if (readOnce) {
4503 // record start succeeds only if first read from audio input
4504 // succeeds
4505 if (mBytesRead >= 0) {
4506 mActiveTrack->mState = TrackBase::ACTIVE;
4507 } else {
4508 mActiveTrack.clear();
4509 }
4510 mStartStopCond.broadcast();
4511 }
4512 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004513 }
4514 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004515
Eric Laurent81784c32012-11-19 14:55:58 -08004516 lockEffectChains_l(effectChains);
4517 }
4518
4519 if (mActiveTrack != 0) {
4520 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4521 mActiveTrack->mState != TrackBase::RESUMING) {
4522 unlockEffectChains(effectChains);
4523 usleep(kRecordThreadSleepUs);
4524 continue;
4525 }
4526 for (size_t i = 0; i < effectChains.size(); i ++) {
4527 effectChains[i]->process_l();
4528 }
4529
4530 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004531 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004532 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004533 readOnce = true;
4534 size_t framesOut = buffer.frameCount;
4535 if (mResampler == NULL) {
4536 // no resampling
4537 while (framesOut) {
4538 size_t framesIn = mFrameCount - mRsmpInIndex;
4539 if (framesIn) {
4540 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4541 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4542 mActiveTrack->mFrameSize;
4543 if (framesIn > framesOut)
4544 framesIn = framesOut;
4545 mRsmpInIndex += framesIn;
4546 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004547 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004548 memcpy(dst, src, framesIn * mFrameSize);
4549 } else {
4550 if (mChannelCount == 1) {
4551 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4552 (int16_t *)src, framesIn);
4553 } else {
4554 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4555 (int16_t *)src, framesIn);
4556 }
4557 }
4558 }
Alok Kediya601e9b52013-09-27 11:55:10 +05304559 if (framesOut && (mFrameCount == mRsmpInIndex)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004560 void *readInto;
Ethan Chen8d420ed2013-11-14 00:40:54 -08004561#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05304562 int InputBytes;
4563 /*Fix me: How does framesOut become 0 in this condition */
4564 if (( framesOut != mFrameCount) &&
4565 ((mFormat != AUDIO_FORMAT_PCM_16_BIT)&&
4566 (!(mActiveTrack->mFlags & TRACK_VOICE_COMMUNICATION)))) {
4567 readInto = buffer.raw;
4568 InputBytes = buffer.frameCount * mFrameSize;
4569 } else if (framesOut == mFrameCount &&
4570 (mChannelCount == mReqChannelCount ||
4571 ((mFormat != AUDIO_FORMAT_PCM_16_BIT) &&
4572 (!(mActiveTrack->mFlags & TRACK_VOICE_COMMUNICATION))))) {
4573 readInto = buffer.raw;
4574 InputBytes = mBufferSize;
4575 framesOut = 0;
4576 } else {
4577 readInto = mRsmpInBuffer;
4578 mRsmpInIndex = 0;
4579 InputBytes = mBufferSize;
4580 }
Ethan Chen8d420ed2013-11-14 00:40:54 -08004581#else
4582 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4583 readInto = buffer.raw;
4584 framesOut = 0;
4585 } else {
4586 readInto = mRsmpInBuffer;
4587 mRsmpInIndex = 0;
4588 }
4589#endif
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004590 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Ethan Chen8d420ed2013-11-14 00:40:54 -08004591#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05304592 InputBytes);
Ethan Chen8d420ed2013-11-14 00:40:54 -08004593#else
4594 mBufferSize);
4595#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004596 if (mBytesRead <= 0) {
4597 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4598 {
4599 ALOGE("Error reading audio input");
4600 // Force input into standby so that it tries to
4601 // recover at next read attempt
4602 inputStandBy();
4603 usleep(kRecordThreadSleepUs);
4604 }
4605 mRsmpInIndex = mFrameCount;
4606 framesOut = 0;
4607 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004608 }
4609#ifdef TEE_SINK
4610 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004611 (void) mTeeSink->write(readInto,
4612 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4613 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004614#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004615 }
4616 }
4617 } else {
4618 // resampling
4619
Glenn Kasten34af0262013-07-30 11:52:39 -07004620 // resampler accumulates, but we only have one source track
4621 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004622 // alter output frame count as if we were expecting stereo samples
4623 if (mChannelCount == 1 && mReqChannelCount == 1) {
4624 framesOut >>= 1;
4625 }
4626 mResampler->resample(mRsmpOutBuffer, framesOut,
4627 this /* AudioBufferProvider* */);
4628 // ditherAndClamp() works as long as all buffers returned by
4629 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4630 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004631 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004632 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4633 // the resampler always outputs stereo samples:
4634 // do post stereo to mono conversion
4635 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4636 framesOut);
4637 } else {
4638 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4639 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004640 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004641
4642 }
4643 if (mFramestoDrop == 0) {
4644 mActiveTrack->releaseBuffer(&buffer);
4645 } else {
4646 if (mFramestoDrop > 0) {
4647 mFramestoDrop -= buffer.frameCount;
4648 if (mFramestoDrop <= 0) {
4649 clearSyncStartEvent();
4650 }
4651 } else {
4652 mFramestoDrop += buffer.frameCount;
4653 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4654 mSyncStartEvent->isCancelled()) {
4655 ALOGW("Synced record %s, session %d, trigger session %d",
4656 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4657 mActiveTrack->sessionId(),
4658 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4659 clearSyncStartEvent();
4660 }
4661 }
4662 }
4663 mActiveTrack->clearOverflow();
4664 }
4665 // client isn't retrieving buffers fast enough
4666 else {
4667 if (!mActiveTrack->setOverflow()) {
4668 nsecs_t now = systemTime();
4669 if ((now - lastWarning) > kWarningThrottleNs) {
4670 ALOGW("RecordThread: buffer overflow");
4671 lastWarning = now;
4672 }
4673 }
4674 // Release the processor for a while before asking for a new buffer.
4675 // This will give the application more chance to read from the buffer and
4676 // clear the overflow.
4677 usleep(kRecordThreadSleepUs);
4678 }
4679 }
4680 // enable changes in effect chain
4681 unlockEffectChains(effectChains);
4682 effectChains.clear();
4683 }
4684
4685 standby();
4686
4687 {
4688 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004689 for (size_t i = 0; i < mTracks.size(); i++) {
4690 sp<RecordTrack> track = mTracks[i];
4691 track->invalidate();
4692 }
Eric Laurent81784c32012-11-19 14:55:58 -08004693 mActiveTrack.clear();
4694 mStartStopCond.broadcast();
4695 }
4696
4697 releaseWakeLock();
4698
4699 ALOGV("RecordThread %p exiting", this);
4700 return false;
4701}
4702
4703void AudioFlinger::RecordThread::standby()
4704{
4705 if (!mStandby) {
4706 inputStandBy();
4707 mStandby = true;
4708 }
4709}
4710
4711void AudioFlinger::RecordThread::inputStandBy()
4712{
4713 mInput->stream->common.standby(&mInput->stream->common);
4714}
4715
4716sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4717 const sp<AudioFlinger::Client>& client,
4718 uint32_t sampleRate,
4719 audio_format_t format,
4720 audio_channel_mask_t channelMask,
4721 size_t frameCount,
4722 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004723 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004724 pid_t tid,
4725 status_t *status)
4726{
4727 sp<RecordTrack> track;
4728 status_t lStatus;
4729
4730 lStatus = initCheck();
4731 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004732 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004733 goto Exit;
4734 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004735 // client expresses a preference for FAST, but we get the final say
4736 if (*flags & IAudioFlinger::TRACK_FAST) {
4737 if (
4738 // use case: callback handler and frame count is default or at least as large as HAL
4739 (
4740 (tid != -1) &&
4741 ((frameCount == 0) ||
4742 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4743 ) &&
4744 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4745 // mono or stereo
4746 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4747 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4748 // hardware sample rate
4749 (sampleRate == mSampleRate) &&
4750 // record thread has an associated fast recorder
4751 hasFastRecorder()
4752 // FIXME test that RecordThread for this fast track has a capable output HAL
4753 // FIXME add a permission test also?
4754 ) {
4755 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4756 if (frameCount == 0) {
4757 frameCount = mFrameCount * kFastTrackMultiplier;
4758 }
4759 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4760 frameCount, mFrameCount);
4761 } else {
4762 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4763 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4764 "hasFastRecorder=%d tid=%d",
4765 frameCount, mFrameCount, format,
4766 audio_is_linear_pcm(format),
4767 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4768 *flags &= ~IAudioFlinger::TRACK_FAST;
4769 // For compatibility with AudioRecord calculation, buffer depth is forced
4770 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4771 // This is probably too conservative, but legacy application code may depend on it.
4772 // If you change this calculation, also review the start threshold which is related.
4773 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4774 size_t mNormalFrameCount = 2048; // FIXME
Alok Kediya601e9b52013-09-27 11:55:10 +05304775 uint32_t minBufCount = 0;
4776 if (mSampleRate) {
4777 minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4778 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004779 if (minBufCount < 2) {
4780 minBufCount = 2;
4781 }
4782 size_t minFrameCount = mNormalFrameCount * minBufCount;
4783 if (frameCount < minFrameCount) {
4784 frameCount = minFrameCount;
4785 }
4786 }
4787 }
4788
Eric Laurent81784c32012-11-19 14:55:58 -08004789 // FIXME use flags and tid similar to createTrack_l()
4790
4791 { // scope for mLock
4792 Mutex::Autolock _l(mLock);
4793
4794 track = new RecordTrack(this, client, sampleRate,
Ethan Chen8d420ed2013-11-14 00:40:54 -08004795#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05304796 format, channelMask, frameCount, *flags, sessionId);
Ethan Chen8d420ed2013-11-14 00:40:54 -08004797#else
4798 format, channelMask, frameCount, sessionId);
4799#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004800
4801 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004802 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004803 lStatus = NO_MEMORY;
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004804 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004805 goto Exit;
4806 }
4807 mTracks.add(track);
4808
4809 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4810 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4811 mAudioFlinger->btNrecIsOff();
4812 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4813 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004814
4815 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4816 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4817 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4818 // so ask activity manager to do this on our behalf
4819 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4820 }
Eric Laurent81784c32012-11-19 14:55:58 -08004821 }
4822 lStatus = NO_ERROR;
4823
4824Exit:
4825 if (status) {
4826 *status = lStatus;
4827 }
4828 return track;
4829}
4830
4831status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4832 AudioSystem::sync_event_t event,
4833 int triggerSession)
4834{
4835 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4836 sp<ThreadBase> strongMe = this;
4837 status_t status = NO_ERROR;
4838
4839 if (event == AudioSystem::SYNC_EVENT_NONE) {
4840 clearSyncStartEvent();
4841 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4842 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4843 triggerSession,
4844 recordTrack->sessionId(),
4845 syncStartEventCallback,
4846 this);
4847 // Sync event can be cancelled by the trigger session if the track is not in a
4848 // compatible state in which case we start record immediately
4849 if (mSyncStartEvent->isCancelled()) {
4850 clearSyncStartEvent();
4851 } else {
4852 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4853 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4854 }
4855 }
4856
4857 {
4858 AutoMutex lock(mLock);
4859 if (mActiveTrack != 0) {
4860 if (recordTrack != mActiveTrack.get()) {
4861 status = -EBUSY;
4862 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4863 mActiveTrack->mState = TrackBase::ACTIVE;
4864 }
4865 return status;
4866 }
4867
4868 recordTrack->mState = TrackBase::IDLE;
4869 mActiveTrack = recordTrack;
4870 mLock.unlock();
4871 status_t status = AudioSystem::startInput(mId);
4872 mLock.lock();
4873 if (status != NO_ERROR) {
4874 mActiveTrack.clear();
4875 clearSyncStartEvent();
4876 return status;
4877 }
4878 mRsmpInIndex = mFrameCount;
4879 mBytesRead = 0;
4880 if (mResampler != NULL) {
4881 mResampler->reset();
4882 }
4883 mActiveTrack->mState = TrackBase::RESUMING;
4884 // signal thread to start
4885 ALOGV("Signal record thread");
4886 mWaitWorkCV.broadcast();
4887 // do not wait for mStartStopCond if exiting
4888 if (exitPending()) {
4889 mActiveTrack.clear();
4890 status = INVALID_OPERATION;
4891 goto startError;
4892 }
4893 mStartStopCond.wait(mLock);
4894 if (mActiveTrack == 0) {
4895 ALOGV("Record failed to start");
4896 status = BAD_VALUE;
4897 goto startError;
4898 }
4899 ALOGV("Record started OK");
4900 return status;
4901 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004902
Eric Laurent81784c32012-11-19 14:55:58 -08004903startError:
4904 AudioSystem::stopInput(mId);
4905 clearSyncStartEvent();
4906 return status;
4907}
4908
4909void AudioFlinger::RecordThread::clearSyncStartEvent()
4910{
4911 if (mSyncStartEvent != 0) {
4912 mSyncStartEvent->cancel();
4913 }
4914 mSyncStartEvent.clear();
4915 mFramestoDrop = 0;
4916}
4917
4918void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4919{
4920 sp<SyncEvent> strongEvent = event.promote();
4921
4922 if (strongEvent != 0) {
4923 RecordThread *me = (RecordThread *)strongEvent->cookie();
4924 me->handleSyncStartEvent(strongEvent);
4925 }
4926}
4927
4928void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4929{
4930 if (event == mSyncStartEvent) {
4931 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4932 // from audio HAL
4933 mFramestoDrop = mFrameCount * 2;
4934 }
4935}
4936
Glenn Kastena8356f62013-07-25 14:37:52 -07004937bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004938 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004939 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004940 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4941 return false;
4942 }
4943 recordTrack->mState = TrackBase::PAUSING;
4944 // do not wait for mStartStopCond if exiting
4945 if (exitPending()) {
4946 return true;
4947 }
4948 mStartStopCond.wait(mLock);
4949 // if we have been restarted, recordTrack == mActiveTrack.get() here
4950 if (exitPending() || recordTrack != mActiveTrack.get()) {
4951 ALOGV("Record stopped OK");
4952 return true;
4953 }
4954 return false;
4955}
4956
4957bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4958{
4959 return false;
4960}
4961
4962status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4963{
4964#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4965 if (!isValidSyncEvent(event)) {
4966 return BAD_VALUE;
4967 }
4968
4969 int eventSession = event->triggerSession();
4970 status_t ret = NAME_NOT_FOUND;
4971
4972 Mutex::Autolock _l(mLock);
4973
4974 for (size_t i = 0; i < mTracks.size(); i++) {
4975 sp<RecordTrack> track = mTracks[i];
4976 if (eventSession == track->sessionId()) {
4977 (void) track->setSyncEvent(event);
4978 ret = NO_ERROR;
4979 }
4980 }
4981 return ret;
4982#else
4983 return BAD_VALUE;
4984#endif
4985}
4986
4987// destroyTrack_l() must be called with ThreadBase::mLock held
4988void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4989{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004990 track->terminate();
4991 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004992 // active tracks are removed by threadLoop()
4993 if (mActiveTrack != track) {
4994 removeTrack_l(track);
4995 }
4996}
4997
4998void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4999{
5000 mTracks.remove(track);
5001 // need anything related to effects here?
5002}
5003
5004void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5005{
5006 dumpInternals(fd, args);
5007 dumpTracks(fd, args);
5008 dumpEffectChains(fd, args);
5009}
5010
5011void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5012{
5013 const size_t SIZE = 256;
5014 char buffer[SIZE];
5015 String8 result;
5016
5017 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5018 result.append(buffer);
5019
5020 if (mActiveTrack != 0) {
5021 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5022 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08005023 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005024 result.append(buffer);
5025 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5026 result.append(buffer);
5027 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
5028 result.append(buffer);
5029 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
5030 result.append(buffer);
5031 } else {
5032 result.append("No active record client\n");
5033 }
5034
5035 write(fd, result.string(), result.size());
5036
5037 dumpBase(fd, args);
5038}
5039
5040void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
5041{
5042 const size_t SIZE = 256;
5043 char buffer[SIZE];
5044 String8 result;
5045
5046 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5047 result.append(buffer);
5048 RecordTrack::appendDumpHeader(result);
5049 for (size_t i = 0; i < mTracks.size(); ++i) {
5050 sp<RecordTrack> track = mTracks[i];
5051 if (track != 0) {
5052 track->dump(buffer, SIZE);
5053 result.append(buffer);
5054 }
5055 }
5056
5057 if (mActiveTrack != 0) {
5058 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5059 result.append(buffer);
5060 RecordTrack::appendDumpHeader(result);
5061 mActiveTrack->dump(buffer, SIZE);
5062 result.append(buffer);
5063
5064 }
5065 write(fd, result.string(), result.size());
5066}
5067
5068// AudioBufferProvider interface
5069status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5070{
5071 size_t framesReq = buffer->frameCount;
5072 size_t framesReady = mFrameCount - mRsmpInIndex;
5073 int channelCount;
5074
5075 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005076 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005077 if (mBytesRead <= 0) {
5078 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5079 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5080 // Force input into standby so that it tries to
5081 // recover at next read attempt
5082 inputStandBy();
5083 usleep(kRecordThreadSleepUs);
5084 }
5085 buffer->raw = NULL;
5086 buffer->frameCount = 0;
5087 return NOT_ENOUGH_DATA;
5088 }
5089 mRsmpInIndex = 0;
5090 framesReady = mFrameCount;
5091 }
5092
5093 if (framesReq > framesReady) {
5094 framesReq = framesReady;
5095 }
5096
5097 if (mChannelCount == 1 && mReqChannelCount == 2) {
5098 channelCount = 1;
5099 } else {
5100 channelCount = 2;
5101 }
5102 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5103 buffer->frameCount = framesReq;
5104 return NO_ERROR;
5105}
5106
5107// AudioBufferProvider interface
5108void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5109{
5110 mRsmpInIndex += buffer->frameCount;
5111 buffer->frameCount = 0;
5112}
5113
5114bool AudioFlinger::RecordThread::checkForNewParameters_l()
5115{
5116 bool reconfig = false;
5117
5118 while (!mNewParameters.isEmpty()) {
5119 status_t status = NO_ERROR;
5120 String8 keyValuePair = mNewParameters[0];
5121 AudioParameter param = AudioParameter(keyValuePair);
5122 int value;
5123 audio_format_t reqFormat = mFormat;
5124 uint32_t reqSamplingRate = mReqSampleRate;
5125 uint32_t reqChannelCount = mReqChannelCount;
5126
5127 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5128 reqSamplingRate = value;
5129 reconfig = true;
5130 }
5131 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005132 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5133 status = BAD_VALUE;
5134 } else {
5135 reqFormat = (audio_format_t) value;
5136 reconfig = true;
5137 }
Eric Laurent81784c32012-11-19 14:55:58 -08005138 }
5139 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Alok Kediya601e9b52013-09-27 11:55:10 +05305140 reqChannelCount = getInputChannelCount(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005141 reconfig = true;
5142 }
5143 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5144 // do not accept frame count changes if tracks are open as the track buffer
5145 // size depends on frame count and correct behavior would not be guaranteed
5146 // if frame count is changed after track creation
5147 if (mActiveTrack != 0) {
5148 status = INVALID_OPERATION;
5149 } else {
5150 reconfig = true;
5151 }
5152 }
5153 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5154 // forward device change to effects that have requested to be
5155 // aware of attached audio device.
5156 for (size_t i = 0; i < mEffectChains.size(); i++) {
5157 mEffectChains[i]->setDevice_l(value);
5158 }
5159
5160 // store input device and output device but do not forward output device to audio HAL.
5161 // Note that status is ignored by the caller for output device
5162 // (see AudioFlinger::setParameters()
5163 if (audio_is_output_devices(value)) {
5164 mOutDevice = value;
5165 status = BAD_VALUE;
5166 } else {
5167 mInDevice = value;
5168 // disable AEC and NS if the device is a BT SCO headset supporting those
5169 // pre processings
5170 if (mTracks.size() > 0) {
5171 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5172 mAudioFlinger->btNrecIsOff();
5173 for (size_t i = 0; i < mTracks.size(); i++) {
5174 sp<RecordTrack> track = mTracks[i];
5175 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5176 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5177 }
5178 }
5179 }
5180 }
5181 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5182 mAudioSource != (audio_source_t)value) {
5183 // forward device change to effects that have requested to be
5184 // aware of attached audio device.
5185 for (size_t i = 0; i < mEffectChains.size(); i++) {
5186 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5187 }
5188 mAudioSource = (audio_source_t)value;
5189 }
5190 if (status == NO_ERROR) {
5191 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5192 keyValuePair.string());
5193 if (status == INVALID_OPERATION) {
5194 inputStandBy();
5195 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5196 keyValuePair.string());
5197 }
5198 if (reconfig) {
5199 if (status == BAD_VALUE &&
5200 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5201 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005202 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005203 <= (2 * reqSamplingRate)) &&
Alok Kediya601e9b52013-09-27 11:55:10 +05305204 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common))
Eric Laurent81784c32012-11-19 14:55:58 -08005205 <= FCC_2 &&
5206 (reqChannelCount <= FCC_2)) {
5207 status = NO_ERROR;
5208 }
5209 if (status == NO_ERROR) {
5210 readInputParameters();
5211 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5212 }
5213 }
5214 }
5215
5216 mNewParameters.removeAt(0);
5217
5218 mParamStatus = status;
5219 mParamCond.signal();
5220 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5221 // already timed out waiting for the status and will never signal the condition.
5222 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5223 }
5224 return reconfig;
5225}
5226
5227String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5228{
Eric Laurent81784c32012-11-19 14:55:58 -08005229 Mutex::Autolock _l(mLock);
5230 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005231 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005232 }
5233
Glenn Kastend8ea6992013-07-16 14:17:15 -07005234 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5235 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005236 free(s);
5237 return out_s8;
5238}
5239
5240void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5241 AudioSystem::OutputDescriptor desc;
5242 void *param2 = NULL;
5243
5244 switch (event) {
5245 case AudioSystem::INPUT_OPENED:
5246 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005247 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005248 desc.samplingRate = mSampleRate;
5249 desc.format = mFormat;
5250 desc.frameCount = mFrameCount;
5251 desc.latency = 0;
5252 param2 = &desc;
5253 break;
5254
5255 case AudioSystem::INPUT_CLOSED:
5256 default:
5257 break;
5258 }
5259 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5260}
5261
5262void AudioFlinger::RecordThread::readInputParameters()
5263{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005264 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005265 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005266 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005267 mRsmpOutBuffer = NULL;
5268 delete mResampler;
5269 mResampler = NULL;
5270
5271 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5272 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Alok Kediya601e9b52013-09-27 11:55:10 +05305273 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005274 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Ethan Chen8d420ed2013-11-14 00:40:54 -08005275#ifndef QCOM_HARDWARE
5276 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5277 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5278 }
5279#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005280 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005281 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5282 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005283 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5284
5285 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5286 {
5287 int channelCount;
5288 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5289 // stereo to mono post process as the resampler always outputs stereo.
5290 if (mChannelCount == 1 && mReqChannelCount == 2) {
5291 channelCount = 1;
5292 } else {
5293 channelCount = 2;
5294 }
5295 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5296 mResampler->setSampleRate(mSampleRate);
5297 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005298 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005299
5300 // optmization: if mono to mono, alter input frame count as if we were inputing
5301 // stereo samples
5302 if (mChannelCount == 1 && mReqChannelCount == 1) {
5303 mFrameCount >>= 1;
5304 }
5305
5306 }
5307 mRsmpInIndex = mFrameCount;
5308}
5309
5310unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5311{
5312 Mutex::Autolock _l(mLock);
5313 if (initCheck() != NO_ERROR) {
5314 return 0;
5315 }
5316
5317 return mInput->stream->get_input_frames_lost(mInput->stream);
5318}
5319
5320uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5321{
5322 Mutex::Autolock _l(mLock);
5323 uint32_t result = 0;
5324 if (getEffectChain_l(sessionId) != 0) {
5325 result = EFFECT_SESSION;
5326 }
5327
5328 for (size_t i = 0; i < mTracks.size(); ++i) {
5329 if (sessionId == mTracks[i]->sessionId()) {
5330 result |= TRACK_SESSION;
5331 break;
5332 }
5333 }
5334
5335 return result;
5336}
5337
5338KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5339{
5340 KeyedVector<int, bool> ids;
5341 Mutex::Autolock _l(mLock);
5342 for (size_t j = 0; j < mTracks.size(); ++j) {
5343 sp<RecordThread::RecordTrack> track = mTracks[j];
5344 int sessionId = track->sessionId();
5345 if (ids.indexOfKey(sessionId) < 0) {
5346 ids.add(sessionId, true);
5347 }
5348 }
5349 return ids;
5350}
5351
5352AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5353{
5354 Mutex::Autolock _l(mLock);
5355 AudioStreamIn *input = mInput;
5356 mInput = NULL;
5357 return input;
5358}
5359
5360// this method must always be called either with ThreadBase mLock held or inside the thread loop
5361audio_stream_t* AudioFlinger::RecordThread::stream() const
5362{
5363 if (mInput == NULL) {
5364 return NULL;
5365 }
5366 return &mInput->stream->common;
5367}
5368
5369status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5370{
5371 // only one chain per input thread
5372 if (mEffectChains.size() != 0) {
5373 return INVALID_OPERATION;
5374 }
5375 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5376
5377 chain->setInBuffer(NULL);
5378 chain->setOutBuffer(NULL);
5379
5380 checkSuspendOnAddEffectChain_l(chain);
5381
5382 mEffectChains.add(chain);
5383
5384 return NO_ERROR;
5385}
5386
5387size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5388{
5389 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5390 ALOGW_IF(mEffectChains.size() != 1,
5391 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5392 chain.get(), mEffectChains.size(), this);
5393 if (mEffectChains.size() == 1) {
5394 mEffectChains.removeAt(0);
5395 }
5396 return 0;
5397}
5398
Ethan Chen8d420ed2013-11-14 00:40:54 -08005399#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05305400// ----------------------------------------------------------------------------
5401
5402AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
5403 int output, AudioSessionDescriptor *outputDesc,
5404 IDirectTrackClient* client, audio_output_flags_t outflag)
5405 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
5406 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag),
5407 mEffectsThreadScratchBuffer(NULL)
5408{
5409#ifdef SRS_PROCESSING
5410 ALOGD("SRS_Processing - DirectAudioTrack - OutNotify_Init: %p TID %d\n", this, gettid());
5411 POSTPRO_PATCH_ICS_OUTPROC_DIRECT_INIT(this, gettid());
5412 SRS_Processing::ProcessOutRoute(SRS_Processing::AUTO, this, outputDesc->device);
5413#endif
5414 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5415 ALOGV("create effects thread for LPA");
5416 createEffectThread();
5417 allocateBufPool();
5418#ifdef SRS_PROCESSING
5419 } else if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL) {
5420 ALOGV("create effects thread for TUNNEL");
5421 createEffectThread();
5422#endif
5423 }
5424 outputDesc->mVolumeScale = 1.0;
5425 mDeathRecipient = new PMDeathRecipient(this);
5426 acquireWakeLock();
5427}
5428
5429void AudioFlinger::DirectAudioTrack::signalEffect() {
5430 if (mFlag & AUDIO_OUTPUT_FLAG_LPA){
5431 mEffectConfigChanged = true;
5432 mEffectCv.signal();
5433 }
5434#ifdef SRS_PROCESSING
5435 if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL){
5436 mEffectConfigChanged = true;
5437 mEffectCv.signal();
5438 }
5439#endif
5440}
5441
5442AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
5443#ifdef SRS_PROCESSING
5444 ALOGD("SRS_Processing - DirectAudioTrack - OutNotify_Init: %p TID %d\n", this, gettid());
5445 POSTPRO_PATCH_ICS_OUTPROC_DIRECT_EXIT(this, gettid());
5446#endif
5447 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5448 requestAndWaitForEffectsThreadExit();
5449 mAudioFlinger->deleteEffectSession();
5450 deallocateBufPool();
5451#ifdef SRS_PROCESSING
5452 } else if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL) {
5453 requestAndWaitForEffectsThreadExit();
5454 mAudioFlinger->deleteEffectSession();
5455#endif
5456 }
5457 AudioSystem::releaseOutput(mOutput);
5458 releaseWakeLock();
5459
5460 {
5461 Mutex::Autolock _l(pmLock);
5462 if (mPowerManager != 0) {
5463 sp<IBinder> binder = mPowerManager->asBinder();
5464 binder->unlinkToDeath(mDeathRecipient);
5465 }
5466 }
5467}
5468
5469status_t AudioFlinger::DirectAudioTrack::start() {
5470 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5471 if(mIsPaused) {
5472 mIsPaused = false;
5473 mOutputDesc->stream->start(mOutputDesc->stream);
5474 }
5475 mOutputDesc->mActive = true;
5476 mOutputDesc->stream->set_volume(mOutputDesc->stream,
5477 mOutputDesc->mVolumeLeft * mOutputDesc->mVolumeScale,
5478 mOutputDesc->mVolumeRight* mOutputDesc->mVolumeScale);
5479 return NO_ERROR;
5480}
5481
5482void AudioFlinger::DirectAudioTrack::stop() {
5483 ALOGV("DirectAudioTrack::stop");
5484 mOutputDesc->mActive = false;
5485 mOutputDesc->stream->stop(mOutputDesc->stream);
5486 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5487}
5488
5489void AudioFlinger::DirectAudioTrack::pause() {
5490 if(!mIsPaused) {
5491 mIsPaused = true;
5492 mOutputDesc->stream->pause(mOutputDesc->stream);
5493 mOutputDesc->mActive = false;
5494 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5495 }
5496}
5497
5498ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
5499 ALOGV("Writing to AudioSessionOut");
5500 int isAvail = 0;
5501 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
5502 if (!isAvail) {
5503 return 0;
5504 }
5505
5506 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5507 mEffectLock.lock();
5508 List<BufferInfo>::iterator it = mEffectsPool.begin();
5509 BufferInfo buf = *it;
5510 mEffectsPool.erase(it);
5511 memcpy((char *) buf.localBuf, (char *)buffer, size);
5512 buf.bytesToWrite = size;
5513 mEffectsPool.push_back(buf);
5514 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
5515 (int16_t*)buf.localBuf, (int16_t*)buffer, (int)size, true);
5516 mEffectLock.unlock();
5517 }
5518 ALOGV("out of Writing to AudioSessionOut");
5519 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
5520}
5521
5522void AudioFlinger::DirectAudioTrack::flush() {
5523 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5524 mEffectLock.lock();
5525 mEffectsPool.clear();
5526 mEffectsPool = mBufPool;
5527 mEffectLock.unlock();
5528 }
5529 mOutputDesc->stream->flush(mOutputDesc->stream);
5530}
5531
5532void AudioFlinger::DirectAudioTrack::mute(bool muted) {
5533}
5534
5535void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
5536 ALOGV("DirectAudioTrack::setVolume left: %f, right: %f", left, right);
5537 if(mOutputDesc) {
5538 mOutputDesc->mVolumeLeft = left;
5539 mOutputDesc->mVolumeRight = right;
5540 if(mOutputDesc->mActive && mOutputDesc->stream) {
5541 mOutputDesc->stream->set_volume(mOutputDesc->stream,
5542 left * mOutputDesc->mVolumeScale,
5543 right* mOutputDesc->mVolumeScale);
5544 } else {
5545 ALOGD("stream is not active, so cache and send when stream is active");
5546 }
5547 } else {
5548 ALOGD("output descriptor is not valid to set the volume");
5549 }
5550}
5551
5552int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
5553 int64_t time;
5554 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
5555 ALOGV("Timestamp %lld",time);
5556 return time;
5557}
5558
5559void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
5560 if (delayUs == 0 ) {
5561 ALOGV("Notify Audio Track of EOS event");
5562 mClient->notify(DIRECT_TRACK_EOS);
5563 } else {
5564 ALOGV("Notify Audio Track of hardware failure event");
5565 mClient->notify(DIRECT_TRACK_HW_FAIL);
5566 }
5567}
5568
5569void AudioFlinger::DirectAudioTrack::allocateBufPool() {
5570 void *dsp_buf = NULL;
5571 void *local_buf = NULL;
5572
5573 //1. get the ion buffer information
5574 struct buf_info* buf = NULL;
5575 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
5576 ALOGV("get buffer info %p",buf);
5577 if (!buf) {
5578 ALOGV("buffer is NULL");
5579 return;
5580 }
5581 int nSize = buf->bufsize;
5582 int bufferCount = buf->nBufs;
5583
5584 //2. allocate the buffer pool, allocate local buffers
5585 for (int i = 0; i < bufferCount; i++) {
5586 dsp_buf = (void *)buf->buffers[i];
5587 local_buf = malloc(nSize);
5588 memset(local_buf, 0, nSize);
5589 // Store this information for internal mapping / maintanence
5590 BufferInfo buf(local_buf, dsp_buf, nSize);
5591 buf.bytesToWrite = 0;
5592 mBufPool.push_back(buf);
5593 mEffectsPool.push_back(buf);
5594
5595 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
5596 }
5597
5598 mEffectsThreadScratchBuffer = malloc(nSize);
5599 ALOGV("effectsThreadScratchBuffer = %x",mEffectsThreadScratchBuffer);
5600
5601 free(buf);
5602}
5603
5604void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
5605
5606 //1. Deallocate the local memory
5607 //2. Remove all the buffers from bufpool
5608 mEffectLock.lock();
5609 while (!mBufPool.empty()) {
5610 List<BufferInfo>::iterator it = mBufPool.begin();
5611 BufferInfo &memBuffer = *it;
5612 // free the local buffer corresponding to mem buffer
5613 if (memBuffer.localBuf) {
5614 free(memBuffer.localBuf);
5615 memBuffer.localBuf = NULL;
5616 }
5617 ALOGV("Removing from bufpool");
5618 mBufPool.erase(it);
5619 }
5620 mEffectsPool.clear();
5621 mEffectLock.unlock();
5622
5623 free(mEffectsThreadScratchBuffer);
5624 mEffectsThreadScratchBuffer = NULL;
5625}
5626
5627status_t AudioFlinger::DirectAudioTrack::onTransact(
5628 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5629{
5630 return BnDirectTrack::onTransact(code, data, reply, flags);
5631}
5632
5633AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
5634{
5635 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
5636 pBaseClass = (DirectAudioTrack*)obj;
5637}
5638
5639void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
5640 pBaseClass->mAudioFlinger.clear();
5641 ALOGW("AudioFlinger server died!");
5642}
5643
5644void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
5645 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
5646 ALOGV("ioConfigChanged() event %d", event);
5647 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
5648 ALOGV("Received notification for change in effect module");
5649 // Seek to current media time - flush the decoded buffers with the driver
5650 pBaseClass->mEffectConfigChanged = true;
5651 // Signal effects thread to re-apply effects
5652 ALOGV("Signalling Effects Thread");
5653 pBaseClass->mEffectCv.signal();
5654
5655 }
5656 ALOGV("ioConfigChanged Out");
5657}
5658
5659void AudioFlinger::DirectAudioTrack::acquireWakeLock()
5660{
5661 Mutex::Autolock _l(pmLock);
5662
5663 if (mPowerManager == 0) {
5664 // use checkService() to avoid blocking if power service is not up yet
5665 sp<IBinder> binder =
5666 defaultServiceManager()->checkService(String16("power"));
5667 if (binder == 0) {
5668 ALOGW("Thread %s cannot connect to the power manager service", lockName);
5669 } else {
5670 mPowerManager = interface_cast<IPowerManager>(binder);
5671 binder->linkToDeath(mDeathRecipient);
5672 }
5673 }
5674 if (mPowerManager != 0 && mWakeLockToken == 0) {
5675 sp<IBinder> binder = new BBinder();
5676 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
5677 binder,
5678 String16(lockName),
5679 String16("media"));
5680 if (status == NO_ERROR) {
5681 mWakeLockToken = binder;
5682 }
5683 ALOGV("acquireWakeLock() status %d", status);
5684 }
5685}
5686
5687void AudioFlinger::DirectAudioTrack::releaseWakeLock()
5688{
5689 Mutex::Autolock _l(pmLock);
5690
5691 if (mWakeLockToken != 0) {
5692 ALOGV("releaseWakeLock()");
5693 if (mPowerManager != 0) {
5694 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
5695 }
5696 mWakeLockToken.clear();
5697 }
5698}
5699
5700void AudioFlinger::DirectAudioTrack::clearPowerManager()
5701{
5702 releaseWakeLock();
5703 Mutex::Autolock _l(pmLock);
5704 mPowerManager.clear();
5705}
5706
5707void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
5708{
5709 parentClass->clearPowerManager();
5710 ALOGW("power manager service died !!!");
5711}
5712
5713// ----------------------------------------------------------------------------
Ethan Chen8d420ed2013-11-14 00:40:54 -08005714#endif
Alok Kediya601e9b52013-09-27 11:55:10 +05305715
Eric Laurent81784c32012-11-19 14:55:58 -08005716}; // namespace android