blob: 568329f06bfbc05783d04d8d5862ae4a223bb06b [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
Alok Kediya601e9b52013-09-27 11:55:10 +053088#define DIRECT_TRACK_EOS 1
89#define DIRECT_TRACK_HW_FAIL 6
90static const char lockName[] = "DirectTrack";
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
108// maximum time to wait for setParameters to complete
109static const nsecs_t kSetParametersTimeoutNs = seconds(2);
110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
116// minimum normal mix buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalMixBufferSizeMs = 20;
118// maximum normal mix buffer size
119static const uint32_t kMaxNormalMixBufferSizeMs = 24;
120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
141// Priorities for requestPriority
142static const int kPriorityAudioApp = 2;
143static const int kPriorityFastMixer = 3;
144
145// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
146// for the track. The client then sub-divides this into smaller buffers for its use.
147// Currently the client uses double-buffering by default, but doesn't tell us about that.
148// So for now we just assume that client is double-buffered.
149// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
150// N-buffering, so AudioFlinger could allocate the right amount of memory.
151// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800152static const int kFastTrackMultiplier = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800153
154// ----------------------------------------------------------------------------
155
156#ifdef ADD_BATTERY_DATA
157// To collect the amplifier usage
158static void addBatteryData(uint32_t params) {
159 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
160 if (service == NULL) {
161 // it already logged
162 return;
163 }
164
165 service->addBatteryData(params);
166}
167#endif
168
169
170// ----------------------------------------------------------------------------
171// CPU Stats
172// ----------------------------------------------------------------------------
173
174class CpuStats {
175public:
176 CpuStats();
177 void sample(const String8 &title);
178#ifdef DEBUG_CPU_USAGE
179private:
180 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
181 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
182
183 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
184
185 int mCpuNum; // thread's current CPU number
186 int mCpukHz; // frequency of thread's current CPU in kHz
187#endif
188};
189
190CpuStats::CpuStats()
191#ifdef DEBUG_CPU_USAGE
192 : mCpuNum(-1), mCpukHz(-1)
193#endif
194{
195}
196
197void CpuStats::sample(const String8 &title) {
198#ifdef DEBUG_CPU_USAGE
199 // get current thread's delta CPU time in wall clock ns
200 double wcNs;
201 bool valid = mCpuUsage.sampleAndEnable(wcNs);
202
203 // record sample for wall clock statistics
204 if (valid) {
205 mWcStats.sample(wcNs);
206 }
207
208 // get the current CPU number
209 int cpuNum = sched_getcpu();
210
211 // get the current CPU frequency in kHz
212 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
213
214 // check if either CPU number or frequency changed
215 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
216 mCpuNum = cpuNum;
217 mCpukHz = cpukHz;
218 // ignore sample for purposes of cycles
219 valid = false;
220 }
221
222 // if no change in CPU number or frequency, then record sample for cycle statistics
223 if (valid && mCpukHz > 0) {
224 double cycles = wcNs * cpukHz * 0.000001;
225 mHzStats.sample(cycles);
226 }
227
228 unsigned n = mWcStats.n();
229 // mCpuUsage.elapsed() is expensive, so don't call it every loop
230 if ((n & 127) == 1) {
231 long long elapsed = mCpuUsage.elapsed();
232 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
233 double perLoop = elapsed / (double) n;
234 double perLoop100 = perLoop * 0.01;
235 double perLoop1k = perLoop * 0.001;
236 double mean = mWcStats.mean();
237 double stddev = mWcStats.stddev();
238 double minimum = mWcStats.minimum();
239 double maximum = mWcStats.maximum();
240 double meanCycles = mHzStats.mean();
241 double stddevCycles = mHzStats.stddev();
242 double minCycles = mHzStats.minimum();
243 double maxCycles = mHzStats.maximum();
244 mCpuUsage.resetElapsed();
245 mWcStats.reset();
246 mHzStats.reset();
247 ALOGD("CPU usage for %s over past %.1f secs\n"
248 " (%u mixer loops at %.1f mean ms per loop):\n"
249 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
250 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
251 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
252 title.string(),
253 elapsed * .000000001, n, perLoop * .000001,
254 mean * .001,
255 stddev * .001,
256 minimum * .001,
257 maximum * .001,
258 mean / perLoop100,
259 stddev / perLoop100,
260 minimum / perLoop100,
261 maximum / perLoop100,
262 meanCycles / perLoop1k,
263 stddevCycles / perLoop1k,
264 minCycles / perLoop1k,
265 maxCycles / perLoop1k);
266
267 }
268 }
269#endif
270};
271
272// ----------------------------------------------------------------------------
273// ThreadBase
274// ----------------------------------------------------------------------------
275
276AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
277 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
278 : Thread(false /*canCallJava*/),
279 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700280 mAudioFlinger(audioFlinger),
281 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, and mFormat are
282 // set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800283 mParamStatus(NO_ERROR),
284 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
285 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
286 // mName will be set by concrete (non-virtual) subclass
287 mDeathRecipient(new PMDeathRecipient(this))
288{
289}
290
291AudioFlinger::ThreadBase::~ThreadBase()
292{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700293 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
294 for (size_t i = 0; i < mConfigEvents.size(); i++) {
295 delete mConfigEvents[i];
296 }
297 mConfigEvents.clear();
298
Eric Laurent81784c32012-11-19 14:55:58 -0800299 mParamCond.broadcast();
300 // do not lock the mutex in destructor
301 releaseWakeLock_l();
302 if (mPowerManager != 0) {
303 sp<IBinder> binder = mPowerManager->asBinder();
304 binder->unlinkToDeath(mDeathRecipient);
305 }
306}
307
308void AudioFlinger::ThreadBase::exit()
309{
310 ALOGV("ThreadBase::exit");
311 // do any cleanup required for exit to succeed
312 preExit();
313 {
314 // This lock prevents the following race in thread (uniprocessor for illustration):
315 // if (!exitPending()) {
316 // // context switch from here to exit()
317 // // exit() calls requestExit(), what exitPending() observes
318 // // exit() calls signal(), which is dropped since no waiters
319 // // context switch back from exit() to here
320 // mWaitWorkCV.wait(...);
321 // // now thread is hung
322 // }
323 AutoMutex lock(mLock);
324 requestExit();
325 mWaitWorkCV.broadcast();
326 }
327 // When Thread::requestExitAndWait is made virtual and this method is renamed to
328 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
329 requestExitAndWait();
330}
331
332status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
333{
334 status_t status;
335
336 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
337 Mutex::Autolock _l(mLock);
338
339 mNewParameters.add(keyValuePairs);
340 mWaitWorkCV.signal();
341 // wait condition with timeout in case the thread loop has exited
342 // before the request could be processed
343 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
344 status = mParamStatus;
345 mWaitWorkCV.signal();
346 } else {
347 status = TIMED_OUT;
348 }
349 return status;
350}
351
Alok Kediya601e9b52013-09-27 11:55:10 +0530352void AudioFlinger::ThreadBase::effectConfigChanged() {
353 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
354 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
355}
356
Eric Laurent81784c32012-11-19 14:55:58 -0800357void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
358{
359 Mutex::Autolock _l(mLock);
360 sendIoConfigEvent_l(event, param);
361}
362
363// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
364void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
365{
366 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
367 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
368 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
369 param);
370 mWaitWorkCV.signal();
371}
372
373// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
374void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
375{
376 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
377 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
378 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
379 mConfigEvents.size(), pid, tid, prio);
380 mWaitWorkCV.signal();
381}
382
383void AudioFlinger::ThreadBase::processConfigEvents()
384{
385 mLock.lock();
386 while (!mConfigEvents.isEmpty()) {
387 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
388 ConfigEvent *event = mConfigEvents[0];
389 mConfigEvents.removeAt(0);
390 // release mLock before locking AudioFlinger mLock: lock order is always
391 // AudioFlinger then ThreadBase to avoid cross deadlock
392 mLock.unlock();
393 switch(event->type()) {
394 case CFG_EVENT_PRIO: {
395 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700396 // FIXME Need to understand why this has be done asynchronously
397 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
398 true /*asynchronous*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800399 if (err != 0) {
400 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
401 "error %d",
402 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
403 }
404 } break;
405 case CFG_EVENT_IO: {
406 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
407 mAudioFlinger->mLock.lock();
408 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
409 mAudioFlinger->mLock.unlock();
410 } break;
411 default:
412 ALOGE("processConfigEvents() unknown event type %d", event->type());
413 break;
414 }
415 delete event;
416 mLock.lock();
417 }
418 mLock.unlock();
419}
420
421void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
422{
423 const size_t SIZE = 256;
424 char buffer[SIZE];
425 String8 result;
426
427 bool locked = AudioFlinger::dumpTryLock(mLock);
428 if (!locked) {
429 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
430 write(fd, buffer, strlen(buffer));
431 }
432
433 snprintf(buffer, SIZE, "io handle: %d\n", mId);
434 result.append(buffer);
435 snprintf(buffer, SIZE, "TID: %d\n", getTid());
436 result.append(buffer);
437 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
438 result.append(buffer);
439 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
440 result.append(buffer);
441 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
442 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700443 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800444 result.append(buffer);
445 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
446 result.append(buffer);
447 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
448 result.append(buffer);
449 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
450 result.append(buffer);
451
452 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
453 result.append(buffer);
454 result.append(" Index Command");
455 for (size_t i = 0; i < mNewParameters.size(); ++i) {
456 snprintf(buffer, SIZE, "\n %02d ", i);
457 result.append(buffer);
458 result.append(mNewParameters[i]);
459 }
460
461 snprintf(buffer, SIZE, "\n\nPending config events: \n");
462 result.append(buffer);
463 for (size_t i = 0; i < mConfigEvents.size(); i++) {
464 mConfigEvents[i]->dump(buffer, SIZE);
465 result.append(buffer);
466 }
467 result.append("\n");
468
469 write(fd, result.string(), result.size());
470
471 if (locked) {
472 mLock.unlock();
473 }
474}
475
476void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
477{
478 const size_t SIZE = 256;
479 char buffer[SIZE];
480 String8 result;
481
482 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
483 write(fd, buffer, strlen(buffer));
484
485 for (size_t i = 0; i < mEffectChains.size(); ++i) {
486 sp<EffectChain> chain = mEffectChains[i];
487 if (chain != 0) {
488 chain->dump(fd, args);
489 }
490 }
491}
492
Marco Nelissene14a5d62013-10-03 08:51:24 -0700493void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800494{
495 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700496 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800497}
498
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100499String16 AudioFlinger::ThreadBase::getWakeLockTag()
500{
501 switch (mType) {
502 case MIXER:
503 return String16("AudioMix");
504 case DIRECT:
505 return String16("AudioDirectOut");
506 case DUPLICATING:
507 return String16("AudioDup");
508 case RECORD:
509 return String16("AudioIn");
510 case OFFLOAD:
511 return String16("AudioOffload");
512 default:
513 ALOG_ASSERT(false);
514 return String16("AudioUnknown");
515 }
516}
517
Marco Nelissene14a5d62013-10-03 08:51:24 -0700518void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800519{
520 if (mPowerManager == 0) {
521 // use checkService() to avoid blocking if power service is not up yet
522 sp<IBinder> binder =
523 defaultServiceManager()->checkService(String16("power"));
524 if (binder == 0) {
525 ALOGW("Thread %s cannot connect to the power manager service", mName);
526 } else {
527 mPowerManager = interface_cast<IPowerManager>(binder);
528 binder->linkToDeath(mDeathRecipient);
529 }
530 }
531 if (mPowerManager != 0) {
532 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700533 status_t status;
534 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700535 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700536 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100537 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700538 String16("media"),
539 uid);
540 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700541 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700542 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100543 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700544 String16("media"));
545 }
Eric Laurent81784c32012-11-19 14:55:58 -0800546 if (status == NO_ERROR) {
547 mWakeLockToken = binder;
548 }
549 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
550 }
551}
552
553void AudioFlinger::ThreadBase::releaseWakeLock()
554{
555 Mutex::Autolock _l(mLock);
556 releaseWakeLock_l();
557}
558
559void AudioFlinger::ThreadBase::releaseWakeLock_l()
560{
561 if (mWakeLockToken != 0) {
562 ALOGV("releaseWakeLock_l() %s", mName);
563 if (mPowerManager != 0) {
564 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
565 }
566 mWakeLockToken.clear();
567 }
568}
569
570void AudioFlinger::ThreadBase::clearPowerManager()
571{
572 Mutex::Autolock _l(mLock);
573 releaseWakeLock_l();
574 mPowerManager.clear();
575}
576
577void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
578{
579 sp<ThreadBase> thread = mThread.promote();
580 if (thread != 0) {
581 thread->clearPowerManager();
582 }
583 ALOGW("power manager service died !!!");
584}
585
586void AudioFlinger::ThreadBase::setEffectSuspended(
587 const effect_uuid_t *type, bool suspend, int sessionId)
588{
589 Mutex::Autolock _l(mLock);
590 setEffectSuspended_l(type, suspend, sessionId);
591}
592
593void AudioFlinger::ThreadBase::setEffectSuspended_l(
594 const effect_uuid_t *type, bool suspend, int sessionId)
595{
596 sp<EffectChain> chain = getEffectChain_l(sessionId);
597 if (chain != 0) {
598 if (type != NULL) {
599 chain->setEffectSuspended_l(type, suspend);
600 } else {
601 chain->setEffectSuspendedAll_l(suspend);
602 }
603 }
604
605 updateSuspendedSessions_l(type, suspend, sessionId);
606}
607
608void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
609{
610 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
611 if (index < 0) {
612 return;
613 }
614
615 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
616 mSuspendedSessions.valueAt(index);
617
618 for (size_t i = 0; i < sessionEffects.size(); i++) {
619 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
620 for (int j = 0; j < desc->mRefCount; j++) {
621 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
622 chain->setEffectSuspendedAll_l(true);
623 } else {
624 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
625 desc->mType.timeLow);
626 chain->setEffectSuspended_l(&desc->mType, true);
627 }
628 }
629 }
630}
631
632void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
633 bool suspend,
634 int sessionId)
635{
636 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
637
638 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
639
640 if (suspend) {
641 if (index >= 0) {
642 sessionEffects = mSuspendedSessions.valueAt(index);
643 } else {
644 mSuspendedSessions.add(sessionId, sessionEffects);
645 }
646 } else {
647 if (index < 0) {
648 return;
649 }
650 sessionEffects = mSuspendedSessions.valueAt(index);
651 }
652
653
654 int key = EffectChain::kKeyForSuspendAll;
655 if (type != NULL) {
656 key = type->timeLow;
657 }
658 index = sessionEffects.indexOfKey(key);
659
660 sp<SuspendedSessionDesc> desc;
661 if (suspend) {
662 if (index >= 0) {
663 desc = sessionEffects.valueAt(index);
664 } else {
665 desc = new SuspendedSessionDesc();
666 if (type != NULL) {
667 desc->mType = *type;
668 }
669 sessionEffects.add(key, desc);
670 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
671 }
672 desc->mRefCount++;
673 } else {
674 if (index < 0) {
675 return;
676 }
677 desc = sessionEffects.valueAt(index);
678 if (--desc->mRefCount == 0) {
679 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
680 sessionEffects.removeItemsAt(index);
681 if (sessionEffects.isEmpty()) {
682 ALOGV("updateSuspendedSessions_l() restore removing session %d",
683 sessionId);
684 mSuspendedSessions.removeItem(sessionId);
685 }
686 }
687 }
688 if (!sessionEffects.isEmpty()) {
689 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
690 }
691}
692
693void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
694 bool enabled,
695 int sessionId)
696{
697 Mutex::Autolock _l(mLock);
698 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
699}
700
701void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
702 bool enabled,
703 int sessionId)
704{
705 if (mType != RECORD) {
706 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
707 // another session. This gives the priority to well behaved effect control panels
708 // and applications not using global effects.
709 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
710 // global effects
711 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
712 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
713 }
714 }
715
716 sp<EffectChain> chain = getEffectChain_l(sessionId);
717 if (chain != 0) {
718 chain->checkSuspendOnEffectEnabled(effect, enabled);
719 }
720}
721
722// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
723sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
724 const sp<AudioFlinger::Client>& client,
725 const sp<IEffectClient>& effectClient,
726 int32_t priority,
727 int sessionId,
728 effect_descriptor_t *desc,
729 int *enabled,
730 status_t *status
731 )
732{
733 sp<EffectModule> effect;
734 sp<EffectHandle> handle;
735 status_t lStatus;
736 sp<EffectChain> chain;
737 bool chainCreated = false;
738 bool effectCreated = false;
739 bool effectRegistered = false;
740
741 lStatus = initCheck();
742 if (lStatus != NO_ERROR) {
743 ALOGW("createEffect_l() Audio driver not initialized.");
744 goto Exit;
745 }
746
Eric Laurent5baf2af2013-09-12 17:37:00 -0700747 // Allow global effects only on offloaded and mixer threads
748 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
749 switch (mType) {
750 case MIXER:
751 case OFFLOAD:
752 break;
753 case DIRECT:
754 case DUPLICATING:
755 case RECORD:
756 default:
757 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
758 lStatus = BAD_VALUE;
759 goto Exit;
760 }
Eric Laurent81784c32012-11-19 14:55:58 -0800761 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700762
Eric Laurent81784c32012-11-19 14:55:58 -0800763 // Only Pre processor effects are allowed on input threads and only on input threads
764 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
765 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
766 desc->name, desc->flags, mType);
767 lStatus = BAD_VALUE;
768 goto Exit;
769 }
770
771 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
772
773 { // scope for mLock
774 Mutex::Autolock _l(mLock);
775
776 // check for existing effect chain with the requested audio session
777 chain = getEffectChain_l(sessionId);
778 if (chain == 0) {
779 // create a new chain for this session
780 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
781 chain = new EffectChain(this, sessionId);
782 addEffectChain_l(chain);
783 chain->setStrategy(getStrategyForSession_l(sessionId));
784 chainCreated = true;
Alok Kediya601e9b52013-09-27 11:55:10 +0530785 if(sessionId == mAudioFlinger->mLPASessionId) {
786 // Clear reference to previous effect chain if any
787 if(mAudioFlinger->mLPAEffectChain.get()) {
788 mAudioFlinger->mLPAEffectChain.clear();
789 }
790 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
791 mAudioFlinger->mLPAEffectChain = chain;
792 chain->setLPAFlag(true);
793 // For LPA, the volume will be applied in DSP. No need for volume
794 // control in the Effect chain, so setting it to unity.
795 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
796 chain->setVolume_l(&volume,&volume);
797 }
Eric Laurent81784c32012-11-19 14:55:58 -0800798 } else {
799 effect = chain->getEffectFromDesc_l(desc);
800 }
801
802 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
803
804 if (effect == 0) {
805 int id = mAudioFlinger->nextUniqueId();
806 // Check CPU and memory usage
807 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
808 if (lStatus != NO_ERROR) {
809 goto Exit;
810 }
811 effectRegistered = true;
812 // create a new effect module if none present in the chain
813 effect = new EffectModule(this, chain, desc, id, sessionId);
814 lStatus = effect->status();
815 if (lStatus != NO_ERROR) {
816 goto Exit;
817 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700818 effect->setOffloaded(mType == OFFLOAD, mId);
819
Eric Laurent81784c32012-11-19 14:55:58 -0800820 lStatus = chain->addEffect_l(effect);
821 if (lStatus != NO_ERROR) {
822 goto Exit;
823 }
824 effectCreated = true;
825
Alok Kediya601e9b52013-09-27 11:55:10 +0530826 effect->setDevice(mAudioFlinger->mLPASessionId == sessionId ? mAudioFlinger->mDirectDevice:mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -0800827 effect->setDevice(mInDevice);
828 effect->setMode(mAudioFlinger->getMode());
829 effect->setAudioSource(mAudioSource);
830 }
831 // create effect handle and connect it to effect module
832 handle = new EffectHandle(effect, client, effectClient, priority);
833 lStatus = effect->addHandle(handle.get());
834 if (enabled != NULL) {
835 *enabled = (int)effect->isEnabled();
836 }
837 }
838
839Exit:
840 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
841 Mutex::Autolock _l(mLock);
842 if (effectCreated) {
843 chain->removeEffect_l(effect);
844 }
845 if (effectRegistered) {
846 AudioSystem::unregisterEffect(effect->id());
847 }
848 if (chainCreated) {
849 removeEffectChain_l(chain);
850 }
851 handle.clear();
852 }
853
854 if (status != NULL) {
855 *status = lStatus;
856 }
857 return handle;
858}
859
860sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
861{
862 Mutex::Autolock _l(mLock);
863 return getEffect_l(sessionId, effectId);
864}
865
866sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
867{
868 sp<EffectChain> chain = getEffectChain_l(sessionId);
869 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
870}
871
872// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
873// PlaybackThread::mLock held
874status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
875{
876 // check for existing effect chain with the requested audio session
877 int sessionId = effect->sessionId();
878 sp<EffectChain> chain = getEffectChain_l(sessionId);
879 bool chainCreated = false;
880
Eric Laurent5baf2af2013-09-12 17:37:00 -0700881 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
882 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
883 this, effect->desc().name, effect->desc().flags);
884
Eric Laurent81784c32012-11-19 14:55:58 -0800885 if (chain == 0) {
886 // create a new chain for this session
887 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
888 chain = new EffectChain(this, sessionId);
889 addEffectChain_l(chain);
890 chain->setStrategy(getStrategyForSession_l(sessionId));
891 chainCreated = true;
892 }
893 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
894
895 if (chain->getEffectFromId_l(effect->id()) != 0) {
896 ALOGW("addEffect_l() %p effect %s already present in chain %p",
897 this, effect->desc().name, chain.get());
898 return BAD_VALUE;
899 }
900
Eric Laurent5baf2af2013-09-12 17:37:00 -0700901 effect->setOffloaded(mType == OFFLOAD, mId);
902
Eric Laurent81784c32012-11-19 14:55:58 -0800903 status_t status = chain->addEffect_l(effect);
904 if (status != NO_ERROR) {
905 if (chainCreated) {
906 removeEffectChain_l(chain);
907 }
908 return status;
909 }
910
911 effect->setDevice(mOutDevice);
912 effect->setDevice(mInDevice);
913 effect->setMode(mAudioFlinger->getMode());
914 effect->setAudioSource(mAudioSource);
915 return NO_ERROR;
916}
917
918void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
919
920 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
921 effect_descriptor_t desc = effect->desc();
922 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
923 detachAuxEffect_l(effect->id());
924 }
925
926 sp<EffectChain> chain = effect->chain().promote();
927 if (chain != 0) {
928 // remove effect chain if removing last effect
929 if (chain->removeEffect_l(effect) == 0) {
930 removeEffectChain_l(chain);
931 }
932 } else {
933 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
934 }
935}
936
937void AudioFlinger::ThreadBase::lockEffectChains_l(
938 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
939{
940 effectChains = mEffectChains;
Alok Kediya601e9b52013-09-27 11:55:10 +0530941 mAudioFlinger->mAllChainsLocked = true;
Eric Laurent81784c32012-11-19 14:55:58 -0800942 for (size_t i = 0; i < mEffectChains.size(); i++) {
Alok Kediya601e9b52013-09-27 11:55:10 +0530943 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain) {
944 mEffectChains[i]->lock();
945 } else {
946 mAudioFlinger-> mAllChainsLocked = false;
947 }
Eric Laurent81784c32012-11-19 14:55:58 -0800948 }
949}
950
951void AudioFlinger::ThreadBase::unlockEffectChains(
952 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
953{
954 for (size_t i = 0; i < effectChains.size(); i++) {
Alok Kediya601e9b52013-09-27 11:55:10 +0530955 if (mAudioFlinger->mAllChainsLocked || effectChains[i] != mAudioFlinger->mLPAEffectChain)
956 effectChains[i]->unlock();
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
958}
959
960sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
961{
962 Mutex::Autolock _l(mLock);
963 return getEffectChain_l(sessionId);
964}
965
966sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
967{
968 size_t size = mEffectChains.size();
969 for (size_t i = 0; i < size; i++) {
970 if (mEffectChains[i]->sessionId() == sessionId) {
971 return mEffectChains[i];
972 }
973 }
974 return 0;
975}
976
977void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
978{
979 Mutex::Autolock _l(mLock);
980 size_t size = mEffectChains.size();
981 for (size_t i = 0; i < size; i++) {
982 mEffectChains[i]->setMode_l(mode);
983 }
984}
985
986void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
987 EffectHandle *handle,
988 bool unpinIfLast) {
989
990 Mutex::Autolock _l(mLock);
991 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
992 // delete the effect module if removing last handle on it
993 if (effect->removeHandle(handle) == 0) {
994 if (!effect->isPinned() || unpinIfLast) {
995 removeEffect_l(effect);
996 AudioSystem::unregisterEffect(effect->id());
997 }
998 }
999}
1000
1001// ----------------------------------------------------------------------------
1002// Playback
1003// ----------------------------------------------------------------------------
1004
1005AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1006 AudioStreamOut* output,
1007 audio_io_handle_t id,
1008 audio_devices_t device,
1009 type_t type)
1010 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001011 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001012 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001013 // mStreamTypes[] initialized in constructor body
1014 mOutput(output),
1015 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1016 mMixerStatus(MIXER_IDLE),
1017 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1018 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001019 mBytesRemaining(0),
1020 mCurrentWriteLength(0),
1021 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001022 mWriteAckSequence(0),
1023 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001024 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001025 mScreenState(AudioFlinger::mScreenState),
1026 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001027 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1028 // mLatchD, mLatchQ,
1029 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001030{
1031 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001032 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001033
1034 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1035 // it would be safer to explicitly pass initial masterVolume/masterMute as
1036 // parameter.
1037 //
1038 // If the HAL we are using has support for master volume or master mute,
1039 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1040 // and the mute set to false).
1041 mMasterVolume = audioFlinger->masterVolume_l();
1042 mMasterMute = audioFlinger->masterMute_l();
1043 if (mOutput && mOutput->audioHwDev) {
1044 if (mOutput->audioHwDev->canSetMasterVolume()) {
1045 mMasterVolume = 1.0;
1046 }
1047
1048 if (mOutput->audioHwDev->canSetMasterMute()) {
1049 mMasterMute = false;
1050 }
1051 }
1052
1053 readOutputParameters();
1054
1055 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1056 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1057 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1058 stream = (audio_stream_type_t) (stream + 1)) {
1059 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1060 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1061 }
1062 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1063 // because mAudioFlinger doesn't have one to copy from
1064}
1065
1066AudioFlinger::PlaybackThread::~PlaybackThread()
1067{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001068 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001069 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001070}
1071
1072void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1073{
1074 dumpInternals(fd, args);
1075 dumpTracks(fd, args);
1076 dumpEffectChains(fd, args);
1077}
1078
1079void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1080{
1081 const size_t SIZE = 256;
1082 char buffer[SIZE];
1083 String8 result;
1084
1085 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1086 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1087 const stream_type_t *st = &mStreamTypes[i];
1088 if (i > 0) {
1089 result.appendFormat(", ");
1090 }
1091 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1092 if (st->mute) {
1093 result.append("M");
1094 }
1095 }
1096 result.append("\n");
1097 write(fd, result.string(), result.length());
1098 result.clear();
1099
1100 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1101 result.append(buffer);
1102 Track::appendDumpHeader(result);
1103 for (size_t i = 0; i < mTracks.size(); ++i) {
1104 sp<Track> track = mTracks[i];
1105 if (track != 0) {
1106 track->dump(buffer, SIZE);
1107 result.append(buffer);
1108 }
1109 }
1110
1111 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1112 result.append(buffer);
1113 Track::appendDumpHeader(result);
1114 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1115 sp<Track> track = mActiveTracks[i].promote();
1116 if (track != 0) {
1117 track->dump(buffer, SIZE);
1118 result.append(buffer);
1119 }
1120 }
1121 write(fd, result.string(), result.size());
1122
1123 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1124 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1125 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1126 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1127}
1128
1129void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1130{
1131 const size_t SIZE = 256;
1132 char buffer[SIZE];
1133 String8 result;
1134
1135 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1136 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001137 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1138 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001139 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1140 ns2ms(systemTime() - mLastWriteTime));
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1143 result.append(buffer);
1144 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1145 result.append(buffer);
1146 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1147 result.append(buffer);
1148 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1149 result.append(buffer);
1150 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1151 result.append(buffer);
1152 write(fd, result.string(), result.size());
1153 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1154
1155 dumpBase(fd, args);
1156}
1157
1158// Thread virtuals
1159status_t AudioFlinger::PlaybackThread::readyToRun()
1160{
1161 status_t status = initCheck();
1162 if (status == NO_ERROR) {
1163 ALOGI("AudioFlinger's thread %p ready to run", this);
1164 } else {
1165 ALOGE("No working audio driver found.");
1166 }
1167 return status;
1168}
1169
1170void AudioFlinger::PlaybackThread::onFirstRef()
1171{
1172 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1173}
1174
1175// ThreadBase virtuals
1176void AudioFlinger::PlaybackThread::preExit()
1177{
1178 ALOGV(" preExit()");
1179 // FIXME this is using hard-coded strings but in the future, this functionality will be
1180 // converted to use audio HAL extensions required to support tunneling
1181 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1182}
1183
1184// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1185sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1186 const sp<AudioFlinger::Client>& client,
1187 audio_stream_type_t streamType,
1188 uint32_t sampleRate,
1189 audio_format_t format,
1190 audio_channel_mask_t channelMask,
1191 size_t frameCount,
1192 const sp<IMemory>& sharedBuffer,
1193 int sessionId,
1194 IAudioFlinger::track_flags_t *flags,
1195 pid_t tid,
1196 status_t *status)
1197{
1198 sp<Track> track;
1199 status_t lStatus;
1200
1201 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1202
1203 // client expresses a preference for FAST, but we get the final say
1204 if (*flags & IAudioFlinger::TRACK_FAST) {
1205 if (
1206 // not timed
1207 (!isTimed) &&
1208 // either of these use cases:
1209 (
1210 // use case 1: shared buffer with any frame count
1211 (
1212 (sharedBuffer != 0)
1213 ) ||
1214 // use case 2: callback handler and frame count is default or at least as large as HAL
1215 (
1216 (tid != -1) &&
1217 ((frameCount == 0) ||
1218 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1219 )
1220 ) &&
1221 // PCM data
1222 audio_is_linear_pcm(format) &&
1223 // mono or stereo
1224 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1225 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1226#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1227 // hardware sample rate
1228 (sampleRate == mSampleRate) &&
1229#endif
1230 // normal mixer has an associated fast mixer
1231 hasFastMixer() &&
1232 // there are sufficient fast track slots available
1233 (mFastTrackAvailMask != 0)
1234 // FIXME test that MixerThread for this fast track has a capable output HAL
1235 // FIXME add a permission test also?
1236 ) {
1237 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1238 if (frameCount == 0) {
1239 frameCount = mFrameCount * kFastTrackMultiplier;
1240 }
1241 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1242 frameCount, mFrameCount);
1243 } else {
1244 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1245 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1246 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1247 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1248 audio_is_linear_pcm(format),
1249 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1250 *flags &= ~IAudioFlinger::TRACK_FAST;
1251 // For compatibility with AudioTrack calculation, buffer depth is forced
1252 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1253 // This is probably too conservative, but legacy application code may depend on it.
1254 // If you change this calculation, also review the start threshold which is related.
1255 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
Alok Kediya601e9b52013-09-27 11:55:10 +05301256 uint32_t minBufCount = 0;
1257 if (mSampleRate) {
1258 minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1259 }
Eric Laurent81784c32012-11-19 14:55:58 -08001260 if (minBufCount < 2) {
1261 minBufCount = 2;
1262 }
1263 size_t minFrameCount = mNormalFrameCount * minBufCount;
1264 if (frameCount < minFrameCount) {
1265 frameCount = minFrameCount;
1266 }
1267 }
1268 }
1269
1270 if (mType == DIRECT) {
Alok Kediya601e9b52013-09-27 11:55:10 +05301271 if (((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM)
1272 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AMR_NB)
1273 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AMR_WB)
1274 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRC)
1275 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCB)
1276 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCWB)
1277 ||((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_EVRCNW)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001278 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1279 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1280 "for output %p with format %d",
1281 sampleRate, format, channelMask, mOutput, mFormat);
1282 lStatus = BAD_VALUE;
1283 goto Exit;
1284 }
1285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001286 } else if (mType == OFFLOAD) {
1287 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1288 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1289 "for output %p with format %d",
1290 sampleRate, format, channelMask, mOutput, mFormat);
1291 lStatus = BAD_VALUE;
1292 goto Exit;
1293 }
Eric Laurent81784c32012-11-19 14:55:58 -08001294 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001295 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1296 ALOGE("createTrack_l() Bad parameter: format %d \""
1297 "for output %p with format %d",
1298 format, mOutput, mFormat);
1299 lStatus = BAD_VALUE;
1300 goto Exit;
1301 }
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1303 if (sampleRate > mSampleRate*2) {
1304 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1305 lStatus = BAD_VALUE;
1306 goto Exit;
1307 }
1308 }
1309
1310 lStatus = initCheck();
1311 if (lStatus != NO_ERROR) {
1312 ALOGE("Audio driver not initialized.");
1313 goto Exit;
1314 }
1315
1316 { // scope for mLock
1317 Mutex::Autolock _l(mLock);
1318
1319 // all tracks in same audio session must share the same routing strategy otherwise
1320 // conflicts will happen when tracks are moved from one output to another by audio policy
1321 // manager
1322 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1323 for (size_t i = 0; i < mTracks.size(); ++i) {
1324 sp<Track> t = mTracks[i];
1325 if (t != 0 && !t->isOutputTrack()) {
1326 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1327 if (sessionId == t->sessionId() && strategy != actual) {
1328 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1329 strategy, actual);
1330 lStatus = BAD_VALUE;
1331 goto Exit;
1332 }
1333 }
1334 }
1335
1336 if (!isTimed) {
1337 track = new Track(this, client, streamType, sampleRate, format,
1338 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1339 } else {
1340 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1341 channelMask, frameCount, sharedBuffer, sessionId);
1342 }
1343 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1344 lStatus = NO_MEMORY;
1345 goto Exit;
1346 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001347
Eric Laurent81784c32012-11-19 14:55:58 -08001348 mTracks.add(track);
1349
1350 sp<EffectChain> chain = getEffectChain_l(sessionId);
1351 if (chain != 0) {
1352 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1353 track->setMainBuffer(chain->inBuffer());
1354 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1355 chain->incTrackCnt();
1356 }
1357
1358 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1359 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1360 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1361 // so ask activity manager to do this on our behalf
1362 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1363 }
1364 }
1365
1366 lStatus = NO_ERROR;
1367
1368Exit:
1369 if (status) {
1370 *status = lStatus;
1371 }
1372 return track;
1373}
1374
1375uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1376{
1377 return latency;
1378}
1379
1380uint32_t AudioFlinger::PlaybackThread::latency() const
1381{
1382 Mutex::Autolock _l(mLock);
1383 return latency_l();
1384}
1385uint32_t AudioFlinger::PlaybackThread::latency_l() const
1386{
1387 if (initCheck() == NO_ERROR) {
1388 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1389 } else {
1390 return 0;
1391 }
1392}
1393
1394void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1395{
1396 Mutex::Autolock _l(mLock);
1397 // Don't apply master volume in SW if our HAL can do it for us.
1398 if (mOutput && mOutput->audioHwDev &&
1399 mOutput->audioHwDev->canSetMasterVolume()) {
1400 mMasterVolume = 1.0;
1401 } else {
1402 mMasterVolume = value;
1403 }
1404}
1405
1406void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1407{
1408 Mutex::Autolock _l(mLock);
1409 // Don't apply master mute in SW if our HAL can do it for us.
1410 if (mOutput && mOutput->audioHwDev &&
1411 mOutput->audioHwDev->canSetMasterMute()) {
1412 mMasterMute = false;
1413 } else {
1414 mMasterMute = muted;
1415 }
1416}
1417
1418void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1419{
1420 Mutex::Autolock _l(mLock);
1421 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001422 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001423}
1424
1425void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1426{
1427 Mutex::Autolock _l(mLock);
1428 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001429 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001430}
1431
1432float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1433{
1434 Mutex::Autolock _l(mLock);
1435 return mStreamTypes[stream].volume;
1436}
1437
1438// addTrack_l() must be called with ThreadBase::mLock held
1439status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1440{
1441 status_t status = ALREADY_EXISTS;
1442
1443 // set retry count for buffer fill
1444 track->mRetryCount = kMaxTrackStartupRetries;
1445 if (mActiveTracks.indexOf(track) < 0) {
1446 // the track is newly added, make sure it fills up all its
1447 // buffers before playing. This is to ensure the client will
1448 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001449 if (!track->isOutputTrack()) {
1450 TrackBase::track_state state = track->mState;
1451 mLock.unlock();
1452 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1453 mLock.lock();
1454 // abort track was stopped/paused while we released the lock
1455 if (state != track->mState) {
1456 if (status == NO_ERROR) {
1457 mLock.unlock();
1458 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1459 mLock.lock();
1460 }
1461 return INVALID_OPERATION;
1462 }
1463 // abort if start is rejected by audio policy manager
1464 if (status != NO_ERROR) {
1465 return PERMISSION_DENIED;
1466 }
1467#ifdef ADD_BATTERY_DATA
1468 // to track the speaker usage
1469 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1470#endif
1471 }
1472
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001473 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001474 track->mResetDone = false;
1475 track->mPresentationCompleteFrames = 0;
1476 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001477 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1478 if (chain != 0) {
1479 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1480 track->sessionId());
1481 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001482 }
1483
1484 status = NO_ERROR;
1485 }
1486
Eric Laurentede6c3b2013-09-19 14:37:46 -07001487 ALOGV("signal playback thread");
1488 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001489
1490 return status;
1491}
1492
Eric Laurentbfb1b832013-01-07 09:53:42 -08001493bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001494{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001496 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001497 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1498 track->mState = TrackBase::STOPPED;
1499 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001501 } else if (track->isFastTrack() || track->isOffloaded()) {
1502 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001503 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001504
1505 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001506}
1507
1508void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1509{
1510 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1511 mTracks.remove(track);
1512 deleteTrackName_l(track->name());
1513 // redundant as track is about to be destroyed, for dumpsys only
1514 track->mName = -1;
1515 if (track->isFastTrack()) {
1516 int index = track->mFastIndex;
1517 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1518 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1519 mFastTrackAvailMask |= 1 << index;
1520 // redundant as track is about to be destroyed, for dumpsys only
1521 track->mFastIndex = -1;
1522 }
1523 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1524 if (chain != 0) {
1525 chain->decTrackCnt();
1526 }
1527}
1528
Eric Laurentede6c3b2013-09-19 14:37:46 -07001529void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001530{
1531 // Thread could be blocked waiting for async
1532 // so signal it to handle state changes immediately
1533 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1534 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1535 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001536 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001537}
1538
Eric Laurent81784c32012-11-19 14:55:58 -08001539String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1540{
Eric Laurent81784c32012-11-19 14:55:58 -08001541 Mutex::Autolock _l(mLock);
1542 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001543 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001544 }
1545
Glenn Kastend8ea6992013-07-16 14:17:15 -07001546 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1547 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001548 free(s);
1549 return out_s8;
1550}
1551
1552// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1553void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1554 AudioSystem::OutputDescriptor desc;
1555 void *param2 = NULL;
1556
1557 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1558 param);
1559
1560 switch (event) {
1561 case AudioSystem::OUTPUT_OPENED:
1562 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001563 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001564 desc.samplingRate = mSampleRate;
1565 desc.format = mFormat;
1566 desc.frameCount = mNormalFrameCount; // FIXME see
1567 // AudioFlinger::frameCount(audio_io_handle_t)
1568 desc.latency = latency();
1569 param2 = &desc;
1570 break;
1571
1572 case AudioSystem::STREAM_CONFIG_CHANGED:
1573 param2 = &param;
1574 case AudioSystem::OUTPUT_CLOSED:
1575 default:
1576 break;
1577 }
1578 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1579}
1580
Eric Laurentbfb1b832013-01-07 09:53:42 -08001581void AudioFlinger::PlaybackThread::writeCallback()
1582{
1583 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001584 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585}
1586
1587void AudioFlinger::PlaybackThread::drainCallback()
1588{
1589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001590 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001591}
1592
Eric Laurent3b4529e2013-09-05 18:09:19 -07001593void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001594{
1595 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001596 // reject out of sequence requests
1597 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1598 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001599 mWaitWorkCV.signal();
1600 }
1601}
1602
Eric Laurent3b4529e2013-09-05 18:09:19 -07001603void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001604{
1605 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001606 // reject out of sequence requests
1607 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1608 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001609 mWaitWorkCV.signal();
1610 }
1611}
1612
1613// static
1614int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1615 void *param,
1616 void *cookie)
1617{
1618 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1619 ALOGV("asyncCallback() event %d", event);
1620 switch (event) {
1621 case STREAM_CBK_EVENT_WRITE_READY:
1622 me->writeCallback();
1623 break;
1624 case STREAM_CBK_EVENT_DRAIN_READY:
1625 me->drainCallback();
1626 break;
1627 default:
1628 ALOGW("asyncCallback() unknown event %d", event);
1629 break;
1630 }
1631 return 0;
1632}
1633
Eric Laurent81784c32012-11-19 14:55:58 -08001634void AudioFlinger::PlaybackThread::readOutputParameters()
1635{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001636 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001637 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1638 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001639 if (!audio_is_output_channel(mChannelMask)) {
1640 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1641 }
1642 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1643 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1644 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1645 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001646 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001647 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001648 if (!audio_is_valid_format(mFormat)) {
1649 LOG_FATAL("HAL format %d not valid for output", mFormat);
1650 }
1651 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1652 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1653 mFormat);
1654 }
Eric Laurent81784c32012-11-19 14:55:58 -08001655 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1656 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1657 if (mFrameCount & 15) {
1658 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1659 mFrameCount);
1660 }
1661
Eric Laurentbfb1b832013-01-07 09:53:42 -08001662 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1663 (mOutput->stream->set_callback != NULL)) {
1664 if (mOutput->stream->set_callback(mOutput->stream,
1665 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1666 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001667 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001668 }
1669 }
1670
Eric Laurent81784c32012-11-19 14:55:58 -08001671 // Calculate size of normal mix buffer relative to the HAL output buffer size
1672 double multiplier = 1.0;
1673 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1674 kUseFastMixer == FastMixer_Dynamic)) {
1675 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1676 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1677 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1678 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1679 maxNormalFrameCount = maxNormalFrameCount & ~15;
1680 if (maxNormalFrameCount < minNormalFrameCount) {
1681 maxNormalFrameCount = minNormalFrameCount;
1682 }
1683 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1684 if (multiplier <= 1.0) {
1685 multiplier = 1.0;
1686 } else if (multiplier <= 2.0) {
1687 if (2 * mFrameCount <= maxNormalFrameCount) {
1688 multiplier = 2.0;
1689 } else {
1690 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1691 }
1692 } else {
1693 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1694 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1695 // track, but we sometimes have to do this to satisfy the maximum frame count
1696 // constraint)
1697 // FIXME this rounding up should not be done if no HAL SRC
1698 uint32_t truncMult = (uint32_t) multiplier;
1699 if ((truncMult & 1)) {
1700 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1701 ++truncMult;
1702 }
1703 }
1704 multiplier = (double) truncMult;
1705 }
1706 }
1707 mNormalFrameCount = multiplier * mFrameCount;
1708 // round up to nearest 16 frames to satisfy AudioMixer
1709 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1710 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1711 mNormalFrameCount);
1712
Eric Laurentbfb1b832013-01-07 09:53:42 -08001713 delete[] mAllocMixBuffer;
1714 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1715 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1716 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1717 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001718
1719 // force reconfiguration of effect chains and engines to take new buffer size and audio
1720 // parameters into account
1721 // Note that mLock is not held when readOutputParameters() is called from the constructor
1722 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1723 // matter.
1724 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1725 Vector< sp<EffectChain> > effectChains = mEffectChains;
1726 for (size_t i = 0; i < effectChains.size(); i ++) {
1727 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1728 }
1729}
1730
1731
1732status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1733{
1734 if (halFrames == NULL || dspFrames == NULL) {
1735 return BAD_VALUE;
1736 }
1737 Mutex::Autolock _l(mLock);
1738 if (initCheck() != NO_ERROR) {
1739 return INVALID_OPERATION;
1740 }
1741 size_t framesWritten = mBytesWritten / mFrameSize;
1742 *halFrames = framesWritten;
1743
1744 if (isSuspended()) {
1745 // return an estimation of rendered frames when the output is suspended
1746 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1747 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1748 return NO_ERROR;
1749 } else {
1750 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1751 }
1752}
1753
1754uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1755{
1756 Mutex::Autolock _l(mLock);
1757 uint32_t result = 0;
1758 if (getEffectChain_l(sessionId) != 0) {
1759 result = EFFECT_SESSION;
1760 }
1761
1762 for (size_t i = 0; i < mTracks.size(); ++i) {
1763 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001764 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001765 result |= TRACK_SESSION;
1766 break;
1767 }
1768 }
1769
1770 return result;
1771}
1772
1773uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1774{
1775 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1776 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1777 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1778 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1779 }
1780 for (size_t i = 0; i < mTracks.size(); i++) {
1781 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001782 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001783 return AudioSystem::getStrategyForStream(track->streamType());
1784 }
1785 }
1786 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1787}
1788
1789
1790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1791{
1792 Mutex::Autolock _l(mLock);
1793 return mOutput;
1794}
1795
1796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1797{
1798 Mutex::Autolock _l(mLock);
1799 AudioStreamOut *output = mOutput;
1800 mOutput = NULL;
1801 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1802 // must push a NULL and wait for ack
1803 mOutputSink.clear();
1804 mPipeSink.clear();
1805 mNormalSink.clear();
1806 return output;
1807}
1808
1809// this method must always be called either with ThreadBase mLock held or inside the thread loop
1810audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1811{
1812 if (mOutput == NULL) {
1813 return NULL;
1814 }
1815 return &mOutput->stream->common;
1816}
1817
1818uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1819{
1820 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1821}
1822
1823status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1824{
1825 if (!isValidSyncEvent(event)) {
1826 return BAD_VALUE;
1827 }
1828
1829 Mutex::Autolock _l(mLock);
1830
1831 for (size_t i = 0; i < mTracks.size(); ++i) {
1832 sp<Track> track = mTracks[i];
1833 if (event->triggerSession() == track->sessionId()) {
1834 (void) track->setSyncEvent(event);
1835 return NO_ERROR;
1836 }
1837 }
1838
1839 return NAME_NOT_FOUND;
1840}
1841
1842bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1843{
1844 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1845}
1846
1847void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1848 const Vector< sp<Track> >& tracksToRemove)
1849{
1850 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001851 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001852 for (size_t i = 0 ; i < count ; i++) {
1853 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001854 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856#ifdef ADD_BATTERY_DATA
1857 // to track the speaker usage
1858 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1859#endif
1860 if (track->isTerminated()) {
1861 AudioSystem::releaseOutput(mId);
1862 }
Eric Laurent81784c32012-11-19 14:55:58 -08001863 }
1864 }
1865 }
Eric Laurent81784c32012-11-19 14:55:58 -08001866}
1867
1868void AudioFlinger::PlaybackThread::checkSilentMode_l()
1869{
1870 if (!mMasterMute) {
1871 char value[PROPERTY_VALUE_MAX];
1872 if (property_get("ro.audio.silent", value, "0") > 0) {
1873 char *endptr;
1874 unsigned long ul = strtoul(value, &endptr, 0);
1875 if (*endptr == '\0' && ul != 0) {
1876 ALOGD("Silence is golden");
1877 // The setprop command will not allow a property to be changed after
1878 // the first time it is set, so we don't have to worry about un-muting.
1879 setMasterMute_l(true);
1880 }
1881 }
1882 }
1883}
1884
1885// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001886ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001887{
1888 // FIXME rewrite to reduce number of system calls
1889 mLastWriteTime = systemTime();
1890 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001892
1893 // If an NBAIO sink is present, use it to write the normal mixer's submix
1894 if (mNormalSink != 0) {
1895#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896 size_t count = mBytesRemaining >> mBitShift;
1897 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001898 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001899 // update the setpoint when AudioFlinger::mScreenState changes
1900 uint32_t screenState = AudioFlinger::mScreenState;
1901 if (screenState != mScreenState) {
1902 mScreenState = screenState;
1903 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1904 if (pipe != NULL) {
1905 pipe->setAvgFrames((mScreenState & 1) ?
1906 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1907 }
1908 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001909 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001910 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001911 if (framesWritten > 0) {
1912 bytesWritten = framesWritten << mBitShift;
1913 } else {
1914 bytesWritten = framesWritten;
1915 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001916 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001917 if (status == NO_ERROR) {
1918 size_t totalFramesWritten = mNormalSink->framesWritten();
1919 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1920 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1921 mLatchDValid = true;
1922 }
1923 }
Eric Laurent81784c32012-11-19 14:55:58 -08001924 // otherwise use the HAL / AudioStreamOut directly
1925 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001926 // Direct output and offload threads
1927 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1928 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001929 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1930 mWriteAckSequence += 2;
1931 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001933 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001934 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001935 // FIXME We should have an implementation of timestamps for direct output threads.
1936 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001937 bytesWritten = mOutput->stream->write(mOutput->stream,
1938 mMixBuffer + offset, mBytesRemaining);
1939 if (mUseAsyncWrite &&
1940 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1941 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001942 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001944 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 }
Eric Laurent81784c32012-11-19 14:55:58 -08001946 }
1947
Eric Laurent81784c32012-11-19 14:55:58 -08001948 mNumWrites++;
1949 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950
1951 return bytesWritten;
1952}
1953
1954void AudioFlinger::PlaybackThread::threadLoop_drain()
1955{
1956 if (mOutput->stream->drain) {
1957 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1958 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001959 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1960 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001961 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001962 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 }
1964 mOutput->stream->drain(mOutput->stream,
1965 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1966 : AUDIO_DRAIN_ALL);
1967 }
1968}
1969
1970void AudioFlinger::PlaybackThread::threadLoop_exit()
1971{
1972 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001973}
1974
1975/*
1976The derived values that are cached:
1977 - mixBufferSize from frame count * frame size
1978 - activeSleepTime from activeSleepTimeUs()
1979 - idleSleepTime from idleSleepTimeUs()
1980 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1981 - maxPeriod from frame count and sample rate (MIXER only)
1982
1983The parameters that affect these derived values are:
1984 - frame count
1985 - frame size
1986 - sample rate
1987 - device type: A2DP or not
1988 - device latency
1989 - format: PCM or not
1990 - active sleep time
1991 - idle sleep time
1992*/
1993
1994void AudioFlinger::PlaybackThread::cacheParameters_l()
1995{
1996 mixBufferSize = mNormalFrameCount * mFrameSize;
1997 activeSleepTime = activeSleepTimeUs();
1998 idleSleepTime = idleSleepTimeUs();
1999}
2000
2001void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2002{
Glenn Kasten7c027242012-12-26 14:43:16 -08002003 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002004 this, streamType, mTracks.size());
2005 Mutex::Autolock _l(mLock);
2006
2007 size_t size = mTracks.size();
2008 for (size_t i = 0; i < size; i++) {
2009 sp<Track> t = mTracks[i];
2010 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002011 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002012 }
2013 }
2014}
2015
2016status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2017{
2018 int session = chain->sessionId();
2019 int16_t *buffer = mMixBuffer;
2020 bool ownsBuffer = false;
2021
2022 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2023 if (session > 0) {
2024 // Only one effect chain can be present in direct output thread and it uses
2025 // the mix buffer as input
2026 if (mType != DIRECT) {
2027 size_t numSamples = mNormalFrameCount * mChannelCount;
2028 buffer = new int16_t[numSamples];
2029 memset(buffer, 0, numSamples * sizeof(int16_t));
2030 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2031 ownsBuffer = true;
2032 }
2033
2034 // Attach all tracks with same session ID to this chain.
2035 for (size_t i = 0; i < mTracks.size(); ++i) {
2036 sp<Track> track = mTracks[i];
2037 if (session == track->sessionId()) {
2038 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2039 buffer);
2040 track->setMainBuffer(buffer);
2041 chain->incTrackCnt();
2042 }
2043 }
2044
2045 // indicate all active tracks in the chain
2046 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2047 sp<Track> track = mActiveTracks[i].promote();
2048 if (track == 0) {
2049 continue;
2050 }
2051 if (session == track->sessionId()) {
2052 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2053 chain->incActiveTrackCnt();
2054 }
2055 }
2056 }
2057
2058 chain->setInBuffer(buffer, ownsBuffer);
2059 chain->setOutBuffer(mMixBuffer);
2060 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2061 // chains list in order to be processed last as it contains output stage effects
2062 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2063 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2064 // after track specific effects and before output stage
2065 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2066 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2067 // Effect chain for other sessions are inserted at beginning of effect
2068 // chains list to be processed before output mix effects. Relative order between other
2069 // sessions is not important
2070 size_t size = mEffectChains.size();
2071 size_t i = 0;
2072 for (i = 0; i < size; i++) {
2073 if (mEffectChains[i]->sessionId() < session) {
2074 break;
2075 }
2076 }
2077 mEffectChains.insertAt(chain, i);
2078 checkSuspendOnAddEffectChain_l(chain);
2079
2080 return NO_ERROR;
2081}
2082
2083size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2084{
2085 int session = chain->sessionId();
2086
2087 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2088
2089 for (size_t i = 0; i < mEffectChains.size(); i++) {
2090 if (chain == mEffectChains[i]) {
2091 mEffectChains.removeAt(i);
2092 // detach all active tracks from the chain
2093 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2094 sp<Track> track = mActiveTracks[i].promote();
2095 if (track == 0) {
2096 continue;
2097 }
2098 if (session == track->sessionId()) {
2099 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2100 chain.get(), session);
2101 chain->decActiveTrackCnt();
2102 }
2103 }
2104
2105 // detach all tracks with same session ID from this chain
2106 for (size_t i = 0; i < mTracks.size(); ++i) {
2107 sp<Track> track = mTracks[i];
2108 if (session == track->sessionId()) {
2109 track->setMainBuffer(mMixBuffer);
2110 chain->decTrackCnt();
2111 }
2112 }
2113 break;
2114 }
2115 }
2116 return mEffectChains.size();
2117}
2118
2119status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2120 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2121{
2122 Mutex::Autolock _l(mLock);
2123 return attachAuxEffect_l(track, EffectId);
2124}
2125
2126status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2127 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2128{
2129 status_t status = NO_ERROR;
2130
2131 if (EffectId == 0) {
2132 track->setAuxBuffer(0, NULL);
2133 } else {
2134 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2135 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2136 if (effect != 0) {
2137 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2138 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2139 } else {
2140 status = INVALID_OPERATION;
2141 }
2142 } else {
2143 status = BAD_VALUE;
2144 }
2145 }
2146 return status;
2147}
2148
2149void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2150{
2151 for (size_t i = 0; i < mTracks.size(); ++i) {
2152 sp<Track> track = mTracks[i];
2153 if (track->auxEffectId() == effectId) {
2154 attachAuxEffect_l(track, 0);
2155 }
2156 }
2157}
2158
2159bool AudioFlinger::PlaybackThread::threadLoop()
2160{
2161 Vector< sp<Track> > tracksToRemove;
2162
2163 standbyTime = systemTime();
2164
Alok Kediya601e9b52013-09-27 11:55:10 +05302165#ifdef SRS_PROCESSING
2166if (mType == MIXER) {
2167 POSTPRO_PATCH_ICS_OUTPROC_MIX_INIT(this, gettid());
2168 } else if (mType == DUPLICATING) {
2169 POSTPRO_PATCH_ICS_OUTPROC_DUPE_INIT(this, gettid());
2170 }
2171#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002172 // MIXER
2173 nsecs_t lastWarning = 0;
2174
2175 // DUPLICATING
2176 // FIXME could this be made local to while loop?
2177 writeFrames = 0;
2178
2179 cacheParameters_l();
2180 sleepTime = idleSleepTime;
2181
2182 if (mType == MIXER) {
2183 sleepTimeShift = 0;
2184 }
2185
2186 CpuStats cpuStats;
2187 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2188
2189 acquireWakeLock();
2190
Glenn Kasten9e58b552013-01-18 15:09:48 -08002191 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2192 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2193 // and then that string will be logged at the next convenient opportunity.
2194 const char *logString = NULL;
2195
Eric Laurent664539d2013-09-23 18:24:31 -07002196 checkSilentMode_l();
2197
Eric Laurent81784c32012-11-19 14:55:58 -08002198 while (!exitPending())
2199 {
2200 cpuStats.sample(myName);
2201
2202 Vector< sp<EffectChain> > effectChains;
2203
2204 processConfigEvents();
2205
2206 { // scope for mLock
2207
2208 Mutex::Autolock _l(mLock);
2209
Glenn Kasten9e58b552013-01-18 15:09:48 -08002210 if (logString != NULL) {
2211 mNBLogWriter->logTimestamp();
2212 mNBLogWriter->log(logString);
2213 logString = NULL;
2214 }
2215
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002216 if (mLatchDValid) {
2217 mLatchQ = mLatchD;
2218 mLatchDValid = false;
2219 mLatchQValid = true;
2220 }
2221
Eric Laurent81784c32012-11-19 14:55:58 -08002222 if (checkForNewParameters_l()) {
2223 cacheParameters_l();
2224 }
2225
2226 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 if (mSignalPending) {
2228 // A signal was raised while we were unlocked
2229 mSignalPending = false;
2230 } else if (waitingAsyncCallback_l()) {
2231 if (exitPending()) {
2232 break;
2233 }
2234 releaseWakeLock_l();
2235 ALOGV("wait async completion");
2236 mWaitWorkCV.wait(mLock);
2237 ALOGV("async completion/wake");
2238 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002239 standbyTime = systemTime() + standbyDelay;
2240 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002241
2242 continue;
2243 }
2244 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 isSuspended()) {
2246 // put audio hardware into standby after short delay
2247 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002248
2249 threadLoop_standby();
2250
2251 mStandby = true;
2252 }
2253
2254 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2255 // we're about to wait, flush the binder command buffer
2256 IPCThreadState::self()->flushCommands();
2257
2258 clearOutputTracks();
2259
2260 if (exitPending()) {
2261 break;
2262 }
2263
2264 releaseWakeLock_l();
2265 // wait until we have something to do...
2266 ALOGV("%s going to sleep", myName.string());
2267 mWaitWorkCV.wait(mLock);
2268 ALOGV("%s waking up", myName.string());
2269 acquireWakeLock_l();
2270
2271 mMixerStatus = MIXER_IDLE;
2272 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2273 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002275 checkSilentMode_l();
2276
2277 standbyTime = systemTime() + standbyDelay;
2278 sleepTime = idleSleepTime;
2279 if (mType == MIXER) {
2280 sleepTimeShift = 0;
2281 }
2282
2283 continue;
2284 }
2285 }
Eric Laurent81784c32012-11-19 14:55:58 -08002286 // mMixerStatusIgnoringFastTracks is also updated internally
2287 mMixerStatus = prepareTracks_l(&tracksToRemove);
2288
2289 // prevent any changes in effect chain list and in each effect chain
2290 // during mixing and effect process as the audio buffers could be deleted
2291 // or modified if an effect is created or deleted
2292 lockEffectChains_l(effectChains);
2293 }
2294
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295 if (mBytesRemaining == 0) {
2296 mCurrentWriteLength = 0;
2297 if (mMixerStatus == MIXER_TRACKS_READY) {
2298 // threadLoop_mix() sets mCurrentWriteLength
2299 threadLoop_mix();
2300 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2301 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2302 // threadLoop_sleepTime sets sleepTime to 0 if data
2303 // must be written to HAL
2304 threadLoop_sleepTime();
2305 if (sleepTime == 0) {
2306 mCurrentWriteLength = mixBufferSize;
2307 }
2308 }
2309 mBytesRemaining = mCurrentWriteLength;
2310 if (isSuspended()) {
2311 sleepTime = suspendSleepTimeUs();
2312 // simulate write to HAL when suspended
2313 mBytesWritten += mixBufferSize;
2314 mBytesRemaining = 0;
2315 }
Eric Laurent81784c32012-11-19 14:55:58 -08002316
Eric Laurentbfb1b832013-01-07 09:53:42 -08002317 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002318 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002319 for (size_t i = 0; i < effectChains.size(); i ++) {
Alok Kediya601e9b52013-09-27 11:55:10 +05302320 if (effectChains[i] != mAudioFlinger->mLPAEffectChain) {
2321 effectChains[i]->process_l();
2322 }
2323 }
Eric Laurent81784c32012-11-19 14:55:58 -08002324 }
2325 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002326 // Process effect chains for offloaded thread even if no audio
2327 // was read from audio track: process only updates effect state
2328 // and thus does have to be synchronized with audio writes but may have
2329 // to be called while waiting for async write callback
2330 if (mType == OFFLOAD) {
2331 for (size_t i = 0; i < effectChains.size(); i ++) {
Ethan Chendbfb39e2013-11-06 01:23:02 -08002332 effectChains[i]->process_l();
Eric Laurent59fe0102013-09-27 18:48:26 -07002333 }
2334 }
Eric Laurent81784c32012-11-19 14:55:58 -08002335
2336 // enable changes in effect chain
2337 unlockEffectChains(effectChains);
2338
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 if (!waitingAsyncCallback()) {
2340 // sleepTime == 0 means we must write to audio hardware
2341 if (sleepTime == 0) {
Alok Kediya601e9b52013-09-27 11:55:10 +05302342#ifdef SRS_PROCESSING
2343 if (mType == MIXER) {
2344 POSTPRO_PATCH_ICS_OUTPROC_MIX_SAMPLES(this, mFormat, mMixBuffer,
2345 mixBufferSize, mSampleRate, mChannelCount);
2346 } else if (mType == DUPLICATING) {
2347 POSTPRO_PATCH_ICS_OUTPROC_DUPE_SAMPLES(this, mFormat, mMixBuffer,
2348 mixBufferSize, mSampleRate, mChannelCount);
2349 }
2350#endif
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 if (mBytesRemaining) {
2352 ssize_t ret = threadLoop_write();
2353 if (ret < 0) {
2354 mBytesRemaining = 0;
2355 } else {
2356 mBytesWritten += ret;
2357 mBytesRemaining -= ret;
2358 }
2359 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2360 (mMixerStatus == MIXER_DRAIN_ALL)) {
2361 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002362 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363if (mType == MIXER) {
2364 // write blocked detection
2365 nsecs_t now = systemTime();
2366 nsecs_t delta = now - mLastWriteTime;
2367 if (!mStandby && delta > maxPeriod) {
2368 mNumDelayedWrites++;
2369 if ((now - lastWarning) > kWarningThrottleNs) {
2370 ATRACE_NAME("underrun");
2371 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2372 ns2ms(delta), mNumDelayedWrites, this);
2373 lastWarning = now;
2374 }
2375 }
Eric Laurent81784c32012-11-19 14:55:58 -08002376}
2377
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 mStandby = false;
2379 } else {
2380 usleep(sleepTime);
2381 }
Eric Laurent81784c32012-11-19 14:55:58 -08002382 }
2383
2384 // Finally let go of removed track(s), without the lock held
2385 // since we can't guarantee the destructors won't acquire that
2386 // same lock. This will also mutate and push a new fast mixer state.
2387 threadLoop_removeTracks(tracksToRemove);
2388 tracksToRemove.clear();
2389
2390 // FIXME I don't understand the need for this here;
2391 // it was in the original code but maybe the
2392 // assignment in saveOutputTracks() makes this unnecessary?
2393 clearOutputTracks();
2394
2395 // Effect chains will be actually deleted here if they were removed from
2396 // mEffectChains list during mixing or effects processing
2397 effectChains.clear();
2398
2399 // FIXME Note that the above .clear() is no longer necessary since effectChains
2400 // is now local to this block, but will keep it for now (at least until merge done).
2401 }
2402
Eric Laurentbfb1b832013-01-07 09:53:42 -08002403 threadLoop_exit();
2404
Eric Laurent81784c32012-11-19 14:55:58 -08002405 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002407 // put output stream into standby mode
2408 if (!mStandby) {
2409 mOutput->stream->common.standby(&mOutput->stream->common);
2410 }
2411 }
2412
Alok Kediya601e9b52013-09-27 11:55:10 +05302413#ifdef SRS_PROCESSING
2414 if (mType == MIXER) {
2415 POSTPRO_PATCH_ICS_OUTPROC_MIX_EXIT(this, gettid());
2416 } else if (mType == DUPLICATING) {
2417 POSTPRO_PATCH_ICS_OUTPROC_DUPE_EXIT(this, gettid());
2418 }
2419#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002420 releaseWakeLock();
2421
2422 ALOGV("Thread %p type %d exiting", this, mType);
2423 return false;
2424}
2425
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426// removeTracks_l() must be called with ThreadBase::mLock held
2427void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2428{
2429 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002430 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002431 for (size_t i=0 ; i<count ; i++) {
2432 const sp<Track>& track = tracksToRemove.itemAt(i);
2433 mActiveTracks.remove(track);
2434 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2435 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2436 if (chain != 0) {
2437 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2438 track->sessionId());
2439 chain->decActiveTrackCnt();
2440 }
2441 if (track->isTerminated()) {
2442 removeTrack_l(track);
2443 }
2444 }
2445 }
2446
2447}
Eric Laurent81784c32012-11-19 14:55:58 -08002448
Eric Laurentaccc1472013-09-20 09:36:34 -07002449status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2450{
2451 if (mNormalSink != 0) {
2452 return mNormalSink->getTimestamp(timestamp);
2453 }
2454 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2455 uint64_t position64;
2456 int ret = mOutput->stream->get_presentation_position(
2457 mOutput->stream, &position64, &timestamp.mTime);
2458 if (ret == 0) {
2459 timestamp.mPosition = (uint32_t)position64;
2460 return NO_ERROR;
2461 }
2462 }
2463 return INVALID_OPERATION;
2464}
Eric Laurent81784c32012-11-19 14:55:58 -08002465// ----------------------------------------------------------------------------
2466
2467AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2468 audio_io_handle_t id, audio_devices_t device, type_t type)
2469 : PlaybackThread(audioFlinger, output, id, device, type),
2470 // mAudioMixer below
2471 // mFastMixer below
2472 mFastMixerFutex(0)
2473 // mOutputSink below
2474 // mPipeSink below
2475 // mNormalSink below
2476{
2477 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002478 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002479 "mFrameCount=%d, mNormalFrameCount=%d",
2480 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2481 mNormalFrameCount);
2482 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2483
2484 // FIXME - Current mixer implementation only supports stereo output
2485 if (mChannelCount != FCC_2) {
2486 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2487 }
2488
2489 // create an NBAIO sink for the HAL output stream, and negotiate
2490 mOutputSink = new AudioStreamOutSink(output->stream);
2491 size_t numCounterOffers = 0;
2492 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2493 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2494 ALOG_ASSERT(index == 0);
2495
2496 // initialize fast mixer depending on configuration
2497 bool initFastMixer;
2498 switch (kUseFastMixer) {
2499 case FastMixer_Never:
2500 initFastMixer = false;
2501 break;
2502 case FastMixer_Always:
2503 initFastMixer = true;
2504 break;
2505 case FastMixer_Static:
2506 case FastMixer_Dynamic:
2507 initFastMixer = mFrameCount < mNormalFrameCount;
2508 break;
2509 }
2510 if (initFastMixer) {
2511
2512 // create a MonoPipe to connect our submix to FastMixer
2513 NBAIO_Format format = mOutputSink->format();
2514 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2515 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2516 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2517 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2518 const NBAIO_Format offers[1] = {format};
2519 size_t numCounterOffers = 0;
2520 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2521 ALOG_ASSERT(index == 0);
2522 monoPipe->setAvgFrames((mScreenState & 1) ?
2523 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2524 mPipeSink = monoPipe;
2525
Glenn Kasten46909e72013-02-26 09:20:22 -08002526#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002527 if (mTeeSinkOutputEnabled) {
2528 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2529 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2530 numCounterOffers = 0;
2531 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2532 ALOG_ASSERT(index == 0);
2533 mTeeSink = teeSink;
2534 PipeReader *teeSource = new PipeReader(*teeSink);
2535 numCounterOffers = 0;
2536 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2537 ALOG_ASSERT(index == 0);
2538 mTeeSource = teeSource;
2539 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002540#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002541
2542 // create fast mixer and configure it initially with just one fast track for our submix
2543 mFastMixer = new FastMixer();
2544 FastMixerStateQueue *sq = mFastMixer->sq();
2545#ifdef STATE_QUEUE_DUMP
2546 sq->setObserverDump(&mStateQueueObserverDump);
2547 sq->setMutatorDump(&mStateQueueMutatorDump);
2548#endif
2549 FastMixerState *state = sq->begin();
2550 FastTrack *fastTrack = &state->mFastTracks[0];
2551 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2552 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2553 fastTrack->mVolumeProvider = NULL;
2554 fastTrack->mGeneration++;
2555 state->mFastTracksGen++;
2556 state->mTrackMask = 1;
2557 // fast mixer will use the HAL output sink
2558 state->mOutputSink = mOutputSink.get();
2559 state->mOutputSinkGen++;
2560 state->mFrameCount = mFrameCount;
2561 state->mCommand = FastMixerState::COLD_IDLE;
2562 // already done in constructor initialization list
2563 //mFastMixerFutex = 0;
2564 state->mColdFutexAddr = &mFastMixerFutex;
2565 state->mColdGen++;
2566 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002567#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002568 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002569#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002570 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2571 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002572 sq->end();
2573 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2574
2575 // start the fast mixer
2576 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2577 pid_t tid = mFastMixer->getTid();
2578 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2579 if (err != 0) {
2580 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2581 kPriorityFastMixer, getpid_cached, tid, err);
2582 }
2583
2584#ifdef AUDIO_WATCHDOG
2585 // create and start the watchdog
2586 mAudioWatchdog = new AudioWatchdog();
2587 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2588 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2589 tid = mAudioWatchdog->getTid();
2590 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2591 if (err != 0) {
2592 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2593 kPriorityFastMixer, getpid_cached, tid, err);
2594 }
2595#endif
2596
2597 } else {
2598 mFastMixer = NULL;
2599 }
2600
2601 switch (kUseFastMixer) {
2602 case FastMixer_Never:
2603 case FastMixer_Dynamic:
2604 mNormalSink = mOutputSink;
2605 break;
2606 case FastMixer_Always:
2607 mNormalSink = mPipeSink;
2608 break;
2609 case FastMixer_Static:
2610 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2611 break;
2612 }
2613}
2614
2615AudioFlinger::MixerThread::~MixerThread()
2616{
2617 if (mFastMixer != NULL) {
2618 FastMixerStateQueue *sq = mFastMixer->sq();
2619 FastMixerState *state = sq->begin();
2620 if (state->mCommand == FastMixerState::COLD_IDLE) {
2621 int32_t old = android_atomic_inc(&mFastMixerFutex);
2622 if (old == -1) {
2623 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2624 }
2625 }
2626 state->mCommand = FastMixerState::EXIT;
2627 sq->end();
2628 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2629 mFastMixer->join();
2630 // Though the fast mixer thread has exited, it's state queue is still valid.
2631 // We'll use that extract the final state which contains one remaining fast track
2632 // corresponding to our sub-mix.
2633 state = sq->begin();
2634 ALOG_ASSERT(state->mTrackMask == 1);
2635 FastTrack *fastTrack = &state->mFastTracks[0];
2636 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2637 delete fastTrack->mBufferProvider;
2638 sq->end(false /*didModify*/);
2639 delete mFastMixer;
2640#ifdef AUDIO_WATCHDOG
2641 if (mAudioWatchdog != 0) {
2642 mAudioWatchdog->requestExit();
2643 mAudioWatchdog->requestExitAndWait();
2644 mAudioWatchdog.clear();
2645 }
2646#endif
2647 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002648 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002649 delete mAudioMixer;
2650}
2651
2652
2653uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2654{
2655 if (mFastMixer != NULL) {
2656 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
Alok Kediya601e9b52013-09-27 11:55:10 +05302657 if(mSampleRate)
2658 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2659 else
2660 ALOGW("SampleRate is 0");
Eric Laurent81784c32012-11-19 14:55:58 -08002661 }
2662 return latency;
2663}
2664
2665
2666void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2667{
2668 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2669}
2670
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002672{
2673 // FIXME we should only do one push per cycle; confirm this is true
2674 // Start the fast mixer if it's not already running
2675 if (mFastMixer != NULL) {
2676 FastMixerStateQueue *sq = mFastMixer->sq();
2677 FastMixerState *state = sq->begin();
2678 if (state->mCommand != FastMixerState::MIX_WRITE &&
2679 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2680 if (state->mCommand == FastMixerState::COLD_IDLE) {
2681 int32_t old = android_atomic_inc(&mFastMixerFutex);
2682 if (old == -1) {
2683 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2684 }
2685#ifdef AUDIO_WATCHDOG
2686 if (mAudioWatchdog != 0) {
2687 mAudioWatchdog->resume();
2688 }
2689#endif
2690 }
2691 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002692 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2693 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002694 sq->end();
2695 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2696 if (kUseFastMixer == FastMixer_Dynamic) {
2697 mNormalSink = mPipeSink;
2698 }
2699 } else {
2700 sq->end(false /*didModify*/);
2701 }
2702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002704}
2705
2706void AudioFlinger::MixerThread::threadLoop_standby()
2707{
2708 // Idle the fast mixer if it's currently running
2709 if (mFastMixer != NULL) {
2710 FastMixerStateQueue *sq = mFastMixer->sq();
2711 FastMixerState *state = sq->begin();
2712 if (!(state->mCommand & FastMixerState::IDLE)) {
2713 state->mCommand = FastMixerState::COLD_IDLE;
2714 state->mColdFutexAddr = &mFastMixerFutex;
2715 state->mColdGen++;
2716 mFastMixerFutex = 0;
2717 sq->end();
2718 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2719 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2720 if (kUseFastMixer == FastMixer_Dynamic) {
2721 mNormalSink = mOutputSink;
2722 }
2723#ifdef AUDIO_WATCHDOG
2724 if (mAudioWatchdog != 0) {
2725 mAudioWatchdog->pause();
2726 }
2727#endif
2728 } else {
2729 sq->end(false /*didModify*/);
2730 }
2731 }
2732 PlaybackThread::threadLoop_standby();
2733}
2734
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735// Empty implementation for standard mixer
2736// Overridden for offloaded playback
2737void AudioFlinger::PlaybackThread::flushOutput_l()
2738{
2739}
2740
2741bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2742{
2743 return false;
2744}
2745
2746bool AudioFlinger::PlaybackThread::shouldStandby_l()
2747{
2748 return !mStandby;
2749}
2750
2751bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2752{
2753 Mutex::Autolock _l(mLock);
2754 return waitingAsyncCallback_l();
2755}
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757// shared by MIXER and DIRECT, overridden by DUPLICATING
2758void AudioFlinger::PlaybackThread::threadLoop_standby()
2759{
2760 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2761 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002763 // discard any pending drain or write ack by incrementing sequence
2764 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2765 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002766 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002767 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2768 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 }
Eric Laurent81784c32012-11-19 14:55:58 -08002770}
2771
2772void AudioFlinger::MixerThread::threadLoop_mix()
2773{
2774 // obtain the presentation timestamp of the next output buffer
2775 int64_t pts;
2776 status_t status = INVALID_OPERATION;
2777
Ricardo Cerqueira0d44b5b2013-11-03 02:46:27 +00002778#ifndef ICS_AUDIO_BLOB
Eric Laurent81784c32012-11-19 14:55:58 -08002779 if (mNormalSink != 0) {
2780 status = mNormalSink->getNextWriteTimestamp(&pts);
2781 } else {
2782 status = mOutputSink->getNextWriteTimestamp(&pts);
2783 }
Ricardo Cerqueira0d44b5b2013-11-03 02:46:27 +00002784#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002785
2786 if (status != NO_ERROR) {
2787 pts = AudioBufferProvider::kInvalidPTS;
2788 }
2789
2790 // mix buffers...
2791 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002793 // increase sleep time progressively when application underrun condition clears.
2794 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2795 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2796 // such that we would underrun the audio HAL.
2797 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2798 sleepTimeShift--;
2799 }
2800 sleepTime = 0;
2801 standbyTime = systemTime() + standbyDelay;
2802 //TODO: delay standby when effects have a tail
2803}
2804
2805void AudioFlinger::MixerThread::threadLoop_sleepTime()
2806{
2807 // If no tracks are ready, sleep once for the duration of an output
2808 // buffer size, then write 0s to the output
2809 if (sleepTime == 0) {
2810 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2811 sleepTime = activeSleepTime >> sleepTimeShift;
2812 if (sleepTime < kMinThreadSleepTimeUs) {
2813 sleepTime = kMinThreadSleepTimeUs;
2814 }
2815 // reduce sleep time in case of consecutive application underruns to avoid
2816 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2817 // duration we would end up writing less data than needed by the audio HAL if
2818 // the condition persists.
2819 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2820 sleepTimeShift++;
2821 }
2822 } else {
2823 sleepTime = idleSleepTime;
2824 }
2825 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2826 memset (mMixBuffer, 0, mixBufferSize);
2827 sleepTime = 0;
2828 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2829 "anticipated start");
2830 }
2831 // TODO add standby time extension fct of effect tail
2832}
2833
2834// prepareTracks_l() must be called with ThreadBase::mLock held
2835AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2836 Vector< sp<Track> > *tracksToRemove)
2837{
2838
2839 mixer_state mixerStatus = MIXER_IDLE;
2840 // find out which tracks need to be processed
2841 size_t count = mActiveTracks.size();
2842 size_t mixedTracks = 0;
2843 size_t tracksWithEffect = 0;
2844 // counts only _active_ fast tracks
2845 size_t fastTracks = 0;
2846 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2847
2848 float masterVolume = mMasterVolume;
2849 bool masterMute = mMasterMute;
2850
2851 if (masterMute) {
2852 masterVolume = 0;
2853 }
2854 // Delegate master volume control to effect in output mix effect chain if needed
2855 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2856 if (chain != 0) {
2857 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2858 chain->setVolume_l(&v, &v);
2859 masterVolume = (float)((v + (1 << 23)) >> 24);
2860 chain.clear();
2861 }
2862
2863 // prepare a new state to push
2864 FastMixerStateQueue *sq = NULL;
2865 FastMixerState *state = NULL;
2866 bool didModify = false;
2867 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2868 if (mFastMixer != NULL) {
2869 sq = mFastMixer->sq();
2870 state = sq->begin();
2871 }
2872
2873 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002874 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002875 if (t == 0) {
2876 continue;
2877 }
2878
2879 // this const just means the local variable doesn't change
2880 Track* const track = t.get();
2881
2882 // process fast tracks
2883 if (track->isFastTrack()) {
2884
2885 // It's theoretically possible (though unlikely) for a fast track to be created
2886 // and then removed within the same normal mix cycle. This is not a problem, as
2887 // the track never becomes active so it's fast mixer slot is never touched.
2888 // The converse, of removing an (active) track and then creating a new track
2889 // at the identical fast mixer slot within the same normal mix cycle,
2890 // is impossible because the slot isn't marked available until the end of each cycle.
2891 int j = track->mFastIndex;
2892 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2893 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2894 FastTrack *fastTrack = &state->mFastTracks[j];
2895
2896 // Determine whether the track is currently in underrun condition,
2897 // and whether it had a recent underrun.
2898 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2899 FastTrackUnderruns underruns = ftDump->mUnderruns;
2900 uint32_t recentFull = (underruns.mBitFields.mFull -
2901 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2902 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2903 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2904 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2905 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2906 uint32_t recentUnderruns = recentPartial + recentEmpty;
2907 track->mObservedUnderruns = underruns;
2908 // don't count underruns that occur while stopping or pausing
2909 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002910 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2911 recentUnderruns > 0) {
2912 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2913 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002914 }
2915
2916 // This is similar to the state machine for normal tracks,
2917 // with a few modifications for fast tracks.
2918 bool isActive = true;
2919 switch (track->mState) {
2920 case TrackBase::STOPPING_1:
2921 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002923 track->mState = TrackBase::STOPPING_2;
2924 }
2925 break;
2926 case TrackBase::PAUSING:
2927 // ramp down is not yet implemented
2928 track->setPaused();
2929 break;
2930 case TrackBase::RESUMING:
2931 // ramp up is not yet implemented
2932 track->mState = TrackBase::ACTIVE;
2933 break;
2934 case TrackBase::ACTIVE:
2935 if (recentFull > 0 || recentPartial > 0) {
2936 // track has provided at least some frames recently: reset retry count
2937 track->mRetryCount = kMaxTrackRetries;
2938 }
2939 if (recentUnderruns == 0) {
2940 // no recent underruns: stay active
2941 break;
2942 }
2943 // there has recently been an underrun of some kind
2944 if (track->sharedBuffer() == 0) {
2945 // were any of the recent underruns "empty" (no frames available)?
2946 if (recentEmpty == 0) {
2947 // no, then ignore the partial underruns as they are allowed indefinitely
2948 break;
2949 }
2950 // there has recently been an "empty" underrun: decrement the retry counter
2951 if (--(track->mRetryCount) > 0) {
2952 break;
2953 }
2954 // indicate to client process that the track was disabled because of underrun;
2955 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002956 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002957 // remove from active list, but state remains ACTIVE [confusing but true]
2958 isActive = false;
2959 break;
2960 }
2961 // fall through
2962 case TrackBase::STOPPING_2:
2963 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002964 case TrackBase::STOPPED:
2965 case TrackBase::FLUSHED: // flush() while active
2966 // Check for presentation complete if track is inactive
2967 // We have consumed all the buffers of this track.
2968 // This would be incomplete if we auto-paused on underrun
2969 {
2970 size_t audioHALFrames =
2971 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2972 size_t framesWritten = mBytesWritten / mFrameSize;
2973 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2974 // track stays in active list until presentation is complete
2975 break;
2976 }
2977 }
2978 if (track->isStopping_2()) {
2979 track->mState = TrackBase::STOPPED;
2980 }
2981 if (track->isStopped()) {
2982 // Can't reset directly, as fast mixer is still polling this track
2983 // track->reset();
2984 // So instead mark this track as needing to be reset after push with ack
2985 resetMask |= 1 << i;
2986 }
2987 isActive = false;
2988 break;
2989 case TrackBase::IDLE:
2990 default:
2991 LOG_FATAL("unexpected track state %d", track->mState);
2992 }
2993
2994 if (isActive) {
2995 // was it previously inactive?
2996 if (!(state->mTrackMask & (1 << j))) {
2997 ExtendedAudioBufferProvider *eabp = track;
2998 VolumeProvider *vp = track;
2999 fastTrack->mBufferProvider = eabp;
3000 fastTrack->mVolumeProvider = vp;
3001 fastTrack->mSampleRate = track->mSampleRate;
3002 fastTrack->mChannelMask = track->mChannelMask;
3003 fastTrack->mGeneration++;
3004 state->mTrackMask |= 1 << j;
3005 didModify = true;
3006 // no acknowledgement required for newly active tracks
3007 }
3008 // cache the combined master volume and stream type volume for fast mixer; this
3009 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003010 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003011 ++fastTracks;
3012 } else {
3013 // was it previously active?
3014 if (state->mTrackMask & (1 << j)) {
3015 fastTrack->mBufferProvider = NULL;
3016 fastTrack->mGeneration++;
3017 state->mTrackMask &= ~(1 << j);
3018 didModify = true;
3019 // If any fast tracks were removed, we must wait for acknowledgement
3020 // because we're about to decrement the last sp<> on those tracks.
3021 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3022 } else {
3023 LOG_FATAL("fast track %d should have been active", j);
3024 }
3025 tracksToRemove->add(track);
3026 // Avoids a misleading display in dumpsys
3027 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3028 }
3029 continue;
3030 }
3031
3032 { // local variable scope to avoid goto warning
3033
3034 audio_track_cblk_t* cblk = track->cblk();
3035
3036 // The first time a track is added we wait
3037 // for all its buffers to be filled before processing it
3038 int name = track->name();
3039 // make sure that we have enough frames to mix one full buffer.
3040 // enforce this condition only once to enable draining the buffer in case the client
3041 // app does not call stop() and relies on underrun to stop:
3042 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3043 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003044 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003045 uint32_t sr = track->sampleRate();
3046 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003047 desiredFrames = mNormalFrameCount;
3048 } else {
3049 // +1 for rounding and +1 for additional sample needed for interpolation
Alok Kediya601e9b52013-09-27 11:55:10 +05303050 if (mSampleRate) {
3051 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
3052 } else {
3053 desiredFrames = 2;
3054 ALOGW("SampleRate is 0");
3055 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003056 // add frames already consumed but not yet released by the resampler
3057 // because cblk->framesReady() will include these frames
3058 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3059 // the minimum track buffer size is normally twice the number of frames necessary
3060 // to fill one buffer and the resampler should not leave more than one buffer worth
3061 // of unreleased frames after each pass, but just in case...
3062 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3063 }
Eric Laurent81784c32012-11-19 14:55:58 -08003064 uint32_t minFrames = 1;
3065 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3066 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003067 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003068 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003069 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
3070 size_t framesReady;
3071 if (track->sharedBuffer() == 0) {
3072 framesReady = track->framesReady();
3073 } else if (track->isStopped()) {
3074 framesReady = 0;
3075 } else {
3076 framesReady = 1;
3077 }
3078 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003079 !track->isPaused() && !track->isTerminated())
3080 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003081 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003082
3083 mixedTracks++;
3084
3085 // track->mainBuffer() != mMixBuffer means there is an effect chain
3086 // connected to the track
3087 chain.clear();
3088 if (track->mainBuffer() != mMixBuffer) {
3089 chain = getEffectChain_l(track->sessionId());
3090 // Delegate volume control to effect in track effect chain if needed
3091 if (chain != 0) {
3092 tracksWithEffect++;
3093 } else {
3094 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3095 "session %d",
3096 name, track->sessionId());
3097 }
3098 }
3099
3100
3101 int param = AudioMixer::VOLUME;
3102 if (track->mFillingUpStatus == Track::FS_FILLED) {
3103 // no ramp for the first volume setting
3104 track->mFillingUpStatus = Track::FS_ACTIVE;
3105 if (track->mState == TrackBase::RESUMING) {
3106 track->mState = TrackBase::ACTIVE;
3107 param = AudioMixer::RAMP_VOLUME;
3108 }
3109 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003110 // FIXME should not make a decision based on mServer
3111 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003112 // If the track is stopped before the first frame was mixed,
3113 // do not apply ramp
3114 param = AudioMixer::RAMP_VOLUME;
3115 }
3116
3117 // compute volume for this track
3118 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003119 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003120 vl = vr = va = 0;
3121 if (track->isPausing()) {
3122 track->setPaused();
3123 }
3124 } else {
3125
3126 // read original volumes with volume control
3127 float typeVolume = mStreamTypes[track->streamType()].volume;
3128 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003129 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003130 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003131 vl = vlr & 0xFFFF;
3132 vr = vlr >> 16;
3133 // track volumes come from shared memory, so can't be trusted and must be clamped
3134 if (vl > MAX_GAIN_INT) {
3135 ALOGV("Track left volume out of range: %04X", vl);
3136 vl = MAX_GAIN_INT;
3137 }
3138 if (vr > MAX_GAIN_INT) {
3139 ALOGV("Track right volume out of range: %04X", vr);
3140 vr = MAX_GAIN_INT;
3141 }
3142 // now apply the master volume and stream type volume
3143 vl = (uint32_t)(v * vl) << 12;
3144 vr = (uint32_t)(v * vr) << 12;
3145 // assuming master volume and stream type volume each go up to 1.0,
3146 // vl and vr are now in 8.24 format
3147
Glenn Kastene3aa6592012-12-04 12:22:46 -08003148 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003149 // send level comes from shared memory and so may be corrupt
3150 if (sendLevel > MAX_GAIN_INT) {
3151 ALOGV("Track send level out of range: %04X", sendLevel);
3152 sendLevel = MAX_GAIN_INT;
3153 }
3154 va = (uint32_t)(v * sendLevel);
3155 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156
Eric Laurent81784c32012-11-19 14:55:58 -08003157 // Delegate volume control to effect in track effect chain if needed
3158 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3159 // Do not ramp volume if volume is controlled by effect
3160 param = AudioMixer::VOLUME;
3161 track->mHasVolumeController = true;
3162 } else {
3163 // force no volume ramp when volume controller was just disabled or removed
3164 // from effect chain to avoid volume spike
3165 if (track->mHasVolumeController) {
3166 param = AudioMixer::VOLUME;
3167 }
3168 track->mHasVolumeController = false;
3169 }
3170
3171 // Convert volumes from 8.24 to 4.12 format
3172 // This additional clamping is needed in case chain->setVolume_l() overshot
3173 vl = (vl + (1 << 11)) >> 12;
3174 if (vl > MAX_GAIN_INT) {
3175 vl = MAX_GAIN_INT;
3176 }
3177 vr = (vr + (1 << 11)) >> 12;
3178 if (vr > MAX_GAIN_INT) {
3179 vr = MAX_GAIN_INT;
3180 }
3181
3182 if (va > MAX_GAIN_INT) {
3183 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3184 }
3185
3186 // XXX: these things DON'T need to be done each time
3187 mAudioMixer->setBufferProvider(name, track);
3188 mAudioMixer->enable(name);
3189
3190 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3191 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3192 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3193 mAudioMixer->setParameter(
3194 name,
3195 AudioMixer::TRACK,
3196 AudioMixer::FORMAT, (void *)track->format());
3197 mAudioMixer->setParameter(
3198 name,
3199 AudioMixer::TRACK,
3200 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003201 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3202 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003203 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003204 if (reqSampleRate == 0) {
3205 reqSampleRate = mSampleRate;
3206 } else if (reqSampleRate > maxSampleRate) {
3207 reqSampleRate = maxSampleRate;
3208 }
Eric Laurent81784c32012-11-19 14:55:58 -08003209 mAudioMixer->setParameter(
3210 name,
3211 AudioMixer::RESAMPLE,
3212 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003213 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003214 mAudioMixer->setParameter(
3215 name,
3216 AudioMixer::TRACK,
3217 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3218 mAudioMixer->setParameter(
3219 name,
3220 AudioMixer::TRACK,
3221 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3222
3223 // reset retry count
3224 track->mRetryCount = kMaxTrackRetries;
3225
3226 // If one track is ready, set the mixer ready if:
3227 // - the mixer was not ready during previous round OR
3228 // - no other track is not ready
3229 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3230 mixerStatus != MIXER_TRACKS_ENABLED) {
3231 mixerStatus = MIXER_TRACKS_READY;
3232 }
3233 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003234 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003235 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003236 }
Eric Laurent81784c32012-11-19 14:55:58 -08003237 // clear effect chain input buffer if an active track underruns to avoid sending
3238 // previous audio buffer again to effects
3239 chain = getEffectChain_l(track->sessionId());
3240 if (chain != 0) {
3241 chain->clearInputBuffer();
3242 }
3243
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003244 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003245 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3246 track->isStopped() || track->isPaused()) {
3247 // We have consumed all the buffers of this track.
3248 // Remove it from the list of active tracks.
3249 // TODO: use actual buffer filling status instead of latency when available from
3250 // audio HAL
3251 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3252 size_t framesWritten = mBytesWritten / mFrameSize;
3253 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3254 if (track->isStopped()) {
3255 track->reset();
3256 }
3257 tracksToRemove->add(track);
3258 }
3259 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003260 // No buffers for this track. Give it a few chances to
3261 // fill a buffer, then remove it from active list.
3262 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003263 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003264 tracksToRemove->add(track);
3265 // indicate to client process that the track was disabled because of underrun;
3266 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003267 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003268 // If one track is not ready, mark the mixer also not ready if:
3269 // - the mixer was ready during previous round OR
3270 // - no other track is ready
3271 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3272 mixerStatus != MIXER_TRACKS_READY) {
3273 mixerStatus = MIXER_TRACKS_ENABLED;
3274 }
3275 }
3276 mAudioMixer->disable(name);
3277 }
3278
3279 } // local variable scope to avoid goto warning
3280track_is_ready: ;
3281
3282 }
3283
3284 // Push the new FastMixer state if necessary
3285 bool pauseAudioWatchdog = false;
3286 if (didModify) {
3287 state->mFastTracksGen++;
3288 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3289 if (kUseFastMixer == FastMixer_Dynamic &&
3290 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3291 state->mCommand = FastMixerState::COLD_IDLE;
3292 state->mColdFutexAddr = &mFastMixerFutex;
3293 state->mColdGen++;
3294 mFastMixerFutex = 0;
3295 if (kUseFastMixer == FastMixer_Dynamic) {
3296 mNormalSink = mOutputSink;
3297 }
3298 // If we go into cold idle, need to wait for acknowledgement
3299 // so that fast mixer stops doing I/O.
3300 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3301 pauseAudioWatchdog = true;
3302 }
Eric Laurent81784c32012-11-19 14:55:58 -08003303 }
3304 if (sq != NULL) {
3305 sq->end(didModify);
3306 sq->push(block);
3307 }
3308#ifdef AUDIO_WATCHDOG
3309 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3310 mAudioWatchdog->pause();
3311 }
3312#endif
3313
3314 // Now perform the deferred reset on fast tracks that have stopped
3315 while (resetMask != 0) {
3316 size_t i = __builtin_ctz(resetMask);
3317 ALOG_ASSERT(i < count);
3318 resetMask &= ~(1 << i);
3319 sp<Track> t = mActiveTracks[i].promote();
3320 if (t == 0) {
3321 continue;
3322 }
3323 Track* track = t.get();
3324 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3325 track->reset();
3326 }
3327
3328 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003330
3331 // mix buffer must be cleared if all tracks are connected to an
3332 // effect chain as in this case the mixer will not write to
3333 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003334 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3335 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003336 // FIXME as a performance optimization, should remember previous zero status
3337 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3338 }
3339
3340 // if any fast tracks, then status is ready
3341 mMixerStatusIgnoringFastTracks = mixerStatus;
3342 if (fastTracks > 0) {
3343 mixerStatus = MIXER_TRACKS_READY;
3344 }
3345 return mixerStatus;
3346}
3347
3348// getTrackName_l() must be called with ThreadBase::mLock held
3349int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3350{
3351 return mAudioMixer->getTrackName(channelMask, sessionId);
3352}
3353
3354// deleteTrackName_l() must be called with ThreadBase::mLock held
3355void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3356{
3357 ALOGV("remove track (%d) and delete from mixer", name);
3358 mAudioMixer->deleteTrackName(name);
3359}
3360
3361// checkForNewParameters_l() must be called with ThreadBase::mLock held
3362bool AudioFlinger::MixerThread::checkForNewParameters_l()
3363{
3364 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3365 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3366 bool reconfig = false;
3367
3368 while (!mNewParameters.isEmpty()) {
3369
3370 if (mFastMixer != NULL) {
3371 FastMixerStateQueue *sq = mFastMixer->sq();
3372 FastMixerState *state = sq->begin();
3373 if (!(state->mCommand & FastMixerState::IDLE)) {
3374 previousCommand = state->mCommand;
3375 state->mCommand = FastMixerState::HOT_IDLE;
3376 sq->end();
3377 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3378 } else {
3379 sq->end(false /*didModify*/);
3380 }
3381 }
3382
3383 status_t status = NO_ERROR;
3384 String8 keyValuePair = mNewParameters[0];
3385 AudioParameter param = AudioParameter(keyValuePair);
3386 int value;
3387
Alok Kediya601e9b52013-09-27 11:55:10 +05303388#ifdef SRS_PROCESSING
3389 POSTPRO_PATCH_ICS_OUTPROC_MIX_ROUTE(this, param, value);
3390#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003391 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3392 reconfig = true;
3393 }
3394 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3395 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3396 status = BAD_VALUE;
3397 } else {
3398 reconfig = true;
3399 }
3400 }
3401 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003402 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003403 status = BAD_VALUE;
3404 } else {
3405 reconfig = true;
3406 }
3407 }
3408 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3409 // do not accept frame count changes if tracks are open as the track buffer
3410 // size depends on frame count and correct behavior would not be guaranteed
3411 // if frame count is changed after track creation
3412 if (!mTracks.isEmpty()) {
3413 status = INVALID_OPERATION;
3414 } else {
3415 reconfig = true;
3416 }
3417 }
3418 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3419#ifdef ADD_BATTERY_DATA
3420 // when changing the audio output device, call addBatteryData to notify
3421 // the change
3422 if (mOutDevice != value) {
3423 uint32_t params = 0;
3424 // check whether speaker is on
3425 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3426 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3427 }
3428
3429 audio_devices_t deviceWithoutSpeaker
3430 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3431 // check if any other device (except speaker) is on
3432 if (value & deviceWithoutSpeaker ) {
3433 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3434 }
3435
3436 if (params != 0) {
3437 addBatteryData(params);
3438 }
3439 }
3440#endif
3441
3442 // forward device change to effects that have requested to be
3443 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003444 if (value != AUDIO_DEVICE_NONE) {
3445 mOutDevice = value;
3446 for (size_t i = 0; i < mEffectChains.size(); i++) {
3447 mEffectChains[i]->setDevice_l(mOutDevice);
3448 }
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
3450 }
3451
3452 if (status == NO_ERROR) {
3453 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3454 keyValuePair.string());
3455 if (!mStandby && status == INVALID_OPERATION) {
3456 mOutput->stream->common.standby(&mOutput->stream->common);
3457 mStandby = true;
3458 mBytesWritten = 0;
3459 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3460 keyValuePair.string());
3461 }
3462 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003463 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003464 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003465 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3466 for (size_t i = 0; i < mTracks.size() ; i++) {
3467 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3468 if (name < 0) {
3469 break;
3470 }
3471 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3474 }
3475 }
3476
3477 mNewParameters.removeAt(0);
3478
3479 mParamStatus = status;
3480 mParamCond.signal();
3481 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3482 // already timed out waiting for the status and will never signal the condition.
3483 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3484 }
3485
3486 if (!(previousCommand & FastMixerState::IDLE)) {
3487 ALOG_ASSERT(mFastMixer != NULL);
3488 FastMixerStateQueue *sq = mFastMixer->sq();
3489 FastMixerState *state = sq->begin();
3490 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3491 state->mCommand = previousCommand;
3492 sq->end();
3493 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3494 }
3495
3496 return reconfig;
3497}
3498
3499
3500void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3501{
3502 const size_t SIZE = 256;
3503 char buffer[SIZE];
3504 String8 result;
3505
3506 PlaybackThread::dumpInternals(fd, args);
3507
3508 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3509 result.append(buffer);
3510 write(fd, result.string(), result.size());
3511
3512 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003513 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003514 copy.dump(fd);
3515
3516#ifdef STATE_QUEUE_DUMP
3517 // Similar for state queue
3518 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3519 observerCopy.dump(fd);
3520 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3521 mutatorCopy.dump(fd);
3522#endif
3523
Glenn Kasten46909e72013-02-26 09:20:22 -08003524#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003525 // Write the tee output to a .wav file
3526 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003527#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003528
3529#ifdef AUDIO_WATCHDOG
3530 if (mAudioWatchdog != 0) {
3531 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3532 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3533 wdCopy.dump(fd);
3534 }
3535#endif
3536}
3537
3538uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3539{
3540 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3541}
3542
3543uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3544{
3545 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3546}
3547
3548void AudioFlinger::MixerThread::cacheParameters_l()
3549{
3550 PlaybackThread::cacheParameters_l();
3551
3552 // FIXME: Relaxed timing because of a certain device that can't meet latency
3553 // Should be reduced to 2x after the vendor fixes the driver issue
3554 // increase threshold again due to low power audio mode. The way this warning
3555 // threshold is calculated and its usefulness should be reconsidered anyway.
3556 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3557}
3558
3559// ----------------------------------------------------------------------------
3560
3561AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3562 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3563 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3564 // mLeftVolFloat, mRightVolFloat
3565{
3566}
3567
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3569 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3570 ThreadBase::type_t type)
3571 : PlaybackThread(audioFlinger, output, id, device, type)
3572 // mLeftVolFloat, mRightVolFloat
3573{
3574}
3575
Eric Laurent81784c32012-11-19 14:55:58 -08003576AudioFlinger::DirectOutputThread::~DirectOutputThread()
3577{
3578}
3579
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3581{
3582 audio_track_cblk_t* cblk = track->cblk();
3583 float left, right;
3584
3585 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3586 left = right = 0;
3587 } else {
3588 float typeVolume = mStreamTypes[track->streamType()].volume;
3589 float v = mMasterVolume * typeVolume;
3590 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3591 uint32_t vlr = proxy->getVolumeLR();
3592 float v_clamped = v * (vlr & 0xFFFF);
3593 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3594 left = v_clamped/MAX_GAIN;
3595 v_clamped = v * (vlr >> 16);
3596 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3597 right = v_clamped/MAX_GAIN;
3598 }
3599
3600 if (lastTrack) {
3601 if (left != mLeftVolFloat || right != mRightVolFloat) {
3602 mLeftVolFloat = left;
3603 mRightVolFloat = right;
3604
3605 // Convert volumes from float to 8.24
3606 uint32_t vl = (uint32_t)(left * (1 << 24));
3607 uint32_t vr = (uint32_t)(right * (1 << 24));
3608
3609 // Delegate volume control to effect in track effect chain if needed
3610 // only one effect chain can be present on DirectOutputThread, so if
3611 // there is one, the track is connected to it
3612 if (!mEffectChains.isEmpty()) {
3613 mEffectChains[0]->setVolume_l(&vl, &vr);
3614 left = (float)vl / (1 << 24);
3615 right = (float)vr / (1 << 24);
3616 }
3617 if (mOutput->stream->set_volume) {
3618 mOutput->stream->set_volume(mOutput->stream, left, right);
3619 }
3620 }
3621 }
3622}
3623
3624
Eric Laurent81784c32012-11-19 14:55:58 -08003625AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3626 Vector< sp<Track> > *tracksToRemove
3627)
3628{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003629 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003630 mixer_state mixerStatus = MIXER_IDLE;
3631
3632 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003633 for (size_t i = 0; i < count; i++) {
3634 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003635 // The track died recently
3636 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003637 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003638 }
3639
3640 Track* const track = t.get();
3641 audio_track_cblk_t* cblk = track->cblk();
3642
3643 // The first time a track is added we wait
3644 // for all its buffers to be filled before processing it
3645 uint32_t minFrames;
3646 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3647 minFrames = mNormalFrameCount;
3648 } else {
3649 minFrames = 1;
3650 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003651 // Only consider last track started for volume and mixer state control.
3652 // This is the last entry in mActiveTracks unless a track underruns.
3653 // As we only care about the transition phase between two tracks on a
3654 // direct output, it is not a problem to ignore the underrun case.
3655 bool last = (i == (count - 1));
3656
Eric Laurent81784c32012-11-19 14:55:58 -08003657 if ((track->framesReady() >= minFrames) && track->isReady() &&
3658 !track->isPaused() && !track->isTerminated())
3659 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003660 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003661
3662 if (track->mFillingUpStatus == Track::FS_FILLED) {
3663 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003664 // make sure processVolume_l() will apply new volume even if 0
3665 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003666 if (track->mState == TrackBase::RESUMING) {
3667 track->mState = TrackBase::ACTIVE;
3668 }
3669 }
3670
3671 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672 processVolume_l(track, last);
3673 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003674 // reset retry count
3675 track->mRetryCount = kMaxTrackRetriesDirect;
3676 mActiveTrack = t;
3677 mixerStatus = MIXER_TRACKS_READY;
3678 }
Eric Laurent81784c32012-11-19 14:55:58 -08003679 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003680 // clear effect chain input buffer if the last active track started underruns
3681 // to avoid sending previous audio buffer again to effects
3682 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003683 mEffectChains[0]->clearInputBuffer();
3684 }
3685
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003686 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003687 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3688 track->isStopped() || track->isPaused()) {
3689 // We have consumed all the buffers of this track.
3690 // Remove it from the list of active tracks.
3691 // TODO: implement behavior for compressed audio
3692 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3693 size_t framesWritten = mBytesWritten / mFrameSize;
3694 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3695 if (track->isStopped()) {
3696 track->reset();
3697 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003698 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003699 }
3700 } else {
3701 // No buffers for this track. Give it a few chances to
3702 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003703 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003704 if (--(track->mRetryCount) <= 0) {
3705 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003706 tracksToRemove->add(track);
Alok Kediya601e9b52013-09-27 11:55:10 +05303707 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003708 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003709 mixerStatus = MIXER_TRACKS_ENABLED;
3710 }
3711 }
3712 }
3713 }
3714
Eric Laurent81784c32012-11-19 14:55:58 -08003715 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003717
3718 return mixerStatus;
3719}
3720
3721void AudioFlinger::DirectOutputThread::threadLoop_mix()
3722{
Eric Laurent81784c32012-11-19 14:55:58 -08003723 size_t frameCount = mFrameCount;
3724 int8_t *curBuf = (int8_t *)mMixBuffer;
3725 // output audio to hardware
3726 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003727 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003728 buffer.frameCount = frameCount;
3729 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003730 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003731 memset(curBuf, 0, frameCount * mFrameSize);
3732 break;
3733 }
3734 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3735 frameCount -= buffer.frameCount;
3736 curBuf += buffer.frameCount * mFrameSize;
3737 mActiveTrack->releaseBuffer(&buffer);
3738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003739 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003740 sleepTime = 0;
3741 standbyTime = systemTime() + standbyDelay;
3742 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003743}
3744
3745void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3746{
3747 if (sleepTime == 0) {
3748 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3749 sleepTime = activeSleepTime;
3750 } else {
3751 sleepTime = idleSleepTime;
3752 }
3753 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3754 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3755 sleepTime = 0;
3756 }
3757}
3758
3759// getTrackName_l() must be called with ThreadBase::mLock held
3760int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3761 int sessionId)
3762{
3763 return 0;
3764}
3765
3766// deleteTrackName_l() must be called with ThreadBase::mLock held
3767void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3768{
3769}
3770
3771// checkForNewParameters_l() must be called with ThreadBase::mLock held
3772bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3773{
3774 bool reconfig = false;
3775
3776 while (!mNewParameters.isEmpty()) {
3777 status_t status = NO_ERROR;
3778 String8 keyValuePair = mNewParameters[0];
3779 AudioParameter param = AudioParameter(keyValuePair);
3780 int value;
3781
3782 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3783 // do not accept frame count changes if tracks are open as the track buffer
3784 // size depends on frame count and correct behavior would not be garantied
3785 // if frame count is changed after track creation
3786 if (!mTracks.isEmpty()) {
3787 status = INVALID_OPERATION;
3788 } else {
3789 reconfig = true;
3790 }
3791 }
3792 if (status == NO_ERROR) {
3793 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3794 keyValuePair.string());
3795 if (!mStandby && status == INVALID_OPERATION) {
3796 mOutput->stream->common.standby(&mOutput->stream->common);
3797 mStandby = true;
3798 mBytesWritten = 0;
3799 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3800 keyValuePair.string());
3801 }
3802 if (status == NO_ERROR && reconfig) {
3803 readOutputParameters();
3804 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3805 }
3806 }
3807
3808 mNewParameters.removeAt(0);
3809
3810 mParamStatus = status;
3811 mParamCond.signal();
3812 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3813 // already timed out waiting for the status and will never signal the condition.
3814 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3815 }
3816 return reconfig;
3817}
3818
3819uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3820{
3821 uint32_t time;
3822 if (audio_is_linear_pcm(mFormat)) {
3823 time = PlaybackThread::activeSleepTimeUs();
3824 } else {
3825 time = 10000;
3826 }
3827 return time;
3828}
3829
3830uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3831{
3832 uint32_t time;
3833 if (audio_is_linear_pcm(mFormat)) {
3834 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3835 } else {
3836 time = 10000;
3837 }
3838 return time;
3839}
3840
3841uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3842{
3843 uint32_t time;
3844 if (audio_is_linear_pcm(mFormat)) {
3845 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3846 } else {
3847 time = 10000;
3848 }
3849 return time;
3850}
3851
3852void AudioFlinger::DirectOutputThread::cacheParameters_l()
3853{
3854 PlaybackThread::cacheParameters_l();
3855
3856 // use shorter standby delay as on normal output to release
3857 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003858 if (audio_is_linear_pcm(mFormat)) {
3859 standbyDelay = microseconds(activeSleepTime*2);
3860 } else {
3861 standbyDelay = kOffloadStandbyDelayNs;
3862 }
Eric Laurent81784c32012-11-19 14:55:58 -08003863}
3864
3865// ----------------------------------------------------------------------------
3866
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003868 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003870 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003871 mWriteAckSequence(0),
3872 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003873{
3874}
3875
3876AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3877{
3878}
3879
3880void AudioFlinger::AsyncCallbackThread::onFirstRef()
3881{
3882 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3883}
3884
3885bool AudioFlinger::AsyncCallbackThread::threadLoop()
3886{
3887 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003888 uint32_t writeAckSequence;
3889 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890
3891 {
3892 Mutex::Autolock _l(mLock);
3893 mWaitWorkCV.wait(mLock);
3894 if (exitPending()) {
3895 break;
3896 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003897 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3898 mWriteAckSequence, mDrainSequence);
3899 writeAckSequence = mWriteAckSequence;
3900 mWriteAckSequence &= ~1;
3901 drainSequence = mDrainSequence;
3902 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 }
3904 {
Eric Laurent4de95592013-09-26 15:28:21 -07003905 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3906 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003907 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003908 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003910 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003911 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 }
3913 }
3914 }
3915 }
3916 return false;
3917}
3918
3919void AudioFlinger::AsyncCallbackThread::exit()
3920{
3921 ALOGV("AsyncCallbackThread::exit");
3922 Mutex::Autolock _l(mLock);
3923 requestExit();
3924 mWaitWorkCV.broadcast();
3925}
3926
Eric Laurent3b4529e2013-09-05 18:09:19 -07003927void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928{
3929 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003930 // bit 0 is cleared
3931 mWriteAckSequence = sequence << 1;
3932}
3933
3934void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3935{
3936 Mutex::Autolock _l(mLock);
3937 // ignore unexpected callbacks
3938 if (mWriteAckSequence & 2) {
3939 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003940 mWaitWorkCV.signal();
3941 }
3942}
3943
Eric Laurent3b4529e2013-09-05 18:09:19 -07003944void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945{
3946 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003947 // bit 0 is cleared
3948 mDrainSequence = sequence << 1;
3949}
3950
3951void AudioFlinger::AsyncCallbackThread::resetDraining()
3952{
3953 Mutex::Autolock _l(mLock);
3954 // ignore unexpected callbacks
3955 if (mDrainSequence & 2) {
3956 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957 mWaitWorkCV.signal();
3958 }
3959}
3960
3961
3962// ----------------------------------------------------------------------------
3963AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3964 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3965 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3966 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003967 mFlushPending(false),
Eric Laurent6a99d202013-10-17 18:59:26 -07003968 mPausedBytesRemaining(0),
3969 mPreviousTrack(NULL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971}
3972
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973void AudioFlinger::OffloadThread::threadLoop_exit()
3974{
3975 if (mFlushPending || mHwPaused) {
3976 // If a flush is pending or track was paused, just discard buffered data
3977 flushHw_l();
3978 } else {
3979 mMixerStatus = MIXER_DRAIN_ALL;
3980 threadLoop_drain();
3981 }
3982 mCallbackThread->exit();
3983 PlaybackThread::threadLoop_exit();
3984}
3985
3986AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3987 Vector< sp<Track> > *tracksToRemove
3988)
3989{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003990 size_t count = mActiveTracks.size();
3991
3992 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003993 bool doHwPause = false;
3994 bool doHwResume = false;
3995
Eric Laurentede6c3b2013-09-19 14:37:46 -07003996 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3997
Eric Laurentbfb1b832013-01-07 09:53:42 -08003998 // find out which tracks need to be processed
3999 for (size_t i = 0; i < count; i++) {
4000 sp<Track> t = mActiveTracks[i].promote();
4001 // The track died recently
4002 if (t == 0) {
4003 continue;
4004 }
4005 Track* const track = t.get();
4006 audio_track_cblk_t* cblk = track->cblk();
4007 if (mPreviousTrack != NULL) {
Eric Laurent6a99d202013-10-17 18:59:26 -07004008 if (t.get() != mPreviousTrack) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004009 // Flush any data still being written from last track
4010 mBytesRemaining = 0;
4011 if (mPausedBytesRemaining) {
4012 // Last track was paused so we also need to flush saved
4013 // mixbuffer state and invalidate track so that it will
4014 // re-submit that unwritten data when it is next resumed
4015 mPausedBytesRemaining = 0;
4016 // Invalidate is a bit drastic - would be more efficient
4017 // to have a flag to tell client that some of the
4018 // previously written data was lost
4019 mPreviousTrack->invalidate();
4020 }
4021 }
4022 }
Eric Laurent6a99d202013-10-17 18:59:26 -07004023 mPreviousTrack = t.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 bool last = (i == (count - 1));
4025 if (track->isPausing()) {
4026 track->setPaused();
4027 if (last) {
4028 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004029 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004030 mHwPaused = true;
4031 }
4032 // If we were part way through writing the mixbuffer to
4033 // the HAL we must save this until we resume
4034 // BUG - this will be wrong if a different track is made active,
4035 // in that case we want to discard the pending data in the
4036 // mixbuffer and tell the client to present it again when the
4037 // track is resumed
4038 mPausedWriteLength = mCurrentWriteLength;
4039 mPausedBytesRemaining = mBytesRemaining;
4040 mBytesRemaining = 0; // stop writing
4041 }
4042 tracksToRemove->add(track);
4043 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004044 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004045 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046 if (track->mFillingUpStatus == Track::FS_FILLED) {
4047 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004048 // make sure processVolume_l() will apply new volume even if 0
4049 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004050 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004052 if (last) {
4053 if (mPausedBytesRemaining) {
4054 // Need to continue write that was interrupted
4055 mCurrentWriteLength = mPausedWriteLength;
4056 mBytesRemaining = mPausedBytesRemaining;
4057 mPausedBytesRemaining = 0;
4058 }
4059 if (mHwPaused) {
4060 doHwResume = true;
4061 mHwPaused = false;
4062 // threadLoop_mix() will handle the case that we need to
4063 // resume an interrupted write
4064 }
4065 // enable write to audio HAL
4066 sleepTime = 0;
4067 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004068 }
4069 }
4070
4071 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004072 // reset retry count
4073 track->mRetryCount = kMaxTrackRetriesOffload;
4074 mActiveTrack = t;
4075 mixerStatus = MIXER_TRACKS_READY;
4076 }
4077 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004078 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004079 if (track->isStopping_1()) {
4080 // Hardware buffer can hold a large amount of audio so we must
4081 // wait for all current track's data to drain before we say
4082 // that the track is stopped.
4083 if (mBytesRemaining == 0) {
4084 // Only start draining when all data in mixbuffer
4085 // has been written
4086 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4087 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a99d202013-10-17 18:59:26 -07004088 // do not drain if no data was ever sent to HAL (mStandby == true)
4089 if (last && !mStandby) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07004090 sleepTime = 0;
4091 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004092 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07004093 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004094 if (mHwPaused) {
4095 // It is possible to move from PAUSED to STOPPING_1 without
4096 // a resume so we must ensure hardware is running
4097 mOutput->stream->resume(mOutput->stream);
4098 mHwPaused = false;
4099 }
4100 }
4101 }
4102 } else if (track->isStopping_2()) {
Eric Laurent6a99d202013-10-17 18:59:26 -07004103 // Drain has completed or we are in standby, signal presentation complete
4104 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004105 track->mState = TrackBase::STOPPED;
4106 size_t audioHALFrames =
4107 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4108 size_t framesWritten =
4109 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4110 track->presentationComplete(framesWritten, audioHALFrames);
4111 track->reset();
4112 tracksToRemove->add(track);
4113 }
4114 } else {
4115 // No buffers for this track. Give it a few chances to
4116 // fill a buffer, then remove it from active list.
4117 if (--(track->mRetryCount) <= 0) {
4118 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4119 track->name());
4120 tracksToRemove->add(track);
4121 } else if (last){
4122 mixerStatus = MIXER_TRACKS_ENABLED;
4123 }
4124 }
4125 }
4126 // compute volume for this track
4127 processVolume_l(track, last);
4128 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004129
Eric Laurentea0fade2013-10-04 16:23:48 -07004130 // make sure the pause/flush/resume sequence is executed in the right order.
4131 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4132 // before flush and then resume HW. This can happen in case of pause/flush/resume
4133 // if resume is received before pause is executed.
4134 if (doHwPause || (mFlushPending && !mHwPaused && (count != 0))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004135 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004136 if (!doHwPause) {
4137 doHwResume = true;
4138 }
Eric Laurent972a1732013-09-04 09:42:59 -07004139 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004140 if (mFlushPending) {
4141 flushHw_l();
4142 mFlushPending = false;
4143 }
Eric Laurent972a1732013-09-04 09:42:59 -07004144 if (doHwResume) {
4145 mOutput->stream->resume(mOutput->stream);
4146 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004147
Eric Laurentbfb1b832013-01-07 09:53:42 -08004148 // remove all the tracks that need to be...
4149 removeTracks_l(*tracksToRemove);
4150
4151 return mixerStatus;
4152}
4153
4154void AudioFlinger::OffloadThread::flushOutput_l()
4155{
4156 mFlushPending = true;
4157}
4158
4159// must be called with thread mutex locked
4160bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4161{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004162 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4163 mWriteAckSequence, mDrainSequence);
4164 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 return true;
4166 }
4167 return false;
4168}
4169
4170// must be called with thread mutex locked
4171bool AudioFlinger::OffloadThread::shouldStandby_l()
4172{
4173 bool TrackPaused = false;
4174
4175 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4176 // after a timeout and we will enter standby then.
4177 if (mTracks.size() > 0) {
4178 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4179 }
4180
4181 return !mStandby && !TrackPaused;
4182}
4183
4184
4185bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4186{
4187 Mutex::Autolock _l(mLock);
4188 return waitingAsyncCallback_l();
4189}
4190
4191void AudioFlinger::OffloadThread::flushHw_l()
4192{
4193 mOutput->stream->flush(mOutput->stream);
4194 // Flush anything still waiting in the mixbuffer
4195 mCurrentWriteLength = 0;
4196 mBytesRemaining = 0;
4197 mPausedWriteLength = 0;
4198 mPausedBytesRemaining = 0;
4199 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004200 // discard any pending drain or write ack by incrementing sequence
4201 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4202 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004203 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004204 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4205 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206 }
4207}
4208
4209// ----------------------------------------------------------------------------
4210
Eric Laurent81784c32012-11-19 14:55:58 -08004211AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4212 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4213 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4214 DUPLICATING),
4215 mWaitTimeMs(UINT_MAX)
4216{
4217 addOutputTrack(mainThread);
4218}
4219
4220AudioFlinger::DuplicatingThread::~DuplicatingThread()
4221{
4222 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4223 mOutputTracks[i]->destroy();
4224 }
4225}
4226
4227void AudioFlinger::DuplicatingThread::threadLoop_mix()
4228{
4229 // mix buffers...
4230 if (outputsReady(outputTracks)) {
4231 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4232 } else {
4233 memset(mMixBuffer, 0, mixBufferSize);
4234 }
4235 sleepTime = 0;
4236 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004237 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 standbyTime = systemTime() + standbyDelay;
4239}
4240
4241void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4242{
4243 if (sleepTime == 0) {
4244 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4245 sleepTime = activeSleepTime;
4246 } else {
4247 sleepTime = idleSleepTime;
4248 }
4249 } else if (mBytesWritten != 0) {
4250 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4251 writeFrames = mNormalFrameCount;
4252 memset(mMixBuffer, 0, mixBufferSize);
4253 } else {
4254 // flush remaining overflow buffers in output tracks
4255 writeFrames = 0;
4256 }
4257 sleepTime = 0;
4258 }
4259}
4260
Eric Laurentbfb1b832013-01-07 09:53:42 -08004261ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004262{
4263 for (size_t i = 0; i < outputTracks.size(); i++) {
4264 outputTracks[i]->write(mMixBuffer, writeFrames);
4265 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004266 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004267}
4268
4269void AudioFlinger::DuplicatingThread::threadLoop_standby()
4270{
4271 // DuplicatingThread implements standby by stopping all tracks
4272 for (size_t i = 0; i < outputTracks.size(); i++) {
4273 outputTracks[i]->stop();
4274 }
4275}
4276
4277void AudioFlinger::DuplicatingThread::saveOutputTracks()
4278{
4279 outputTracks = mOutputTracks;
4280}
4281
4282void AudioFlinger::DuplicatingThread::clearOutputTracks()
4283{
4284 outputTracks.clear();
4285}
4286
4287void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4288{
4289 Mutex::Autolock _l(mLock);
4290 // FIXME explain this formula
Alok Kediya601e9b52013-09-27 11:55:10 +05304291 int sampleRate = thread->sampleRate();
4292 size_t frameCount = 0;
4293 if (sampleRate)
4294 frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Eric Laurent81784c32012-11-19 14:55:58 -08004295 OutputTrack *outputTrack = new OutputTrack(thread,
4296 this,
4297 mSampleRate,
4298 mFormat,
4299 mChannelMask,
4300 frameCount);
4301 if (outputTrack->cblk() != NULL) {
4302 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4303 mOutputTracks.add(outputTrack);
4304 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4305 updateWaitTime_l();
4306 }
4307}
4308
4309void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4310{
4311 Mutex::Autolock _l(mLock);
4312 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4313 if (mOutputTracks[i]->thread() == thread) {
4314 mOutputTracks[i]->destroy();
4315 mOutputTracks.removeAt(i);
4316 updateWaitTime_l();
4317 return;
4318 }
4319 }
4320 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4321}
4322
4323// caller must hold mLock
4324void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4325{
4326 mWaitTimeMs = UINT_MAX;
4327 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4328 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4329 if (strong != 0) {
4330 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4331 if (waitTimeMs < mWaitTimeMs) {
4332 mWaitTimeMs = waitTimeMs;
4333 }
4334 }
4335 }
4336}
4337
4338
4339bool AudioFlinger::DuplicatingThread::outputsReady(
4340 const SortedVector< sp<OutputTrack> > &outputTracks)
4341{
4342 for (size_t i = 0; i < outputTracks.size(); i++) {
4343 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4344 if (thread == 0) {
4345 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4346 outputTracks[i].get());
4347 return false;
4348 }
4349 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4350 // see note at standby() declaration
4351 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4352 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4353 thread.get());
4354 return false;
4355 }
4356 }
4357 return true;
4358}
4359
4360uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4361{
4362 return (mWaitTimeMs * 1000) / 2;
4363}
4364
4365void AudioFlinger::DuplicatingThread::cacheParameters_l()
4366{
4367 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4368 updateWaitTime_l();
4369
4370 MixerThread::cacheParameters_l();
4371}
4372
4373// ----------------------------------------------------------------------------
4374// Record
4375// ----------------------------------------------------------------------------
4376
4377AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4378 AudioStreamIn *input,
4379 uint32_t sampleRate,
4380 audio_channel_mask_t channelMask,
4381 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004382 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004383 audio_devices_t inDevice
4384#ifdef TEE_SINK
4385 , const sp<NBAIO_Sink>& teeSink
4386#endif
4387 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004388 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004389 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004390 // mRsmpInIndex and mBufferSize set by readInputParameters()
Alok Kediya601e9b52013-09-27 11:55:10 +05304391 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004392 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004393 // mBytesRead is only meaningful while active, and so is cleared in start()
4394 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004395#ifdef TEE_SINK
4396 , mTeeSink(teeSink)
4397#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004398{
4399 snprintf(mName, kNameLength, "AudioIn_%X", id);
4400
4401 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004402 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004403}
4404
4405
4406AudioFlinger::RecordThread::~RecordThread()
4407{
4408 delete[] mRsmpInBuffer;
4409 delete mResampler;
4410 delete[] mRsmpOutBuffer;
4411}
4412
4413void AudioFlinger::RecordThread::onFirstRef()
4414{
4415 run(mName, PRIORITY_URGENT_AUDIO);
4416}
4417
4418status_t AudioFlinger::RecordThread::readyToRun()
4419{
4420 status_t status = initCheck();
4421 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4422 return status;
4423}
4424
4425bool AudioFlinger::RecordThread::threadLoop()
4426{
4427 AudioBufferProvider::Buffer buffer;
4428 sp<RecordTrack> activeTrack;
4429 Vector< sp<EffectChain> > effectChains;
4430
4431 nsecs_t lastWarning = 0;
4432
4433 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004434 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004435
4436 // used to verify we've read at least once before evaluating how many bytes were read
4437 bool readOnce = false;
4438
4439 // start recording
4440 while (!exitPending()) {
4441
4442 processConfigEvents();
4443
4444 { // scope for mLock
4445 Mutex::Autolock _l(mLock);
4446 checkForNewParameters_l();
4447 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4448 standby();
4449
4450 if (exitPending()) {
4451 break;
4452 }
4453
4454 releaseWakeLock_l();
4455 ALOGV("RecordThread: loop stopping");
4456 // go to sleep
4457 mWaitWorkCV.wait(mLock);
4458 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004459 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004460 continue;
4461 }
4462 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004463 if (mActiveTrack->isTerminated()) {
4464 removeTrack_l(mActiveTrack);
4465 mActiveTrack.clear();
4466 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004467 standby();
4468 mActiveTrack.clear();
4469 mStartStopCond.broadcast();
4470 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4471 if (mReqChannelCount != mActiveTrack->channelCount()) {
4472 mActiveTrack.clear();
4473 mStartStopCond.broadcast();
4474 } else if (readOnce) {
4475 // record start succeeds only if first read from audio input
4476 // succeeds
4477 if (mBytesRead >= 0) {
4478 mActiveTrack->mState = TrackBase::ACTIVE;
4479 } else {
4480 mActiveTrack.clear();
4481 }
4482 mStartStopCond.broadcast();
4483 }
4484 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
4486 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004487
Eric Laurent81784c32012-11-19 14:55:58 -08004488 lockEffectChains_l(effectChains);
4489 }
4490
4491 if (mActiveTrack != 0) {
4492 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4493 mActiveTrack->mState != TrackBase::RESUMING) {
4494 unlockEffectChains(effectChains);
4495 usleep(kRecordThreadSleepUs);
4496 continue;
4497 }
4498 for (size_t i = 0; i < effectChains.size(); i ++) {
4499 effectChains[i]->process_l();
4500 }
4501
4502 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004503 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004504 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004505 readOnce = true;
4506 size_t framesOut = buffer.frameCount;
4507 if (mResampler == NULL) {
4508 // no resampling
4509 while (framesOut) {
4510 size_t framesIn = mFrameCount - mRsmpInIndex;
4511 if (framesIn) {
4512 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4513 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4514 mActiveTrack->mFrameSize;
4515 if (framesIn > framesOut)
4516 framesIn = framesOut;
4517 mRsmpInIndex += framesIn;
4518 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004519 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004520 memcpy(dst, src, framesIn * mFrameSize);
4521 } else {
4522 if (mChannelCount == 1) {
4523 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4524 (int16_t *)src, framesIn);
4525 } else {
4526 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4527 (int16_t *)src, framesIn);
4528 }
4529 }
4530 }
Alok Kediya601e9b52013-09-27 11:55:10 +05304531 if (framesOut && (mFrameCount == mRsmpInIndex)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004532 void *readInto;
Alok Kediya601e9b52013-09-27 11:55:10 +05304533 int InputBytes;
4534 /*Fix me: How does framesOut become 0 in this condition */
4535 if (( framesOut != mFrameCount) &&
4536 ((mFormat != AUDIO_FORMAT_PCM_16_BIT)&&
4537 (!(mActiveTrack->mFlags & TRACK_VOICE_COMMUNICATION)))) {
4538 readInto = buffer.raw;
4539 InputBytes = buffer.frameCount * mFrameSize;
4540 } else if (framesOut == mFrameCount &&
4541 (mChannelCount == mReqChannelCount ||
4542 ((mFormat != AUDIO_FORMAT_PCM_16_BIT) &&
4543 (!(mActiveTrack->mFlags & TRACK_VOICE_COMMUNICATION))))) {
4544 readInto = buffer.raw;
4545 InputBytes = mBufferSize;
4546 framesOut = 0;
4547 } else {
4548 readInto = mRsmpInBuffer;
4549 mRsmpInIndex = 0;
4550 InputBytes = mBufferSize;
4551 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004552 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Alok Kediya601e9b52013-09-27 11:55:10 +05304553 InputBytes);
Eric Laurent81784c32012-11-19 14:55:58 -08004554 if (mBytesRead <= 0) {
4555 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4556 {
4557 ALOGE("Error reading audio input");
4558 // Force input into standby so that it tries to
4559 // recover at next read attempt
4560 inputStandBy();
4561 usleep(kRecordThreadSleepUs);
4562 }
4563 mRsmpInIndex = mFrameCount;
4564 framesOut = 0;
4565 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004566 }
4567#ifdef TEE_SINK
4568 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004569 (void) mTeeSink->write(readInto,
4570 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4571 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004572#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004573 }
4574 }
4575 } else {
4576 // resampling
4577
Glenn Kasten34af0262013-07-30 11:52:39 -07004578 // resampler accumulates, but we only have one source track
4579 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004580 // alter output frame count as if we were expecting stereo samples
4581 if (mChannelCount == 1 && mReqChannelCount == 1) {
4582 framesOut >>= 1;
4583 }
4584 mResampler->resample(mRsmpOutBuffer, framesOut,
4585 this /* AudioBufferProvider* */);
4586 // ditherAndClamp() works as long as all buffers returned by
4587 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4588 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004589 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004590 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4591 // the resampler always outputs stereo samples:
4592 // do post stereo to mono conversion
4593 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4594 framesOut);
4595 } else {
4596 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4597 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004598 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004599
4600 }
4601 if (mFramestoDrop == 0) {
4602 mActiveTrack->releaseBuffer(&buffer);
4603 } else {
4604 if (mFramestoDrop > 0) {
4605 mFramestoDrop -= buffer.frameCount;
4606 if (mFramestoDrop <= 0) {
4607 clearSyncStartEvent();
4608 }
4609 } else {
4610 mFramestoDrop += buffer.frameCount;
4611 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4612 mSyncStartEvent->isCancelled()) {
4613 ALOGW("Synced record %s, session %d, trigger session %d",
4614 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4615 mActiveTrack->sessionId(),
4616 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4617 clearSyncStartEvent();
4618 }
4619 }
4620 }
4621 mActiveTrack->clearOverflow();
4622 }
4623 // client isn't retrieving buffers fast enough
4624 else {
4625 if (!mActiveTrack->setOverflow()) {
4626 nsecs_t now = systemTime();
4627 if ((now - lastWarning) > kWarningThrottleNs) {
4628 ALOGW("RecordThread: buffer overflow");
4629 lastWarning = now;
4630 }
4631 }
4632 // Release the processor for a while before asking for a new buffer.
4633 // This will give the application more chance to read from the buffer and
4634 // clear the overflow.
4635 usleep(kRecordThreadSleepUs);
4636 }
4637 }
4638 // enable changes in effect chain
4639 unlockEffectChains(effectChains);
4640 effectChains.clear();
4641 }
4642
4643 standby();
4644
4645 {
4646 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004647 for (size_t i = 0; i < mTracks.size(); i++) {
4648 sp<RecordTrack> track = mTracks[i];
4649 track->invalidate();
4650 }
Eric Laurent81784c32012-11-19 14:55:58 -08004651 mActiveTrack.clear();
4652 mStartStopCond.broadcast();
4653 }
4654
4655 releaseWakeLock();
4656
4657 ALOGV("RecordThread %p exiting", this);
4658 return false;
4659}
4660
4661void AudioFlinger::RecordThread::standby()
4662{
4663 if (!mStandby) {
4664 inputStandBy();
4665 mStandby = true;
4666 }
4667}
4668
4669void AudioFlinger::RecordThread::inputStandBy()
4670{
4671 mInput->stream->common.standby(&mInput->stream->common);
4672}
4673
4674sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4675 const sp<AudioFlinger::Client>& client,
4676 uint32_t sampleRate,
4677 audio_format_t format,
4678 audio_channel_mask_t channelMask,
4679 size_t frameCount,
4680 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004681 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004682 pid_t tid,
4683 status_t *status)
4684{
4685 sp<RecordTrack> track;
4686 status_t lStatus;
4687
4688 lStatus = initCheck();
4689 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004690 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004691 goto Exit;
4692 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004693 // client expresses a preference for FAST, but we get the final say
4694 if (*flags & IAudioFlinger::TRACK_FAST) {
4695 if (
4696 // use case: callback handler and frame count is default or at least as large as HAL
4697 (
4698 (tid != -1) &&
4699 ((frameCount == 0) ||
4700 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4701 ) &&
4702 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4703 // mono or stereo
4704 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4705 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4706 // hardware sample rate
4707 (sampleRate == mSampleRate) &&
4708 // record thread has an associated fast recorder
4709 hasFastRecorder()
4710 // FIXME test that RecordThread for this fast track has a capable output HAL
4711 // FIXME add a permission test also?
4712 ) {
4713 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4714 if (frameCount == 0) {
4715 frameCount = mFrameCount * kFastTrackMultiplier;
4716 }
4717 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4718 frameCount, mFrameCount);
4719 } else {
4720 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4721 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4722 "hasFastRecorder=%d tid=%d",
4723 frameCount, mFrameCount, format,
4724 audio_is_linear_pcm(format),
4725 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4726 *flags &= ~IAudioFlinger::TRACK_FAST;
4727 // For compatibility with AudioRecord calculation, buffer depth is forced
4728 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4729 // This is probably too conservative, but legacy application code may depend on it.
4730 // If you change this calculation, also review the start threshold which is related.
4731 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4732 size_t mNormalFrameCount = 2048; // FIXME
Alok Kediya601e9b52013-09-27 11:55:10 +05304733 uint32_t minBufCount = 0;
4734 if (mSampleRate) {
4735 minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4736 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004737 if (minBufCount < 2) {
4738 minBufCount = 2;
4739 }
4740 size_t minFrameCount = mNormalFrameCount * minBufCount;
4741 if (frameCount < minFrameCount) {
4742 frameCount = minFrameCount;
4743 }
4744 }
4745 }
4746
Eric Laurent81784c32012-11-19 14:55:58 -08004747 // FIXME use flags and tid similar to createTrack_l()
4748
4749 { // scope for mLock
4750 Mutex::Autolock _l(mLock);
4751
4752 track = new RecordTrack(this, client, sampleRate,
Alok Kediya601e9b52013-09-27 11:55:10 +05304753 format, channelMask, frameCount, *flags, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004754
4755 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004756 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004757 lStatus = NO_MEMORY;
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004758 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004759 goto Exit;
4760 }
4761 mTracks.add(track);
4762
4763 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4764 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4765 mAudioFlinger->btNrecIsOff();
4766 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4767 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004768
4769 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4770 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4771 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4772 // so ask activity manager to do this on our behalf
4773 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 }
4776 lStatus = NO_ERROR;
4777
4778Exit:
4779 if (status) {
4780 *status = lStatus;
4781 }
4782 return track;
4783}
4784
4785status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4786 AudioSystem::sync_event_t event,
4787 int triggerSession)
4788{
4789 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4790 sp<ThreadBase> strongMe = this;
4791 status_t status = NO_ERROR;
4792
4793 if (event == AudioSystem::SYNC_EVENT_NONE) {
4794 clearSyncStartEvent();
4795 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4796 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4797 triggerSession,
4798 recordTrack->sessionId(),
4799 syncStartEventCallback,
4800 this);
4801 // Sync event can be cancelled by the trigger session if the track is not in a
4802 // compatible state in which case we start record immediately
4803 if (mSyncStartEvent->isCancelled()) {
4804 clearSyncStartEvent();
4805 } else {
4806 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4807 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4808 }
4809 }
4810
4811 {
4812 AutoMutex lock(mLock);
4813 if (mActiveTrack != 0) {
4814 if (recordTrack != mActiveTrack.get()) {
4815 status = -EBUSY;
4816 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4817 mActiveTrack->mState = TrackBase::ACTIVE;
4818 }
4819 return status;
4820 }
4821
4822 recordTrack->mState = TrackBase::IDLE;
4823 mActiveTrack = recordTrack;
4824 mLock.unlock();
4825 status_t status = AudioSystem::startInput(mId);
4826 mLock.lock();
4827 if (status != NO_ERROR) {
4828 mActiveTrack.clear();
4829 clearSyncStartEvent();
4830 return status;
4831 }
4832 mRsmpInIndex = mFrameCount;
4833 mBytesRead = 0;
4834 if (mResampler != NULL) {
4835 mResampler->reset();
4836 }
4837 mActiveTrack->mState = TrackBase::RESUMING;
4838 // signal thread to start
4839 ALOGV("Signal record thread");
4840 mWaitWorkCV.broadcast();
4841 // do not wait for mStartStopCond if exiting
4842 if (exitPending()) {
4843 mActiveTrack.clear();
4844 status = INVALID_OPERATION;
4845 goto startError;
4846 }
4847 mStartStopCond.wait(mLock);
4848 if (mActiveTrack == 0) {
4849 ALOGV("Record failed to start");
4850 status = BAD_VALUE;
4851 goto startError;
4852 }
4853 ALOGV("Record started OK");
4854 return status;
4855 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004856
Eric Laurent81784c32012-11-19 14:55:58 -08004857startError:
4858 AudioSystem::stopInput(mId);
4859 clearSyncStartEvent();
4860 return status;
4861}
4862
4863void AudioFlinger::RecordThread::clearSyncStartEvent()
4864{
4865 if (mSyncStartEvent != 0) {
4866 mSyncStartEvent->cancel();
4867 }
4868 mSyncStartEvent.clear();
4869 mFramestoDrop = 0;
4870}
4871
4872void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4873{
4874 sp<SyncEvent> strongEvent = event.promote();
4875
4876 if (strongEvent != 0) {
4877 RecordThread *me = (RecordThread *)strongEvent->cookie();
4878 me->handleSyncStartEvent(strongEvent);
4879 }
4880}
4881
4882void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4883{
4884 if (event == mSyncStartEvent) {
4885 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4886 // from audio HAL
4887 mFramestoDrop = mFrameCount * 2;
4888 }
4889}
4890
Glenn Kastena8356f62013-07-25 14:37:52 -07004891bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004892 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004893 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004894 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4895 return false;
4896 }
4897 recordTrack->mState = TrackBase::PAUSING;
4898 // do not wait for mStartStopCond if exiting
4899 if (exitPending()) {
4900 return true;
4901 }
4902 mStartStopCond.wait(mLock);
4903 // if we have been restarted, recordTrack == mActiveTrack.get() here
4904 if (exitPending() || recordTrack != mActiveTrack.get()) {
4905 ALOGV("Record stopped OK");
4906 return true;
4907 }
4908 return false;
4909}
4910
4911bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4912{
4913 return false;
4914}
4915
4916status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4917{
4918#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4919 if (!isValidSyncEvent(event)) {
4920 return BAD_VALUE;
4921 }
4922
4923 int eventSession = event->triggerSession();
4924 status_t ret = NAME_NOT_FOUND;
4925
4926 Mutex::Autolock _l(mLock);
4927
4928 for (size_t i = 0; i < mTracks.size(); i++) {
4929 sp<RecordTrack> track = mTracks[i];
4930 if (eventSession == track->sessionId()) {
4931 (void) track->setSyncEvent(event);
4932 ret = NO_ERROR;
4933 }
4934 }
4935 return ret;
4936#else
4937 return BAD_VALUE;
4938#endif
4939}
4940
4941// destroyTrack_l() must be called with ThreadBase::mLock held
4942void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4943{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004944 track->terminate();
4945 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004946 // active tracks are removed by threadLoop()
4947 if (mActiveTrack != track) {
4948 removeTrack_l(track);
4949 }
4950}
4951
4952void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4953{
4954 mTracks.remove(track);
4955 // need anything related to effects here?
4956}
4957
4958void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4959{
4960 dumpInternals(fd, args);
4961 dumpTracks(fd, args);
4962 dumpEffectChains(fd, args);
4963}
4964
4965void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4966{
4967 const size_t SIZE = 256;
4968 char buffer[SIZE];
4969 String8 result;
4970
4971 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4972 result.append(buffer);
4973
4974 if (mActiveTrack != 0) {
4975 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4976 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004977 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004978 result.append(buffer);
4979 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4980 result.append(buffer);
4981 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4982 result.append(buffer);
4983 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4984 result.append(buffer);
4985 } else {
4986 result.append("No active record client\n");
4987 }
4988
4989 write(fd, result.string(), result.size());
4990
4991 dumpBase(fd, args);
4992}
4993
4994void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4995{
4996 const size_t SIZE = 256;
4997 char buffer[SIZE];
4998 String8 result;
4999
5000 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
5001 result.append(buffer);
5002 RecordTrack::appendDumpHeader(result);
5003 for (size_t i = 0; i < mTracks.size(); ++i) {
5004 sp<RecordTrack> track = mTracks[i];
5005 if (track != 0) {
5006 track->dump(buffer, SIZE);
5007 result.append(buffer);
5008 }
5009 }
5010
5011 if (mActiveTrack != 0) {
5012 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5013 result.append(buffer);
5014 RecordTrack::appendDumpHeader(result);
5015 mActiveTrack->dump(buffer, SIZE);
5016 result.append(buffer);
5017
5018 }
5019 write(fd, result.string(), result.size());
5020}
5021
5022// AudioBufferProvider interface
5023status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5024{
5025 size_t framesReq = buffer->frameCount;
5026 size_t framesReady = mFrameCount - mRsmpInIndex;
5027 int channelCount;
5028
5029 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005030 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005031 if (mBytesRead <= 0) {
5032 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5033 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5034 // Force input into standby so that it tries to
5035 // recover at next read attempt
5036 inputStandBy();
5037 usleep(kRecordThreadSleepUs);
5038 }
5039 buffer->raw = NULL;
5040 buffer->frameCount = 0;
5041 return NOT_ENOUGH_DATA;
5042 }
5043 mRsmpInIndex = 0;
5044 framesReady = mFrameCount;
5045 }
5046
5047 if (framesReq > framesReady) {
5048 framesReq = framesReady;
5049 }
5050
5051 if (mChannelCount == 1 && mReqChannelCount == 2) {
5052 channelCount = 1;
5053 } else {
5054 channelCount = 2;
5055 }
5056 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5057 buffer->frameCount = framesReq;
5058 return NO_ERROR;
5059}
5060
5061// AudioBufferProvider interface
5062void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5063{
5064 mRsmpInIndex += buffer->frameCount;
5065 buffer->frameCount = 0;
5066}
5067
5068bool AudioFlinger::RecordThread::checkForNewParameters_l()
5069{
5070 bool reconfig = false;
5071
5072 while (!mNewParameters.isEmpty()) {
5073 status_t status = NO_ERROR;
5074 String8 keyValuePair = mNewParameters[0];
5075 AudioParameter param = AudioParameter(keyValuePair);
5076 int value;
5077 audio_format_t reqFormat = mFormat;
5078 uint32_t reqSamplingRate = mReqSampleRate;
5079 uint32_t reqChannelCount = mReqChannelCount;
5080
5081 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5082 reqSamplingRate = value;
5083 reconfig = true;
5084 }
5085 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005086 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5087 status = BAD_VALUE;
5088 } else {
5089 reqFormat = (audio_format_t) value;
5090 reconfig = true;
5091 }
Eric Laurent81784c32012-11-19 14:55:58 -08005092 }
5093 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Alok Kediya601e9b52013-09-27 11:55:10 +05305094 reqChannelCount = getInputChannelCount(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005095 reconfig = true;
5096 }
5097 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5098 // do not accept frame count changes if tracks are open as the track buffer
5099 // size depends on frame count and correct behavior would not be guaranteed
5100 // if frame count is changed after track creation
5101 if (mActiveTrack != 0) {
5102 status = INVALID_OPERATION;
5103 } else {
5104 reconfig = true;
5105 }
5106 }
5107 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5108 // forward device change to effects that have requested to be
5109 // aware of attached audio device.
5110 for (size_t i = 0; i < mEffectChains.size(); i++) {
5111 mEffectChains[i]->setDevice_l(value);
5112 }
5113
5114 // store input device and output device but do not forward output device to audio HAL.
5115 // Note that status is ignored by the caller for output device
5116 // (see AudioFlinger::setParameters()
5117 if (audio_is_output_devices(value)) {
5118 mOutDevice = value;
5119 status = BAD_VALUE;
5120 } else {
5121 mInDevice = value;
5122 // disable AEC and NS if the device is a BT SCO headset supporting those
5123 // pre processings
5124 if (mTracks.size() > 0) {
5125 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5126 mAudioFlinger->btNrecIsOff();
5127 for (size_t i = 0; i < mTracks.size(); i++) {
5128 sp<RecordTrack> track = mTracks[i];
5129 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5130 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5131 }
5132 }
5133 }
5134 }
5135 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5136 mAudioSource != (audio_source_t)value) {
5137 // forward device change to effects that have requested to be
5138 // aware of attached audio device.
5139 for (size_t i = 0; i < mEffectChains.size(); i++) {
5140 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5141 }
5142 mAudioSource = (audio_source_t)value;
5143 }
5144 if (status == NO_ERROR) {
5145 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5146 keyValuePair.string());
5147 if (status == INVALID_OPERATION) {
5148 inputStandBy();
5149 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5150 keyValuePair.string());
5151 }
5152 if (reconfig) {
5153 if (status == BAD_VALUE &&
5154 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5155 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005156 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005157 <= (2 * reqSamplingRate)) &&
Alok Kediya601e9b52013-09-27 11:55:10 +05305158 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common))
Eric Laurent81784c32012-11-19 14:55:58 -08005159 <= FCC_2 &&
5160 (reqChannelCount <= FCC_2)) {
5161 status = NO_ERROR;
5162 }
5163 if (status == NO_ERROR) {
5164 readInputParameters();
5165 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5166 }
5167 }
5168 }
5169
5170 mNewParameters.removeAt(0);
5171
5172 mParamStatus = status;
5173 mParamCond.signal();
5174 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5175 // already timed out waiting for the status and will never signal the condition.
5176 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5177 }
5178 return reconfig;
5179}
5180
5181String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5182{
Eric Laurent81784c32012-11-19 14:55:58 -08005183 Mutex::Autolock _l(mLock);
5184 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005185 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005186 }
5187
Glenn Kastend8ea6992013-07-16 14:17:15 -07005188 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5189 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005190 free(s);
5191 return out_s8;
5192}
5193
5194void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5195 AudioSystem::OutputDescriptor desc;
5196 void *param2 = NULL;
5197
5198 switch (event) {
5199 case AudioSystem::INPUT_OPENED:
5200 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005201 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005202 desc.samplingRate = mSampleRate;
5203 desc.format = mFormat;
5204 desc.frameCount = mFrameCount;
5205 desc.latency = 0;
5206 param2 = &desc;
5207 break;
5208
5209 case AudioSystem::INPUT_CLOSED:
5210 default:
5211 break;
5212 }
5213 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5214}
5215
5216void AudioFlinger::RecordThread::readInputParameters()
5217{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005218 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005219 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005220 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005221 mRsmpOutBuffer = NULL;
5222 delete mResampler;
5223 mResampler = NULL;
5224
5225 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5226 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Alok Kediya601e9b52013-09-27 11:55:10 +05305227 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005228 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5229 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005230 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5231 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005232 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5233
5234 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5235 {
5236 int channelCount;
5237 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5238 // stereo to mono post process as the resampler always outputs stereo.
5239 if (mChannelCount == 1 && mReqChannelCount == 2) {
5240 channelCount = 1;
5241 } else {
5242 channelCount = 2;
5243 }
5244 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5245 mResampler->setSampleRate(mSampleRate);
5246 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005247 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005248
5249 // optmization: if mono to mono, alter input frame count as if we were inputing
5250 // stereo samples
5251 if (mChannelCount == 1 && mReqChannelCount == 1) {
5252 mFrameCount >>= 1;
5253 }
5254
5255 }
5256 mRsmpInIndex = mFrameCount;
5257}
5258
5259unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5260{
5261 Mutex::Autolock _l(mLock);
5262 if (initCheck() != NO_ERROR) {
5263 return 0;
5264 }
5265
5266 return mInput->stream->get_input_frames_lost(mInput->stream);
5267}
5268
5269uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5270{
5271 Mutex::Autolock _l(mLock);
5272 uint32_t result = 0;
5273 if (getEffectChain_l(sessionId) != 0) {
5274 result = EFFECT_SESSION;
5275 }
5276
5277 for (size_t i = 0; i < mTracks.size(); ++i) {
5278 if (sessionId == mTracks[i]->sessionId()) {
5279 result |= TRACK_SESSION;
5280 break;
5281 }
5282 }
5283
5284 return result;
5285}
5286
5287KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5288{
5289 KeyedVector<int, bool> ids;
5290 Mutex::Autolock _l(mLock);
5291 for (size_t j = 0; j < mTracks.size(); ++j) {
5292 sp<RecordThread::RecordTrack> track = mTracks[j];
5293 int sessionId = track->sessionId();
5294 if (ids.indexOfKey(sessionId) < 0) {
5295 ids.add(sessionId, true);
5296 }
5297 }
5298 return ids;
5299}
5300
5301AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5302{
5303 Mutex::Autolock _l(mLock);
5304 AudioStreamIn *input = mInput;
5305 mInput = NULL;
5306 return input;
5307}
5308
5309// this method must always be called either with ThreadBase mLock held or inside the thread loop
5310audio_stream_t* AudioFlinger::RecordThread::stream() const
5311{
5312 if (mInput == NULL) {
5313 return NULL;
5314 }
5315 return &mInput->stream->common;
5316}
5317
5318status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5319{
5320 // only one chain per input thread
5321 if (mEffectChains.size() != 0) {
5322 return INVALID_OPERATION;
5323 }
5324 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5325
5326 chain->setInBuffer(NULL);
5327 chain->setOutBuffer(NULL);
5328
5329 checkSuspendOnAddEffectChain_l(chain);
5330
5331 mEffectChains.add(chain);
5332
5333 return NO_ERROR;
5334}
5335
5336size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5337{
5338 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5339 ALOGW_IF(mEffectChains.size() != 1,
5340 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5341 chain.get(), mEffectChains.size(), this);
5342 if (mEffectChains.size() == 1) {
5343 mEffectChains.removeAt(0);
5344 }
5345 return 0;
5346}
5347
Alok Kediya601e9b52013-09-27 11:55:10 +05305348// ----------------------------------------------------------------------------
5349
5350AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
5351 int output, AudioSessionDescriptor *outputDesc,
5352 IDirectTrackClient* client, audio_output_flags_t outflag)
5353 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
5354 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag),
5355 mEffectsThreadScratchBuffer(NULL)
5356{
5357#ifdef SRS_PROCESSING
5358 ALOGD("SRS_Processing - DirectAudioTrack - OutNotify_Init: %p TID %d\n", this, gettid());
5359 POSTPRO_PATCH_ICS_OUTPROC_DIRECT_INIT(this, gettid());
5360 SRS_Processing::ProcessOutRoute(SRS_Processing::AUTO, this, outputDesc->device);
5361#endif
5362 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5363 ALOGV("create effects thread for LPA");
5364 createEffectThread();
5365 allocateBufPool();
5366#ifdef SRS_PROCESSING
5367 } else if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL) {
5368 ALOGV("create effects thread for TUNNEL");
5369 createEffectThread();
5370#endif
5371 }
5372 outputDesc->mVolumeScale = 1.0;
5373 mDeathRecipient = new PMDeathRecipient(this);
5374 acquireWakeLock();
5375}
5376
5377void AudioFlinger::DirectAudioTrack::signalEffect() {
5378 if (mFlag & AUDIO_OUTPUT_FLAG_LPA){
5379 mEffectConfigChanged = true;
5380 mEffectCv.signal();
5381 }
5382#ifdef SRS_PROCESSING
5383 if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL){
5384 mEffectConfigChanged = true;
5385 mEffectCv.signal();
5386 }
5387#endif
5388}
5389
5390AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
5391#ifdef SRS_PROCESSING
5392 ALOGD("SRS_Processing - DirectAudioTrack - OutNotify_Init: %p TID %d\n", this, gettid());
5393 POSTPRO_PATCH_ICS_OUTPROC_DIRECT_EXIT(this, gettid());
5394#endif
5395 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5396 requestAndWaitForEffectsThreadExit();
5397 mAudioFlinger->deleteEffectSession();
5398 deallocateBufPool();
5399#ifdef SRS_PROCESSING
5400 } else if (mFlag & AUDIO_OUTPUT_FLAG_TUNNEL) {
5401 requestAndWaitForEffectsThreadExit();
5402 mAudioFlinger->deleteEffectSession();
5403#endif
5404 }
5405 AudioSystem::releaseOutput(mOutput);
5406 releaseWakeLock();
5407
5408 {
5409 Mutex::Autolock _l(pmLock);
5410 if (mPowerManager != 0) {
5411 sp<IBinder> binder = mPowerManager->asBinder();
5412 binder->unlinkToDeath(mDeathRecipient);
5413 }
5414 }
5415}
5416
5417status_t AudioFlinger::DirectAudioTrack::start() {
5418 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5419 if(mIsPaused) {
5420 mIsPaused = false;
5421 mOutputDesc->stream->start(mOutputDesc->stream);
5422 }
5423 mOutputDesc->mActive = true;
5424 mOutputDesc->stream->set_volume(mOutputDesc->stream,
5425 mOutputDesc->mVolumeLeft * mOutputDesc->mVolumeScale,
5426 mOutputDesc->mVolumeRight* mOutputDesc->mVolumeScale);
5427 return NO_ERROR;
5428}
5429
5430void AudioFlinger::DirectAudioTrack::stop() {
5431 ALOGV("DirectAudioTrack::stop");
5432 mOutputDesc->mActive = false;
5433 mOutputDesc->stream->stop(mOutputDesc->stream);
5434 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5435}
5436
5437void AudioFlinger::DirectAudioTrack::pause() {
5438 if(!mIsPaused) {
5439 mIsPaused = true;
5440 mOutputDesc->stream->pause(mOutputDesc->stream);
5441 mOutputDesc->mActive = false;
5442 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
5443 }
5444}
5445
5446ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
5447 ALOGV("Writing to AudioSessionOut");
5448 int isAvail = 0;
5449 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
5450 if (!isAvail) {
5451 return 0;
5452 }
5453
5454 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5455 mEffectLock.lock();
5456 List<BufferInfo>::iterator it = mEffectsPool.begin();
5457 BufferInfo buf = *it;
5458 mEffectsPool.erase(it);
5459 memcpy((char *) buf.localBuf, (char *)buffer, size);
5460 buf.bytesToWrite = size;
5461 mEffectsPool.push_back(buf);
5462 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
5463 (int16_t*)buf.localBuf, (int16_t*)buffer, (int)size, true);
5464 mEffectLock.unlock();
5465 }
5466 ALOGV("out of Writing to AudioSessionOut");
5467 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
5468}
5469
5470void AudioFlinger::DirectAudioTrack::flush() {
5471 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
5472 mEffectLock.lock();
5473 mEffectsPool.clear();
5474 mEffectsPool = mBufPool;
5475 mEffectLock.unlock();
5476 }
5477 mOutputDesc->stream->flush(mOutputDesc->stream);
5478}
5479
5480void AudioFlinger::DirectAudioTrack::mute(bool muted) {
5481}
5482
5483void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
5484 ALOGV("DirectAudioTrack::setVolume left: %f, right: %f", left, right);
5485 if(mOutputDesc) {
5486 mOutputDesc->mVolumeLeft = left;
5487 mOutputDesc->mVolumeRight = right;
5488 if(mOutputDesc->mActive && mOutputDesc->stream) {
5489 mOutputDesc->stream->set_volume(mOutputDesc->stream,
5490 left * mOutputDesc->mVolumeScale,
5491 right* mOutputDesc->mVolumeScale);
5492 } else {
5493 ALOGD("stream is not active, so cache and send when stream is active");
5494 }
5495 } else {
5496 ALOGD("output descriptor is not valid to set the volume");
5497 }
5498}
5499
5500int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
5501 int64_t time;
5502 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
5503 ALOGV("Timestamp %lld",time);
5504 return time;
5505}
5506
5507void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
5508 if (delayUs == 0 ) {
5509 ALOGV("Notify Audio Track of EOS event");
5510 mClient->notify(DIRECT_TRACK_EOS);
5511 } else {
5512 ALOGV("Notify Audio Track of hardware failure event");
5513 mClient->notify(DIRECT_TRACK_HW_FAIL);
5514 }
5515}
5516
5517void AudioFlinger::DirectAudioTrack::allocateBufPool() {
5518 void *dsp_buf = NULL;
5519 void *local_buf = NULL;
5520
5521 //1. get the ion buffer information
5522 struct buf_info* buf = NULL;
5523 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
5524 ALOGV("get buffer info %p",buf);
5525 if (!buf) {
5526 ALOGV("buffer is NULL");
5527 return;
5528 }
5529 int nSize = buf->bufsize;
5530 int bufferCount = buf->nBufs;
5531
5532 //2. allocate the buffer pool, allocate local buffers
5533 for (int i = 0; i < bufferCount; i++) {
5534 dsp_buf = (void *)buf->buffers[i];
5535 local_buf = malloc(nSize);
5536 memset(local_buf, 0, nSize);
5537 // Store this information for internal mapping / maintanence
5538 BufferInfo buf(local_buf, dsp_buf, nSize);
5539 buf.bytesToWrite = 0;
5540 mBufPool.push_back(buf);
5541 mEffectsPool.push_back(buf);
5542
5543 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
5544 }
5545
5546 mEffectsThreadScratchBuffer = malloc(nSize);
5547 ALOGV("effectsThreadScratchBuffer = %x",mEffectsThreadScratchBuffer);
5548
5549 free(buf);
5550}
5551
5552void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
5553
5554 //1. Deallocate the local memory
5555 //2. Remove all the buffers from bufpool
5556 mEffectLock.lock();
5557 while (!mBufPool.empty()) {
5558 List<BufferInfo>::iterator it = mBufPool.begin();
5559 BufferInfo &memBuffer = *it;
5560 // free the local buffer corresponding to mem buffer
5561 if (memBuffer.localBuf) {
5562 free(memBuffer.localBuf);
5563 memBuffer.localBuf = NULL;
5564 }
5565 ALOGV("Removing from bufpool");
5566 mBufPool.erase(it);
5567 }
5568 mEffectsPool.clear();
5569 mEffectLock.unlock();
5570
5571 free(mEffectsThreadScratchBuffer);
5572 mEffectsThreadScratchBuffer = NULL;
5573}
5574
5575status_t AudioFlinger::DirectAudioTrack::onTransact(
5576 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5577{
5578 return BnDirectTrack::onTransact(code, data, reply, flags);
5579}
5580
5581AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
5582{
5583 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
5584 pBaseClass = (DirectAudioTrack*)obj;
5585}
5586
5587void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
5588 pBaseClass->mAudioFlinger.clear();
5589 ALOGW("AudioFlinger server died!");
5590}
5591
5592void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
5593 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
5594 ALOGV("ioConfigChanged() event %d", event);
5595 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
5596 ALOGV("Received notification for change in effect module");
5597 // Seek to current media time - flush the decoded buffers with the driver
5598 pBaseClass->mEffectConfigChanged = true;
5599 // Signal effects thread to re-apply effects
5600 ALOGV("Signalling Effects Thread");
5601 pBaseClass->mEffectCv.signal();
5602
5603 }
5604 ALOGV("ioConfigChanged Out");
5605}
5606
5607void AudioFlinger::DirectAudioTrack::acquireWakeLock()
5608{
5609 Mutex::Autolock _l(pmLock);
5610
5611 if (mPowerManager == 0) {
5612 // use checkService() to avoid blocking if power service is not up yet
5613 sp<IBinder> binder =
5614 defaultServiceManager()->checkService(String16("power"));
5615 if (binder == 0) {
5616 ALOGW("Thread %s cannot connect to the power manager service", lockName);
5617 } else {
5618 mPowerManager = interface_cast<IPowerManager>(binder);
5619 binder->linkToDeath(mDeathRecipient);
5620 }
5621 }
5622 if (mPowerManager != 0 && mWakeLockToken == 0) {
5623 sp<IBinder> binder = new BBinder();
5624 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
5625 binder,
5626 String16(lockName),
5627 String16("media"));
5628 if (status == NO_ERROR) {
5629 mWakeLockToken = binder;
5630 }
5631 ALOGV("acquireWakeLock() status %d", status);
5632 }
5633}
5634
5635void AudioFlinger::DirectAudioTrack::releaseWakeLock()
5636{
5637 Mutex::Autolock _l(pmLock);
5638
5639 if (mWakeLockToken != 0) {
5640 ALOGV("releaseWakeLock()");
5641 if (mPowerManager != 0) {
5642 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
5643 }
5644 mWakeLockToken.clear();
5645 }
5646}
5647
5648void AudioFlinger::DirectAudioTrack::clearPowerManager()
5649{
5650 releaseWakeLock();
5651 Mutex::Autolock _l(pmLock);
5652 mPowerManager.clear();
5653}
5654
5655void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
5656{
5657 parentClass->clearPowerManager();
5658 ALOGW("power manager service died !!!");
5659}
5660
5661// ----------------------------------------------------------------------------
5662
Eric Laurent81784c32012-11-19 14:55:58 -08005663}; // namespace android