blob: 1b0a6019e1db8cc97f6162c8d3ff99d5a1aeaa90 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080037#include <audio_utils/format.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038
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
68// ----------------------------------------------------------------------------
69
70// Note: the following macro is used for extremely verbose logging message. In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well. Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on. Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
82
83namespace android {
84
85// retry counts for buffer fill timeout
86// 50 * ~20msecs = 1 second
87static const int8_t kMaxTrackRetries = 50;
88static const int8_t kMaxTrackStartupRetries = 50;
89// allow less retry attempts on direct output thread.
90// direct outputs can be a scarce resource in audio hardware and should
91// be released as quickly as possible.
92static const int8_t kMaxTrackRetriesDirect = 2;
93
94// don't warn about blocked writes or record buffer overflows more often than this
95static const nsecs_t kWarningThrottleNs = seconds(5);
96
97// RecordThread loop sleep time upon application overrun or audio HAL read error
98static const int kRecordThreadSleepUs = 5000;
99
100// maximum time to wait for setParameters to complete
101static const nsecs_t kSetParametersTimeoutNs = seconds(2);
102
103// minimum sleep time for the mixer thread loop when tracks are active but in underrun
104static const uint32_t kMinThreadSleepTimeUs = 5000;
105// maximum divider applied to the active sleep time in the mixer thread loop
106static const uint32_t kMaxThreadSleepTimeShift = 2;
107
Andy Hung09a50072014-02-27 14:30:47 -0800108// minimum normal sink buffer size, expressed in milliseconds rather than frames
109static const uint32_t kMinNormalSinkBufferSizeMs = 20;
110// maximum normal sink buffer size
111static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800112
Eric Laurent972a1732013-09-04 09:42:59 -0700113// Offloaded output thread standby delay: allows track transition without going to standby
114static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
115
Eric Laurent81784c32012-11-19 14:55:58 -0800116// Whether to use fast mixer
117static const enum {
118 FastMixer_Never, // never initialize or use: for debugging only
119 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
120 // normal mixer multiplier is 1
121 FastMixer_Static, // initialize if needed, then use all the time if initialized,
122 // multiplier is calculated based on min & max normal mixer buffer size
123 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
124 // multiplier is calculated based on min & max normal mixer buffer size
125 // FIXME for FastMixer_Dynamic:
126 // Supporting this option will require fixing HALs that can't handle large writes.
127 // For example, one HAL implementation returns an error from a large write,
128 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
129 // We could either fix the HAL implementations, or provide a wrapper that breaks
130 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
131} kUseFastMixer = FastMixer_Static;
132
133// Priorities for requestPriority
134static const int kPriorityAudioApp = 2;
135static const int kPriorityFastMixer = 3;
136
137// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
138// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800139// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
140// So for now we just assume that client is double-buffered for fast tracks.
141// FIXME It would be better for client to tell AudioFlinger the value of N,
142// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800143// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800144static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800145
146// ----------------------------------------------------------------------------
147
148#ifdef ADD_BATTERY_DATA
149// To collect the amplifier usage
150static void addBatteryData(uint32_t params) {
151 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
152 if (service == NULL) {
153 // it already logged
154 return;
155 }
156
157 service->addBatteryData(params);
158}
159#endif
160
161
162// ----------------------------------------------------------------------------
163// CPU Stats
164// ----------------------------------------------------------------------------
165
166class CpuStats {
167public:
168 CpuStats();
169 void sample(const String8 &title);
170#ifdef DEBUG_CPU_USAGE
171private:
172 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
173 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
174
175 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
176
177 int mCpuNum; // thread's current CPU number
178 int mCpukHz; // frequency of thread's current CPU in kHz
179#endif
180};
181
182CpuStats::CpuStats()
183#ifdef DEBUG_CPU_USAGE
184 : mCpuNum(-1), mCpukHz(-1)
185#endif
186{
187}
188
Glenn Kasten0f11b512014-01-31 16:18:54 -0800189void CpuStats::sample(const String8 &title
190#ifndef DEBUG_CPU_USAGE
191 __unused
192#endif
193 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800194#ifdef DEBUG_CPU_USAGE
195 // get current thread's delta CPU time in wall clock ns
196 double wcNs;
197 bool valid = mCpuUsage.sampleAndEnable(wcNs);
198
199 // record sample for wall clock statistics
200 if (valid) {
201 mWcStats.sample(wcNs);
202 }
203
204 // get the current CPU number
205 int cpuNum = sched_getcpu();
206
207 // get the current CPU frequency in kHz
208 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
209
210 // check if either CPU number or frequency changed
211 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
212 mCpuNum = cpuNum;
213 mCpukHz = cpukHz;
214 // ignore sample for purposes of cycles
215 valid = false;
216 }
217
218 // if no change in CPU number or frequency, then record sample for cycle statistics
219 if (valid && mCpukHz > 0) {
220 double cycles = wcNs * cpukHz * 0.000001;
221 mHzStats.sample(cycles);
222 }
223
224 unsigned n = mWcStats.n();
225 // mCpuUsage.elapsed() is expensive, so don't call it every loop
226 if ((n & 127) == 1) {
227 long long elapsed = mCpuUsage.elapsed();
228 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
229 double perLoop = elapsed / (double) n;
230 double perLoop100 = perLoop * 0.01;
231 double perLoop1k = perLoop * 0.001;
232 double mean = mWcStats.mean();
233 double stddev = mWcStats.stddev();
234 double minimum = mWcStats.minimum();
235 double maximum = mWcStats.maximum();
236 double meanCycles = mHzStats.mean();
237 double stddevCycles = mHzStats.stddev();
238 double minCycles = mHzStats.minimum();
239 double maxCycles = mHzStats.maximum();
240 mCpuUsage.resetElapsed();
241 mWcStats.reset();
242 mHzStats.reset();
243 ALOGD("CPU usage for %s over past %.1f secs\n"
244 " (%u mixer loops at %.1f mean ms per loop):\n"
245 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
246 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
247 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
248 title.string(),
249 elapsed * .000000001, n, perLoop * .000001,
250 mean * .001,
251 stddev * .001,
252 minimum * .001,
253 maximum * .001,
254 mean / perLoop100,
255 stddev / perLoop100,
256 minimum / perLoop100,
257 maximum / perLoop100,
258 meanCycles / perLoop1k,
259 stddevCycles / perLoop1k,
260 minCycles / perLoop1k,
261 maxCycles / perLoop1k);
262
263 }
264 }
265#endif
266};
267
268// ----------------------------------------------------------------------------
269// ThreadBase
270// ----------------------------------------------------------------------------
271
272AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
273 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
274 : Thread(false /*canCallJava*/),
275 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700276 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700277 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800278 // are set by PlaybackThread::readOutputParameters_l() or
279 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800280 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700281 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800282 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
283 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
284 // mName will be set by concrete (non-virtual) subclass
285 mDeathRecipient(new PMDeathRecipient(this))
286{
287}
288
289AudioFlinger::ThreadBase::~ThreadBase()
290{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700291 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
292 for (size_t i = 0; i < mConfigEvents.size(); i++) {
293 delete mConfigEvents[i];
294 }
295 mConfigEvents.clear();
296
Eric Laurent81784c32012-11-19 14:55:58 -0800297 mParamCond.broadcast();
298 // do not lock the mutex in destructor
299 releaseWakeLock_l();
300 if (mPowerManager != 0) {
301 sp<IBinder> binder = mPowerManager->asBinder();
302 binder->unlinkToDeath(mDeathRecipient);
303 }
304}
305
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700306status_t AudioFlinger::ThreadBase::readyToRun()
307{
308 status_t status = initCheck();
309 if (status == NO_ERROR) {
310 ALOGI("AudioFlinger's thread %p ready to run", this);
311 } else {
312 ALOGE("No working audio driver found.");
313 }
314 return status;
315}
316
Eric Laurent81784c32012-11-19 14:55:58 -0800317void AudioFlinger::ThreadBase::exit()
318{
319 ALOGV("ThreadBase::exit");
320 // do any cleanup required for exit to succeed
321 preExit();
322 {
323 // This lock prevents the following race in thread (uniprocessor for illustration):
324 // if (!exitPending()) {
325 // // context switch from here to exit()
326 // // exit() calls requestExit(), what exitPending() observes
327 // // exit() calls signal(), which is dropped since no waiters
328 // // context switch back from exit() to here
329 // mWaitWorkCV.wait(...);
330 // // now thread is hung
331 // }
332 AutoMutex lock(mLock);
333 requestExit();
334 mWaitWorkCV.broadcast();
335 }
336 // When Thread::requestExitAndWait is made virtual and this method is renamed to
337 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
338 requestExitAndWait();
339}
340
341status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
342{
343 status_t status;
344
345 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
346 Mutex::Autolock _l(mLock);
347
348 mNewParameters.add(keyValuePairs);
349 mWaitWorkCV.signal();
350 // wait condition with timeout in case the thread loop has exited
351 // before the request could be processed
352 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
353 status = mParamStatus;
354 mWaitWorkCV.signal();
355 } else {
356 status = TIMED_OUT;
357 }
358 return status;
359}
360
361void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
362{
363 Mutex::Autolock _l(mLock);
364 sendIoConfigEvent_l(event, param);
365}
366
367// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
368void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
369{
370 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
371 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
372 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
373 param);
374 mWaitWorkCV.signal();
375}
376
377// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
378void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
379{
380 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
381 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
382 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
383 mConfigEvents.size(), pid, tid, prio);
384 mWaitWorkCV.signal();
385}
386
387void AudioFlinger::ThreadBase::processConfigEvents()
388{
Glenn Kastenf7773312013-08-13 16:00:42 -0700389 Mutex::Autolock _l(mLock);
390 processConfigEvents_l();
391}
392
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700393// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700394void AudioFlinger::ThreadBase::processConfigEvents_l()
395{
Eric Laurent81784c32012-11-19 14:55:58 -0800396 while (!mConfigEvents.isEmpty()) {
397 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
398 ConfigEvent *event = mConfigEvents[0];
399 mConfigEvents.removeAt(0);
400 // release mLock before locking AudioFlinger mLock: lock order is always
401 // AudioFlinger then ThreadBase to avoid cross deadlock
402 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700403 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700404 case CFG_EVENT_PRIO: {
405 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
406 // FIXME Need to understand why this has be done asynchronously
407 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
408 true /*asynchronous*/);
409 if (err != 0) {
410 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
411 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
412 }
413 } break;
414 case CFG_EVENT_IO: {
415 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700416 {
417 Mutex::Autolock _l(mAudioFlinger->mLock);
418 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
419 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700420 } break;
421 default:
422 ALOGE("processConfigEvents() unknown event type %d", event->type());
423 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800424 }
425 delete event;
426 mLock.lock();
427 }
Eric Laurent81784c32012-11-19 14:55:58 -0800428}
429
Marco Nelissenb2208842014-02-07 14:00:50 -0800430String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
431 String8 s;
432 if (output) {
433 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
434 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
435 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
436 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
437 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
438 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
439 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
440 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
441 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
442 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
443 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
444 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
445 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
446 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
447 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
448 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
449 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
450 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
451 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
452 } else {
453 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
454 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
455 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
456 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
457 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
458 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
459 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
460 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
461 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
462 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
463 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
464 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
465 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
466 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
467 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
468 }
469 int len = s.length();
470 if (s.length() > 2) {
471 char *str = s.lockBuffer(len);
472 s.unlockBuffer(len - 2);
473 }
474 return s;
475}
476
Glenn Kasten0f11b512014-01-31 16:18:54 -0800477void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800478{
479 const size_t SIZE = 256;
480 char buffer[SIZE];
481 String8 result;
482
483 bool locked = AudioFlinger::dumpTryLock(mLock);
484 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800485 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800486 }
487
Marco Nelissenb2208842014-02-07 14:00:50 -0800488 fdprintf(fd, " I/O handle: %d\n", mId);
489 fdprintf(fd, " TID: %d\n", getTid());
490 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
491 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000492 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800493 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
494 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
495 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
496 channelMaskToString(mChannelMask, mType != RECORD).string());
497 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000498 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800499 fdprintf(fd, " Pending setParameters commands:");
500 size_t numParams = mNewParameters.size();
501 if (numParams) {
502 fdprintf(fd, "\n Index Command");
503 for (size_t i = 0; i < numParams; ++i) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000504 fdprintf(fd, "\n %02zu ", i);
Marco Nelissenb2208842014-02-07 14:00:50 -0800505 fdprintf(fd, mNewParameters[i]);
506 }
507 fdprintf(fd, "\n");
508 } else {
509 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800510 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800511 fdprintf(fd, " Pending config events:");
512 size_t numConfig = mConfigEvents.size();
513 if (numConfig) {
514 for (size_t i = 0; i < numConfig; i++) {
515 mConfigEvents[i]->dump(buffer, SIZE);
516 fdprintf(fd, "\n %s", buffer);
517 }
518 fdprintf(fd, "\n");
519 } else {
520 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800521 }
Eric Laurent81784c32012-11-19 14:55:58 -0800522
523 if (locked) {
524 mLock.unlock();
525 }
526}
527
528void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
529{
530 const size_t SIZE = 256;
531 char buffer[SIZE];
532 String8 result;
533
Marco Nelissenb2208842014-02-07 14:00:50 -0800534 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000535 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800536 write(fd, buffer, strlen(buffer));
537
Marco Nelissenb2208842014-02-07 14:00:50 -0800538 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800539 sp<EffectChain> chain = mEffectChains[i];
540 if (chain != 0) {
541 chain->dump(fd, args);
542 }
543 }
544}
545
Marco Nelissene14a5d62013-10-03 08:51:24 -0700546void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800547{
548 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700549 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800550}
551
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100552String16 AudioFlinger::ThreadBase::getWakeLockTag()
553{
554 switch (mType) {
555 case MIXER:
556 return String16("AudioMix");
557 case DIRECT:
558 return String16("AudioDirectOut");
559 case DUPLICATING:
560 return String16("AudioDup");
561 case RECORD:
562 return String16("AudioIn");
563 case OFFLOAD:
564 return String16("AudioOffload");
565 default:
566 ALOG_ASSERT(false);
567 return String16("AudioUnknown");
568 }
569}
570
Marco Nelissene14a5d62013-10-03 08:51:24 -0700571void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800572{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800573 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800574 if (mPowerManager != 0) {
575 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700576 status_t status;
577 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700578 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700579 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100580 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700581 String16("media"),
582 uid);
583 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700584 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700585 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100586 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700587 String16("media"));
588 }
Eric Laurent81784c32012-11-19 14:55:58 -0800589 if (status == NO_ERROR) {
590 mWakeLockToken = binder;
591 }
592 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
593 }
594}
595
596void AudioFlinger::ThreadBase::releaseWakeLock()
597{
598 Mutex::Autolock _l(mLock);
599 releaseWakeLock_l();
600}
601
602void AudioFlinger::ThreadBase::releaseWakeLock_l()
603{
604 if (mWakeLockToken != 0) {
605 ALOGV("releaseWakeLock_l() %s", mName);
606 if (mPowerManager != 0) {
607 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
608 }
609 mWakeLockToken.clear();
610 }
611}
612
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800613void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
614 Mutex::Autolock _l(mLock);
615 updateWakeLockUids_l(uids);
616}
617
618void AudioFlinger::ThreadBase::getPowerManager_l() {
619
620 if (mPowerManager == 0) {
621 // use checkService() to avoid blocking if power service is not up yet
622 sp<IBinder> binder =
623 defaultServiceManager()->checkService(String16("power"));
624 if (binder == 0) {
625 ALOGW("Thread %s cannot connect to the power manager service", mName);
626 } else {
627 mPowerManager = interface_cast<IPowerManager>(binder);
628 binder->linkToDeath(mDeathRecipient);
629 }
630 }
631}
632
633void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
634
635 getPowerManager_l();
636 if (mWakeLockToken == NULL) {
637 ALOGE("no wake lock to update!");
638 return;
639 }
640 if (mPowerManager != 0) {
641 sp<IBinder> binder = new BBinder();
642 status_t status;
643 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
644 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
645 }
646}
647
Eric Laurent81784c32012-11-19 14:55:58 -0800648void AudioFlinger::ThreadBase::clearPowerManager()
649{
650 Mutex::Autolock _l(mLock);
651 releaseWakeLock_l();
652 mPowerManager.clear();
653}
654
Glenn Kasten0f11b512014-01-31 16:18:54 -0800655void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
657 sp<ThreadBase> thread = mThread.promote();
658 if (thread != 0) {
659 thread->clearPowerManager();
660 }
661 ALOGW("power manager service died !!!");
662}
663
664void AudioFlinger::ThreadBase::setEffectSuspended(
665 const effect_uuid_t *type, bool suspend, int sessionId)
666{
667 Mutex::Autolock _l(mLock);
668 setEffectSuspended_l(type, suspend, sessionId);
669}
670
671void AudioFlinger::ThreadBase::setEffectSuspended_l(
672 const effect_uuid_t *type, bool suspend, int sessionId)
673{
674 sp<EffectChain> chain = getEffectChain_l(sessionId);
675 if (chain != 0) {
676 if (type != NULL) {
677 chain->setEffectSuspended_l(type, suspend);
678 } else {
679 chain->setEffectSuspendedAll_l(suspend);
680 }
681 }
682
683 updateSuspendedSessions_l(type, suspend, sessionId);
684}
685
686void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
687{
688 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
689 if (index < 0) {
690 return;
691 }
692
693 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
694 mSuspendedSessions.valueAt(index);
695
696 for (size_t i = 0; i < sessionEffects.size(); i++) {
697 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
698 for (int j = 0; j < desc->mRefCount; j++) {
699 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
700 chain->setEffectSuspendedAll_l(true);
701 } else {
702 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
703 desc->mType.timeLow);
704 chain->setEffectSuspended_l(&desc->mType, true);
705 }
706 }
707 }
708}
709
710void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
711 bool suspend,
712 int sessionId)
713{
714 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
715
716 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
717
718 if (suspend) {
719 if (index >= 0) {
720 sessionEffects = mSuspendedSessions.valueAt(index);
721 } else {
722 mSuspendedSessions.add(sessionId, sessionEffects);
723 }
724 } else {
725 if (index < 0) {
726 return;
727 }
728 sessionEffects = mSuspendedSessions.valueAt(index);
729 }
730
731
732 int key = EffectChain::kKeyForSuspendAll;
733 if (type != NULL) {
734 key = type->timeLow;
735 }
736 index = sessionEffects.indexOfKey(key);
737
738 sp<SuspendedSessionDesc> desc;
739 if (suspend) {
740 if (index >= 0) {
741 desc = sessionEffects.valueAt(index);
742 } else {
743 desc = new SuspendedSessionDesc();
744 if (type != NULL) {
745 desc->mType = *type;
746 }
747 sessionEffects.add(key, desc);
748 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
749 }
750 desc->mRefCount++;
751 } else {
752 if (index < 0) {
753 return;
754 }
755 desc = sessionEffects.valueAt(index);
756 if (--desc->mRefCount == 0) {
757 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
758 sessionEffects.removeItemsAt(index);
759 if (sessionEffects.isEmpty()) {
760 ALOGV("updateSuspendedSessions_l() restore removing session %d",
761 sessionId);
762 mSuspendedSessions.removeItem(sessionId);
763 }
764 }
765 }
766 if (!sessionEffects.isEmpty()) {
767 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
768 }
769}
770
771void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
772 bool enabled,
773 int sessionId)
774{
775 Mutex::Autolock _l(mLock);
776 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
777}
778
779void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
780 bool enabled,
781 int sessionId)
782{
783 if (mType != RECORD) {
784 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
785 // another session. This gives the priority to well behaved effect control panels
786 // and applications not using global effects.
787 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
788 // global effects
789 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
790 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
791 }
792 }
793
794 sp<EffectChain> chain = getEffectChain_l(sessionId);
795 if (chain != 0) {
796 chain->checkSuspendOnEffectEnabled(effect, enabled);
797 }
798}
799
800// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
801sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
802 const sp<AudioFlinger::Client>& client,
803 const sp<IEffectClient>& effectClient,
804 int32_t priority,
805 int sessionId,
806 effect_descriptor_t *desc,
807 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700808 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800809{
810 sp<EffectModule> effect;
811 sp<EffectHandle> handle;
812 status_t lStatus;
813 sp<EffectChain> chain;
814 bool chainCreated = false;
815 bool effectCreated = false;
816 bool effectRegistered = false;
817
818 lStatus = initCheck();
819 if (lStatus != NO_ERROR) {
820 ALOGW("createEffect_l() Audio driver not initialized.");
821 goto Exit;
822 }
823
Andy Hung98ef9782014-03-04 14:46:50 -0800824 // Reject any effect on Direct output threads for now, since the format of
825 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
826 if (mType == DIRECT) {
827 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
828 desc->name, mName);
829 lStatus = BAD_VALUE;
830 goto Exit;
831 }
832
Eric Laurent5baf2af2013-09-12 17:37:00 -0700833 // Allow global effects only on offloaded and mixer threads
834 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
835 switch (mType) {
836 case MIXER:
837 case OFFLOAD:
838 break;
839 case DIRECT:
840 case DUPLICATING:
841 case RECORD:
842 default:
843 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
844 lStatus = BAD_VALUE;
845 goto Exit;
846 }
Eric Laurent81784c32012-11-19 14:55:58 -0800847 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700848
Eric Laurent81784c32012-11-19 14:55:58 -0800849 // Only Pre processor effects are allowed on input threads and only on input threads
850 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
851 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
852 desc->name, desc->flags, mType);
853 lStatus = BAD_VALUE;
854 goto Exit;
855 }
856
857 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
858
859 { // scope for mLock
860 Mutex::Autolock _l(mLock);
861
862 // check for existing effect chain with the requested audio session
863 chain = getEffectChain_l(sessionId);
864 if (chain == 0) {
865 // create a new chain for this session
866 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
867 chain = new EffectChain(this, sessionId);
868 addEffectChain_l(chain);
869 chain->setStrategy(getStrategyForSession_l(sessionId));
870 chainCreated = true;
871 } else {
872 effect = chain->getEffectFromDesc_l(desc);
873 }
874
875 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
876
877 if (effect == 0) {
878 int id = mAudioFlinger->nextUniqueId();
879 // Check CPU and memory usage
880 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
881 if (lStatus != NO_ERROR) {
882 goto Exit;
883 }
884 effectRegistered = true;
885 // create a new effect module if none present in the chain
886 effect = new EffectModule(this, chain, desc, id, sessionId);
887 lStatus = effect->status();
888 if (lStatus != NO_ERROR) {
889 goto Exit;
890 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700891 effect->setOffloaded(mType == OFFLOAD, mId);
892
Eric Laurent81784c32012-11-19 14:55:58 -0800893 lStatus = chain->addEffect_l(effect);
894 if (lStatus != NO_ERROR) {
895 goto Exit;
896 }
897 effectCreated = true;
898
899 effect->setDevice(mOutDevice);
900 effect->setDevice(mInDevice);
901 effect->setMode(mAudioFlinger->getMode());
902 effect->setAudioSource(mAudioSource);
903 }
904 // create effect handle and connect it to effect module
905 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800906 lStatus = handle->initCheck();
907 if (lStatus == OK) {
908 lStatus = effect->addHandle(handle.get());
909 }
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (enabled != NULL) {
911 *enabled = (int)effect->isEnabled();
912 }
913 }
914
915Exit:
916 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
917 Mutex::Autolock _l(mLock);
918 if (effectCreated) {
919 chain->removeEffect_l(effect);
920 }
921 if (effectRegistered) {
922 AudioSystem::unregisterEffect(effect->id());
923 }
924 if (chainCreated) {
925 removeEffectChain_l(chain);
926 }
927 handle.clear();
928 }
929
Glenn Kasten9156ef32013-08-06 15:39:08 -0700930 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800931 return handle;
932}
933
934sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
935{
936 Mutex::Autolock _l(mLock);
937 return getEffect_l(sessionId, effectId);
938}
939
940sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
941{
942 sp<EffectChain> chain = getEffectChain_l(sessionId);
943 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
944}
945
946// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
947// PlaybackThread::mLock held
948status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
949{
950 // check for existing effect chain with the requested audio session
951 int sessionId = effect->sessionId();
952 sp<EffectChain> chain = getEffectChain_l(sessionId);
953 bool chainCreated = false;
954
Eric Laurent5baf2af2013-09-12 17:37:00 -0700955 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
956 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
957 this, effect->desc().name, effect->desc().flags);
958
Eric Laurent81784c32012-11-19 14:55:58 -0800959 if (chain == 0) {
960 // create a new chain for this session
961 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
962 chain = new EffectChain(this, sessionId);
963 addEffectChain_l(chain);
964 chain->setStrategy(getStrategyForSession_l(sessionId));
965 chainCreated = true;
966 }
967 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
968
969 if (chain->getEffectFromId_l(effect->id()) != 0) {
970 ALOGW("addEffect_l() %p effect %s already present in chain %p",
971 this, effect->desc().name, chain.get());
972 return BAD_VALUE;
973 }
974
Eric Laurent5baf2af2013-09-12 17:37:00 -0700975 effect->setOffloaded(mType == OFFLOAD, mId);
976
Eric Laurent81784c32012-11-19 14:55:58 -0800977 status_t status = chain->addEffect_l(effect);
978 if (status != NO_ERROR) {
979 if (chainCreated) {
980 removeEffectChain_l(chain);
981 }
982 return status;
983 }
984
985 effect->setDevice(mOutDevice);
986 effect->setDevice(mInDevice);
987 effect->setMode(mAudioFlinger->getMode());
988 effect->setAudioSource(mAudioSource);
989 return NO_ERROR;
990}
991
992void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
993
994 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
995 effect_descriptor_t desc = effect->desc();
996 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
997 detachAuxEffect_l(effect->id());
998 }
999
1000 sp<EffectChain> chain = effect->chain().promote();
1001 if (chain != 0) {
1002 // remove effect chain if removing last effect
1003 if (chain->removeEffect_l(effect) == 0) {
1004 removeEffectChain_l(chain);
1005 }
1006 } else {
1007 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1008 }
1009}
1010
1011void AudioFlinger::ThreadBase::lockEffectChains_l(
1012 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1013{
1014 effectChains = mEffectChains;
1015 for (size_t i = 0; i < mEffectChains.size(); i++) {
1016 mEffectChains[i]->lock();
1017 }
1018}
1019
1020void AudioFlinger::ThreadBase::unlockEffectChains(
1021 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1022{
1023 for (size_t i = 0; i < effectChains.size(); i++) {
1024 effectChains[i]->unlock();
1025 }
1026}
1027
1028sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1029{
1030 Mutex::Autolock _l(mLock);
1031 return getEffectChain_l(sessionId);
1032}
1033
1034sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1035{
1036 size_t size = mEffectChains.size();
1037 for (size_t i = 0; i < size; i++) {
1038 if (mEffectChains[i]->sessionId() == sessionId) {
1039 return mEffectChains[i];
1040 }
1041 }
1042 return 0;
1043}
1044
1045void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1046{
1047 Mutex::Autolock _l(mLock);
1048 size_t size = mEffectChains.size();
1049 for (size_t i = 0; i < size; i++) {
1050 mEffectChains[i]->setMode_l(mode);
1051 }
1052}
1053
1054void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1055 EffectHandle *handle,
1056 bool unpinIfLast) {
1057
1058 Mutex::Autolock _l(mLock);
1059 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1060 // delete the effect module if removing last handle on it
1061 if (effect->removeHandle(handle) == 0) {
1062 if (!effect->isPinned() || unpinIfLast) {
1063 removeEffect_l(effect);
1064 AudioSystem::unregisterEffect(effect->id());
1065 }
1066 }
1067}
1068
1069// ----------------------------------------------------------------------------
1070// Playback
1071// ----------------------------------------------------------------------------
1072
1073AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1074 AudioStreamOut* output,
1075 audio_io_handle_t id,
1076 audio_devices_t device,
1077 type_t type)
1078 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001079 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001080 mMixerBufferEnabled(false),
1081 mMixerBuffer(NULL),
1082 mMixerBufferSize(0),
1083 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1084 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001085 mEffectBufferEnabled(false),
1086 mEffectBuffer(NULL),
1087 mEffectBufferSize(0),
1088 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1089 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001090 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001091 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001092 // mStreamTypes[] initialized in constructor body
1093 mOutput(output),
1094 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1095 mMixerStatus(MIXER_IDLE),
1096 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1097 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001098 mBytesRemaining(0),
1099 mCurrentWriteLength(0),
1100 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001101 mWriteAckSequence(0),
1102 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001103 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001104 mScreenState(AudioFlinger::mScreenState),
1105 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001106 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1107 // mLatchD, mLatchQ,
1108 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001109{
1110 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001111 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001112
1113 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1114 // it would be safer to explicitly pass initial masterVolume/masterMute as
1115 // parameter.
1116 //
1117 // If the HAL we are using has support for master volume or master mute,
1118 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1119 // and the mute set to false).
1120 mMasterVolume = audioFlinger->masterVolume_l();
1121 mMasterMute = audioFlinger->masterMute_l();
1122 if (mOutput && mOutput->audioHwDev) {
1123 if (mOutput->audioHwDev->canSetMasterVolume()) {
1124 mMasterVolume = 1.0;
1125 }
1126
1127 if (mOutput->audioHwDev->canSetMasterMute()) {
1128 mMasterMute = false;
1129 }
1130 }
1131
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001132 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001133
1134 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1135 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1136 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1137 stream = (audio_stream_type_t) (stream + 1)) {
1138 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1139 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1140 }
1141 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1142 // because mAudioFlinger doesn't have one to copy from
1143}
1144
1145AudioFlinger::PlaybackThread::~PlaybackThread()
1146{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001147 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001148 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001149 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001150 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001151}
1152
1153void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1154{
1155 dumpInternals(fd, args);
1156 dumpTracks(fd, args);
1157 dumpEffectChains(fd, args);
1158}
1159
Glenn Kasten0f11b512014-01-31 16:18:54 -08001160void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001161{
1162 const size_t SIZE = 256;
1163 char buffer[SIZE];
1164 String8 result;
1165
Marco Nelissenb2208842014-02-07 14:00:50 -08001166 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001167 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1168 const stream_type_t *st = &mStreamTypes[i];
1169 if (i > 0) {
1170 result.appendFormat(", ");
1171 }
1172 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1173 if (st->mute) {
1174 result.append("M");
1175 }
1176 }
1177 result.append("\n");
1178 write(fd, result.string(), result.length());
1179 result.clear();
1180
Eric Laurent81784c32012-11-19 14:55:58 -08001181 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1182 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001183 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001184 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001185
1186 size_t numtracks = mTracks.size();
1187 size_t numactive = mActiveTracks.size();
1188 fdprintf(fd, " %d Tracks", numtracks);
1189 size_t numactiveseen = 0;
1190 if (numtracks) {
1191 fdprintf(fd, " of which %d are active\n", numactive);
1192 Track::appendDumpHeader(result);
1193 for (size_t i = 0; i < numtracks; ++i) {
1194 sp<Track> track = mTracks[i];
1195 if (track != 0) {
1196 bool active = mActiveTracks.indexOf(track) >= 0;
1197 if (active) {
1198 numactiveseen++;
1199 }
1200 track->dump(buffer, SIZE, active);
1201 result.append(buffer);
1202 }
1203 }
1204 } else {
1205 result.append("\n");
1206 }
1207 if (numactiveseen != numactive) {
1208 // some tracks in the active list were not in the tracks list
1209 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1210 " not in the track list\n");
1211 result.append(buffer);
1212 Track::appendDumpHeader(result);
1213 for (size_t i = 0; i < numactive; ++i) {
1214 sp<Track> track = mActiveTracks[i].promote();
1215 if (track != 0 && mTracks.indexOf(track) < 0) {
1216 track->dump(buffer, SIZE, true);
1217 result.append(buffer);
1218 }
1219 }
1220 }
1221
1222 write(fd, result.string(), result.size());
1223
Eric Laurent81784c32012-11-19 14:55:58 -08001224}
1225
1226void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1227{
Marco Nelissenb2208842014-02-07 14:00:50 -08001228 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001229 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001230 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1231 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1232 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1233 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1234 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001235 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001236 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001237 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001238 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001239
1240 dumpBase(fd, args);
1241}
1242
1243// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001244
1245void AudioFlinger::PlaybackThread::onFirstRef()
1246{
1247 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1248}
1249
1250// ThreadBase virtuals
1251void AudioFlinger::PlaybackThread::preExit()
1252{
1253 ALOGV(" preExit()");
1254 // FIXME this is using hard-coded strings but in the future, this functionality will be
1255 // converted to use audio HAL extensions required to support tunneling
1256 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1257}
1258
1259// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1260sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1261 const sp<AudioFlinger::Client>& client,
1262 audio_stream_type_t streamType,
1263 uint32_t sampleRate,
1264 audio_format_t format,
1265 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001266 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001267 const sp<IMemory>& sharedBuffer,
1268 int sessionId,
1269 IAudioFlinger::track_flags_t *flags,
1270 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001271 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001272 status_t *status)
1273{
Glenn Kasten74935e42013-12-19 08:56:45 -08001274 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001275 sp<Track> track;
1276 status_t lStatus;
1277
1278 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1279
1280 // client expresses a preference for FAST, but we get the final say
1281 if (*flags & IAudioFlinger::TRACK_FAST) {
1282 if (
1283 // not timed
1284 (!isTimed) &&
1285 // either of these use cases:
1286 (
1287 // use case 1: shared buffer with any frame count
1288 (
1289 (sharedBuffer != 0)
1290 ) ||
1291 // use case 2: callback handler and frame count is default or at least as large as HAL
1292 (
1293 (tid != -1) &&
1294 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001295 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001296 )
1297 ) &&
1298 // PCM data
1299 audio_is_linear_pcm(format) &&
1300 // mono or stereo
1301 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1302 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001303 // hardware sample rate
1304 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // normal mixer has an associated fast mixer
1306 hasFastMixer() &&
1307 // there are sufficient fast track slots available
1308 (mFastTrackAvailMask != 0)
1309 // FIXME test that MixerThread for this fast track has a capable output HAL
1310 // FIXME add a permission test also?
1311 ) {
1312 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1313 if (frameCount == 0) {
1314 frameCount = mFrameCount * kFastTrackMultiplier;
1315 }
1316 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1317 frameCount, mFrameCount);
1318 } else {
1319 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1320 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1321 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1322 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1323 audio_is_linear_pcm(format),
1324 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1325 *flags &= ~IAudioFlinger::TRACK_FAST;
1326 // For compatibility with AudioTrack calculation, buffer depth is forced
1327 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1328 // This is probably too conservative, but legacy application code may depend on it.
1329 // If you change this calculation, also review the start threshold which is related.
1330 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1331 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1332 if (minBufCount < 2) {
1333 minBufCount = 2;
1334 }
1335 size_t minFrameCount = mNormalFrameCount * minBufCount;
1336 if (frameCount < minFrameCount) {
1337 frameCount = minFrameCount;
1338 }
1339 }
1340 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001341 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001342
1343 if (mType == DIRECT) {
1344 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1345 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001346 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1347 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001348 sampleRate, format, channelMask, mOutput, mFormat);
1349 lStatus = BAD_VALUE;
1350 goto Exit;
1351 }
1352 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001353 } else if (mType == OFFLOAD) {
1354 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001355 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1356 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001357 sampleRate, format, channelMask, mOutput, mFormat);
1358 lStatus = BAD_VALUE;
1359 goto Exit;
1360 }
Eric Laurent81784c32012-11-19 14:55:58 -08001361 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001362 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001363 ALOGE("createTrack_l() Bad parameter: format %#x \""
1364 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001365 format, mOutput, mFormat);
1366 lStatus = BAD_VALUE;
1367 goto Exit;
1368 }
Eric Laurent81784c32012-11-19 14:55:58 -08001369 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1370 if (sampleRate > mSampleRate*2) {
1371 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1372 lStatus = BAD_VALUE;
1373 goto Exit;
1374 }
1375 }
1376
1377 lStatus = initCheck();
1378 if (lStatus != NO_ERROR) {
1379 ALOGE("Audio driver not initialized.");
1380 goto Exit;
1381 }
1382
1383 { // scope for mLock
1384 Mutex::Autolock _l(mLock);
1385
1386 // all tracks in same audio session must share the same routing strategy otherwise
1387 // conflicts will happen when tracks are moved from one output to another by audio policy
1388 // manager
1389 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1390 for (size_t i = 0; i < mTracks.size(); ++i) {
1391 sp<Track> t = mTracks[i];
1392 if (t != 0 && !t->isOutputTrack()) {
1393 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1394 if (sessionId == t->sessionId() && strategy != actual) {
1395 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1396 strategy, actual);
1397 lStatus = BAD_VALUE;
1398 goto Exit;
1399 }
1400 }
1401 }
1402
1403 if (!isTimed) {
1404 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001405 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001406 } else {
1407 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001408 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001409 }
Glenn Kasten03003332013-08-06 15:40:54 -07001410
1411 // new Track always returns non-NULL,
1412 // but TimedTrack::create() is a factory that could fail by returning NULL
1413 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1414 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001415 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001416 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001417 goto Exit;
1418 }
1419 mTracks.add(track);
1420
1421 sp<EffectChain> chain = getEffectChain_l(sessionId);
1422 if (chain != 0) {
1423 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1424 track->setMainBuffer(chain->inBuffer());
1425 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1426 chain->incTrackCnt();
1427 }
1428
1429 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1430 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1431 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1432 // so ask activity manager to do this on our behalf
1433 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1434 }
1435 }
1436
1437 lStatus = NO_ERROR;
1438
1439Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001440 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001441 return track;
1442}
1443
1444uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1445{
1446 return latency;
1447}
1448
1449uint32_t AudioFlinger::PlaybackThread::latency() const
1450{
1451 Mutex::Autolock _l(mLock);
1452 return latency_l();
1453}
1454uint32_t AudioFlinger::PlaybackThread::latency_l() const
1455{
1456 if (initCheck() == NO_ERROR) {
1457 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1458 } else {
1459 return 0;
1460 }
1461}
1462
1463void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1464{
1465 Mutex::Autolock _l(mLock);
1466 // Don't apply master volume in SW if our HAL can do it for us.
1467 if (mOutput && mOutput->audioHwDev &&
1468 mOutput->audioHwDev->canSetMasterVolume()) {
1469 mMasterVolume = 1.0;
1470 } else {
1471 mMasterVolume = value;
1472 }
1473}
1474
1475void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1476{
1477 Mutex::Autolock _l(mLock);
1478 // Don't apply master mute in SW if our HAL can do it for us.
1479 if (mOutput && mOutput->audioHwDev &&
1480 mOutput->audioHwDev->canSetMasterMute()) {
1481 mMasterMute = false;
1482 } else {
1483 mMasterMute = muted;
1484 }
1485}
1486
1487void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1488{
1489 Mutex::Autolock _l(mLock);
1490 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001491 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001492}
1493
1494void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1495{
1496 Mutex::Autolock _l(mLock);
1497 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001498 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001499}
1500
1501float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1502{
1503 Mutex::Autolock _l(mLock);
1504 return mStreamTypes[stream].volume;
1505}
1506
1507// addTrack_l() must be called with ThreadBase::mLock held
1508status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1509{
1510 status_t status = ALREADY_EXISTS;
1511
1512 // set retry count for buffer fill
1513 track->mRetryCount = kMaxTrackStartupRetries;
1514 if (mActiveTracks.indexOf(track) < 0) {
1515 // the track is newly added, make sure it fills up all its
1516 // buffers before playing. This is to ensure the client will
1517 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518 if (!track->isOutputTrack()) {
1519 TrackBase::track_state state = track->mState;
1520 mLock.unlock();
1521 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1522 mLock.lock();
1523 // abort track was stopped/paused while we released the lock
1524 if (state != track->mState) {
1525 if (status == NO_ERROR) {
1526 mLock.unlock();
1527 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1528 mLock.lock();
1529 }
1530 return INVALID_OPERATION;
1531 }
1532 // abort if start is rejected by audio policy manager
1533 if (status != NO_ERROR) {
1534 return PERMISSION_DENIED;
1535 }
1536#ifdef ADD_BATTERY_DATA
1537 // to track the speaker usage
1538 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1539#endif
1540 }
1541
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001542 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001543 track->mResetDone = false;
1544 track->mPresentationCompleteFrames = 0;
1545 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001546 mWakeLockUids.add(track->uid());
1547 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001548 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001549 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1550 if (chain != 0) {
1551 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1552 track->sessionId());
1553 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001554 }
1555
1556 status = NO_ERROR;
1557 }
1558
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001559 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001560 return status;
1561}
1562
Eric Laurentbfb1b832013-01-07 09:53:42 -08001563bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001564{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001565 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001566 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001567 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1568 track->mState = TrackBase::STOPPED;
1569 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001570 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001571 } else if (track->isFastTrack() || track->isOffloaded()) {
1572 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001573 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001574
1575 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001576}
1577
1578void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1579{
1580 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1581 mTracks.remove(track);
1582 deleteTrackName_l(track->name());
1583 // redundant as track is about to be destroyed, for dumpsys only
1584 track->mName = -1;
1585 if (track->isFastTrack()) {
1586 int index = track->mFastIndex;
1587 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1588 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1589 mFastTrackAvailMask |= 1 << index;
1590 // redundant as track is about to be destroyed, for dumpsys only
1591 track->mFastIndex = -1;
1592 }
1593 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1594 if (chain != 0) {
1595 chain->decTrackCnt();
1596 }
1597}
1598
Eric Laurentede6c3b2013-09-19 14:37:46 -07001599void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600{
1601 // Thread could be blocked waiting for async
1602 // so signal it to handle state changes immediately
1603 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1604 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1605 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001606 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001607}
1608
Eric Laurent81784c32012-11-19 14:55:58 -08001609String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1610{
Eric Laurent81784c32012-11-19 14:55:58 -08001611 Mutex::Autolock _l(mLock);
1612 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001613 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001614 }
1615
Glenn Kastend8ea6992013-07-16 14:17:15 -07001616 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1617 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001618 free(s);
1619 return out_s8;
1620}
1621
1622// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1623void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1624 AudioSystem::OutputDescriptor desc;
1625 void *param2 = NULL;
1626
1627 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1628 param);
1629
1630 switch (event) {
1631 case AudioSystem::OUTPUT_OPENED:
1632 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001633 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 desc.samplingRate = mSampleRate;
1635 desc.format = mFormat;
1636 desc.frameCount = mNormalFrameCount; // FIXME see
1637 // AudioFlinger::frameCount(audio_io_handle_t)
1638 desc.latency = latency();
1639 param2 = &desc;
1640 break;
1641
1642 case AudioSystem::STREAM_CONFIG_CHANGED:
1643 param2 = &param;
1644 case AudioSystem::OUTPUT_CLOSED:
1645 default:
1646 break;
1647 }
1648 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1649}
1650
Eric Laurentbfb1b832013-01-07 09:53:42 -08001651void AudioFlinger::PlaybackThread::writeCallback()
1652{
1653 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001654 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655}
1656
1657void AudioFlinger::PlaybackThread::drainCallback()
1658{
1659 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001660 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001661}
1662
Eric Laurent3b4529e2013-09-05 18:09:19 -07001663void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664{
1665 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001666 // reject out of sequence requests
1667 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1668 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669 mWaitWorkCV.signal();
1670 }
1671}
1672
Eric Laurent3b4529e2013-09-05 18:09:19 -07001673void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001674{
1675 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001676 // reject out of sequence requests
1677 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1678 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 mWaitWorkCV.signal();
1680 }
1681}
1682
1683// static
1684int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001685 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001686 void *cookie)
1687{
1688 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1689 ALOGV("asyncCallback() event %d", event);
1690 switch (event) {
1691 case STREAM_CBK_EVENT_WRITE_READY:
1692 me->writeCallback();
1693 break;
1694 case STREAM_CBK_EVENT_DRAIN_READY:
1695 me->drainCallback();
1696 break;
1697 default:
1698 ALOGW("asyncCallback() unknown event %d", event);
1699 break;
1700 }
1701 return 0;
1702}
1703
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001704void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001705{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001706 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001707 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1708 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001709 if (!audio_is_output_channel(mChannelMask)) {
1710 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1711 }
1712 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1713 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1714 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1715 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001716 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001717 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001718 if (!audio_is_valid_format(mFormat)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001719 LOG_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001720 }
1721 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001722 LOG_FATAL("HAL format %#x not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001723 mFormat);
1724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001726 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1727 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001728 if (mFrameCount & 15) {
1729 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1730 mFrameCount);
1731 }
1732
Eric Laurentbfb1b832013-01-07 09:53:42 -08001733 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1734 (mOutput->stream->set_callback != NULL)) {
1735 if (mOutput->stream->set_callback(mOutput->stream,
1736 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1737 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001738 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 }
1740 }
1741
Andy Hung09a50072014-02-27 14:30:47 -08001742 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001743 double multiplier = 1.0;
1744 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1745 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001746 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1747 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001748 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1749 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1750 maxNormalFrameCount = maxNormalFrameCount & ~15;
1751 if (maxNormalFrameCount < minNormalFrameCount) {
1752 maxNormalFrameCount = minNormalFrameCount;
1753 }
1754 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1755 if (multiplier <= 1.0) {
1756 multiplier = 1.0;
1757 } else if (multiplier <= 2.0) {
1758 if (2 * mFrameCount <= maxNormalFrameCount) {
1759 multiplier = 2.0;
1760 } else {
1761 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1762 }
1763 } else {
1764 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001765 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08001766 // track, but we sometimes have to do this to satisfy the maximum frame count
1767 // constraint)
1768 // FIXME this rounding up should not be done if no HAL SRC
1769 uint32_t truncMult = (uint32_t) multiplier;
1770 if ((truncMult & 1)) {
1771 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1772 ++truncMult;
1773 }
1774 }
1775 multiplier = (double) truncMult;
1776 }
1777 }
1778 mNormalFrameCount = multiplier * mFrameCount;
1779 // round up to nearest 16 frames to satisfy AudioMixer
1780 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001781 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001782 mNormalFrameCount);
1783
Andy Hung010a1a12014-03-13 13:57:33 -07001784 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1785 // Originally this was int16_t[] array, need to remove legacy implications.
1786 free(mSinkBuffer);
1787 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001788 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1789 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1790 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001791 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001792
Andy Hung69aed5f2014-02-25 17:24:40 -08001793 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1794 // drives the output.
1795 free(mMixerBuffer);
1796 mMixerBuffer = NULL;
1797 if (mMixerBufferEnabled) {
1798 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1799 mMixerBufferSize = mNormalFrameCount * mChannelCount
1800 * audio_bytes_per_sample(mMixerBufferFormat);
1801 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1802 }
Andy Hung98ef9782014-03-04 14:46:50 -08001803 free(mEffectBuffer);
1804 mEffectBuffer = NULL;
1805 if (mEffectBufferEnabled) {
1806 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1807 mEffectBufferSize = mNormalFrameCount * mChannelCount
1808 * audio_bytes_per_sample(mEffectBufferFormat);
1809 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1810 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001811
Eric Laurent81784c32012-11-19 14:55:58 -08001812 // force reconfiguration of effect chains and engines to take new buffer size and audio
1813 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001814 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001815 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1816 // matter.
1817 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1818 Vector< sp<EffectChain> > effectChains = mEffectChains;
1819 for (size_t i = 0; i < effectChains.size(); i ++) {
1820 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1821 }
1822}
1823
1824
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001825status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001826{
1827 if (halFrames == NULL || dspFrames == NULL) {
1828 return BAD_VALUE;
1829 }
1830 Mutex::Autolock _l(mLock);
1831 if (initCheck() != NO_ERROR) {
1832 return INVALID_OPERATION;
1833 }
1834 size_t framesWritten = mBytesWritten / mFrameSize;
1835 *halFrames = framesWritten;
1836
1837 if (isSuspended()) {
1838 // return an estimation of rendered frames when the output is suspended
1839 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1840 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1841 return NO_ERROR;
1842 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001843 status_t status;
1844 uint32_t frames;
1845 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1846 *dspFrames = (size_t)frames;
1847 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001848 }
1849}
1850
1851uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1852{
1853 Mutex::Autolock _l(mLock);
1854 uint32_t result = 0;
1855 if (getEffectChain_l(sessionId) != 0) {
1856 result = EFFECT_SESSION;
1857 }
1858
1859 for (size_t i = 0; i < mTracks.size(); ++i) {
1860 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001861 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001862 result |= TRACK_SESSION;
1863 break;
1864 }
1865 }
1866
1867 return result;
1868}
1869
1870uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1871{
1872 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1873 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1874 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1875 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1876 }
1877 for (size_t i = 0; i < mTracks.size(); i++) {
1878 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001879 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001880 return AudioSystem::getStrategyForStream(track->streamType());
1881 }
1882 }
1883 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1884}
1885
1886
1887AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1888{
1889 Mutex::Autolock _l(mLock);
1890 return mOutput;
1891}
1892
1893AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1894{
1895 Mutex::Autolock _l(mLock);
1896 AudioStreamOut *output = mOutput;
1897 mOutput = NULL;
1898 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1899 // must push a NULL and wait for ack
1900 mOutputSink.clear();
1901 mPipeSink.clear();
1902 mNormalSink.clear();
1903 return output;
1904}
1905
1906// this method must always be called either with ThreadBase mLock held or inside the thread loop
1907audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1908{
1909 if (mOutput == NULL) {
1910 return NULL;
1911 }
1912 return &mOutput->stream->common;
1913}
1914
1915uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1916{
1917 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1918}
1919
1920status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1921{
1922 if (!isValidSyncEvent(event)) {
1923 return BAD_VALUE;
1924 }
1925
1926 Mutex::Autolock _l(mLock);
1927
1928 for (size_t i = 0; i < mTracks.size(); ++i) {
1929 sp<Track> track = mTracks[i];
1930 if (event->triggerSession() == track->sessionId()) {
1931 (void) track->setSyncEvent(event);
1932 return NO_ERROR;
1933 }
1934 }
1935
1936 return NAME_NOT_FOUND;
1937}
1938
1939bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1940{
1941 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1942}
1943
1944void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1945 const Vector< sp<Track> >& tracksToRemove)
1946{
1947 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001948 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001949 for (size_t i = 0 ; i < count ; i++) {
1950 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001952 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953#ifdef ADD_BATTERY_DATA
1954 // to track the speaker usage
1955 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1956#endif
1957 if (track->isTerminated()) {
1958 AudioSystem::releaseOutput(mId);
1959 }
Eric Laurent81784c32012-11-19 14:55:58 -08001960 }
1961 }
1962 }
Eric Laurent81784c32012-11-19 14:55:58 -08001963}
1964
1965void AudioFlinger::PlaybackThread::checkSilentMode_l()
1966{
1967 if (!mMasterMute) {
1968 char value[PROPERTY_VALUE_MAX];
1969 if (property_get("ro.audio.silent", value, "0") > 0) {
1970 char *endptr;
1971 unsigned long ul = strtoul(value, &endptr, 0);
1972 if (*endptr == '\0' && ul != 0) {
1973 ALOGD("Silence is golden");
1974 // The setprop command will not allow a property to be changed after
1975 // the first time it is set, so we don't have to worry about un-muting.
1976 setMasterMute_l(true);
1977 }
1978 }
1979 }
1980}
1981
1982// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001983ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001984{
1985 // FIXME rewrite to reduce number of system calls
1986 mLastWriteTime = systemTime();
1987 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07001989 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08001990
1991 // If an NBAIO sink is present, use it to write the normal mixer's submix
1992 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07001993 const size_t count = mBytesRemaining / mFrameSize;
1994
Simon Wilson2d590962012-11-29 15:18:50 -08001995 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001996 // update the setpoint when AudioFlinger::mScreenState changes
1997 uint32_t screenState = AudioFlinger::mScreenState;
1998 if (screenState != mScreenState) {
1999 mScreenState = screenState;
2000 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2001 if (pipe != NULL) {
2002 pipe->setAvgFrames((mScreenState & 1) ?
2003 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2004 }
2005 }
Andy Hung010a1a12014-03-13 13:57:33 -07002006 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002007 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002008 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002009 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002010 } else {
2011 bytesWritten = framesWritten;
2012 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002013 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002014 if (status == NO_ERROR) {
2015 size_t totalFramesWritten = mNormalSink->framesWritten();
2016 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2017 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2018 mLatchDValid = true;
2019 }
2020 }
Eric Laurent81784c32012-11-19 14:55:58 -08002021 // otherwise use the HAL / AudioStreamOut directly
2022 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002023 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002024
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002026 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2027 mWriteAckSequence += 2;
2028 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002030 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002031 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002032 // FIXME We should have an implementation of timestamps for direct output threads.
2033 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002034 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002035 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002036 if (mUseAsyncWrite &&
2037 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2038 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002039 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002041 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042 }
Eric Laurent81784c32012-11-19 14:55:58 -08002043 }
2044
Eric Laurent81784c32012-11-19 14:55:58 -08002045 mNumWrites++;
2046 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002047 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048 return bytesWritten;
2049}
2050
2051void AudioFlinger::PlaybackThread::threadLoop_drain()
2052{
2053 if (mOutput->stream->drain) {
2054 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2055 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002056 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2057 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002058 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002059 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 }
2061 mOutput->stream->drain(mOutput->stream,
2062 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2063 : AUDIO_DRAIN_ALL);
2064 }
2065}
2066
2067void AudioFlinger::PlaybackThread::threadLoop_exit()
2068{
2069 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002070}
2071
2072/*
2073The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002074 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002075 - activeSleepTime from activeSleepTimeUs()
2076 - idleSleepTime from idleSleepTimeUs()
2077 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2078 - maxPeriod from frame count and sample rate (MIXER only)
2079
2080The parameters that affect these derived values are:
2081 - frame count
2082 - frame size
2083 - sample rate
2084 - device type: A2DP or not
2085 - device latency
2086 - format: PCM or not
2087 - active sleep time
2088 - idle sleep time
2089*/
2090
2091void AudioFlinger::PlaybackThread::cacheParameters_l()
2092{
Andy Hung25c2dac2014-02-27 14:56:00 -08002093 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002094 activeSleepTime = activeSleepTimeUs();
2095 idleSleepTime = idleSleepTimeUs();
2096}
2097
2098void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2099{
Glenn Kasten7c027242012-12-26 14:43:16 -08002100 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002101 this, streamType, mTracks.size());
2102 Mutex::Autolock _l(mLock);
2103
2104 size_t size = mTracks.size();
2105 for (size_t i = 0; i < size; i++) {
2106 sp<Track> t = mTracks[i];
2107 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002108 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002109 }
2110 }
2111}
2112
2113status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2114{
2115 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002116 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2117 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002118 bool ownsBuffer = false;
2119
2120 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2121 if (session > 0) {
2122 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002123 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002124 if (mType != DIRECT) {
2125 size_t numSamples = mNormalFrameCount * mChannelCount;
2126 buffer = new int16_t[numSamples];
2127 memset(buffer, 0, numSamples * sizeof(int16_t));
2128 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2129 ownsBuffer = true;
2130 }
2131
2132 // Attach all tracks with same session ID to this chain.
2133 for (size_t i = 0; i < mTracks.size(); ++i) {
2134 sp<Track> track = mTracks[i];
2135 if (session == track->sessionId()) {
2136 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2137 buffer);
2138 track->setMainBuffer(buffer);
2139 chain->incTrackCnt();
2140 }
2141 }
2142
2143 // indicate all active tracks in the chain
2144 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2145 sp<Track> track = mActiveTracks[i].promote();
2146 if (track == 0) {
2147 continue;
2148 }
2149 if (session == track->sessionId()) {
2150 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2151 chain->incActiveTrackCnt();
2152 }
2153 }
2154 }
2155
2156 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002157 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2158 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2160 // chains list in order to be processed last as it contains output stage effects
2161 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2162 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2163 // after track specific effects and before output stage
2164 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2165 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2166 // Effect chain for other sessions are inserted at beginning of effect
2167 // chains list to be processed before output mix effects. Relative order between other
2168 // sessions is not important
2169 size_t size = mEffectChains.size();
2170 size_t i = 0;
2171 for (i = 0; i < size; i++) {
2172 if (mEffectChains[i]->sessionId() < session) {
2173 break;
2174 }
2175 }
2176 mEffectChains.insertAt(chain, i);
2177 checkSuspendOnAddEffectChain_l(chain);
2178
2179 return NO_ERROR;
2180}
2181
2182size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2183{
2184 int session = chain->sessionId();
2185
2186 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2187
2188 for (size_t i = 0; i < mEffectChains.size(); i++) {
2189 if (chain == mEffectChains[i]) {
2190 mEffectChains.removeAt(i);
2191 // detach all active tracks from the chain
2192 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2193 sp<Track> track = mActiveTracks[i].promote();
2194 if (track == 0) {
2195 continue;
2196 }
2197 if (session == track->sessionId()) {
2198 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2199 chain.get(), session);
2200 chain->decActiveTrackCnt();
2201 }
2202 }
2203
2204 // detach all tracks with same session ID from this chain
2205 for (size_t i = 0; i < mTracks.size(); ++i) {
2206 sp<Track> track = mTracks[i];
2207 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002208 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002209 chain->decTrackCnt();
2210 }
2211 }
2212 break;
2213 }
2214 }
2215 return mEffectChains.size();
2216}
2217
2218status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2219 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2220{
2221 Mutex::Autolock _l(mLock);
2222 return attachAuxEffect_l(track, EffectId);
2223}
2224
2225status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2226 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2227{
2228 status_t status = NO_ERROR;
2229
2230 if (EffectId == 0) {
2231 track->setAuxBuffer(0, NULL);
2232 } else {
2233 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2234 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2235 if (effect != 0) {
2236 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2237 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2238 } else {
2239 status = INVALID_OPERATION;
2240 }
2241 } else {
2242 status = BAD_VALUE;
2243 }
2244 }
2245 return status;
2246}
2247
2248void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2249{
2250 for (size_t i = 0; i < mTracks.size(); ++i) {
2251 sp<Track> track = mTracks[i];
2252 if (track->auxEffectId() == effectId) {
2253 attachAuxEffect_l(track, 0);
2254 }
2255 }
2256}
2257
2258bool AudioFlinger::PlaybackThread::threadLoop()
2259{
2260 Vector< sp<Track> > tracksToRemove;
2261
2262 standbyTime = systemTime();
2263
2264 // MIXER
2265 nsecs_t lastWarning = 0;
2266
2267 // DUPLICATING
2268 // FIXME could this be made local to while loop?
2269 writeFrames = 0;
2270
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002271 int lastGeneration = 0;
2272
Eric Laurent81784c32012-11-19 14:55:58 -08002273 cacheParameters_l();
2274 sleepTime = idleSleepTime;
2275
2276 if (mType == MIXER) {
2277 sleepTimeShift = 0;
2278 }
2279
2280 CpuStats cpuStats;
2281 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2282
2283 acquireWakeLock();
2284
Glenn Kasten9e58b552013-01-18 15:09:48 -08002285 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2286 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2287 // and then that string will be logged at the next convenient opportunity.
2288 const char *logString = NULL;
2289
Eric Laurent664539d2013-09-23 18:24:31 -07002290 checkSilentMode_l();
2291
Eric Laurent81784c32012-11-19 14:55:58 -08002292 while (!exitPending())
2293 {
2294 cpuStats.sample(myName);
2295
2296 Vector< sp<EffectChain> > effectChains;
2297
2298 processConfigEvents();
2299
2300 { // scope for mLock
2301
2302 Mutex::Autolock _l(mLock);
2303
Glenn Kasten9e58b552013-01-18 15:09:48 -08002304 if (logString != NULL) {
2305 mNBLogWriter->logTimestamp();
2306 mNBLogWriter->log(logString);
2307 logString = NULL;
2308 }
2309
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002310 if (mLatchDValid) {
2311 mLatchQ = mLatchD;
2312 mLatchDValid = false;
2313 mLatchQValid = true;
2314 }
2315
Eric Laurent81784c32012-11-19 14:55:58 -08002316 if (checkForNewParameters_l()) {
2317 cacheParameters_l();
2318 }
2319
2320 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321 if (mSignalPending) {
2322 // A signal was raised while we were unlocked
2323 mSignalPending = false;
2324 } else if (waitingAsyncCallback_l()) {
2325 if (exitPending()) {
2326 break;
2327 }
2328 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002329 mWakeLockUids.clear();
2330 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331 ALOGV("wait async completion");
2332 mWaitWorkCV.wait(mLock);
2333 ALOGV("async completion/wake");
2334 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002335 standbyTime = systemTime() + standbyDelay;
2336 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002337
2338 continue;
2339 }
2340 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 isSuspended()) {
2342 // put audio hardware into standby after short delay
2343 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002344
2345 threadLoop_standby();
2346
2347 mStandby = true;
2348 }
2349
2350 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2351 // we're about to wait, flush the binder command buffer
2352 IPCThreadState::self()->flushCommands();
2353
2354 clearOutputTracks();
2355
2356 if (exitPending()) {
2357 break;
2358 }
2359
2360 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002361 mWakeLockUids.clear();
2362 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002363 // wait until we have something to do...
2364 ALOGV("%s going to sleep", myName.string());
2365 mWaitWorkCV.wait(mLock);
2366 ALOGV("%s waking up", myName.string());
2367 acquireWakeLock_l();
2368
2369 mMixerStatus = MIXER_IDLE;
2370 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2371 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002373 checkSilentMode_l();
2374
2375 standbyTime = systemTime() + standbyDelay;
2376 sleepTime = idleSleepTime;
2377 if (mType == MIXER) {
2378 sleepTimeShift = 0;
2379 }
2380
2381 continue;
2382 }
2383 }
Eric Laurent81784c32012-11-19 14:55:58 -08002384 // mMixerStatusIgnoringFastTracks is also updated internally
2385 mMixerStatus = prepareTracks_l(&tracksToRemove);
2386
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002387 // compare with previously applied list
2388 if (lastGeneration != mActiveTracksGeneration) {
2389 // update wakelock
2390 updateWakeLockUids_l(mWakeLockUids);
2391 lastGeneration = mActiveTracksGeneration;
2392 }
2393
Eric Laurent81784c32012-11-19 14:55:58 -08002394 // prevent any changes in effect chain list and in each effect chain
2395 // during mixing and effect process as the audio buffers could be deleted
2396 // or modified if an effect is created or deleted
2397 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002398 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002399
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 if (mBytesRemaining == 0) {
2401 mCurrentWriteLength = 0;
2402 if (mMixerStatus == MIXER_TRACKS_READY) {
2403 // threadLoop_mix() sets mCurrentWriteLength
2404 threadLoop_mix();
2405 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2406 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2407 // threadLoop_sleepTime sets sleepTime to 0 if data
2408 // must be written to HAL
2409 threadLoop_sleepTime();
2410 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002411 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 }
2413 }
Andy Hung98ef9782014-03-04 14:46:50 -08002414 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2415 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2416 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2417 // or mSinkBuffer (if there are no effects).
2418 //
2419 // This is done pre-effects computation; if effects change to
2420 // support higher precision, this needs to move.
2421 //
2422 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2423 // TODO use sleepTime == 0 as an additional condition.
2424 if (mMixerBufferValid) {
2425 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2426 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2427
2428 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2429 mNormalFrameCount * mChannelCount);
2430 }
2431
Eric Laurentbfb1b832013-01-07 09:53:42 -08002432 mBytesRemaining = mCurrentWriteLength;
2433 if (isSuspended()) {
2434 sleepTime = suspendSleepTimeUs();
2435 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002436 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002437 mBytesRemaining = 0;
2438 }
Eric Laurent81784c32012-11-19 14:55:58 -08002439
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002441 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442 for (size_t i = 0; i < effectChains.size(); i ++) {
2443 effectChains[i]->process_l();
2444 }
Eric Laurent81784c32012-11-19 14:55:58 -08002445 }
2446 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002447 // Process effect chains for offloaded thread even if no audio
2448 // was read from audio track: process only updates effect state
2449 // and thus does have to be synchronized with audio writes but may have
2450 // to be called while waiting for async write callback
2451 if (mType == OFFLOAD) {
2452 for (size_t i = 0; i < effectChains.size(); i ++) {
2453 effectChains[i]->process_l();
2454 }
2455 }
Eric Laurent81784c32012-11-19 14:55:58 -08002456
Andy Hung98ef9782014-03-04 14:46:50 -08002457 // Only if the Effects buffer is enabled and there is data in the
2458 // Effects buffer (buffer valid), we need to
2459 // copy into the sink buffer.
2460 // TODO use sleepTime == 0 as an additional condition.
2461 if (mEffectBufferValid) {
2462 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2463 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2464 mNormalFrameCount * mChannelCount);
2465 }
2466
Eric Laurent81784c32012-11-19 14:55:58 -08002467 // enable changes in effect chain
2468 unlockEffectChains(effectChains);
2469
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470 if (!waitingAsyncCallback()) {
2471 // sleepTime == 0 means we must write to audio hardware
2472 if (sleepTime == 0) {
2473 if (mBytesRemaining) {
2474 ssize_t ret = threadLoop_write();
2475 if (ret < 0) {
2476 mBytesRemaining = 0;
2477 } else {
2478 mBytesWritten += ret;
2479 mBytesRemaining -= ret;
2480 }
2481 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2482 (mMixerStatus == MIXER_DRAIN_ALL)) {
2483 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002484 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002485 if (mType == MIXER) {
2486 // write blocked detection
2487 nsecs_t now = systemTime();
2488 nsecs_t delta = now - mLastWriteTime;
2489 if (!mStandby && delta > maxPeriod) {
2490 mNumDelayedWrites++;
2491 if ((now - lastWarning) > kWarningThrottleNs) {
2492 ATRACE_NAME("underrun");
2493 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2494 ns2ms(delta), mNumDelayedWrites, this);
2495 lastWarning = now;
2496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 }
2498 }
Eric Laurent81784c32012-11-19 14:55:58 -08002499
Eric Laurentbfb1b832013-01-07 09:53:42 -08002500 } else {
2501 usleep(sleepTime);
2502 }
Eric Laurent81784c32012-11-19 14:55:58 -08002503 }
2504
2505 // Finally let go of removed track(s), without the lock held
2506 // since we can't guarantee the destructors won't acquire that
2507 // same lock. This will also mutate and push a new fast mixer state.
2508 threadLoop_removeTracks(tracksToRemove);
2509 tracksToRemove.clear();
2510
2511 // FIXME I don't understand the need for this here;
2512 // it was in the original code but maybe the
2513 // assignment in saveOutputTracks() makes this unnecessary?
2514 clearOutputTracks();
2515
2516 // Effect chains will be actually deleted here if they were removed from
2517 // mEffectChains list during mixing or effects processing
2518 effectChains.clear();
2519
2520 // FIXME Note that the above .clear() is no longer necessary since effectChains
2521 // is now local to this block, but will keep it for now (at least until merge done).
2522 }
2523
Eric Laurentbfb1b832013-01-07 09:53:42 -08002524 threadLoop_exit();
2525
Eric Laurent81784c32012-11-19 14:55:58 -08002526 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002528 // put output stream into standby mode
2529 if (!mStandby) {
2530 mOutput->stream->common.standby(&mOutput->stream->common);
2531 }
2532 }
2533
2534 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002535 mWakeLockUids.clear();
2536 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002537
2538 ALOGV("Thread %p type %d exiting", this, mType);
2539 return false;
2540}
2541
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542// removeTracks_l() must be called with ThreadBase::mLock held
2543void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2544{
2545 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002546 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002547 for (size_t i=0 ; i<count ; i++) {
2548 const sp<Track>& track = tracksToRemove.itemAt(i);
2549 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002550 mWakeLockUids.remove(track->uid());
2551 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002552 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2553 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2554 if (chain != 0) {
2555 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2556 track->sessionId());
2557 chain->decActiveTrackCnt();
2558 }
2559 if (track->isTerminated()) {
2560 removeTrack_l(track);
2561 }
2562 }
2563 }
2564
2565}
Eric Laurent81784c32012-11-19 14:55:58 -08002566
Eric Laurentaccc1472013-09-20 09:36:34 -07002567status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2568{
2569 if (mNormalSink != 0) {
2570 return mNormalSink->getTimestamp(timestamp);
2571 }
2572 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2573 uint64_t position64;
2574 int ret = mOutput->stream->get_presentation_position(
2575 mOutput->stream, &position64, &timestamp.mTime);
2576 if (ret == 0) {
2577 timestamp.mPosition = (uint32_t)position64;
2578 return NO_ERROR;
2579 }
2580 }
2581 return INVALID_OPERATION;
2582}
Eric Laurent81784c32012-11-19 14:55:58 -08002583// ----------------------------------------------------------------------------
2584
2585AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2586 audio_io_handle_t id, audio_devices_t device, type_t type)
2587 : PlaybackThread(audioFlinger, output, id, device, type),
2588 // mAudioMixer below
2589 // mFastMixer below
2590 mFastMixerFutex(0)
2591 // mOutputSink below
2592 // mPipeSink below
2593 // mNormalSink below
2594{
2595 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002596 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002597 "mFrameCount=%d, mNormalFrameCount=%d",
2598 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2599 mNormalFrameCount);
2600 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2601
2602 // FIXME - Current mixer implementation only supports stereo output
2603 if (mChannelCount != FCC_2) {
2604 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2605 }
2606
2607 // create an NBAIO sink for the HAL output stream, and negotiate
2608 mOutputSink = new AudioStreamOutSink(output->stream);
2609 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002610 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002611 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2612 ALOG_ASSERT(index == 0);
2613
2614 // initialize fast mixer depending on configuration
2615 bool initFastMixer;
2616 switch (kUseFastMixer) {
2617 case FastMixer_Never:
2618 initFastMixer = false;
2619 break;
2620 case FastMixer_Always:
2621 initFastMixer = true;
2622 break;
2623 case FastMixer_Static:
2624 case FastMixer_Dynamic:
2625 initFastMixer = mFrameCount < mNormalFrameCount;
2626 break;
2627 }
2628 if (initFastMixer) {
2629
2630 // create a MonoPipe to connect our submix to FastMixer
2631 NBAIO_Format format = mOutputSink->format();
2632 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2633 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2634 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2635 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2636 const NBAIO_Format offers[1] = {format};
2637 size_t numCounterOffers = 0;
2638 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2639 ALOG_ASSERT(index == 0);
2640 monoPipe->setAvgFrames((mScreenState & 1) ?
2641 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2642 mPipeSink = monoPipe;
2643
Glenn Kasten46909e72013-02-26 09:20:22 -08002644#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002645 if (mTeeSinkOutputEnabled) {
2646 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2647 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2648 numCounterOffers = 0;
2649 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2650 ALOG_ASSERT(index == 0);
2651 mTeeSink = teeSink;
2652 PipeReader *teeSource = new PipeReader(*teeSink);
2653 numCounterOffers = 0;
2654 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2655 ALOG_ASSERT(index == 0);
2656 mTeeSource = teeSource;
2657 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002658#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002659
2660 // create fast mixer and configure it initially with just one fast track for our submix
2661 mFastMixer = new FastMixer();
2662 FastMixerStateQueue *sq = mFastMixer->sq();
2663#ifdef STATE_QUEUE_DUMP
2664 sq->setObserverDump(&mStateQueueObserverDump);
2665 sq->setMutatorDump(&mStateQueueMutatorDump);
2666#endif
2667 FastMixerState *state = sq->begin();
2668 FastTrack *fastTrack = &state->mFastTracks[0];
2669 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2670 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2671 fastTrack->mVolumeProvider = NULL;
2672 fastTrack->mGeneration++;
2673 state->mFastTracksGen++;
2674 state->mTrackMask = 1;
2675 // fast mixer will use the HAL output sink
2676 state->mOutputSink = mOutputSink.get();
2677 state->mOutputSinkGen++;
2678 state->mFrameCount = mFrameCount;
2679 state->mCommand = FastMixerState::COLD_IDLE;
2680 // already done in constructor initialization list
2681 //mFastMixerFutex = 0;
2682 state->mColdFutexAddr = &mFastMixerFutex;
2683 state->mColdGen++;
2684 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002685#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002686 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002687#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002688 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2689 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002690 sq->end();
2691 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2692
2693 // start the fast mixer
2694 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2695 pid_t tid = mFastMixer->getTid();
2696 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2697 if (err != 0) {
2698 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2699 kPriorityFastMixer, getpid_cached, tid, err);
2700 }
2701
2702#ifdef AUDIO_WATCHDOG
2703 // create and start the watchdog
2704 mAudioWatchdog = new AudioWatchdog();
2705 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2706 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2707 tid = mAudioWatchdog->getTid();
2708 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2709 if (err != 0) {
2710 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2711 kPriorityFastMixer, getpid_cached, tid, err);
2712 }
2713#endif
2714
2715 } else {
2716 mFastMixer = NULL;
2717 }
2718
2719 switch (kUseFastMixer) {
2720 case FastMixer_Never:
2721 case FastMixer_Dynamic:
2722 mNormalSink = mOutputSink;
2723 break;
2724 case FastMixer_Always:
2725 mNormalSink = mPipeSink;
2726 break;
2727 case FastMixer_Static:
2728 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2729 break;
2730 }
2731}
2732
2733AudioFlinger::MixerThread::~MixerThread()
2734{
2735 if (mFastMixer != NULL) {
2736 FastMixerStateQueue *sq = mFastMixer->sq();
2737 FastMixerState *state = sq->begin();
2738 if (state->mCommand == FastMixerState::COLD_IDLE) {
2739 int32_t old = android_atomic_inc(&mFastMixerFutex);
2740 if (old == -1) {
2741 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2742 }
2743 }
2744 state->mCommand = FastMixerState::EXIT;
2745 sq->end();
2746 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2747 mFastMixer->join();
2748 // Though the fast mixer thread has exited, it's state queue is still valid.
2749 // We'll use that extract the final state which contains one remaining fast track
2750 // corresponding to our sub-mix.
2751 state = sq->begin();
2752 ALOG_ASSERT(state->mTrackMask == 1);
2753 FastTrack *fastTrack = &state->mFastTracks[0];
2754 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2755 delete fastTrack->mBufferProvider;
2756 sq->end(false /*didModify*/);
2757 delete mFastMixer;
2758#ifdef AUDIO_WATCHDOG
2759 if (mAudioWatchdog != 0) {
2760 mAudioWatchdog->requestExit();
2761 mAudioWatchdog->requestExitAndWait();
2762 mAudioWatchdog.clear();
2763 }
2764#endif
2765 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002766 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002767 delete mAudioMixer;
2768}
2769
2770
2771uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2772{
2773 if (mFastMixer != NULL) {
2774 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2775 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2776 }
2777 return latency;
2778}
2779
2780
2781void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2782{
2783 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2784}
2785
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
2788 // FIXME we should only do one push per cycle; confirm this is true
2789 // Start the fast mixer if it's not already running
2790 if (mFastMixer != NULL) {
2791 FastMixerStateQueue *sq = mFastMixer->sq();
2792 FastMixerState *state = sq->begin();
2793 if (state->mCommand != FastMixerState::MIX_WRITE &&
2794 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2795 if (state->mCommand == FastMixerState::COLD_IDLE) {
2796 int32_t old = android_atomic_inc(&mFastMixerFutex);
2797 if (old == -1) {
2798 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2799 }
2800#ifdef AUDIO_WATCHDOG
2801 if (mAudioWatchdog != 0) {
2802 mAudioWatchdog->resume();
2803 }
2804#endif
2805 }
2806 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002807 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2808 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002809 sq->end();
2810 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2811 if (kUseFastMixer == FastMixer_Dynamic) {
2812 mNormalSink = mPipeSink;
2813 }
2814 } else {
2815 sq->end(false /*didModify*/);
2816 }
2817 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002819}
2820
2821void AudioFlinger::MixerThread::threadLoop_standby()
2822{
2823 // Idle the fast mixer if it's currently running
2824 if (mFastMixer != NULL) {
2825 FastMixerStateQueue *sq = mFastMixer->sq();
2826 FastMixerState *state = sq->begin();
2827 if (!(state->mCommand & FastMixerState::IDLE)) {
2828 state->mCommand = FastMixerState::COLD_IDLE;
2829 state->mColdFutexAddr = &mFastMixerFutex;
2830 state->mColdGen++;
2831 mFastMixerFutex = 0;
2832 sq->end();
2833 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2834 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2835 if (kUseFastMixer == FastMixer_Dynamic) {
2836 mNormalSink = mOutputSink;
2837 }
2838#ifdef AUDIO_WATCHDOG
2839 if (mAudioWatchdog != 0) {
2840 mAudioWatchdog->pause();
2841 }
2842#endif
2843 } else {
2844 sq->end(false /*didModify*/);
2845 }
2846 }
2847 PlaybackThread::threadLoop_standby();
2848}
2849
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2851{
2852 return false;
2853}
2854
2855bool AudioFlinger::PlaybackThread::shouldStandby_l()
2856{
2857 return !mStandby;
2858}
2859
2860bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2861{
2862 Mutex::Autolock _l(mLock);
2863 return waitingAsyncCallback_l();
2864}
2865
Eric Laurent81784c32012-11-19 14:55:58 -08002866// shared by MIXER and DIRECT, overridden by DUPLICATING
2867void AudioFlinger::PlaybackThread::threadLoop_standby()
2868{
2869 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2870 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002872 // discard any pending drain or write ack by incrementing sequence
2873 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2874 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002876 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2877 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 }
Eric Laurent81784c32012-11-19 14:55:58 -08002879}
2880
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002881void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2882{
2883 ALOGV("signal playback thread");
2884 broadcast_l();
2885}
2886
Eric Laurent81784c32012-11-19 14:55:58 -08002887void AudioFlinger::MixerThread::threadLoop_mix()
2888{
2889 // obtain the presentation timestamp of the next output buffer
2890 int64_t pts;
2891 status_t status = INVALID_OPERATION;
2892
2893 if (mNormalSink != 0) {
2894 status = mNormalSink->getNextWriteTimestamp(&pts);
2895 } else {
2896 status = mOutputSink->getNextWriteTimestamp(&pts);
2897 }
2898
2899 if (status != NO_ERROR) {
2900 pts = AudioBufferProvider::kInvalidPTS;
2901 }
2902
2903 // mix buffers...
2904 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002905 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002906 // increase sleep time progressively when application underrun condition clears.
2907 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2908 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2909 // such that we would underrun the audio HAL.
2910 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2911 sleepTimeShift--;
2912 }
2913 sleepTime = 0;
2914 standbyTime = systemTime() + standbyDelay;
2915 //TODO: delay standby when effects have a tail
2916}
2917
2918void AudioFlinger::MixerThread::threadLoop_sleepTime()
2919{
2920 // If no tracks are ready, sleep once for the duration of an output
2921 // buffer size, then write 0s to the output
2922 if (sleepTime == 0) {
2923 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2924 sleepTime = activeSleepTime >> sleepTimeShift;
2925 if (sleepTime < kMinThreadSleepTimeUs) {
2926 sleepTime = kMinThreadSleepTimeUs;
2927 }
2928 // reduce sleep time in case of consecutive application underruns to avoid
2929 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2930 // duration we would end up writing less data than needed by the audio HAL if
2931 // the condition persists.
2932 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2933 sleepTimeShift++;
2934 }
2935 } else {
2936 sleepTime = idleSleepTime;
2937 }
2938 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002939 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2940 // before effects processing or output.
2941 if (mMixerBufferValid) {
2942 memset(mMixerBuffer, 0, mMixerBufferSize);
2943 } else {
2944 memset(mSinkBuffer, 0, mSinkBufferSize);
2945 }
Eric Laurent81784c32012-11-19 14:55:58 -08002946 sleepTime = 0;
2947 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2948 "anticipated start");
2949 }
2950 // TODO add standby time extension fct of effect tail
2951}
2952
2953// prepareTracks_l() must be called with ThreadBase::mLock held
2954AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2955 Vector< sp<Track> > *tracksToRemove)
2956{
2957
2958 mixer_state mixerStatus = MIXER_IDLE;
2959 // find out which tracks need to be processed
2960 size_t count = mActiveTracks.size();
2961 size_t mixedTracks = 0;
2962 size_t tracksWithEffect = 0;
2963 // counts only _active_ fast tracks
2964 size_t fastTracks = 0;
2965 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2966
2967 float masterVolume = mMasterVolume;
2968 bool masterMute = mMasterMute;
2969
2970 if (masterMute) {
2971 masterVolume = 0;
2972 }
2973 // Delegate master volume control to effect in output mix effect chain if needed
2974 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2975 if (chain != 0) {
2976 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2977 chain->setVolume_l(&v, &v);
2978 masterVolume = (float)((v + (1 << 23)) >> 24);
2979 chain.clear();
2980 }
2981
2982 // prepare a new state to push
2983 FastMixerStateQueue *sq = NULL;
2984 FastMixerState *state = NULL;
2985 bool didModify = false;
2986 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2987 if (mFastMixer != NULL) {
2988 sq = mFastMixer->sq();
2989 state = sq->begin();
2990 }
2991
Andy Hung69aed5f2014-02-25 17:24:40 -08002992 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08002993 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08002994
Eric Laurent81784c32012-11-19 14:55:58 -08002995 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002996 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002997 if (t == 0) {
2998 continue;
2999 }
3000
3001 // this const just means the local variable doesn't change
3002 Track* const track = t.get();
3003
3004 // process fast tracks
3005 if (track->isFastTrack()) {
3006
3007 // It's theoretically possible (though unlikely) for a fast track to be created
3008 // and then removed within the same normal mix cycle. This is not a problem, as
3009 // the track never becomes active so it's fast mixer slot is never touched.
3010 // The converse, of removing an (active) track and then creating a new track
3011 // at the identical fast mixer slot within the same normal mix cycle,
3012 // is impossible because the slot isn't marked available until the end of each cycle.
3013 int j = track->mFastIndex;
3014 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3015 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3016 FastTrack *fastTrack = &state->mFastTracks[j];
3017
3018 // Determine whether the track is currently in underrun condition,
3019 // and whether it had a recent underrun.
3020 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3021 FastTrackUnderruns underruns = ftDump->mUnderruns;
3022 uint32_t recentFull = (underruns.mBitFields.mFull -
3023 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3024 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3025 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3026 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3027 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3028 uint32_t recentUnderruns = recentPartial + recentEmpty;
3029 track->mObservedUnderruns = underruns;
3030 // don't count underruns that occur while stopping or pausing
3031 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003032 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3033 recentUnderruns > 0) {
3034 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3035 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
3037
3038 // This is similar to the state machine for normal tracks,
3039 // with a few modifications for fast tracks.
3040 bool isActive = true;
3041 switch (track->mState) {
3042 case TrackBase::STOPPING_1:
3043 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003045 track->mState = TrackBase::STOPPING_2;
3046 }
3047 break;
3048 case TrackBase::PAUSING:
3049 // ramp down is not yet implemented
3050 track->setPaused();
3051 break;
3052 case TrackBase::RESUMING:
3053 // ramp up is not yet implemented
3054 track->mState = TrackBase::ACTIVE;
3055 break;
3056 case TrackBase::ACTIVE:
3057 if (recentFull > 0 || recentPartial > 0) {
3058 // track has provided at least some frames recently: reset retry count
3059 track->mRetryCount = kMaxTrackRetries;
3060 }
3061 if (recentUnderruns == 0) {
3062 // no recent underruns: stay active
3063 break;
3064 }
3065 // there has recently been an underrun of some kind
3066 if (track->sharedBuffer() == 0) {
3067 // were any of the recent underruns "empty" (no frames available)?
3068 if (recentEmpty == 0) {
3069 // no, then ignore the partial underruns as they are allowed indefinitely
3070 break;
3071 }
3072 // there has recently been an "empty" underrun: decrement the retry counter
3073 if (--(track->mRetryCount) > 0) {
3074 break;
3075 }
3076 // indicate to client process that the track was disabled because of underrun;
3077 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003078 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003079 // remove from active list, but state remains ACTIVE [confusing but true]
3080 isActive = false;
3081 break;
3082 }
3083 // fall through
3084 case TrackBase::STOPPING_2:
3085 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003086 case TrackBase::STOPPED:
3087 case TrackBase::FLUSHED: // flush() while active
3088 // Check for presentation complete if track is inactive
3089 // We have consumed all the buffers of this track.
3090 // This would be incomplete if we auto-paused on underrun
3091 {
3092 size_t audioHALFrames =
3093 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3094 size_t framesWritten = mBytesWritten / mFrameSize;
3095 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3096 // track stays in active list until presentation is complete
3097 break;
3098 }
3099 }
3100 if (track->isStopping_2()) {
3101 track->mState = TrackBase::STOPPED;
3102 }
3103 if (track->isStopped()) {
3104 // Can't reset directly, as fast mixer is still polling this track
3105 // track->reset();
3106 // So instead mark this track as needing to be reset after push with ack
3107 resetMask |= 1 << i;
3108 }
3109 isActive = false;
3110 break;
3111 case TrackBase::IDLE:
3112 default:
3113 LOG_FATAL("unexpected track state %d", track->mState);
3114 }
3115
3116 if (isActive) {
3117 // was it previously inactive?
3118 if (!(state->mTrackMask & (1 << j))) {
3119 ExtendedAudioBufferProvider *eabp = track;
3120 VolumeProvider *vp = track;
3121 fastTrack->mBufferProvider = eabp;
3122 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003123 fastTrack->mChannelMask = track->mChannelMask;
3124 fastTrack->mGeneration++;
3125 state->mTrackMask |= 1 << j;
3126 didModify = true;
3127 // no acknowledgement required for newly active tracks
3128 }
3129 // cache the combined master volume and stream type volume for fast mixer; this
3130 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003131 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003132 ++fastTracks;
3133 } else {
3134 // was it previously active?
3135 if (state->mTrackMask & (1 << j)) {
3136 fastTrack->mBufferProvider = NULL;
3137 fastTrack->mGeneration++;
3138 state->mTrackMask &= ~(1 << j);
3139 didModify = true;
3140 // If any fast tracks were removed, we must wait for acknowledgement
3141 // because we're about to decrement the last sp<> on those tracks.
3142 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3143 } else {
3144 LOG_FATAL("fast track %d should have been active", j);
3145 }
3146 tracksToRemove->add(track);
3147 // Avoids a misleading display in dumpsys
3148 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3149 }
3150 continue;
3151 }
3152
3153 { // local variable scope to avoid goto warning
3154
3155 audio_track_cblk_t* cblk = track->cblk();
3156
3157 // The first time a track is added we wait
3158 // for all its buffers to be filled before processing it
3159 int name = track->name();
3160 // make sure that we have enough frames to mix one full buffer.
3161 // enforce this condition only once to enable draining the buffer in case the client
3162 // app does not call stop() and relies on underrun to stop:
3163 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3164 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003165 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003166 uint32_t sr = track->sampleRate();
3167 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003168 desiredFrames = mNormalFrameCount;
3169 } else {
3170 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003171 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003172 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003173 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003174 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003175#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003176 // the minimum track buffer size is normally twice the number of frames necessary
3177 // to fill one buffer and the resampler should not leave more than one buffer worth
3178 // of unreleased frames after each pass, but just in case...
3179 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003180#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003181 }
Eric Laurent81784c32012-11-19 14:55:58 -08003182 uint32_t minFrames = 1;
3183 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3184 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003185 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003186 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003187
3188 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003189 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003190 !track->isPaused() && !track->isTerminated())
3191 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003192 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003193
3194 mixedTracks++;
3195
Andy Hung69aed5f2014-02-25 17:24:40 -08003196 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3197 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003198 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003199 if (track->mainBuffer() != mSinkBuffer &&
3200 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003201 if (mEffectBufferEnabled) {
3202 mEffectBufferValid = true; // Later can set directly.
3203 }
Eric Laurent81784c32012-11-19 14:55:58 -08003204 chain = getEffectChain_l(track->sessionId());
3205 // Delegate volume control to effect in track effect chain if needed
3206 if (chain != 0) {
3207 tracksWithEffect++;
3208 } else {
3209 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3210 "session %d",
3211 name, track->sessionId());
3212 }
3213 }
3214
3215
3216 int param = AudioMixer::VOLUME;
3217 if (track->mFillingUpStatus == Track::FS_FILLED) {
3218 // no ramp for the first volume setting
3219 track->mFillingUpStatus = Track::FS_ACTIVE;
3220 if (track->mState == TrackBase::RESUMING) {
3221 track->mState = TrackBase::ACTIVE;
3222 param = AudioMixer::RAMP_VOLUME;
3223 }
3224 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003225 // FIXME should not make a decision based on mServer
3226 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003227 // If the track is stopped before the first frame was mixed,
3228 // do not apply ramp
3229 param = AudioMixer::RAMP_VOLUME;
3230 }
3231
3232 // compute volume for this track
3233 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003234 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003235 vl = vr = va = 0;
3236 if (track->isPausing()) {
3237 track->setPaused();
3238 }
3239 } else {
3240
3241 // read original volumes with volume control
3242 float typeVolume = mStreamTypes[track->streamType()].volume;
3243 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003244 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003245 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003246 vl = vlr & 0xFFFF;
3247 vr = vlr >> 16;
3248 // track volumes come from shared memory, so can't be trusted and must be clamped
3249 if (vl > MAX_GAIN_INT) {
3250 ALOGV("Track left volume out of range: %04X", vl);
3251 vl = MAX_GAIN_INT;
3252 }
3253 if (vr > MAX_GAIN_INT) {
3254 ALOGV("Track right volume out of range: %04X", vr);
3255 vr = MAX_GAIN_INT;
3256 }
3257 // now apply the master volume and stream type volume
3258 vl = (uint32_t)(v * vl) << 12;
3259 vr = (uint32_t)(v * vr) << 12;
3260 // assuming master volume and stream type volume each go up to 1.0,
3261 // vl and vr are now in 8.24 format
3262
Glenn Kastene3aa6592012-12-04 12:22:46 -08003263 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003264 // send level comes from shared memory and so may be corrupt
3265 if (sendLevel > MAX_GAIN_INT) {
3266 ALOGV("Track send level out of range: %04X", sendLevel);
3267 sendLevel = MAX_GAIN_INT;
3268 }
3269 va = (uint32_t)(v * sendLevel);
3270 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003271
Eric Laurent81784c32012-11-19 14:55:58 -08003272 // Delegate volume control to effect in track effect chain if needed
3273 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3274 // Do not ramp volume if volume is controlled by effect
3275 param = AudioMixer::VOLUME;
3276 track->mHasVolumeController = true;
3277 } else {
3278 // force no volume ramp when volume controller was just disabled or removed
3279 // from effect chain to avoid volume spike
3280 if (track->mHasVolumeController) {
3281 param = AudioMixer::VOLUME;
3282 }
3283 track->mHasVolumeController = false;
3284 }
3285
3286 // Convert volumes from 8.24 to 4.12 format
3287 // This additional clamping is needed in case chain->setVolume_l() overshot
3288 vl = (vl + (1 << 11)) >> 12;
3289 if (vl > MAX_GAIN_INT) {
3290 vl = MAX_GAIN_INT;
3291 }
3292 vr = (vr + (1 << 11)) >> 12;
3293 if (vr > MAX_GAIN_INT) {
3294 vr = MAX_GAIN_INT;
3295 }
3296
3297 if (va > MAX_GAIN_INT) {
3298 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3299 }
3300
3301 // XXX: these things DON'T need to be done each time
3302 mAudioMixer->setBufferProvider(name, track);
3303 mAudioMixer->enable(name);
3304
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003305 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3306 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3307 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003308 mAudioMixer->setParameter(
3309 name,
3310 AudioMixer::TRACK,
3311 AudioMixer::FORMAT, (void *)track->format());
3312 mAudioMixer->setParameter(
3313 name,
3314 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003315 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003316 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3317 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003318 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003319 if (reqSampleRate == 0) {
3320 reqSampleRate = mSampleRate;
3321 } else if (reqSampleRate > maxSampleRate) {
3322 reqSampleRate = maxSampleRate;
3323 }
Eric Laurent81784c32012-11-19 14:55:58 -08003324 mAudioMixer->setParameter(
3325 name,
3326 AudioMixer::RESAMPLE,
3327 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003328 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003329 /*
3330 * Select the appropriate output buffer for the track.
3331 *
Andy Hung98ef9782014-03-04 14:46:50 -08003332 * Tracks with effects go into their own effects chain buffer
3333 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003334 *
3335 * Other tracks can use mMixerBuffer for higher precision
3336 * channel accumulation. If this buffer is enabled
3337 * (mMixerBufferEnabled true), then selected tracks will accumulate
3338 * into it.
3339 *
3340 */
3341 if (mMixerBufferEnabled
3342 && (track->mainBuffer() == mSinkBuffer
3343 || track->mainBuffer() == mMixerBuffer)) {
3344 mAudioMixer->setParameter(
3345 name,
3346 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003347 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003348 mAudioMixer->setParameter(
3349 name,
3350 AudioMixer::TRACK,
3351 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3352 // TODO: override track->mainBuffer()?
3353 mMixerBufferValid = true;
3354 } else {
3355 mAudioMixer->setParameter(
3356 name,
3357 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003358 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003359 mAudioMixer->setParameter(
3360 name,
3361 AudioMixer::TRACK,
3362 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3363 }
Eric Laurent81784c32012-11-19 14:55:58 -08003364 mAudioMixer->setParameter(
3365 name,
3366 AudioMixer::TRACK,
3367 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3368
3369 // reset retry count
3370 track->mRetryCount = kMaxTrackRetries;
3371
3372 // If one track is ready, set the mixer ready if:
3373 // - the mixer was not ready during previous round OR
3374 // - no other track is not ready
3375 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3376 mixerStatus != MIXER_TRACKS_ENABLED) {
3377 mixerStatus = MIXER_TRACKS_READY;
3378 }
3379 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003380 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003381 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003382 }
Eric Laurent81784c32012-11-19 14:55:58 -08003383 // clear effect chain input buffer if an active track underruns to avoid sending
3384 // previous audio buffer again to effects
3385 chain = getEffectChain_l(track->sessionId());
3386 if (chain != 0) {
3387 chain->clearInputBuffer();
3388 }
3389
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003390 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003391 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3392 track->isStopped() || track->isPaused()) {
3393 // We have consumed all the buffers of this track.
3394 // Remove it from the list of active tracks.
3395 // TODO: use actual buffer filling status instead of latency when available from
3396 // audio HAL
3397 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3398 size_t framesWritten = mBytesWritten / mFrameSize;
3399 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3400 if (track->isStopped()) {
3401 track->reset();
3402 }
3403 tracksToRemove->add(track);
3404 }
3405 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003406 // No buffers for this track. Give it a few chances to
3407 // fill a buffer, then remove it from active list.
3408 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003409 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003410 tracksToRemove->add(track);
3411 // indicate to client process that the track was disabled because of underrun;
3412 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003413 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003414 // If one track is not ready, mark the mixer also not ready if:
3415 // - the mixer was ready during previous round OR
3416 // - no other track is ready
3417 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3418 mixerStatus != MIXER_TRACKS_READY) {
3419 mixerStatus = MIXER_TRACKS_ENABLED;
3420 }
3421 }
3422 mAudioMixer->disable(name);
3423 }
3424
3425 } // local variable scope to avoid goto warning
3426track_is_ready: ;
3427
3428 }
3429
3430 // Push the new FastMixer state if necessary
3431 bool pauseAudioWatchdog = false;
3432 if (didModify) {
3433 state->mFastTracksGen++;
3434 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3435 if (kUseFastMixer == FastMixer_Dynamic &&
3436 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3437 state->mCommand = FastMixerState::COLD_IDLE;
3438 state->mColdFutexAddr = &mFastMixerFutex;
3439 state->mColdGen++;
3440 mFastMixerFutex = 0;
3441 if (kUseFastMixer == FastMixer_Dynamic) {
3442 mNormalSink = mOutputSink;
3443 }
3444 // If we go into cold idle, need to wait for acknowledgement
3445 // so that fast mixer stops doing I/O.
3446 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3447 pauseAudioWatchdog = true;
3448 }
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
3450 if (sq != NULL) {
3451 sq->end(didModify);
3452 sq->push(block);
3453 }
3454#ifdef AUDIO_WATCHDOG
3455 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3456 mAudioWatchdog->pause();
3457 }
3458#endif
3459
3460 // Now perform the deferred reset on fast tracks that have stopped
3461 while (resetMask != 0) {
3462 size_t i = __builtin_ctz(resetMask);
3463 ALOG_ASSERT(i < count);
3464 resetMask &= ~(1 << i);
3465 sp<Track> t = mActiveTracks[i].promote();
3466 if (t == 0) {
3467 continue;
3468 }
3469 Track* track = t.get();
3470 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3471 track->reset();
3472 }
3473
3474 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003475 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003476
Andy Hung69aed5f2014-02-25 17:24:40 -08003477 // sink or mix buffer must be cleared if all tracks are connected to an
3478 // effect chain as in this case the mixer will not write to the sink or mix buffer
3479 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003480 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3481 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003482 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003483 if (mMixerBufferValid) {
3484 memset(mMixerBuffer, 0, mMixerBufferSize);
3485 // TODO: In testing, mSinkBuffer below need not be cleared because
3486 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3487 // after mixing.
3488 //
3489 // To enforce this guarantee:
3490 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3491 // (mixedTracks == 0 && fastTracks > 0))
3492 // must imply MIXER_TRACKS_READY.
3493 // Later, we may clear buffers regardless, and skip much of this logic.
3494 }
Andy Hung98ef9782014-03-04 14:46:50 -08003495 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3496 if (mEffectBufferValid) {
3497 memset(mEffectBuffer, 0, mEffectBufferSize);
3498 }
3499 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003500 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003501 }
3502
3503 // if any fast tracks, then status is ready
3504 mMixerStatusIgnoringFastTracks = mixerStatus;
3505 if (fastTracks > 0) {
3506 mixerStatus = MIXER_TRACKS_READY;
3507 }
3508 return mixerStatus;
3509}
3510
3511// getTrackName_l() must be called with ThreadBase::mLock held
3512int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3513{
3514 return mAudioMixer->getTrackName(channelMask, sessionId);
3515}
3516
3517// deleteTrackName_l() must be called with ThreadBase::mLock held
3518void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3519{
3520 ALOGV("remove track (%d) and delete from mixer", name);
3521 mAudioMixer->deleteTrackName(name);
3522}
3523
3524// checkForNewParameters_l() must be called with ThreadBase::mLock held
3525bool AudioFlinger::MixerThread::checkForNewParameters_l()
3526{
3527 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3528 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3529 bool reconfig = false;
3530
3531 while (!mNewParameters.isEmpty()) {
3532
3533 if (mFastMixer != NULL) {
3534 FastMixerStateQueue *sq = mFastMixer->sq();
3535 FastMixerState *state = sq->begin();
3536 if (!(state->mCommand & FastMixerState::IDLE)) {
3537 previousCommand = state->mCommand;
3538 state->mCommand = FastMixerState::HOT_IDLE;
3539 sq->end();
3540 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3541 } else {
3542 sq->end(false /*didModify*/);
3543 }
3544 }
3545
3546 status_t status = NO_ERROR;
3547 String8 keyValuePair = mNewParameters[0];
3548 AudioParameter param = AudioParameter(keyValuePair);
3549 int value;
3550
3551 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3552 reconfig = true;
3553 }
3554 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3555 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3556 status = BAD_VALUE;
3557 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003558 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003559 reconfig = true;
3560 }
3561 }
3562 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003563 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003564 status = BAD_VALUE;
3565 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003566 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003567 reconfig = true;
3568 }
3569 }
3570 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3571 // do not accept frame count changes if tracks are open as the track buffer
3572 // size depends on frame count and correct behavior would not be guaranteed
3573 // if frame count is changed after track creation
3574 if (!mTracks.isEmpty()) {
3575 status = INVALID_OPERATION;
3576 } else {
3577 reconfig = true;
3578 }
3579 }
3580 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3581#ifdef ADD_BATTERY_DATA
3582 // when changing the audio output device, call addBatteryData to notify
3583 // the change
3584 if (mOutDevice != value) {
3585 uint32_t params = 0;
3586 // check whether speaker is on
3587 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3588 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3589 }
3590
3591 audio_devices_t deviceWithoutSpeaker
3592 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3593 // check if any other device (except speaker) is on
3594 if (value & deviceWithoutSpeaker ) {
3595 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3596 }
3597
3598 if (params != 0) {
3599 addBatteryData(params);
3600 }
3601 }
3602#endif
3603
3604 // forward device change to effects that have requested to be
3605 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003606 if (value != AUDIO_DEVICE_NONE) {
3607 mOutDevice = value;
3608 for (size_t i = 0; i < mEffectChains.size(); i++) {
3609 mEffectChains[i]->setDevice_l(mOutDevice);
3610 }
Eric Laurent81784c32012-11-19 14:55:58 -08003611 }
3612 }
3613
3614 if (status == NO_ERROR) {
3615 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3616 keyValuePair.string());
3617 if (!mStandby && status == INVALID_OPERATION) {
3618 mOutput->stream->common.standby(&mOutput->stream->common);
3619 mStandby = true;
3620 mBytesWritten = 0;
3621 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3622 keyValuePair.string());
3623 }
3624 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003625 readOutputParameters_l();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003626 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003627 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3628 for (size_t i = 0; i < mTracks.size() ; i++) {
3629 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3630 if (name < 0) {
3631 break;
3632 }
3633 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003634 }
3635 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3636 }
3637 }
3638
3639 mNewParameters.removeAt(0);
3640
3641 mParamStatus = status;
3642 mParamCond.signal();
3643 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3644 // already timed out waiting for the status and will never signal the condition.
3645 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3646 }
3647
3648 if (!(previousCommand & FastMixerState::IDLE)) {
3649 ALOG_ASSERT(mFastMixer != NULL);
3650 FastMixerStateQueue *sq = mFastMixer->sq();
3651 FastMixerState *state = sq->begin();
3652 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3653 state->mCommand = previousCommand;
3654 sq->end();
3655 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3656 }
3657
3658 return reconfig;
3659}
3660
3661
3662void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3663{
3664 const size_t SIZE = 256;
3665 char buffer[SIZE];
3666 String8 result;
3667
3668 PlaybackThread::dumpInternals(fd, args);
3669
Marco Nelissenb2208842014-02-07 14:00:50 -08003670 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003671
3672 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003673 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003674 copy.dump(fd);
3675
3676#ifdef STATE_QUEUE_DUMP
3677 // Similar for state queue
3678 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3679 observerCopy.dump(fd);
3680 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3681 mutatorCopy.dump(fd);
3682#endif
3683
Glenn Kasten46909e72013-02-26 09:20:22 -08003684#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003685 // Write the tee output to a .wav file
3686 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003687#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003688
3689#ifdef AUDIO_WATCHDOG
3690 if (mAudioWatchdog != 0) {
3691 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3692 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3693 wdCopy.dump(fd);
3694 }
3695#endif
3696}
3697
3698uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3699{
3700 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3701}
3702
3703uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3704{
3705 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3706}
3707
3708void AudioFlinger::MixerThread::cacheParameters_l()
3709{
3710 PlaybackThread::cacheParameters_l();
3711
3712 // FIXME: Relaxed timing because of a certain device that can't meet latency
3713 // Should be reduced to 2x after the vendor fixes the driver issue
3714 // increase threshold again due to low power audio mode. The way this warning
3715 // threshold is calculated and its usefulness should be reconsidered anyway.
3716 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3717}
3718
3719// ----------------------------------------------------------------------------
3720
3721AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3722 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3723 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3724 // mLeftVolFloat, mRightVolFloat
3725{
3726}
3727
Eric Laurentbfb1b832013-01-07 09:53:42 -08003728AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3729 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3730 ThreadBase::type_t type)
3731 : PlaybackThread(audioFlinger, output, id, device, type)
3732 // mLeftVolFloat, mRightVolFloat
3733{
3734}
3735
Eric Laurent81784c32012-11-19 14:55:58 -08003736AudioFlinger::DirectOutputThread::~DirectOutputThread()
3737{
3738}
3739
Eric Laurentbfb1b832013-01-07 09:53:42 -08003740void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3741{
3742 audio_track_cblk_t* cblk = track->cblk();
3743 float left, right;
3744
3745 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3746 left = right = 0;
3747 } else {
3748 float typeVolume = mStreamTypes[track->streamType()].volume;
3749 float v = mMasterVolume * typeVolume;
3750 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3751 uint32_t vlr = proxy->getVolumeLR();
3752 float v_clamped = v * (vlr & 0xFFFF);
3753 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3754 left = v_clamped/MAX_GAIN;
3755 v_clamped = v * (vlr >> 16);
3756 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3757 right = v_clamped/MAX_GAIN;
3758 }
3759
3760 if (lastTrack) {
3761 if (left != mLeftVolFloat || right != mRightVolFloat) {
3762 mLeftVolFloat = left;
3763 mRightVolFloat = right;
3764
3765 // Convert volumes from float to 8.24
3766 uint32_t vl = (uint32_t)(left * (1 << 24));
3767 uint32_t vr = (uint32_t)(right * (1 << 24));
3768
3769 // Delegate volume control to effect in track effect chain if needed
3770 // only one effect chain can be present on DirectOutputThread, so if
3771 // there is one, the track is connected to it
3772 if (!mEffectChains.isEmpty()) {
3773 mEffectChains[0]->setVolume_l(&vl, &vr);
3774 left = (float)vl / (1 << 24);
3775 right = (float)vr / (1 << 24);
3776 }
3777 if (mOutput->stream->set_volume) {
3778 mOutput->stream->set_volume(mOutput->stream, left, right);
3779 }
3780 }
3781 }
3782}
3783
3784
Eric Laurent81784c32012-11-19 14:55:58 -08003785AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3786 Vector< sp<Track> > *tracksToRemove
3787)
3788{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003789 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003790 mixer_state mixerStatus = MIXER_IDLE;
3791
3792 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003793 for (size_t i = 0; i < count; i++) {
3794 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003795 // The track died recently
3796 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003797 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003798 }
3799
3800 Track* const track = t.get();
3801 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003802 // Only consider last track started for volume and mixer state control.
3803 // In theory an older track could underrun and restart after the new one starts
3804 // but as we only care about the transition phase between two tracks on a
3805 // direct output, it is not a problem to ignore the underrun case.
3806 sp<Track> l = mLatestActiveTrack.promote();
3807 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003808
3809 // The first time a track is added we wait
3810 // for all its buffers to be filled before processing it
3811 uint32_t minFrames;
3812 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3813 minFrames = mNormalFrameCount;
3814 } else {
3815 minFrames = 1;
3816 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003817
Eric Laurent81784c32012-11-19 14:55:58 -08003818 if ((track->framesReady() >= minFrames) && track->isReady() &&
3819 !track->isPaused() && !track->isTerminated())
3820 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003821 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003822
3823 if (track->mFillingUpStatus == Track::FS_FILLED) {
3824 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003825 // make sure processVolume_l() will apply new volume even if 0
3826 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003827 if (track->mState == TrackBase::RESUMING) {
3828 track->mState = TrackBase::ACTIVE;
3829 }
3830 }
3831
3832 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003833 processVolume_l(track, last);
3834 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003835 // reset retry count
3836 track->mRetryCount = kMaxTrackRetriesDirect;
3837 mActiveTrack = t;
3838 mixerStatus = MIXER_TRACKS_READY;
3839 }
Eric Laurent81784c32012-11-19 14:55:58 -08003840 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003841 // clear effect chain input buffer if the last active track started underruns
3842 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003843 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003844 mEffectChains[0]->clearInputBuffer();
3845 }
3846
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003847 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003848 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3849 track->isStopped() || track->isPaused()) {
3850 // We have consumed all the buffers of this track.
3851 // Remove it from the list of active tracks.
3852 // TODO: implement behavior for compressed audio
3853 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3854 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003855 if (mStandby || !last ||
3856 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003857 if (track->isStopped()) {
3858 track->reset();
3859 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003860 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003861 }
3862 } else {
3863 // No buffers for this track. Give it a few chances to
3864 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003865 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003866 if (--(track->mRetryCount) <= 0) {
3867 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003868 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003869 // indicate to client process that the track was disabled because of underrun;
3870 // it will then automatically call start() when data is available
3871 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003873 mixerStatus = MIXER_TRACKS_ENABLED;
3874 }
3875 }
3876 }
3877 }
3878
Eric Laurent81784c32012-11-19 14:55:58 -08003879 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003881
3882 return mixerStatus;
3883}
3884
3885void AudioFlinger::DirectOutputThread::threadLoop_mix()
3886{
Eric Laurent81784c32012-11-19 14:55:58 -08003887 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003888 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003889 // output audio to hardware
3890 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003891 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003892 buffer.frameCount = frameCount;
3893 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003894 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003895 memset(curBuf, 0, frameCount * mFrameSize);
3896 break;
3897 }
3898 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3899 frameCount -= buffer.frameCount;
3900 curBuf += buffer.frameCount * mFrameSize;
3901 mActiveTrack->releaseBuffer(&buffer);
3902 }
Andy Hung2098f272014-02-27 14:00:06 -08003903 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003904 sleepTime = 0;
3905 standbyTime = systemTime() + standbyDelay;
3906 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003907}
3908
3909void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3910{
3911 if (sleepTime == 0) {
3912 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3913 sleepTime = activeSleepTime;
3914 } else {
3915 sleepTime = idleSleepTime;
3916 }
3917 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003918 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003919 sleepTime = 0;
3920 }
3921}
3922
3923// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003924int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3925 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003926{
3927 return 0;
3928}
3929
3930// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003931void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003932{
3933}
3934
3935// checkForNewParameters_l() must be called with ThreadBase::mLock held
3936bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3937{
3938 bool reconfig = false;
3939
3940 while (!mNewParameters.isEmpty()) {
3941 status_t status = NO_ERROR;
3942 String8 keyValuePair = mNewParameters[0];
3943 AudioParameter param = AudioParameter(keyValuePair);
3944 int value;
3945
3946 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3947 // do not accept frame count changes if tracks are open as the track buffer
3948 // size depends on frame count and correct behavior would not be garantied
3949 // if frame count is changed after track creation
3950 if (!mTracks.isEmpty()) {
3951 status = INVALID_OPERATION;
3952 } else {
3953 reconfig = true;
3954 }
3955 }
3956 if (status == NO_ERROR) {
3957 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3958 keyValuePair.string());
3959 if (!mStandby && status == INVALID_OPERATION) {
3960 mOutput->stream->common.standby(&mOutput->stream->common);
3961 mStandby = true;
3962 mBytesWritten = 0;
3963 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3964 keyValuePair.string());
3965 }
3966 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003967 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08003968 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3969 }
3970 }
3971
3972 mNewParameters.removeAt(0);
3973
3974 mParamStatus = status;
3975 mParamCond.signal();
3976 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3977 // already timed out waiting for the status and will never signal the condition.
3978 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3979 }
3980 return reconfig;
3981}
3982
3983uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3984{
3985 uint32_t time;
3986 if (audio_is_linear_pcm(mFormat)) {
3987 time = PlaybackThread::activeSleepTimeUs();
3988 } else {
3989 time = 10000;
3990 }
3991 return time;
3992}
3993
3994uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3995{
3996 uint32_t time;
3997 if (audio_is_linear_pcm(mFormat)) {
3998 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3999 } else {
4000 time = 10000;
4001 }
4002 return time;
4003}
4004
4005uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4006{
4007 uint32_t time;
4008 if (audio_is_linear_pcm(mFormat)) {
4009 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4010 } else {
4011 time = 10000;
4012 }
4013 return time;
4014}
4015
4016void AudioFlinger::DirectOutputThread::cacheParameters_l()
4017{
4018 PlaybackThread::cacheParameters_l();
4019
4020 // use shorter standby delay as on normal output to release
4021 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004022 if (audio_is_linear_pcm(mFormat)) {
4023 standbyDelay = microseconds(activeSleepTime*2);
4024 } else {
4025 standbyDelay = kOffloadStandbyDelayNs;
4026 }
Eric Laurent81784c32012-11-19 14:55:58 -08004027}
4028
4029// ----------------------------------------------------------------------------
4030
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004032 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004033 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004034 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004035 mWriteAckSequence(0),
4036 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004037{
4038}
4039
4040AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4041{
4042}
4043
4044void AudioFlinger::AsyncCallbackThread::onFirstRef()
4045{
4046 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4047}
4048
4049bool AudioFlinger::AsyncCallbackThread::threadLoop()
4050{
4051 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004052 uint32_t writeAckSequence;
4053 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004054
4055 {
4056 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004057 while (!((mWriteAckSequence & 1) ||
4058 (mDrainSequence & 1) ||
4059 exitPending())) {
4060 mWaitWorkCV.wait(mLock);
4061 }
4062
Eric Laurentbfb1b832013-01-07 09:53:42 -08004063 if (exitPending()) {
4064 break;
4065 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004066 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4067 mWriteAckSequence, mDrainSequence);
4068 writeAckSequence = mWriteAckSequence;
4069 mWriteAckSequence &= ~1;
4070 drainSequence = mDrainSequence;
4071 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004072 }
4073 {
Eric Laurent4de95592013-09-26 15:28:21 -07004074 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4075 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004076 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004077 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004079 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004080 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 }
4082 }
4083 }
4084 }
4085 return false;
4086}
4087
4088void AudioFlinger::AsyncCallbackThread::exit()
4089{
4090 ALOGV("AsyncCallbackThread::exit");
4091 Mutex::Autolock _l(mLock);
4092 requestExit();
4093 mWaitWorkCV.broadcast();
4094}
4095
Eric Laurent3b4529e2013-09-05 18:09:19 -07004096void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004097{
4098 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004099 // bit 0 is cleared
4100 mWriteAckSequence = sequence << 1;
4101}
4102
4103void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4104{
4105 Mutex::Autolock _l(mLock);
4106 // ignore unexpected callbacks
4107 if (mWriteAckSequence & 2) {
4108 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004109 mWaitWorkCV.signal();
4110 }
4111}
4112
Eric Laurent3b4529e2013-09-05 18:09:19 -07004113void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004114{
4115 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004116 // bit 0 is cleared
4117 mDrainSequence = sequence << 1;
4118}
4119
4120void AudioFlinger::AsyncCallbackThread::resetDraining()
4121{
4122 Mutex::Autolock _l(mLock);
4123 // ignore unexpected callbacks
4124 if (mDrainSequence & 2) {
4125 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126 mWaitWorkCV.signal();
4127 }
4128}
4129
4130
4131// ----------------------------------------------------------------------------
4132AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4133 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4134 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4135 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004136 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004137 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138{
Eric Laurentfd477972013-10-25 18:10:40 -07004139 //FIXME: mStandby should be set to true by ThreadBase constructor
4140 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004141}
4142
Eric Laurentbfb1b832013-01-07 09:53:42 -08004143void AudioFlinger::OffloadThread::threadLoop_exit()
4144{
4145 if (mFlushPending || mHwPaused) {
4146 // If a flush is pending or track was paused, just discard buffered data
4147 flushHw_l();
4148 } else {
4149 mMixerStatus = MIXER_DRAIN_ALL;
4150 threadLoop_drain();
4151 }
4152 mCallbackThread->exit();
4153 PlaybackThread::threadLoop_exit();
4154}
4155
4156AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4157 Vector< sp<Track> > *tracksToRemove
4158)
4159{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004160 size_t count = mActiveTracks.size();
4161
4162 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004163 bool doHwPause = false;
4164 bool doHwResume = false;
4165
Eric Laurentede6c3b2013-09-19 14:37:46 -07004166 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4167
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168 // find out which tracks need to be processed
4169 for (size_t i = 0; i < count; i++) {
4170 sp<Track> t = mActiveTracks[i].promote();
4171 // The track died recently
4172 if (t == 0) {
4173 continue;
4174 }
4175 Track* const track = t.get();
4176 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004177 // Only consider last track started for volume and mixer state control.
4178 // In theory an older track could underrun and restart after the new one starts
4179 // but as we only care about the transition phase between two tracks on a
4180 // direct output, it is not a problem to ignore the underrun case.
4181 sp<Track> l = mLatestActiveTrack.promote();
4182 bool last = l.get() == track;
4183
Haynes Mathew George7844f672014-01-15 12:32:55 -08004184 if (track->isInvalid()) {
4185 ALOGW("An invalidated track shouldn't be in active list");
4186 tracksToRemove->add(track);
4187 continue;
4188 }
4189
4190 if (track->mState == TrackBase::IDLE) {
4191 ALOGW("An idle track shouldn't be in active list");
4192 continue;
4193 }
4194
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 if (track->isPausing()) {
4196 track->setPaused();
4197 if (last) {
4198 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004199 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200 mHwPaused = true;
4201 }
4202 // If we were part way through writing the mixbuffer to
4203 // the HAL we must save this until we resume
4204 // BUG - this will be wrong if a different track is made active,
4205 // in that case we want to discard the pending data in the
4206 // mixbuffer and tell the client to present it again when the
4207 // track is resumed
4208 mPausedWriteLength = mCurrentWriteLength;
4209 mPausedBytesRemaining = mBytesRemaining;
4210 mBytesRemaining = 0; // stop writing
4211 }
4212 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004213 } else if (track->isFlushPending()) {
4214 track->flushAck();
4215 if (last) {
4216 mFlushPending = true;
4217 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004219 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004220 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004221 if (track->mFillingUpStatus == Track::FS_FILLED) {
4222 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004223 // make sure processVolume_l() will apply new volume even if 0
4224 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004225 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004227 if (last) {
4228 if (mPausedBytesRemaining) {
4229 // Need to continue write that was interrupted
4230 mCurrentWriteLength = mPausedWriteLength;
4231 mBytesRemaining = mPausedBytesRemaining;
4232 mPausedBytesRemaining = 0;
4233 }
4234 if (mHwPaused) {
4235 doHwResume = true;
4236 mHwPaused = false;
4237 // threadLoop_mix() will handle the case that we need to
4238 // resume an interrupted write
4239 }
4240 // enable write to audio HAL
4241 sleepTime = 0;
4242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 }
4244 }
4245
4246 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004247 sp<Track> previousTrack = mPreviousTrack.promote();
4248 if (previousTrack != 0) {
4249 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004250 // Flush any data still being written from last track
4251 mBytesRemaining = 0;
4252 if (mPausedBytesRemaining) {
4253 // Last track was paused so we also need to flush saved
4254 // mixbuffer state and invalidate track so that it will
4255 // re-submit that unwritten data when it is next resumed
4256 mPausedBytesRemaining = 0;
4257 // Invalidate is a bit drastic - would be more efficient
4258 // to have a flag to tell client that some of the
4259 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004260 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004261 }
4262 // flush data already sent to the DSP if changing audio session as audio
4263 // comes from a different source. Also invalidate previous track to force a
4264 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004265 if (previousTrack->sessionId() != track->sessionId()) {
4266 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004267 }
4268 }
4269 }
4270 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004271 // reset retry count
4272 track->mRetryCount = kMaxTrackRetriesOffload;
4273 mActiveTrack = t;
4274 mixerStatus = MIXER_TRACKS_READY;
4275 }
4276 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004277 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278 if (track->isStopping_1()) {
4279 // Hardware buffer can hold a large amount of audio so we must
4280 // wait for all current track's data to drain before we say
4281 // that the track is stopped.
4282 if (mBytesRemaining == 0) {
4283 // Only start draining when all data in mixbuffer
4284 // has been written
4285 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4286 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004287 // do not drain if no data was ever sent to HAL (mStandby == true)
4288 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004289 // do not modify drain sequence if we are already draining. This happens
4290 // when resuming from pause after drain.
4291 if ((mDrainSequence & 1) == 0) {
4292 sleepTime = 0;
4293 standbyTime = systemTime() + standbyDelay;
4294 mixerStatus = MIXER_DRAIN_TRACK;
4295 mDrainSequence += 2;
4296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 if (mHwPaused) {
4298 // It is possible to move from PAUSED to STOPPING_1 without
4299 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004300 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301 mHwPaused = false;
4302 }
4303 }
4304 }
4305 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004306 // Drain has completed or we are in standby, signal presentation complete
4307 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308 track->mState = TrackBase::STOPPED;
4309 size_t audioHALFrames =
4310 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4311 size_t framesWritten =
4312 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4313 track->presentationComplete(framesWritten, audioHALFrames);
4314 track->reset();
4315 tracksToRemove->add(track);
4316 }
4317 } else {
4318 // No buffers for this track. Give it a few chances to
4319 // fill a buffer, then remove it from active list.
4320 if (--(track->mRetryCount) <= 0) {
4321 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4322 track->name());
4323 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004324 // indicate to client process that the track was disabled because of underrun;
4325 // it will then automatically call start() when data is available
4326 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 } else if (last){
4328 mixerStatus = MIXER_TRACKS_ENABLED;
4329 }
4330 }
4331 }
4332 // compute volume for this track
4333 processVolume_l(track, last);
4334 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004335
Eric Laurentea0fade2013-10-04 16:23:48 -07004336 // make sure the pause/flush/resume sequence is executed in the right order.
4337 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4338 // before flush and then resume HW. This can happen in case of pause/flush/resume
4339 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004340 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004341 mOutput->stream->pause(mOutput->stream);
4342 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004343 if (mFlushPending) {
4344 flushHw_l();
4345 mFlushPending = false;
4346 }
Eric Laurentfd477972013-10-25 18:10:40 -07004347 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004348 mOutput->stream->resume(mOutput->stream);
4349 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004350
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 // remove all the tracks that need to be...
4352 removeTracks_l(*tracksToRemove);
4353
4354 return mixerStatus;
4355}
4356
Eric Laurentbfb1b832013-01-07 09:53:42 -08004357// must be called with thread mutex locked
4358bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4359{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004360 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4361 mWriteAckSequence, mDrainSequence);
4362 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 return true;
4364 }
4365 return false;
4366}
4367
4368// must be called with thread mutex locked
4369bool AudioFlinger::OffloadThread::shouldStandby_l()
4370{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004371 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004372
4373 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4374 // after a timeout and we will enter standby then.
4375 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004376 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 }
4378
Glenn Kastene6f35b12013-08-19 09:58:50 -07004379 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004380}
4381
4382
4383bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4384{
4385 Mutex::Autolock _l(mLock);
4386 return waitingAsyncCallback_l();
4387}
4388
4389void AudioFlinger::OffloadThread::flushHw_l()
4390{
4391 mOutput->stream->flush(mOutput->stream);
4392 // Flush anything still waiting in the mixbuffer
4393 mCurrentWriteLength = 0;
4394 mBytesRemaining = 0;
4395 mPausedWriteLength = 0;
4396 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004397 mHwPaused = false;
4398
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004400 // discard any pending drain or write ack by incrementing sequence
4401 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4402 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004404 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4405 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004406 }
4407}
4408
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004409void AudioFlinger::OffloadThread::onAddNewTrack_l()
4410{
4411 sp<Track> previousTrack = mPreviousTrack.promote();
4412 sp<Track> latestTrack = mLatestActiveTrack.promote();
4413
4414 if (previousTrack != 0 && latestTrack != 0 &&
4415 (previousTrack->sessionId() != latestTrack->sessionId())) {
4416 mFlushPending = true;
4417 }
4418 PlaybackThread::onAddNewTrack_l();
4419}
4420
Eric Laurentbfb1b832013-01-07 09:53:42 -08004421// ----------------------------------------------------------------------------
4422
Eric Laurent81784c32012-11-19 14:55:58 -08004423AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4424 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4425 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4426 DUPLICATING),
4427 mWaitTimeMs(UINT_MAX)
4428{
4429 addOutputTrack(mainThread);
4430}
4431
4432AudioFlinger::DuplicatingThread::~DuplicatingThread()
4433{
4434 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4435 mOutputTracks[i]->destroy();
4436 }
4437}
4438
4439void AudioFlinger::DuplicatingThread::threadLoop_mix()
4440{
4441 // mix buffers...
4442 if (outputsReady(outputTracks)) {
4443 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4444 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004445 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004446 }
4447 sleepTime = 0;
4448 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004449 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004450 standbyTime = systemTime() + standbyDelay;
4451}
4452
4453void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4454{
4455 if (sleepTime == 0) {
4456 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4457 sleepTime = activeSleepTime;
4458 } else {
4459 sleepTime = idleSleepTime;
4460 }
4461 } else if (mBytesWritten != 0) {
4462 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4463 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004464 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004465 } else {
4466 // flush remaining overflow buffers in output tracks
4467 writeFrames = 0;
4468 }
4469 sleepTime = 0;
4470 }
4471}
4472
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004474{
4475 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004476 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4477 // for delivery downstream as needed. This in-place conversion is safe as
4478 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4479 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4480 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4481 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4482 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4483 }
4484 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004486 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004487 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004488}
4489
4490void AudioFlinger::DuplicatingThread::threadLoop_standby()
4491{
4492 // DuplicatingThread implements standby by stopping all tracks
4493 for (size_t i = 0; i < outputTracks.size(); i++) {
4494 outputTracks[i]->stop();
4495 }
4496}
4497
4498void AudioFlinger::DuplicatingThread::saveOutputTracks()
4499{
4500 outputTracks = mOutputTracks;
4501}
4502
4503void AudioFlinger::DuplicatingThread::clearOutputTracks()
4504{
4505 outputTracks.clear();
4506}
4507
4508void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4509{
4510 Mutex::Autolock _l(mLock);
4511 // FIXME explain this formula
4512 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004513 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4514 // due to current usage case and restrictions on the AudioBufferProvider.
4515 // Actual buffer conversion is done in threadLoop_write().
4516 //
4517 // TODO: This may change in the future, depending on multichannel
4518 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004519 OutputTrack *outputTrack = new OutputTrack(thread,
4520 this,
4521 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004522 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004523 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004524 frameCount,
4525 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004526 if (outputTrack->cblk() != NULL) {
4527 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4528 mOutputTracks.add(outputTrack);
4529 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4530 updateWaitTime_l();
4531 }
4532}
4533
4534void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4535{
4536 Mutex::Autolock _l(mLock);
4537 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4538 if (mOutputTracks[i]->thread() == thread) {
4539 mOutputTracks[i]->destroy();
4540 mOutputTracks.removeAt(i);
4541 updateWaitTime_l();
4542 return;
4543 }
4544 }
4545 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4546}
4547
4548// caller must hold mLock
4549void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4550{
4551 mWaitTimeMs = UINT_MAX;
4552 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4553 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4554 if (strong != 0) {
4555 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4556 if (waitTimeMs < mWaitTimeMs) {
4557 mWaitTimeMs = waitTimeMs;
4558 }
4559 }
4560 }
4561}
4562
4563
4564bool AudioFlinger::DuplicatingThread::outputsReady(
4565 const SortedVector< sp<OutputTrack> > &outputTracks)
4566{
4567 for (size_t i = 0; i < outputTracks.size(); i++) {
4568 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4569 if (thread == 0) {
4570 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4571 outputTracks[i].get());
4572 return false;
4573 }
4574 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4575 // see note at standby() declaration
4576 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4577 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4578 thread.get());
4579 return false;
4580 }
4581 }
4582 return true;
4583}
4584
4585uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4586{
4587 return (mWaitTimeMs * 1000) / 2;
4588}
4589
4590void AudioFlinger::DuplicatingThread::cacheParameters_l()
4591{
4592 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4593 updateWaitTime_l();
4594
4595 MixerThread::cacheParameters_l();
4596}
4597
4598// ----------------------------------------------------------------------------
4599// Record
4600// ----------------------------------------------------------------------------
4601
4602AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4603 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004604 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004605 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004606 audio_devices_t inDevice
4607#ifdef TEE_SINK
4608 , const sp<NBAIO_Sink>& teeSink
4609#endif
4610 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004611 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004612 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004613 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004614 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004615#ifdef TEE_SINK
4616 , mTeeSink(teeSink)
4617#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004618{
4619 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004620 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004621
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004622 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004623}
4624
4625
4626AudioFlinger::RecordThread::~RecordThread()
4627{
Glenn Kasten481fb672013-09-30 14:39:28 -07004628 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004629 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004630}
4631
4632void AudioFlinger::RecordThread::onFirstRef()
4633{
4634 run(mName, PRIORITY_URGENT_AUDIO);
4635}
4636
Eric Laurent81784c32012-11-19 14:55:58 -08004637bool AudioFlinger::RecordThread::threadLoop()
4638{
Eric Laurent81784c32012-11-19 14:55:58 -08004639 nsecs_t lastWarning = 0;
4640
4641 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004642
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004643reacquire_wakelock:
4644 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004645 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004646 {
4647 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004648 size_t size = mActiveTracks.size();
4649 activeTracksGen = mActiveTracksGen;
4650 if (size > 0) {
4651 // FIXME an arbitrary choice
4652 activeTrack = mActiveTracks[0];
4653 acquireWakeLock_l(activeTrack->uid());
4654 if (size > 1) {
4655 SortedVector<int> tmp;
4656 for (size_t i = 0; i < size; i++) {
4657 tmp.add(mActiveTracks[i]->uid());
4658 }
4659 updateWakeLockUids_l(tmp);
4660 }
4661 } else {
4662 acquireWakeLock_l(-1);
4663 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004664 }
4665
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004666 // used to request a deferred sleep, to be executed later while mutex is unlocked
4667 uint32_t sleepUs = 0;
4668
4669 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004670 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004671 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004672
Glenn Kasten5edadd42013-08-14 16:30:49 -07004673 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004674 if (sleepUs > 0) {
4675 usleep(sleepUs);
4676 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004677 }
4678
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004679 // activeTracks accumulates a copy of a subset of mActiveTracks
4680 Vector< sp<RecordTrack> > activeTracks;
4681
Eric Laurent81784c32012-11-19 14:55:58 -08004682 { // scope for mLock
4683 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004684
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004685 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004686 // return value 'reconfig' is currently unused
4687 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004688
Eric Laurent000a4192014-01-29 15:17:32 -08004689 // check exitPending here because checkForNewParameters_l() and
4690 // checkForNewParameters_l() can temporarily release mLock
4691 if (exitPending()) {
4692 break;
4693 }
4694
Glenn Kasten2b806402013-11-20 16:37:38 -08004695 // if no active track(s), then standby and release wakelock
4696 size_t size = mActiveTracks.size();
4697 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004698 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004699 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004700 releaseWakeLock_l();
4701 ALOGV("RecordThread: loop stopping");
4702 // go to sleep
4703 mWaitWorkCV.wait(mLock);
4704 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004705 goto reacquire_wakelock;
4706 }
4707
Glenn Kasten2b806402013-11-20 16:37:38 -08004708 if (mActiveTracksGen != activeTracksGen) {
4709 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004710 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004711 for (size_t i = 0; i < size; i++) {
4712 tmp.add(mActiveTracks[i]->uid());
4713 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004714 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004715 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004716
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004717 bool doBroadcast = false;
4718 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004719
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004720 activeTrack = mActiveTracks[i];
4721 if (activeTrack->isTerminated()) {
4722 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004723 mActiveTracks.remove(activeTrack);
4724 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004725 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004726 continue;
4727 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004728
4729 TrackBase::track_state activeTrackState = activeTrack->mState;
4730 switch (activeTrackState) {
4731
4732 case TrackBase::PAUSING:
4733 mActiveTracks.remove(activeTrack);
4734 mActiveTracksGen++;
4735 doBroadcast = true;
4736 size--;
4737 continue;
4738
4739 case TrackBase::STARTING_1:
4740 sleepUs = 10000;
4741 i++;
4742 continue;
4743
4744 case TrackBase::STARTING_2:
4745 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004746 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004747 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004748 break;
4749
4750 case TrackBase::ACTIVE:
4751 break;
4752
4753 case TrackBase::IDLE:
4754 i++;
4755 continue;
4756
4757 default:
4758 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004759 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004760
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004761 activeTracks.add(activeTrack);
4762 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004763
Glenn Kasten9e982352013-08-14 14:39:50 -07004764 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004765 if (doBroadcast) {
4766 mStartStopCond.broadcast();
4767 }
4768
4769 // sleep if there are no active tracks to process
4770 if (activeTracks.size() == 0) {
4771 if (sleepUs == 0) {
4772 sleepUs = kRecordThreadSleepUs;
4773 }
4774 continue;
4775 }
4776 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004777
Eric Laurent81784c32012-11-19 14:55:58 -08004778 lockEffectChains_l(effectChains);
4779 }
4780
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004781 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004782
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004783 size_t size = effectChains.size();
4784 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004785 // thread mutex is not locked, but effect chain is locked
4786 effectChains[i]->process_l();
4787 }
4788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004789 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4790 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4791 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4792 // If destination is non-contiguous, first read past the nominal end of buffer, then
4793 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004794
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004795 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4796 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4797 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4798 if (bytesRead <= 0) {
4799 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4800 // Force input into standby so that it tries to recover at next read attempt
4801 inputStandBy();
4802 sleepUs = kRecordThreadSleepUs;
4803 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004804 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004805 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4806 size_t framesRead = bytesRead / mFrameSize;
4807 ALOG_ASSERT(framesRead > 0);
4808 if (mTeeSink != 0) {
4809 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4810 }
4811 // If destination is non-contiguous, we now correct for reading past end of buffer.
4812 size_t part1 = mRsmpInFramesP2 - rear;
4813 if (framesRead > part1) {
4814 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4815 (framesRead - part1) * mFrameSize);
4816 }
4817 rear = mRsmpInRear += framesRead;
4818
4819 size = activeTracks.size();
4820 // loop over each active track
4821 for (size_t i = 0; i < size; i++) {
4822 activeTrack = activeTracks[i];
4823
4824 enum {
4825 OVERRUN_UNKNOWN,
4826 OVERRUN_TRUE,
4827 OVERRUN_FALSE
4828 } overrun = OVERRUN_UNKNOWN;
4829
4830 // loop over getNextBuffer to handle circular sink
4831 for (;;) {
4832
4833 activeTrack->mSink.frameCount = ~0;
4834 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4835 size_t framesOut = activeTrack->mSink.frameCount;
4836 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4837
4838 int32_t front = activeTrack->mRsmpInFront;
4839 ssize_t filled = rear - front;
4840 size_t framesIn;
4841
4842 if (filled < 0) {
4843 // should not happen, but treat like a massive overrun and re-sync
4844 framesIn = 0;
4845 activeTrack->mRsmpInFront = rear;
4846 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004847 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004848 framesIn = (size_t) filled;
4849 } else {
4850 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004851 framesIn = mRsmpInFrames;
4852 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004853 overrun = OVERRUN_TRUE;
4854 }
4855
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004856 if (framesOut == 0 || framesIn == 0) {
4857 break;
4858 }
4859
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004860 if (activeTrack->mResampler == NULL) {
4861 // no resampling
4862 if (framesIn > framesOut) {
4863 framesIn = framesOut;
4864 } else {
4865 framesOut = framesIn;
4866 }
4867 int8_t *dst = activeTrack->mSink.i8;
4868 while (framesIn > 0) {
4869 front &= mRsmpInFramesP2 - 1;
4870 size_t part1 = mRsmpInFramesP2 - front;
4871 if (part1 > framesIn) {
4872 part1 = framesIn;
4873 }
4874 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004875 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004876 memcpy(dst, src, part1 * mFrameSize);
4877 } else if (mChannelCount == 1) {
4878 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4879 part1);
4880 } else {
4881 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4882 part1);
4883 }
4884 dst += part1 * activeTrack->mFrameSize;
4885 front += part1;
4886 framesIn -= part1;
4887 }
4888 activeTrack->mRsmpInFront += framesOut;
4889
4890 } else {
4891 // resampling
4892 // FIXME framesInNeeded should really be part of resampler API, and should
4893 // depend on the SRC ratio
4894 // to keep mRsmpInBuffer full so resampler always has sufficient input
4895 size_t framesInNeeded;
4896 // FIXME only re-calculate when it changes, and optimize for common ratios
4897 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4898 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004899 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004900 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4901 framesInNeeded, framesOut, inOverOut);
4902 // Although we theoretically have framesIn in circular buffer, some of those are
4903 // unreleased frames, and thus must be discounted for purpose of budgeting.
4904 size_t unreleased = activeTrack->mRsmpInUnrel;
4905 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004906 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004907 ALOGV("not enough to resample: have %u frames in but need %u in to "
4908 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004909 framesIn, framesInNeeded, framesOut, inOverOut);
4910 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004911 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4912 if (newFramesOut == 0) {
4913 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004914 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004915 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4916 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4917 framesInNeeded, newFramesOut, outOverIn);
4918 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4919 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4920 "given in/out ratio of %.4g",
4921 framesIn, framesInNeeded, newFramesOut, inOverOut);
4922 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004923 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004924 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004925 "given in/out ratio of %.4g",
4926 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004927 }
4928
4929 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4930 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004931 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004932 delete[] activeTrack->mRsmpOutBuffer;
4933 // resampler always outputs stereo
4934 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4935 activeTrack->mRsmpOutFrameCount = framesOut;
4936 }
4937
4938 // resampler accumulates, but we only have one source track
4939 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4940 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004941 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004942 activeTrack->mResamplerBufferProvider
4943 /*this*/ /* AudioBufferProvider* */);
4944 // ditherAndClamp() works as long as all buffers returned by
4945 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004946 if (activeTrack->mChannelCount == 1) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004947 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4948 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4949 framesOut);
4950 // the resampler always outputs stereo samples:
4951 // do post stereo to mono conversion
4952 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4953 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4954 } else {
4955 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4956 activeTrack->mRsmpOutBuffer, framesOut);
4957 }
4958 // now done with mRsmpOutBuffer
4959
4960 }
4961
4962 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4963 overrun = OVERRUN_FALSE;
4964 }
4965
4966 if (activeTrack->mFramesToDrop == 0) {
4967 if (framesOut > 0) {
4968 activeTrack->mSink.frameCount = framesOut;
4969 activeTrack->releaseBuffer(&activeTrack->mSink);
4970 }
4971 } else {
4972 // FIXME could do a partial drop of framesOut
4973 if (activeTrack->mFramesToDrop > 0) {
4974 activeTrack->mFramesToDrop -= framesOut;
4975 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004976 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004977 }
4978 } else {
4979 activeTrack->mFramesToDrop += framesOut;
4980 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
4981 activeTrack->mSyncStartEvent->isCancelled()) {
4982 ALOGW("Synced record %s, session %d, trigger session %d",
4983 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
4984 activeTrack->sessionId(),
4985 (activeTrack->mSyncStartEvent != 0) ?
4986 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004987 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004988 }
4989 }
4990 }
4991
4992 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004993 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004994 }
4995 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004996
4997 switch (overrun) {
4998 case OVERRUN_TRUE:
4999 // client isn't retrieving buffers fast enough
5000 if (!activeTrack->setOverflow()) {
5001 nsecs_t now = systemTime();
5002 // FIXME should lastWarning per track?
5003 if ((now - lastWarning) > kWarningThrottleNs) {
5004 ALOGW("RecordThread: buffer overflow");
5005 lastWarning = now;
5006 }
5007 }
5008 break;
5009 case OVERRUN_FALSE:
5010 activeTrack->clearOverflow();
5011 break;
5012 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005013 break;
5014 }
5015
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005016 }
5017
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // enable changes in effect chain
5019 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005020 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005021 }
5022
Glenn Kasten93e471f2013-08-19 08:40:07 -07005023 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005024
5025 {
5026 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005027 for (size_t i = 0; i < mTracks.size(); i++) {
5028 sp<RecordTrack> track = mTracks[i];
5029 track->invalidate();
5030 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005031 mActiveTracks.clear();
5032 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005033 mStartStopCond.broadcast();
5034 }
5035
5036 releaseWakeLock();
5037
5038 ALOGV("RecordThread %p exiting", this);
5039 return false;
5040}
5041
Glenn Kasten93e471f2013-08-19 08:40:07 -07005042void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005043{
5044 if (!mStandby) {
5045 inputStandBy();
5046 mStandby = true;
5047 }
5048}
5049
5050void AudioFlinger::RecordThread::inputStandBy()
5051{
5052 mInput->stream->common.standby(&mInput->stream->common);
5053}
5054
Glenn Kasten05997e22014-03-13 15:08:33 -07005055// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005056sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005057 const sp<AudioFlinger::Client>& client,
5058 uint32_t sampleRate,
5059 audio_format_t format,
5060 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005061 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005062 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005063 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005064 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005065 pid_t tid,
5066 status_t *status)
5067{
Glenn Kasten74935e42013-12-19 08:56:45 -08005068 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005069 sp<RecordTrack> track;
5070 status_t lStatus;
5071
5072 lStatus = initCheck();
5073 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07005074 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08005075 goto Exit;
5076 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07005077
Glenn Kasten90e58b12013-07-31 16:16:02 -07005078 // client expresses a preference for FAST, but we get the final say
5079 if (*flags & IAudioFlinger::TRACK_FAST) {
5080 if (
5081 // use case: callback handler and frame count is default or at least as large as HAL
5082 (
5083 (tid != -1) &&
5084 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08005085 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005086 ) &&
5087 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
5088 // mono or stereo
5089 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
5090 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
5091 // hardware sample rate
5092 (sampleRate == mSampleRate) &&
5093 // record thread has an associated fast recorder
5094 hasFastRecorder()
5095 // FIXME test that RecordThread for this fast track has a capable output HAL
5096 // FIXME add a permission test also?
5097 ) {
5098 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
5099 if (frameCount == 0) {
5100 frameCount = mFrameCount * kFastTrackMultiplier;
5101 }
5102 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5103 frameCount, mFrameCount);
5104 } else {
5105 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5106 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
5107 "hasFastRecorder=%d tid=%d",
5108 frameCount, mFrameCount, format,
5109 audio_is_linear_pcm(format),
5110 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
5111 *flags &= ~IAudioFlinger::TRACK_FAST;
5112 // For compatibility with AudioRecord calculation, buffer depth is forced
5113 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5114 // This is probably too conservative, but legacy application code may depend on it.
5115 // If you change this calculation, also review the start threshold which is related.
5116 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5117 size_t mNormalFrameCount = 2048; // FIXME
5118 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5119 if (minBufCount < 2) {
5120 minBufCount = 2;
5121 }
5122 size_t minFrameCount = mNormalFrameCount * minBufCount;
5123 if (frameCount < minFrameCount) {
5124 frameCount = minFrameCount;
5125 }
5126 }
5127 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005128 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005129
Eric Laurent81784c32012-11-19 14:55:58 -08005130 // FIXME use flags and tid similar to createTrack_l()
5131
5132 { // scope for mLock
5133 Mutex::Autolock _l(mLock);
5134
5135 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005136 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08005137
Glenn Kasten03003332013-08-06 15:40:54 -07005138 lStatus = track->initCheck();
5139 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005140 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005141 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005142 goto Exit;
5143 }
5144 mTracks.add(track);
5145
5146 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5147 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5148 mAudioFlinger->btNrecIsOff();
5149 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5150 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005151
5152 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5153 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5154 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5155 // so ask activity manager to do this on our behalf
5156 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5157 }
Eric Laurent81784c32012-11-19 14:55:58 -08005158 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005159
Eric Laurent81784c32012-11-19 14:55:58 -08005160 lStatus = NO_ERROR;
5161
5162Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005163 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005164 return track;
5165}
5166
5167status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5168 AudioSystem::sync_event_t event,
5169 int triggerSession)
5170{
5171 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5172 sp<ThreadBase> strongMe = this;
5173 status_t status = NO_ERROR;
5174
5175 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005176 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005177 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005178 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005179 triggerSession,
5180 recordTrack->sessionId(),
5181 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005182 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005183 // Sync event can be cancelled by the trigger session if the track is not in a
5184 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005185 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005186 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005187 } else {
5188 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005189 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005190 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005191 }
5192 }
5193
5194 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005195 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005196 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005197 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5198 if (recordTrack->mState == TrackBase::PAUSING) {
5199 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005200 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005201 } else {
5202 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005203 }
5204 return status;
5205 }
5206
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005207 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5208 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5209 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005211 mActiveTracks.add(recordTrack);
5212 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005213 mLock.unlock();
5214 status_t status = AudioSystem::startInput(mId);
5215 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005216 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005217 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005218 mActiveTracks.remove(recordTrack);
5219 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005220 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005221 return status;
5222 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005223 // Catch up with current buffer indices if thread is already running.
5224 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5225 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5226 // see previously buffered data before it called start(), but with greater risk of overrun.
5227
5228 recordTrack->mRsmpInFront = mRsmpInRear;
5229 recordTrack->mRsmpInUnrel = 0;
5230 // FIXME why reset?
5231 if (recordTrack->mResampler != NULL) {
5232 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005233 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005234 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005235 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005236 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005237 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005238 ALOGV("Record failed to start");
5239 status = BAD_VALUE;
5240 goto startError;
5241 }
Eric Laurent81784c32012-11-19 14:55:58 -08005242 return status;
5243 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005244
Eric Laurent81784c32012-11-19 14:55:58 -08005245startError:
5246 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005247 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005248 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005249 return status;
5250}
5251
Eric Laurent81784c32012-11-19 14:55:58 -08005252void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5253{
5254 sp<SyncEvent> strongEvent = event.promote();
5255
5256 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005257 sp<RefBase> ptr = strongEvent->cookie().promote();
5258 if (ptr != 0) {
5259 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5260 recordTrack->handleSyncStartEvent(strongEvent);
5261 }
Eric Laurent81784c32012-11-19 14:55:58 -08005262 }
5263}
5264
Glenn Kastena8356f62013-07-25 14:37:52 -07005265bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005266 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005267 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005268 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005269 return false;
5270 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005271 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005272 recordTrack->mState = TrackBase::PAUSING;
5273 // do not wait for mStartStopCond if exiting
5274 if (exitPending()) {
5275 return true;
5276 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005277 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005278 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005279 // if we have been restarted, recordTrack is in mActiveTracks here
5280 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005281 ALOGV("Record stopped OK");
5282 return true;
5283 }
5284 return false;
5285}
5286
Glenn Kasten0f11b512014-01-31 16:18:54 -08005287bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005288{
5289 return false;
5290}
5291
Glenn Kasten0f11b512014-01-31 16:18:54 -08005292status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005293{
5294#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5295 if (!isValidSyncEvent(event)) {
5296 return BAD_VALUE;
5297 }
5298
5299 int eventSession = event->triggerSession();
5300 status_t ret = NAME_NOT_FOUND;
5301
5302 Mutex::Autolock _l(mLock);
5303
5304 for (size_t i = 0; i < mTracks.size(); i++) {
5305 sp<RecordTrack> track = mTracks[i];
5306 if (eventSession == track->sessionId()) {
5307 (void) track->setSyncEvent(event);
5308 ret = NO_ERROR;
5309 }
5310 }
5311 return ret;
5312#else
5313 return BAD_VALUE;
5314#endif
5315}
5316
5317// destroyTrack_l() must be called with ThreadBase::mLock held
5318void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5319{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320 track->terminate();
5321 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005322 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005323 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005324 removeTrack_l(track);
5325 }
5326}
5327
5328void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5329{
5330 mTracks.remove(track);
5331 // need anything related to effects here?
5332}
5333
5334void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5335{
5336 dumpInternals(fd, args);
5337 dumpTracks(fd, args);
5338 dumpEffectChains(fd, args);
5339}
5340
5341void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5342{
Marco Nelissenb2208842014-02-07 14:00:50 -08005343 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005344
Glenn Kasten2b806402013-11-20 16:37:38 -08005345 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005346 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005347 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005348 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005349 }
5350
Eric Laurent81784c32012-11-19 14:55:58 -08005351 dumpBase(fd, args);
5352}
5353
Glenn Kasten0f11b512014-01-31 16:18:54 -08005354void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005355{
5356 const size_t SIZE = 256;
5357 char buffer[SIZE];
5358 String8 result;
5359
Marco Nelissenb2208842014-02-07 14:00:50 -08005360 size_t numtracks = mTracks.size();
5361 size_t numactive = mActiveTracks.size();
5362 size_t numactiveseen = 0;
5363 fdprintf(fd, " %d Tracks", numtracks);
5364 if (numtracks) {
5365 fdprintf(fd, " of which %d are active\n", numactive);
5366 RecordTrack::appendDumpHeader(result);
5367 for (size_t i = 0; i < numtracks ; ++i) {
5368 sp<RecordTrack> track = mTracks[i];
5369 if (track != 0) {
5370 bool active = mActiveTracks.indexOf(track) >= 0;
5371 if (active) {
5372 numactiveseen++;
5373 }
5374 track->dump(buffer, SIZE, active);
5375 result.append(buffer);
5376 }
Eric Laurent81784c32012-11-19 14:55:58 -08005377 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005378 } else {
5379 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381
Marco Nelissenb2208842014-02-07 14:00:50 -08005382 if (numactiveseen != numactive) {
5383 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5384 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005385 result.append(buffer);
5386 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005387 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005388 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005389 if (mTracks.indexOf(track) < 0) {
5390 track->dump(buffer, SIZE, true);
5391 result.append(buffer);
5392 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005393 }
Eric Laurent81784c32012-11-19 14:55:58 -08005394
5395 }
5396 write(fd, result.string(), result.size());
5397}
5398
5399// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005400status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5401 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005402{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005403 RecordTrack *activeTrack = mRecordTrack;
5404 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5405 if (threadBase == 0) {
5406 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005407 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005408 return NOT_ENOUGH_DATA;
5409 }
5410 RecordThread *recordThread = (RecordThread *) threadBase.get();
5411 int32_t rear = recordThread->mRsmpInRear;
5412 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005413 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005414 // FIXME should not be P2 (don't want to increase latency)
5415 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005416 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005417 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005418 front &= recordThread->mRsmpInFramesP2 - 1;
5419 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005420 if (part1 > (size_t) filled) {
5421 part1 = filled;
5422 }
5423 size_t ask = buffer->frameCount;
5424 ALOG_ASSERT(ask > 0);
5425 if (part1 > ask) {
5426 part1 = ask;
5427 }
5428 if (part1 == 0) {
5429 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005430 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005431 buffer->raw = NULL;
5432 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005433 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005434 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005435 }
5436
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005437 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005438 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005440 return NO_ERROR;
5441}
5442
5443// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005444void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5445 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005446{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005447 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005448 size_t stepCount = buffer->frameCount;
5449 if (stepCount == 0) {
5450 return;
5451 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005452 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5453 activeTrack->mRsmpInUnrel -= stepCount;
5454 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005455 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 buffer->frameCount = 0;
5457}
5458
5459bool AudioFlinger::RecordThread::checkForNewParameters_l()
5460{
5461 bool reconfig = false;
5462
5463 while (!mNewParameters.isEmpty()) {
5464 status_t status = NO_ERROR;
5465 String8 keyValuePair = mNewParameters[0];
5466 AudioParameter param = AudioParameter(keyValuePair);
5467 int value;
5468 audio_format_t reqFormat = mFormat;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005469 uint32_t samplingRate = mSampleRate;
5470 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005471
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005472 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5473 // channel count change can be requested. Do we mandate the first client defines the
5474 // HAL sampling rate and channel count or do we allow changes on the fly?
Eric Laurent81784c32012-11-19 14:55:58 -08005475 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005476 samplingRate = value;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 reconfig = true;
5478 }
5479 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005480 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5481 status = BAD_VALUE;
5482 } else {
5483 reqFormat = (audio_format_t) value;
5484 reconfig = true;
5485 }
Eric Laurent81784c32012-11-19 14:55:58 -08005486 }
5487 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005488 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5489 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5490 status = BAD_VALUE;
5491 } else {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005492 channelMask = mask;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005493 reconfig = true;
5494 }
Eric Laurent81784c32012-11-19 14:55:58 -08005495 }
5496 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5497 // do not accept frame count changes if tracks are open as the track buffer
5498 // size depends on frame count and correct behavior would not be guaranteed
5499 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005500 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005501 status = INVALID_OPERATION;
5502 } else {
5503 reconfig = true;
5504 }
5505 }
5506 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5507 // forward device change to effects that have requested to be
5508 // aware of attached audio device.
5509 for (size_t i = 0; i < mEffectChains.size(); i++) {
5510 mEffectChains[i]->setDevice_l(value);
5511 }
5512
5513 // store input device and output device but do not forward output device to audio HAL.
5514 // Note that status is ignored by the caller for output device
5515 // (see AudioFlinger::setParameters()
5516 if (audio_is_output_devices(value)) {
5517 mOutDevice = value;
5518 status = BAD_VALUE;
5519 } else {
5520 mInDevice = value;
5521 // disable AEC and NS if the device is a BT SCO headset supporting those
5522 // pre processings
5523 if (mTracks.size() > 0) {
5524 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5525 mAudioFlinger->btNrecIsOff();
5526 for (size_t i = 0; i < mTracks.size(); i++) {
5527 sp<RecordTrack> track = mTracks[i];
5528 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5529 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5530 }
5531 }
5532 }
5533 }
5534 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5535 mAudioSource != (audio_source_t)value) {
5536 // forward device change to effects that have requested to be
5537 // aware of attached audio device.
5538 for (size_t i = 0; i < mEffectChains.size(); i++) {
5539 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5540 }
5541 mAudioSource = (audio_source_t)value;
5542 }
Glenn Kastene198c362013-08-13 09:13:36 -07005543
Eric Laurent81784c32012-11-19 14:55:58 -08005544 if (status == NO_ERROR) {
5545 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5546 keyValuePair.string());
5547 if (status == INVALID_OPERATION) {
5548 inputStandBy();
5549 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5550 keyValuePair.string());
5551 }
5552 if (reconfig) {
5553 if (status == BAD_VALUE &&
5554 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5555 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005556 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005557 <= (2 * samplingRate)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08005558 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5559 <= FCC_2 &&
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005560 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5561 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005562 status = NO_ERROR;
5563 }
5564 if (status == NO_ERROR) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005565 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005566 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5567 }
5568 }
5569 }
5570
5571 mNewParameters.removeAt(0);
5572
5573 mParamStatus = status;
5574 mParamCond.signal();
5575 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5576 // already timed out waiting for the status and will never signal the condition.
5577 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5578 }
5579 return reconfig;
5580}
5581
5582String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5583{
Eric Laurent81784c32012-11-19 14:55:58 -08005584 Mutex::Autolock _l(mLock);
5585 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005586 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005587 }
5588
Glenn Kastend8ea6992013-07-16 14:17:15 -07005589 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5590 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005591 free(s);
5592 return out_s8;
5593}
5594
Glenn Kasten0f11b512014-01-31 16:18:54 -08005595void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005596 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005597 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005598
5599 switch (event) {
5600 case AudioSystem::INPUT_OPENED:
5601 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005602 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005603 desc.samplingRate = mSampleRate;
5604 desc.format = mFormat;
5605 desc.frameCount = mFrameCount;
5606 desc.latency = 0;
5607 param2 = &desc;
5608 break;
5609
5610 case AudioSystem::INPUT_CLOSED:
5611 default:
5612 break;
5613 }
5614 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5615}
5616
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005617void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005618{
Eric Laurent81784c32012-11-19 14:55:58 -08005619 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5620 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005621 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005622 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005623 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005624 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005625 }
Eric Laurent81784c32012-11-19 14:55:58 -08005626 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005627 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5628 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005629 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005630 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07005631 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005632 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005633 // A larger value should allow more old data to be read after a track calls start(),
5634 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005635 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005636 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005638 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5639 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005640
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005641 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5642 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005643}
5644
Glenn Kasten5f972c02014-01-13 09:59:31 -08005645uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005646{
5647 Mutex::Autolock _l(mLock);
5648 if (initCheck() != NO_ERROR) {
5649 return 0;
5650 }
5651
5652 return mInput->stream->get_input_frames_lost(mInput->stream);
5653}
5654
5655uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5656{
5657 Mutex::Autolock _l(mLock);
5658 uint32_t result = 0;
5659 if (getEffectChain_l(sessionId) != 0) {
5660 result = EFFECT_SESSION;
5661 }
5662
5663 for (size_t i = 0; i < mTracks.size(); ++i) {
5664 if (sessionId == mTracks[i]->sessionId()) {
5665 result |= TRACK_SESSION;
5666 break;
5667 }
5668 }
5669
5670 return result;
5671}
5672
5673KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5674{
5675 KeyedVector<int, bool> ids;
5676 Mutex::Autolock _l(mLock);
5677 for (size_t j = 0; j < mTracks.size(); ++j) {
5678 sp<RecordThread::RecordTrack> track = mTracks[j];
5679 int sessionId = track->sessionId();
5680 if (ids.indexOfKey(sessionId) < 0) {
5681 ids.add(sessionId, true);
5682 }
5683 }
5684 return ids;
5685}
5686
5687AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5688{
5689 Mutex::Autolock _l(mLock);
5690 AudioStreamIn *input = mInput;
5691 mInput = NULL;
5692 return input;
5693}
5694
5695// this method must always be called either with ThreadBase mLock held or inside the thread loop
5696audio_stream_t* AudioFlinger::RecordThread::stream() const
5697{
5698 if (mInput == NULL) {
5699 return NULL;
5700 }
5701 return &mInput->stream->common;
5702}
5703
5704status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5705{
5706 // only one chain per input thread
5707 if (mEffectChains.size() != 0) {
5708 return INVALID_OPERATION;
5709 }
5710 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5711
5712 chain->setInBuffer(NULL);
5713 chain->setOutBuffer(NULL);
5714
5715 checkSuspendOnAddEffectChain_l(chain);
5716
5717 mEffectChains.add(chain);
5718
5719 return NO_ERROR;
5720}
5721
5722size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5723{
5724 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5725 ALOGW_IF(mEffectChains.size() != 1,
5726 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5727 chain.get(), mEffectChains.size(), this);
5728 if (mEffectChains.size() == 1) {
5729 mEffectChains.removeAt(0);
5730 }
5731 return 0;
5732}
5733
5734}; // namespace android