blob: b064e89e42c331f134cf04ee1d7871dee4445449 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
Glenn Kasten0f11b512014-01-31 16:18:54 -0800188void CpuStats::sample(const String8 &title
189#ifndef DEBUG_CPU_USAGE
190 __unused
191#endif
192 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef DEBUG_CPU_USAGE
194 // get current thread's delta CPU time in wall clock ns
195 double wcNs;
196 bool valid = mCpuUsage.sampleAndEnable(wcNs);
197
198 // record sample for wall clock statistics
199 if (valid) {
200 mWcStats.sample(wcNs);
201 }
202
203 // get the current CPU number
204 int cpuNum = sched_getcpu();
205
206 // get the current CPU frequency in kHz
207 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
208
209 // check if either CPU number or frequency changed
210 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
211 mCpuNum = cpuNum;
212 mCpukHz = cpukHz;
213 // ignore sample for purposes of cycles
214 valid = false;
215 }
216
217 // if no change in CPU number or frequency, then record sample for cycle statistics
218 if (valid && mCpukHz > 0) {
219 double cycles = wcNs * cpukHz * 0.000001;
220 mHzStats.sample(cycles);
221 }
222
223 unsigned n = mWcStats.n();
224 // mCpuUsage.elapsed() is expensive, so don't call it every loop
225 if ((n & 127) == 1) {
226 long long elapsed = mCpuUsage.elapsed();
227 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
228 double perLoop = elapsed / (double) n;
229 double perLoop100 = perLoop * 0.01;
230 double perLoop1k = perLoop * 0.001;
231 double mean = mWcStats.mean();
232 double stddev = mWcStats.stddev();
233 double minimum = mWcStats.minimum();
234 double maximum = mWcStats.maximum();
235 double meanCycles = mHzStats.mean();
236 double stddevCycles = mHzStats.stddev();
237 double minCycles = mHzStats.minimum();
238 double maxCycles = mHzStats.maximum();
239 mCpuUsage.resetElapsed();
240 mWcStats.reset();
241 mHzStats.reset();
242 ALOGD("CPU usage for %s over past %.1f secs\n"
243 " (%u mixer loops at %.1f mean ms per loop):\n"
244 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
245 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
246 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
247 title.string(),
248 elapsed * .000000001, n, perLoop * .000001,
249 mean * .001,
250 stddev * .001,
251 minimum * .001,
252 maximum * .001,
253 mean / perLoop100,
254 stddev / perLoop100,
255 minimum / perLoop100,
256 maximum / perLoop100,
257 meanCycles / perLoop1k,
258 stddevCycles / perLoop1k,
259 minCycles / perLoop1k,
260 maxCycles / perLoop1k);
261
262 }
263 }
264#endif
265};
266
267// ----------------------------------------------------------------------------
268// ThreadBase
269// ----------------------------------------------------------------------------
270
271AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
272 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
273 : Thread(false /*canCallJava*/),
274 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700275 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700276 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
277 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800278 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700279 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800280 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
281 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
282 // mName will be set by concrete (non-virtual) subclass
283 mDeathRecipient(new PMDeathRecipient(this))
284{
285}
286
287AudioFlinger::ThreadBase::~ThreadBase()
288{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700289 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
290 for (size_t i = 0; i < mConfigEvents.size(); i++) {
291 delete mConfigEvents[i];
292 }
293 mConfigEvents.clear();
294
Eric Laurent81784c32012-11-19 14:55:58 -0800295 mParamCond.broadcast();
296 // do not lock the mutex in destructor
297 releaseWakeLock_l();
298 if (mPowerManager != 0) {
299 sp<IBinder> binder = mPowerManager->asBinder();
300 binder->unlinkToDeath(mDeathRecipient);
301 }
302}
303
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700304status_t AudioFlinger::ThreadBase::readyToRun()
305{
306 status_t status = initCheck();
307 if (status == NO_ERROR) {
308 ALOGI("AudioFlinger's thread %p ready to run", this);
309 } else {
310 ALOGE("No working audio driver found.");
311 }
312 return status;
313}
314
Eric Laurent81784c32012-11-19 14:55:58 -0800315void AudioFlinger::ThreadBase::exit()
316{
317 ALOGV("ThreadBase::exit");
318 // do any cleanup required for exit to succeed
319 preExit();
320 {
321 // This lock prevents the following race in thread (uniprocessor for illustration):
322 // if (!exitPending()) {
323 // // context switch from here to exit()
324 // // exit() calls requestExit(), what exitPending() observes
325 // // exit() calls signal(), which is dropped since no waiters
326 // // context switch back from exit() to here
327 // mWaitWorkCV.wait(...);
328 // // now thread is hung
329 // }
330 AutoMutex lock(mLock);
331 requestExit();
332 mWaitWorkCV.broadcast();
333 }
334 // When Thread::requestExitAndWait is made virtual and this method is renamed to
335 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
336 requestExitAndWait();
337}
338
339status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
340{
341 status_t status;
342
343 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
344 Mutex::Autolock _l(mLock);
345
346 mNewParameters.add(keyValuePairs);
347 mWaitWorkCV.signal();
348 // wait condition with timeout in case the thread loop has exited
349 // before the request could be processed
350 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
351 status = mParamStatus;
352 mWaitWorkCV.signal();
353 } else {
354 status = TIMED_OUT;
355 }
356 return status;
357}
358
359void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
360{
361 Mutex::Autolock _l(mLock);
362 sendIoConfigEvent_l(event, param);
363}
364
365// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
366void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
367{
368 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
369 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
370 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
371 param);
372 mWaitWorkCV.signal();
373}
374
375// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
376void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
377{
378 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
379 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
380 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
381 mConfigEvents.size(), pid, tid, prio);
382 mWaitWorkCV.signal();
383}
384
385void AudioFlinger::ThreadBase::processConfigEvents()
386{
Glenn Kastenf7773312013-08-13 16:00:42 -0700387 Mutex::Autolock _l(mLock);
388 processConfigEvents_l();
389}
390
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700391// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700392void AudioFlinger::ThreadBase::processConfigEvents_l()
393{
Eric Laurent81784c32012-11-19 14:55:58 -0800394 while (!mConfigEvents.isEmpty()) {
395 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
396 ConfigEvent *event = mConfigEvents[0];
397 mConfigEvents.removeAt(0);
398 // release mLock before locking AudioFlinger mLock: lock order is always
399 // AudioFlinger then ThreadBase to avoid cross deadlock
400 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700401 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700402 case CFG_EVENT_PRIO: {
403 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
404 // FIXME Need to understand why this has be done asynchronously
405 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
406 true /*asynchronous*/);
407 if (err != 0) {
408 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
409 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
410 }
411 } break;
412 case CFG_EVENT_IO: {
413 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700414 {
415 Mutex::Autolock _l(mAudioFlinger->mLock);
416 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
417 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700418 } break;
419 default:
420 ALOGE("processConfigEvents() unknown event type %d", event->type());
421 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
423 delete event;
424 mLock.lock();
425 }
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
Marco Nelissenb2208842014-02-07 14:00:50 -0800428String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
429 String8 s;
430 if (output) {
431 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
432 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
433 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
434 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
435 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
436 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
437 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
438 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
439 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
440 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
441 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
442 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
443 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
444 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
445 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
446 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
447 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
448 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
449 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
450 } else {
451 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
452 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
453 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
454 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
455 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
456 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
457 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
458 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
459 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
460 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
461 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
462 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
463 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
464 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
465 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
466 }
467 int len = s.length();
468 if (s.length() > 2) {
469 char *str = s.lockBuffer(len);
470 s.unlockBuffer(len - 2);
471 }
472 return s;
473}
474
Glenn Kasten0f11b512014-01-31 16:18:54 -0800475void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800476{
477 const size_t SIZE = 256;
478 char buffer[SIZE];
479 String8 result;
480
481 bool locked = AudioFlinger::dumpTryLock(mLock);
482 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800483 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800484 }
485
Marco Nelissenb2208842014-02-07 14:00:50 -0800486 fdprintf(fd, " I/O handle: %d\n", mId);
487 fdprintf(fd, " TID: %d\n", getTid());
488 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
489 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000490 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800491 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
492 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
493 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
494 channelMaskToString(mChannelMask, mType != RECORD).string());
495 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000496 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800497 fdprintf(fd, " Pending setParameters commands:");
498 size_t numParams = mNewParameters.size();
499 if (numParams) {
500 fdprintf(fd, "\n Index Command");
501 for (size_t i = 0; i < numParams; ++i) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000502 fdprintf(fd, "\n %02zu ", i);
Marco Nelissenb2208842014-02-07 14:00:50 -0800503 fdprintf(fd, mNewParameters[i]);
504 }
505 fdprintf(fd, "\n");
506 } else {
507 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800508 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800509 fdprintf(fd, " Pending config events:");
510 size_t numConfig = mConfigEvents.size();
511 if (numConfig) {
512 for (size_t i = 0; i < numConfig; i++) {
513 mConfigEvents[i]->dump(buffer, SIZE);
514 fdprintf(fd, "\n %s", buffer);
515 }
516 fdprintf(fd, "\n");
517 } else {
518 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800519 }
Eric Laurent81784c32012-11-19 14:55:58 -0800520
521 if (locked) {
522 mLock.unlock();
523 }
524}
525
526void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
527{
528 const size_t SIZE = 256;
529 char buffer[SIZE];
530 String8 result;
531
Marco Nelissenb2208842014-02-07 14:00:50 -0800532 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000533 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800534 write(fd, buffer, strlen(buffer));
535
Marco Nelissenb2208842014-02-07 14:00:50 -0800536 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800537 sp<EffectChain> chain = mEffectChains[i];
538 if (chain != 0) {
539 chain->dump(fd, args);
540 }
541 }
542}
543
Marco Nelissene14a5d62013-10-03 08:51:24 -0700544void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800545{
546 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700547 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800548}
549
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100550String16 AudioFlinger::ThreadBase::getWakeLockTag()
551{
552 switch (mType) {
553 case MIXER:
554 return String16("AudioMix");
555 case DIRECT:
556 return String16("AudioDirectOut");
557 case DUPLICATING:
558 return String16("AudioDup");
559 case RECORD:
560 return String16("AudioIn");
561 case OFFLOAD:
562 return String16("AudioOffload");
563 default:
564 ALOG_ASSERT(false);
565 return String16("AudioUnknown");
566 }
567}
568
Marco Nelissene14a5d62013-10-03 08:51:24 -0700569void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800570{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800571 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800572 if (mPowerManager != 0) {
573 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700574 status_t status;
575 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700576 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700577 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100578 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700579 String16("media"),
580 uid);
581 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700582 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700583 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100584 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700585 String16("media"));
586 }
Eric Laurent81784c32012-11-19 14:55:58 -0800587 if (status == NO_ERROR) {
588 mWakeLockToken = binder;
589 }
590 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
591 }
592}
593
594void AudioFlinger::ThreadBase::releaseWakeLock()
595{
596 Mutex::Autolock _l(mLock);
597 releaseWakeLock_l();
598}
599
600void AudioFlinger::ThreadBase::releaseWakeLock_l()
601{
602 if (mWakeLockToken != 0) {
603 ALOGV("releaseWakeLock_l() %s", mName);
604 if (mPowerManager != 0) {
605 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
606 }
607 mWakeLockToken.clear();
608 }
609}
610
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800611void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
612 Mutex::Autolock _l(mLock);
613 updateWakeLockUids_l(uids);
614}
615
616void AudioFlinger::ThreadBase::getPowerManager_l() {
617
618 if (mPowerManager == 0) {
619 // use checkService() to avoid blocking if power service is not up yet
620 sp<IBinder> binder =
621 defaultServiceManager()->checkService(String16("power"));
622 if (binder == 0) {
623 ALOGW("Thread %s cannot connect to the power manager service", mName);
624 } else {
625 mPowerManager = interface_cast<IPowerManager>(binder);
626 binder->linkToDeath(mDeathRecipient);
627 }
628 }
629}
630
631void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
632
633 getPowerManager_l();
634 if (mWakeLockToken == NULL) {
635 ALOGE("no wake lock to update!");
636 return;
637 }
638 if (mPowerManager != 0) {
639 sp<IBinder> binder = new BBinder();
640 status_t status;
641 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
642 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
643 }
644}
645
Eric Laurent81784c32012-11-19 14:55:58 -0800646void AudioFlinger::ThreadBase::clearPowerManager()
647{
648 Mutex::Autolock _l(mLock);
649 releaseWakeLock_l();
650 mPowerManager.clear();
651}
652
Glenn Kasten0f11b512014-01-31 16:18:54 -0800653void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
655 sp<ThreadBase> thread = mThread.promote();
656 if (thread != 0) {
657 thread->clearPowerManager();
658 }
659 ALOGW("power manager service died !!!");
660}
661
662void AudioFlinger::ThreadBase::setEffectSuspended(
663 const effect_uuid_t *type, bool suspend, int sessionId)
664{
665 Mutex::Autolock _l(mLock);
666 setEffectSuspended_l(type, suspend, sessionId);
667}
668
669void AudioFlinger::ThreadBase::setEffectSuspended_l(
670 const effect_uuid_t *type, bool suspend, int sessionId)
671{
672 sp<EffectChain> chain = getEffectChain_l(sessionId);
673 if (chain != 0) {
674 if (type != NULL) {
675 chain->setEffectSuspended_l(type, suspend);
676 } else {
677 chain->setEffectSuspendedAll_l(suspend);
678 }
679 }
680
681 updateSuspendedSessions_l(type, suspend, sessionId);
682}
683
684void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
685{
686 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
687 if (index < 0) {
688 return;
689 }
690
691 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
692 mSuspendedSessions.valueAt(index);
693
694 for (size_t i = 0; i < sessionEffects.size(); i++) {
695 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
696 for (int j = 0; j < desc->mRefCount; j++) {
697 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
698 chain->setEffectSuspendedAll_l(true);
699 } else {
700 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
701 desc->mType.timeLow);
702 chain->setEffectSuspended_l(&desc->mType, true);
703 }
704 }
705 }
706}
707
708void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
709 bool suspend,
710 int sessionId)
711{
712 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
713
714 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
715
716 if (suspend) {
717 if (index >= 0) {
718 sessionEffects = mSuspendedSessions.valueAt(index);
719 } else {
720 mSuspendedSessions.add(sessionId, sessionEffects);
721 }
722 } else {
723 if (index < 0) {
724 return;
725 }
726 sessionEffects = mSuspendedSessions.valueAt(index);
727 }
728
729
730 int key = EffectChain::kKeyForSuspendAll;
731 if (type != NULL) {
732 key = type->timeLow;
733 }
734 index = sessionEffects.indexOfKey(key);
735
736 sp<SuspendedSessionDesc> desc;
737 if (suspend) {
738 if (index >= 0) {
739 desc = sessionEffects.valueAt(index);
740 } else {
741 desc = new SuspendedSessionDesc();
742 if (type != NULL) {
743 desc->mType = *type;
744 }
745 sessionEffects.add(key, desc);
746 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
747 }
748 desc->mRefCount++;
749 } else {
750 if (index < 0) {
751 return;
752 }
753 desc = sessionEffects.valueAt(index);
754 if (--desc->mRefCount == 0) {
755 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
756 sessionEffects.removeItemsAt(index);
757 if (sessionEffects.isEmpty()) {
758 ALOGV("updateSuspendedSessions_l() restore removing session %d",
759 sessionId);
760 mSuspendedSessions.removeItem(sessionId);
761 }
762 }
763 }
764 if (!sessionEffects.isEmpty()) {
765 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
766 }
767}
768
769void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
770 bool enabled,
771 int sessionId)
772{
773 Mutex::Autolock _l(mLock);
774 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
775}
776
777void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
778 bool enabled,
779 int sessionId)
780{
781 if (mType != RECORD) {
782 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
783 // another session. This gives the priority to well behaved effect control panels
784 // and applications not using global effects.
785 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
786 // global effects
787 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
788 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
789 }
790 }
791
792 sp<EffectChain> chain = getEffectChain_l(sessionId);
793 if (chain != 0) {
794 chain->checkSuspendOnEffectEnabled(effect, enabled);
795 }
796}
797
798// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
799sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
800 const sp<AudioFlinger::Client>& client,
801 const sp<IEffectClient>& effectClient,
802 int32_t priority,
803 int sessionId,
804 effect_descriptor_t *desc,
805 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700806 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800807{
808 sp<EffectModule> effect;
809 sp<EffectHandle> handle;
810 status_t lStatus;
811 sp<EffectChain> chain;
812 bool chainCreated = false;
813 bool effectCreated = false;
814 bool effectRegistered = false;
815
816 lStatus = initCheck();
817 if (lStatus != NO_ERROR) {
818 ALOGW("createEffect_l() Audio driver not initialized.");
819 goto Exit;
820 }
821
Eric Laurent5baf2af2013-09-12 17:37:00 -0700822 // Allow global effects only on offloaded and mixer threads
823 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
824 switch (mType) {
825 case MIXER:
826 case OFFLOAD:
827 break;
828 case DIRECT:
829 case DUPLICATING:
830 case RECORD:
831 default:
832 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
833 lStatus = BAD_VALUE;
834 goto Exit;
835 }
Eric Laurent81784c32012-11-19 14:55:58 -0800836 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700837
Eric Laurent81784c32012-11-19 14:55:58 -0800838 // Only Pre processor effects are allowed on input threads and only on input threads
839 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
840 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
841 desc->name, desc->flags, mType);
842 lStatus = BAD_VALUE;
843 goto Exit;
844 }
845
846 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
847
848 { // scope for mLock
849 Mutex::Autolock _l(mLock);
850
851 // check for existing effect chain with the requested audio session
852 chain = getEffectChain_l(sessionId);
853 if (chain == 0) {
854 // create a new chain for this session
855 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
856 chain = new EffectChain(this, sessionId);
857 addEffectChain_l(chain);
858 chain->setStrategy(getStrategyForSession_l(sessionId));
859 chainCreated = true;
860 } else {
861 effect = chain->getEffectFromDesc_l(desc);
862 }
863
864 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
865
866 if (effect == 0) {
867 int id = mAudioFlinger->nextUniqueId();
868 // Check CPU and memory usage
869 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
870 if (lStatus != NO_ERROR) {
871 goto Exit;
872 }
873 effectRegistered = true;
874 // create a new effect module if none present in the chain
875 effect = new EffectModule(this, chain, desc, id, sessionId);
876 lStatus = effect->status();
877 if (lStatus != NO_ERROR) {
878 goto Exit;
879 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700880 effect->setOffloaded(mType == OFFLOAD, mId);
881
Eric Laurent81784c32012-11-19 14:55:58 -0800882 lStatus = chain->addEffect_l(effect);
883 if (lStatus != NO_ERROR) {
884 goto Exit;
885 }
886 effectCreated = true;
887
888 effect->setDevice(mOutDevice);
889 effect->setDevice(mInDevice);
890 effect->setMode(mAudioFlinger->getMode());
891 effect->setAudioSource(mAudioSource);
892 }
893 // create effect handle and connect it to effect module
894 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800895 lStatus = handle->initCheck();
896 if (lStatus == OK) {
897 lStatus = effect->addHandle(handle.get());
898 }
Eric Laurent81784c32012-11-19 14:55:58 -0800899 if (enabled != NULL) {
900 *enabled = (int)effect->isEnabled();
901 }
902 }
903
904Exit:
905 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
906 Mutex::Autolock _l(mLock);
907 if (effectCreated) {
908 chain->removeEffect_l(effect);
909 }
910 if (effectRegistered) {
911 AudioSystem::unregisterEffect(effect->id());
912 }
913 if (chainCreated) {
914 removeEffectChain_l(chain);
915 }
916 handle.clear();
917 }
918
Glenn Kasten9156ef32013-08-06 15:39:08 -0700919 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800920 return handle;
921}
922
923sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
924{
925 Mutex::Autolock _l(mLock);
926 return getEffect_l(sessionId, effectId);
927}
928
929sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
930{
931 sp<EffectChain> chain = getEffectChain_l(sessionId);
932 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
933}
934
935// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
936// PlaybackThread::mLock held
937status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
938{
939 // check for existing effect chain with the requested audio session
940 int sessionId = effect->sessionId();
941 sp<EffectChain> chain = getEffectChain_l(sessionId);
942 bool chainCreated = false;
943
Eric Laurent5baf2af2013-09-12 17:37:00 -0700944 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
945 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
946 this, effect->desc().name, effect->desc().flags);
947
Eric Laurent81784c32012-11-19 14:55:58 -0800948 if (chain == 0) {
949 // create a new chain for this session
950 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
951 chain = new EffectChain(this, sessionId);
952 addEffectChain_l(chain);
953 chain->setStrategy(getStrategyForSession_l(sessionId));
954 chainCreated = true;
955 }
956 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
957
958 if (chain->getEffectFromId_l(effect->id()) != 0) {
959 ALOGW("addEffect_l() %p effect %s already present in chain %p",
960 this, effect->desc().name, chain.get());
961 return BAD_VALUE;
962 }
963
Eric Laurent5baf2af2013-09-12 17:37:00 -0700964 effect->setOffloaded(mType == OFFLOAD, mId);
965
Eric Laurent81784c32012-11-19 14:55:58 -0800966 status_t status = chain->addEffect_l(effect);
967 if (status != NO_ERROR) {
968 if (chainCreated) {
969 removeEffectChain_l(chain);
970 }
971 return status;
972 }
973
974 effect->setDevice(mOutDevice);
975 effect->setDevice(mInDevice);
976 effect->setMode(mAudioFlinger->getMode());
977 effect->setAudioSource(mAudioSource);
978 return NO_ERROR;
979}
980
981void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
982
983 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
984 effect_descriptor_t desc = effect->desc();
985 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
986 detachAuxEffect_l(effect->id());
987 }
988
989 sp<EffectChain> chain = effect->chain().promote();
990 if (chain != 0) {
991 // remove effect chain if removing last effect
992 if (chain->removeEffect_l(effect) == 0) {
993 removeEffectChain_l(chain);
994 }
995 } else {
996 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
997 }
998}
999
1000void AudioFlinger::ThreadBase::lockEffectChains_l(
1001 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1002{
1003 effectChains = mEffectChains;
1004 for (size_t i = 0; i < mEffectChains.size(); i++) {
1005 mEffectChains[i]->lock();
1006 }
1007}
1008
1009void AudioFlinger::ThreadBase::unlockEffectChains(
1010 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1011{
1012 for (size_t i = 0; i < effectChains.size(); i++) {
1013 effectChains[i]->unlock();
1014 }
1015}
1016
1017sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1018{
1019 Mutex::Autolock _l(mLock);
1020 return getEffectChain_l(sessionId);
1021}
1022
1023sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1024{
1025 size_t size = mEffectChains.size();
1026 for (size_t i = 0; i < size; i++) {
1027 if (mEffectChains[i]->sessionId() == sessionId) {
1028 return mEffectChains[i];
1029 }
1030 }
1031 return 0;
1032}
1033
1034void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1035{
1036 Mutex::Autolock _l(mLock);
1037 size_t size = mEffectChains.size();
1038 for (size_t i = 0; i < size; i++) {
1039 mEffectChains[i]->setMode_l(mode);
1040 }
1041}
1042
1043void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1044 EffectHandle *handle,
1045 bool unpinIfLast) {
1046
1047 Mutex::Autolock _l(mLock);
1048 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1049 // delete the effect module if removing last handle on it
1050 if (effect->removeHandle(handle) == 0) {
1051 if (!effect->isPinned() || unpinIfLast) {
1052 removeEffect_l(effect);
1053 AudioSystem::unregisterEffect(effect->id());
1054 }
1055 }
1056}
1057
1058// ----------------------------------------------------------------------------
1059// Playback
1060// ----------------------------------------------------------------------------
1061
1062AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1063 AudioStreamOut* output,
1064 audio_io_handle_t id,
1065 audio_devices_t device,
1066 type_t type)
1067 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001068 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001069 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001070 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001071 // mStreamTypes[] initialized in constructor body
1072 mOutput(output),
1073 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1074 mMixerStatus(MIXER_IDLE),
1075 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1076 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001077 mBytesRemaining(0),
1078 mCurrentWriteLength(0),
1079 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001080 mWriteAckSequence(0),
1081 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001082 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001083 mScreenState(AudioFlinger::mScreenState),
1084 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001085 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1086 // mLatchD, mLatchQ,
1087 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001088{
1089 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001090 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001091
1092 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1093 // it would be safer to explicitly pass initial masterVolume/masterMute as
1094 // parameter.
1095 //
1096 // If the HAL we are using has support for master volume or master mute,
1097 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1098 // and the mute set to false).
1099 mMasterVolume = audioFlinger->masterVolume_l();
1100 mMasterMute = audioFlinger->masterMute_l();
1101 if (mOutput && mOutput->audioHwDev) {
1102 if (mOutput->audioHwDev->canSetMasterVolume()) {
1103 mMasterVolume = 1.0;
1104 }
1105
1106 if (mOutput->audioHwDev->canSetMasterMute()) {
1107 mMasterMute = false;
1108 }
1109 }
1110
1111 readOutputParameters();
1112
1113 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1114 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1115 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1116 stream = (audio_stream_type_t) (stream + 1)) {
1117 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1118 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1119 }
1120 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1121 // because mAudioFlinger doesn't have one to copy from
1122}
1123
1124AudioFlinger::PlaybackThread::~PlaybackThread()
1125{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001126 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001127 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001128}
1129
1130void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1131{
1132 dumpInternals(fd, args);
1133 dumpTracks(fd, args);
1134 dumpEffectChains(fd, args);
1135}
1136
Glenn Kasten0f11b512014-01-31 16:18:54 -08001137void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 const size_t SIZE = 256;
1140 char buffer[SIZE];
1141 String8 result;
1142
Marco Nelissenb2208842014-02-07 14:00:50 -08001143 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001144 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1145 const stream_type_t *st = &mStreamTypes[i];
1146 if (i > 0) {
1147 result.appendFormat(", ");
1148 }
1149 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1150 if (st->mute) {
1151 result.append("M");
1152 }
1153 }
1154 result.append("\n");
1155 write(fd, result.string(), result.length());
1156 result.clear();
1157
Eric Laurent81784c32012-11-19 14:55:58 -08001158 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1159 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001160 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001161 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001162
1163 size_t numtracks = mTracks.size();
1164 size_t numactive = mActiveTracks.size();
1165 fdprintf(fd, " %d Tracks", numtracks);
1166 size_t numactiveseen = 0;
1167 if (numtracks) {
1168 fdprintf(fd, " of which %d are active\n", numactive);
1169 Track::appendDumpHeader(result);
1170 for (size_t i = 0; i < numtracks; ++i) {
1171 sp<Track> track = mTracks[i];
1172 if (track != 0) {
1173 bool active = mActiveTracks.indexOf(track) >= 0;
1174 if (active) {
1175 numactiveseen++;
1176 }
1177 track->dump(buffer, SIZE, active);
1178 result.append(buffer);
1179 }
1180 }
1181 } else {
1182 result.append("\n");
1183 }
1184 if (numactiveseen != numactive) {
1185 // some tracks in the active list were not in the tracks list
1186 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1187 " not in the track list\n");
1188 result.append(buffer);
1189 Track::appendDumpHeader(result);
1190 for (size_t i = 0; i < numactive; ++i) {
1191 sp<Track> track = mActiveTracks[i].promote();
1192 if (track != 0 && mTracks.indexOf(track) < 0) {
1193 track->dump(buffer, SIZE, true);
1194 result.append(buffer);
1195 }
1196 }
1197 }
1198
1199 write(fd, result.string(), result.size());
1200
Eric Laurent81784c32012-11-19 14:55:58 -08001201}
1202
1203void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1204{
Marco Nelissenb2208842014-02-07 14:00:50 -08001205 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001206 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001207 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1208 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1209 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1210 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1211 fdprintf(fd, " Suspend count: %d\n", mSuspended);
1212 fdprintf(fd, " Mix buffer : %p\n", mMixBuffer);
1213 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001214
1215 dumpBase(fd, args);
1216}
1217
1218// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001219
1220void AudioFlinger::PlaybackThread::onFirstRef()
1221{
1222 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1223}
1224
1225// ThreadBase virtuals
1226void AudioFlinger::PlaybackThread::preExit()
1227{
1228 ALOGV(" preExit()");
1229 // FIXME this is using hard-coded strings but in the future, this functionality will be
1230 // converted to use audio HAL extensions required to support tunneling
1231 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1232}
1233
1234// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1235sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1236 const sp<AudioFlinger::Client>& client,
1237 audio_stream_type_t streamType,
1238 uint32_t sampleRate,
1239 audio_format_t format,
1240 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001241 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001242 const sp<IMemory>& sharedBuffer,
1243 int sessionId,
1244 IAudioFlinger::track_flags_t *flags,
1245 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001247 status_t *status)
1248{
Glenn Kasten74935e42013-12-19 08:56:45 -08001249 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001250 sp<Track> track;
1251 status_t lStatus;
1252
1253 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1254
1255 // client expresses a preference for FAST, but we get the final say
1256 if (*flags & IAudioFlinger::TRACK_FAST) {
1257 if (
1258 // not timed
1259 (!isTimed) &&
1260 // either of these use cases:
1261 (
1262 // use case 1: shared buffer with any frame count
1263 (
1264 (sharedBuffer != 0)
1265 ) ||
1266 // use case 2: callback handler and frame count is default or at least as large as HAL
1267 (
1268 (tid != -1) &&
1269 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001270 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001271 )
1272 ) &&
1273 // PCM data
1274 audio_is_linear_pcm(format) &&
1275 // mono or stereo
1276 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1277 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001278 // hardware sample rate
1279 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001280 // normal mixer has an associated fast mixer
1281 hasFastMixer() &&
1282 // there are sufficient fast track slots available
1283 (mFastTrackAvailMask != 0)
1284 // FIXME test that MixerThread for this fast track has a capable output HAL
1285 // FIXME add a permission test also?
1286 ) {
1287 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1288 if (frameCount == 0) {
1289 frameCount = mFrameCount * kFastTrackMultiplier;
1290 }
1291 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1292 frameCount, mFrameCount);
1293 } else {
1294 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1295 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1296 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1297 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1298 audio_is_linear_pcm(format),
1299 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1300 *flags &= ~IAudioFlinger::TRACK_FAST;
1301 // For compatibility with AudioTrack calculation, buffer depth is forced
1302 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1303 // This is probably too conservative, but legacy application code may depend on it.
1304 // If you change this calculation, also review the start threshold which is related.
1305 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1306 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1307 if (minBufCount < 2) {
1308 minBufCount = 2;
1309 }
1310 size_t minFrameCount = mNormalFrameCount * minBufCount;
1311 if (frameCount < minFrameCount) {
1312 frameCount = minFrameCount;
1313 }
1314 }
1315 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001316 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001317
1318 if (mType == DIRECT) {
1319 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1320 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001321 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1322 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001323 sampleRate, format, channelMask, mOutput, mFormat);
1324 lStatus = BAD_VALUE;
1325 goto Exit;
1326 }
1327 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001328 } else if (mType == OFFLOAD) {
1329 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001330 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1331 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001332 sampleRate, format, channelMask, mOutput, mFormat);
1333 lStatus = BAD_VALUE;
1334 goto Exit;
1335 }
Eric Laurent81784c32012-11-19 14:55:58 -08001336 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001337 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001338 ALOGE("createTrack_l() Bad parameter: format %#x \""
1339 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001340 format, mOutput, mFormat);
1341 lStatus = BAD_VALUE;
1342 goto Exit;
1343 }
Eric Laurent81784c32012-11-19 14:55:58 -08001344 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1345 if (sampleRate > mSampleRate*2) {
1346 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1347 lStatus = BAD_VALUE;
1348 goto Exit;
1349 }
1350 }
1351
1352 lStatus = initCheck();
1353 if (lStatus != NO_ERROR) {
1354 ALOGE("Audio driver not initialized.");
1355 goto Exit;
1356 }
1357
1358 { // scope for mLock
1359 Mutex::Autolock _l(mLock);
1360
1361 // all tracks in same audio session must share the same routing strategy otherwise
1362 // conflicts will happen when tracks are moved from one output to another by audio policy
1363 // manager
1364 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1365 for (size_t i = 0; i < mTracks.size(); ++i) {
1366 sp<Track> t = mTracks[i];
1367 if (t != 0 && !t->isOutputTrack()) {
1368 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1369 if (sessionId == t->sessionId() && strategy != actual) {
1370 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1371 strategy, actual);
1372 lStatus = BAD_VALUE;
1373 goto Exit;
1374 }
1375 }
1376 }
1377
1378 if (!isTimed) {
1379 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001380 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001381 } else {
1382 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001383 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001384 }
Glenn Kasten03003332013-08-06 15:40:54 -07001385
1386 // new Track always returns non-NULL,
1387 // but TimedTrack::create() is a factory that could fail by returning NULL
1388 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1389 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001390 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001391 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001392 goto Exit;
1393 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001394
Eric Laurent81784c32012-11-19 14:55:58 -08001395 mTracks.add(track);
1396
1397 sp<EffectChain> chain = getEffectChain_l(sessionId);
1398 if (chain != 0) {
1399 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1400 track->setMainBuffer(chain->inBuffer());
1401 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1402 chain->incTrackCnt();
1403 }
1404
1405 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1406 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1407 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1408 // so ask activity manager to do this on our behalf
1409 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1410 }
1411 }
1412
1413 lStatus = NO_ERROR;
1414
1415Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001416 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001417 return track;
1418}
1419
1420uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1421{
1422 return latency;
1423}
1424
1425uint32_t AudioFlinger::PlaybackThread::latency() const
1426{
1427 Mutex::Autolock _l(mLock);
1428 return latency_l();
1429}
1430uint32_t AudioFlinger::PlaybackThread::latency_l() const
1431{
1432 if (initCheck() == NO_ERROR) {
1433 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1434 } else {
1435 return 0;
1436 }
1437}
1438
1439void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1440{
1441 Mutex::Autolock _l(mLock);
1442 // Don't apply master volume in SW if our HAL can do it for us.
1443 if (mOutput && mOutput->audioHwDev &&
1444 mOutput->audioHwDev->canSetMasterVolume()) {
1445 mMasterVolume = 1.0;
1446 } else {
1447 mMasterVolume = value;
1448 }
1449}
1450
1451void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1452{
1453 Mutex::Autolock _l(mLock);
1454 // Don't apply master mute in SW if our HAL can do it for us.
1455 if (mOutput && mOutput->audioHwDev &&
1456 mOutput->audioHwDev->canSetMasterMute()) {
1457 mMasterMute = false;
1458 } else {
1459 mMasterMute = muted;
1460 }
1461}
1462
1463void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1464{
1465 Mutex::Autolock _l(mLock);
1466 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001467 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001468}
1469
1470void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1471{
1472 Mutex::Autolock _l(mLock);
1473 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001474 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001475}
1476
1477float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1478{
1479 Mutex::Autolock _l(mLock);
1480 return mStreamTypes[stream].volume;
1481}
1482
1483// addTrack_l() must be called with ThreadBase::mLock held
1484status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1485{
1486 status_t status = ALREADY_EXISTS;
1487
1488 // set retry count for buffer fill
1489 track->mRetryCount = kMaxTrackStartupRetries;
1490 if (mActiveTracks.indexOf(track) < 0) {
1491 // the track is newly added, make sure it fills up all its
1492 // buffers before playing. This is to ensure the client will
1493 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001494 if (!track->isOutputTrack()) {
1495 TrackBase::track_state state = track->mState;
1496 mLock.unlock();
1497 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1498 mLock.lock();
1499 // abort track was stopped/paused while we released the lock
1500 if (state != track->mState) {
1501 if (status == NO_ERROR) {
1502 mLock.unlock();
1503 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1504 mLock.lock();
1505 }
1506 return INVALID_OPERATION;
1507 }
1508 // abort if start is rejected by audio policy manager
1509 if (status != NO_ERROR) {
1510 return PERMISSION_DENIED;
1511 }
1512#ifdef ADD_BATTERY_DATA
1513 // to track the speaker usage
1514 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1515#endif
1516 }
1517
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001518 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001519 track->mResetDone = false;
1520 track->mPresentationCompleteFrames = 0;
1521 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001522 mWakeLockUids.add(track->uid());
1523 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001524 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001525 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1526 if (chain != 0) {
1527 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1528 track->sessionId());
1529 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001530 }
1531
1532 status = NO_ERROR;
1533 }
1534
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001535 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001536 return status;
1537}
1538
Eric Laurentbfb1b832013-01-07 09:53:42 -08001539bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001540{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001541 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001542 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001543 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1544 track->mState = TrackBase::STOPPED;
1545 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001546 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001547 } else if (track->isFastTrack() || track->isOffloaded()) {
1548 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001549 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001550
1551 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001552}
1553
1554void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1555{
1556 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1557 mTracks.remove(track);
1558 deleteTrackName_l(track->name());
1559 // redundant as track is about to be destroyed, for dumpsys only
1560 track->mName = -1;
1561 if (track->isFastTrack()) {
1562 int index = track->mFastIndex;
1563 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1564 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1565 mFastTrackAvailMask |= 1 << index;
1566 // redundant as track is about to be destroyed, for dumpsys only
1567 track->mFastIndex = -1;
1568 }
1569 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1570 if (chain != 0) {
1571 chain->decTrackCnt();
1572 }
1573}
1574
Eric Laurentede6c3b2013-09-19 14:37:46 -07001575void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001576{
1577 // Thread could be blocked waiting for async
1578 // so signal it to handle state changes immediately
1579 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1580 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1581 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001582 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001583}
1584
Eric Laurent81784c32012-11-19 14:55:58 -08001585String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1586{
Eric Laurent81784c32012-11-19 14:55:58 -08001587 Mutex::Autolock _l(mLock);
1588 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001589 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001590 }
1591
Glenn Kastend8ea6992013-07-16 14:17:15 -07001592 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1593 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 free(s);
1595 return out_s8;
1596}
1597
1598// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1599void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1600 AudioSystem::OutputDescriptor desc;
1601 void *param2 = NULL;
1602
1603 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1604 param);
1605
1606 switch (event) {
1607 case AudioSystem::OUTPUT_OPENED:
1608 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001609 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001610 desc.samplingRate = mSampleRate;
1611 desc.format = mFormat;
1612 desc.frameCount = mNormalFrameCount; // FIXME see
1613 // AudioFlinger::frameCount(audio_io_handle_t)
1614 desc.latency = latency();
1615 param2 = &desc;
1616 break;
1617
1618 case AudioSystem::STREAM_CONFIG_CHANGED:
1619 param2 = &param;
1620 case AudioSystem::OUTPUT_CLOSED:
1621 default:
1622 break;
1623 }
1624 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1625}
1626
Eric Laurentbfb1b832013-01-07 09:53:42 -08001627void AudioFlinger::PlaybackThread::writeCallback()
1628{
1629 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001630 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001631}
1632
1633void AudioFlinger::PlaybackThread::drainCallback()
1634{
1635 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001636 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001637}
1638
Eric Laurent3b4529e2013-09-05 18:09:19 -07001639void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001640{
1641 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001642 // reject out of sequence requests
1643 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1644 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645 mWaitWorkCV.signal();
1646 }
1647}
1648
Eric Laurent3b4529e2013-09-05 18:09:19 -07001649void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001650{
1651 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001652 // reject out of sequence requests
1653 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1654 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655 mWaitWorkCV.signal();
1656 }
1657}
1658
1659// static
1660int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001661 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001662 void *cookie)
1663{
1664 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1665 ALOGV("asyncCallback() event %d", event);
1666 switch (event) {
1667 case STREAM_CBK_EVENT_WRITE_READY:
1668 me->writeCallback();
1669 break;
1670 case STREAM_CBK_EVENT_DRAIN_READY:
1671 me->drainCallback();
1672 break;
1673 default:
1674 ALOGW("asyncCallback() unknown event %d", event);
1675 break;
1676 }
1677 return 0;
1678}
1679
Eric Laurent81784c32012-11-19 14:55:58 -08001680void AudioFlinger::PlaybackThread::readOutputParameters()
1681{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001682 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001683 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1684 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001685 if (!audio_is_output_channel(mChannelMask)) {
1686 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1687 }
1688 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1689 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1690 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1691 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001692 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001693 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001694 if (!audio_is_valid_format(mFormat)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001695 LOG_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001696 }
1697 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001698 LOG_FATAL("HAL format %#x not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001699 mFormat);
1700 }
Eric Laurent81784c32012-11-19 14:55:58 -08001701 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001702 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1703 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001704 if (mFrameCount & 15) {
1705 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1706 mFrameCount);
1707 }
1708
Eric Laurentbfb1b832013-01-07 09:53:42 -08001709 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1710 (mOutput->stream->set_callback != NULL)) {
1711 if (mOutput->stream->set_callback(mOutput->stream,
1712 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1713 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001714 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001715 }
1716 }
1717
Eric Laurent81784c32012-11-19 14:55:58 -08001718 // Calculate size of normal mix buffer relative to the HAL output buffer size
1719 double multiplier = 1.0;
1720 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1721 kUseFastMixer == FastMixer_Dynamic)) {
1722 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1723 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1724 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1725 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1726 maxNormalFrameCount = maxNormalFrameCount & ~15;
1727 if (maxNormalFrameCount < minNormalFrameCount) {
1728 maxNormalFrameCount = minNormalFrameCount;
1729 }
1730 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1731 if (multiplier <= 1.0) {
1732 multiplier = 1.0;
1733 } else if (multiplier <= 2.0) {
1734 if (2 * mFrameCount <= maxNormalFrameCount) {
1735 multiplier = 2.0;
1736 } else {
1737 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1738 }
1739 } else {
1740 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1741 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1742 // track, but we sometimes have to do this to satisfy the maximum frame count
1743 // constraint)
1744 // FIXME this rounding up should not be done if no HAL SRC
1745 uint32_t truncMult = (uint32_t) multiplier;
1746 if ((truncMult & 1)) {
1747 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1748 ++truncMult;
1749 }
1750 }
1751 multiplier = (double) truncMult;
1752 }
1753 }
1754 mNormalFrameCount = multiplier * mFrameCount;
1755 // round up to nearest 16 frames to satisfy AudioMixer
1756 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1757 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1758 mNormalFrameCount);
1759
Glenn Kastenc1fac192013-08-06 07:41:36 -07001760 delete[] mMixBuffer;
1761 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1762 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1763 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1764 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001765
1766 // force reconfiguration of effect chains and engines to take new buffer size and audio
1767 // parameters into account
1768 // Note that mLock is not held when readOutputParameters() is called from the constructor
1769 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1770 // matter.
1771 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1772 Vector< sp<EffectChain> > effectChains = mEffectChains;
1773 for (size_t i = 0; i < effectChains.size(); i ++) {
1774 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1775 }
1776}
1777
1778
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001779status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001780{
1781 if (halFrames == NULL || dspFrames == NULL) {
1782 return BAD_VALUE;
1783 }
1784 Mutex::Autolock _l(mLock);
1785 if (initCheck() != NO_ERROR) {
1786 return INVALID_OPERATION;
1787 }
1788 size_t framesWritten = mBytesWritten / mFrameSize;
1789 *halFrames = framesWritten;
1790
1791 if (isSuspended()) {
1792 // return an estimation of rendered frames when the output is suspended
1793 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1794 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1795 return NO_ERROR;
1796 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001797 status_t status;
1798 uint32_t frames;
1799 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1800 *dspFrames = (size_t)frames;
1801 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001802 }
1803}
1804
1805uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1806{
1807 Mutex::Autolock _l(mLock);
1808 uint32_t result = 0;
1809 if (getEffectChain_l(sessionId) != 0) {
1810 result = EFFECT_SESSION;
1811 }
1812
1813 for (size_t i = 0; i < mTracks.size(); ++i) {
1814 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001815 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001816 result |= TRACK_SESSION;
1817 break;
1818 }
1819 }
1820
1821 return result;
1822}
1823
1824uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1825{
1826 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1827 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1828 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1829 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1830 }
1831 for (size_t i = 0; i < mTracks.size(); i++) {
1832 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001833 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001834 return AudioSystem::getStrategyForStream(track->streamType());
1835 }
1836 }
1837 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1838}
1839
1840
1841AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1842{
1843 Mutex::Autolock _l(mLock);
1844 return mOutput;
1845}
1846
1847AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1848{
1849 Mutex::Autolock _l(mLock);
1850 AudioStreamOut *output = mOutput;
1851 mOutput = NULL;
1852 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1853 // must push a NULL and wait for ack
1854 mOutputSink.clear();
1855 mPipeSink.clear();
1856 mNormalSink.clear();
1857 return output;
1858}
1859
1860// this method must always be called either with ThreadBase mLock held or inside the thread loop
1861audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1862{
1863 if (mOutput == NULL) {
1864 return NULL;
1865 }
1866 return &mOutput->stream->common;
1867}
1868
1869uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1870{
1871 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1872}
1873
1874status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1875{
1876 if (!isValidSyncEvent(event)) {
1877 return BAD_VALUE;
1878 }
1879
1880 Mutex::Autolock _l(mLock);
1881
1882 for (size_t i = 0; i < mTracks.size(); ++i) {
1883 sp<Track> track = mTracks[i];
1884 if (event->triggerSession() == track->sessionId()) {
1885 (void) track->setSyncEvent(event);
1886 return NO_ERROR;
1887 }
1888 }
1889
1890 return NAME_NOT_FOUND;
1891}
1892
1893bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1894{
1895 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1896}
1897
1898void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1899 const Vector< sp<Track> >& tracksToRemove)
1900{
1901 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001902 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001903 for (size_t i = 0 ; i < count ; i++) {
1904 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001905 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001906 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001907#ifdef ADD_BATTERY_DATA
1908 // to track the speaker usage
1909 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1910#endif
1911 if (track->isTerminated()) {
1912 AudioSystem::releaseOutput(mId);
1913 }
Eric Laurent81784c32012-11-19 14:55:58 -08001914 }
1915 }
1916 }
Eric Laurent81784c32012-11-19 14:55:58 -08001917}
1918
1919void AudioFlinger::PlaybackThread::checkSilentMode_l()
1920{
1921 if (!mMasterMute) {
1922 char value[PROPERTY_VALUE_MAX];
1923 if (property_get("ro.audio.silent", value, "0") > 0) {
1924 char *endptr;
1925 unsigned long ul = strtoul(value, &endptr, 0);
1926 if (*endptr == '\0' && ul != 0) {
1927 ALOGD("Silence is golden");
1928 // The setprop command will not allow a property to be changed after
1929 // the first time it is set, so we don't have to worry about un-muting.
1930 setMasterMute_l(true);
1931 }
1932 }
1933 }
1934}
1935
1936// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001937ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001938{
1939 // FIXME rewrite to reduce number of system calls
1940 mLastWriteTime = systemTime();
1941 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001943
1944 // If an NBAIO sink is present, use it to write the normal mixer's submix
1945 if (mNormalSink != 0) {
1946#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 size_t count = mBytesRemaining >> mBitShift;
1948 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001949 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001950 // update the setpoint when AudioFlinger::mScreenState changes
1951 uint32_t screenState = AudioFlinger::mScreenState;
1952 if (screenState != mScreenState) {
1953 mScreenState = screenState;
1954 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1955 if (pipe != NULL) {
1956 pipe->setAvgFrames((mScreenState & 1) ?
1957 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1958 }
1959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001961 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001962 if (framesWritten > 0) {
1963 bytesWritten = framesWritten << mBitShift;
1964 } else {
1965 bytesWritten = framesWritten;
1966 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001967 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001968 if (status == NO_ERROR) {
1969 size_t totalFramesWritten = mNormalSink->framesWritten();
1970 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1971 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1972 mLatchDValid = true;
1973 }
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975 // otherwise use the HAL / AudioStreamOut directly
1976 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001977 // Direct output and offload threads
Eric Laurent04733db2013-11-22 09:29:56 -08001978 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001979 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001980 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1981 mWriteAckSequence += 2;
1982 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001983 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001984 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001986 // FIXME We should have an implementation of timestamps for direct output threads.
1987 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent04733db2013-11-22 09:29:56 -08001989 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001990 if (mUseAsyncWrite &&
1991 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1992 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001993 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001994 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001995 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001996 }
Eric Laurent81784c32012-11-19 14:55:58 -08001997 }
1998
Eric Laurent81784c32012-11-19 14:55:58 -08001999 mNumWrites++;
2000 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002001 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002002 return bytesWritten;
2003}
2004
2005void AudioFlinger::PlaybackThread::threadLoop_drain()
2006{
2007 if (mOutput->stream->drain) {
2008 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2009 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002010 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2011 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002012 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002013 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002014 }
2015 mOutput->stream->drain(mOutput->stream,
2016 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2017 : AUDIO_DRAIN_ALL);
2018 }
2019}
2020
2021void AudioFlinger::PlaybackThread::threadLoop_exit()
2022{
2023 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002024}
2025
2026/*
2027The derived values that are cached:
2028 - mixBufferSize from frame count * frame size
2029 - activeSleepTime from activeSleepTimeUs()
2030 - idleSleepTime from idleSleepTimeUs()
2031 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2032 - maxPeriod from frame count and sample rate (MIXER only)
2033
2034The parameters that affect these derived values are:
2035 - frame count
2036 - frame size
2037 - sample rate
2038 - device type: A2DP or not
2039 - device latency
2040 - format: PCM or not
2041 - active sleep time
2042 - idle sleep time
2043*/
2044
2045void AudioFlinger::PlaybackThread::cacheParameters_l()
2046{
2047 mixBufferSize = mNormalFrameCount * mFrameSize;
2048 activeSleepTime = activeSleepTimeUs();
2049 idleSleepTime = idleSleepTimeUs();
2050}
2051
2052void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2053{
Glenn Kasten7c027242012-12-26 14:43:16 -08002054 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002055 this, streamType, mTracks.size());
2056 Mutex::Autolock _l(mLock);
2057
2058 size_t size = mTracks.size();
2059 for (size_t i = 0; i < size; i++) {
2060 sp<Track> t = mTracks[i];
2061 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002062 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002063 }
2064 }
2065}
2066
2067status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2068{
2069 int session = chain->sessionId();
2070 int16_t *buffer = mMixBuffer;
2071 bool ownsBuffer = false;
2072
2073 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2074 if (session > 0) {
2075 // Only one effect chain can be present in direct output thread and it uses
2076 // the mix buffer as input
2077 if (mType != DIRECT) {
2078 size_t numSamples = mNormalFrameCount * mChannelCount;
2079 buffer = new int16_t[numSamples];
2080 memset(buffer, 0, numSamples * sizeof(int16_t));
2081 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2082 ownsBuffer = true;
2083 }
2084
2085 // Attach all tracks with same session ID to this chain.
2086 for (size_t i = 0; i < mTracks.size(); ++i) {
2087 sp<Track> track = mTracks[i];
2088 if (session == track->sessionId()) {
2089 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2090 buffer);
2091 track->setMainBuffer(buffer);
2092 chain->incTrackCnt();
2093 }
2094 }
2095
2096 // indicate all active tracks in the chain
2097 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2098 sp<Track> track = mActiveTracks[i].promote();
2099 if (track == 0) {
2100 continue;
2101 }
2102 if (session == track->sessionId()) {
2103 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2104 chain->incActiveTrackCnt();
2105 }
2106 }
2107 }
2108
2109 chain->setInBuffer(buffer, ownsBuffer);
2110 chain->setOutBuffer(mMixBuffer);
2111 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2112 // chains list in order to be processed last as it contains output stage effects
2113 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2114 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2115 // after track specific effects and before output stage
2116 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2117 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2118 // Effect chain for other sessions are inserted at beginning of effect
2119 // chains list to be processed before output mix effects. Relative order between other
2120 // sessions is not important
2121 size_t size = mEffectChains.size();
2122 size_t i = 0;
2123 for (i = 0; i < size; i++) {
2124 if (mEffectChains[i]->sessionId() < session) {
2125 break;
2126 }
2127 }
2128 mEffectChains.insertAt(chain, i);
2129 checkSuspendOnAddEffectChain_l(chain);
2130
2131 return NO_ERROR;
2132}
2133
2134size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2135{
2136 int session = chain->sessionId();
2137
2138 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2139
2140 for (size_t i = 0; i < mEffectChains.size(); i++) {
2141 if (chain == mEffectChains[i]) {
2142 mEffectChains.removeAt(i);
2143 // detach all active tracks from 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("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2151 chain.get(), session);
2152 chain->decActiveTrackCnt();
2153 }
2154 }
2155
2156 // detach all tracks with same session ID from this chain
2157 for (size_t i = 0; i < mTracks.size(); ++i) {
2158 sp<Track> track = mTracks[i];
2159 if (session == track->sessionId()) {
2160 track->setMainBuffer(mMixBuffer);
2161 chain->decTrackCnt();
2162 }
2163 }
2164 break;
2165 }
2166 }
2167 return mEffectChains.size();
2168}
2169
2170status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2171 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2172{
2173 Mutex::Autolock _l(mLock);
2174 return attachAuxEffect_l(track, EffectId);
2175}
2176
2177status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2178 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2179{
2180 status_t status = NO_ERROR;
2181
2182 if (EffectId == 0) {
2183 track->setAuxBuffer(0, NULL);
2184 } else {
2185 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2186 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2187 if (effect != 0) {
2188 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2189 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2190 } else {
2191 status = INVALID_OPERATION;
2192 }
2193 } else {
2194 status = BAD_VALUE;
2195 }
2196 }
2197 return status;
2198}
2199
2200void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2201{
2202 for (size_t i = 0; i < mTracks.size(); ++i) {
2203 sp<Track> track = mTracks[i];
2204 if (track->auxEffectId() == effectId) {
2205 attachAuxEffect_l(track, 0);
2206 }
2207 }
2208}
2209
2210bool AudioFlinger::PlaybackThread::threadLoop()
2211{
2212 Vector< sp<Track> > tracksToRemove;
2213
2214 standbyTime = systemTime();
2215
2216 // MIXER
2217 nsecs_t lastWarning = 0;
2218
2219 // DUPLICATING
2220 // FIXME could this be made local to while loop?
2221 writeFrames = 0;
2222
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002223 int lastGeneration = 0;
2224
Eric Laurent81784c32012-11-19 14:55:58 -08002225 cacheParameters_l();
2226 sleepTime = idleSleepTime;
2227
2228 if (mType == MIXER) {
2229 sleepTimeShift = 0;
2230 }
2231
2232 CpuStats cpuStats;
2233 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2234
2235 acquireWakeLock();
2236
Glenn Kasten9e58b552013-01-18 15:09:48 -08002237 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2238 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2239 // and then that string will be logged at the next convenient opportunity.
2240 const char *logString = NULL;
2241
Eric Laurent664539d2013-09-23 18:24:31 -07002242 checkSilentMode_l();
2243
Eric Laurent81784c32012-11-19 14:55:58 -08002244 while (!exitPending())
2245 {
2246 cpuStats.sample(myName);
2247
2248 Vector< sp<EffectChain> > effectChains;
2249
2250 processConfigEvents();
2251
2252 { // scope for mLock
2253
2254 Mutex::Autolock _l(mLock);
2255
Glenn Kasten9e58b552013-01-18 15:09:48 -08002256 if (logString != NULL) {
2257 mNBLogWriter->logTimestamp();
2258 mNBLogWriter->log(logString);
2259 logString = NULL;
2260 }
2261
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002262 if (mLatchDValid) {
2263 mLatchQ = mLatchD;
2264 mLatchDValid = false;
2265 mLatchQValid = true;
2266 }
2267
Eric Laurent81784c32012-11-19 14:55:58 -08002268 if (checkForNewParameters_l()) {
2269 cacheParameters_l();
2270 }
2271
2272 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 if (mSignalPending) {
2274 // A signal was raised while we were unlocked
2275 mSignalPending = false;
2276 } else if (waitingAsyncCallback_l()) {
2277 if (exitPending()) {
2278 break;
2279 }
2280 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002281 mWakeLockUids.clear();
2282 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 ALOGV("wait async completion");
2284 mWaitWorkCV.wait(mLock);
2285 ALOGV("async completion/wake");
2286 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002287 standbyTime = systemTime() + standbyDelay;
2288 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002289
2290 continue;
2291 }
2292 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002293 isSuspended()) {
2294 // put audio hardware into standby after short delay
2295 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002296
2297 threadLoop_standby();
2298
2299 mStandby = true;
2300 }
2301
2302 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2303 // we're about to wait, flush the binder command buffer
2304 IPCThreadState::self()->flushCommands();
2305
2306 clearOutputTracks();
2307
2308 if (exitPending()) {
2309 break;
2310 }
2311
2312 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002313 mWakeLockUids.clear();
2314 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002315 // wait until we have something to do...
2316 ALOGV("%s going to sleep", myName.string());
2317 mWaitWorkCV.wait(mLock);
2318 ALOGV("%s waking up", myName.string());
2319 acquireWakeLock_l();
2320
2321 mMixerStatus = MIXER_IDLE;
2322 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2323 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002325 checkSilentMode_l();
2326
2327 standbyTime = systemTime() + standbyDelay;
2328 sleepTime = idleSleepTime;
2329 if (mType == MIXER) {
2330 sleepTimeShift = 0;
2331 }
2332
2333 continue;
2334 }
2335 }
Eric Laurent81784c32012-11-19 14:55:58 -08002336 // mMixerStatusIgnoringFastTracks is also updated internally
2337 mMixerStatus = prepareTracks_l(&tracksToRemove);
2338
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002339 // compare with previously applied list
2340 if (lastGeneration != mActiveTracksGeneration) {
2341 // update wakelock
2342 updateWakeLockUids_l(mWakeLockUids);
2343 lastGeneration = mActiveTracksGeneration;
2344 }
2345
Eric Laurent81784c32012-11-19 14:55:58 -08002346 // prevent any changes in effect chain list and in each effect chain
2347 // during mixing and effect process as the audio buffers could be deleted
2348 // or modified if an effect is created or deleted
2349 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002350 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002351
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 if (mBytesRemaining == 0) {
2353 mCurrentWriteLength = 0;
2354 if (mMixerStatus == MIXER_TRACKS_READY) {
2355 // threadLoop_mix() sets mCurrentWriteLength
2356 threadLoop_mix();
2357 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2358 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2359 // threadLoop_sleepTime sets sleepTime to 0 if data
2360 // must be written to HAL
2361 threadLoop_sleepTime();
2362 if (sleepTime == 0) {
2363 mCurrentWriteLength = mixBufferSize;
2364 }
2365 }
2366 mBytesRemaining = mCurrentWriteLength;
2367 if (isSuspended()) {
2368 sleepTime = suspendSleepTimeUs();
2369 // simulate write to HAL when suspended
2370 mBytesWritten += mixBufferSize;
2371 mBytesRemaining = 0;
2372 }
Eric Laurent81784c32012-11-19 14:55:58 -08002373
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002375 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 for (size_t i = 0; i < effectChains.size(); i ++) {
2377 effectChains[i]->process_l();
2378 }
Eric Laurent81784c32012-11-19 14:55:58 -08002379 }
2380 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002381 // Process effect chains for offloaded thread even if no audio
2382 // was read from audio track: process only updates effect state
2383 // and thus does have to be synchronized with audio writes but may have
2384 // to be called while waiting for async write callback
2385 if (mType == OFFLOAD) {
2386 for (size_t i = 0; i < effectChains.size(); i ++) {
2387 effectChains[i]->process_l();
2388 }
2389 }
Eric Laurent81784c32012-11-19 14:55:58 -08002390
2391 // enable changes in effect chain
2392 unlockEffectChains(effectChains);
2393
Eric Laurentbfb1b832013-01-07 09:53:42 -08002394 if (!waitingAsyncCallback()) {
2395 // sleepTime == 0 means we must write to audio hardware
2396 if (sleepTime == 0) {
2397 if (mBytesRemaining) {
2398 ssize_t ret = threadLoop_write();
2399 if (ret < 0) {
2400 mBytesRemaining = 0;
2401 } else {
2402 mBytesWritten += ret;
2403 mBytesRemaining -= ret;
2404 }
2405 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2406 (mMixerStatus == MIXER_DRAIN_ALL)) {
2407 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002408 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002409 if (mType == MIXER) {
2410 // write blocked detection
2411 nsecs_t now = systemTime();
2412 nsecs_t delta = now - mLastWriteTime;
2413 if (!mStandby && delta > maxPeriod) {
2414 mNumDelayedWrites++;
2415 if ((now - lastWarning) > kWarningThrottleNs) {
2416 ATRACE_NAME("underrun");
2417 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2418 ns2ms(delta), mNumDelayedWrites, this);
2419 lastWarning = now;
2420 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002421 }
2422 }
Eric Laurent81784c32012-11-19 14:55:58 -08002423
Eric Laurentbfb1b832013-01-07 09:53:42 -08002424 } else {
2425 usleep(sleepTime);
2426 }
Eric Laurent81784c32012-11-19 14:55:58 -08002427 }
2428
2429 // Finally let go of removed track(s), without the lock held
2430 // since we can't guarantee the destructors won't acquire that
2431 // same lock. This will also mutate and push a new fast mixer state.
2432 threadLoop_removeTracks(tracksToRemove);
2433 tracksToRemove.clear();
2434
2435 // FIXME I don't understand the need for this here;
2436 // it was in the original code but maybe the
2437 // assignment in saveOutputTracks() makes this unnecessary?
2438 clearOutputTracks();
2439
2440 // Effect chains will be actually deleted here if they were removed from
2441 // mEffectChains list during mixing or effects processing
2442 effectChains.clear();
2443
2444 // FIXME Note that the above .clear() is no longer necessary since effectChains
2445 // is now local to this block, but will keep it for now (at least until merge done).
2446 }
2447
Eric Laurentbfb1b832013-01-07 09:53:42 -08002448 threadLoop_exit();
2449
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // put output stream into standby mode
2453 if (!mStandby) {
2454 mOutput->stream->common.standby(&mOutput->stream->common);
2455 }
2456 }
2457
2458 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002459 mWakeLockUids.clear();
2460 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002461
2462 ALOGV("Thread %p type %d exiting", this, mType);
2463 return false;
2464}
2465
Eric Laurentbfb1b832013-01-07 09:53:42 -08002466// removeTracks_l() must be called with ThreadBase::mLock held
2467void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2468{
2469 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002470 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002471 for (size_t i=0 ; i<count ; i++) {
2472 const sp<Track>& track = tracksToRemove.itemAt(i);
2473 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002474 mWakeLockUids.remove(track->uid());
2475 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002476 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2477 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2478 if (chain != 0) {
2479 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2480 track->sessionId());
2481 chain->decActiveTrackCnt();
2482 }
2483 if (track->isTerminated()) {
2484 removeTrack_l(track);
2485 }
2486 }
2487 }
2488
2489}
Eric Laurent81784c32012-11-19 14:55:58 -08002490
Eric Laurentaccc1472013-09-20 09:36:34 -07002491status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2492{
2493 if (mNormalSink != 0) {
2494 return mNormalSink->getTimestamp(timestamp);
2495 }
2496 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2497 uint64_t position64;
2498 int ret = mOutput->stream->get_presentation_position(
2499 mOutput->stream, &position64, &timestamp.mTime);
2500 if (ret == 0) {
2501 timestamp.mPosition = (uint32_t)position64;
2502 return NO_ERROR;
2503 }
2504 }
2505 return INVALID_OPERATION;
2506}
Eric Laurent81784c32012-11-19 14:55:58 -08002507// ----------------------------------------------------------------------------
2508
2509AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2510 audio_io_handle_t id, audio_devices_t device, type_t type)
2511 : PlaybackThread(audioFlinger, output, id, device, type),
2512 // mAudioMixer below
2513 // mFastMixer below
2514 mFastMixerFutex(0)
2515 // mOutputSink below
2516 // mPipeSink below
2517 // mNormalSink below
2518{
2519 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002520 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002521 "mFrameCount=%d, mNormalFrameCount=%d",
2522 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2523 mNormalFrameCount);
2524 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2525
2526 // FIXME - Current mixer implementation only supports stereo output
2527 if (mChannelCount != FCC_2) {
2528 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2529 }
2530
2531 // create an NBAIO sink for the HAL output stream, and negotiate
2532 mOutputSink = new AudioStreamOutSink(output->stream);
2533 size_t numCounterOffers = 0;
2534 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2535 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2536 ALOG_ASSERT(index == 0);
2537
2538 // initialize fast mixer depending on configuration
2539 bool initFastMixer;
2540 switch (kUseFastMixer) {
2541 case FastMixer_Never:
2542 initFastMixer = false;
2543 break;
2544 case FastMixer_Always:
2545 initFastMixer = true;
2546 break;
2547 case FastMixer_Static:
2548 case FastMixer_Dynamic:
2549 initFastMixer = mFrameCount < mNormalFrameCount;
2550 break;
2551 }
2552 if (initFastMixer) {
2553
2554 // create a MonoPipe to connect our submix to FastMixer
2555 NBAIO_Format format = mOutputSink->format();
2556 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2557 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2558 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2559 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2560 const NBAIO_Format offers[1] = {format};
2561 size_t numCounterOffers = 0;
2562 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2563 ALOG_ASSERT(index == 0);
2564 monoPipe->setAvgFrames((mScreenState & 1) ?
2565 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2566 mPipeSink = monoPipe;
2567
Glenn Kasten46909e72013-02-26 09:20:22 -08002568#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002569 if (mTeeSinkOutputEnabled) {
2570 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2571 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2572 numCounterOffers = 0;
2573 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2574 ALOG_ASSERT(index == 0);
2575 mTeeSink = teeSink;
2576 PipeReader *teeSource = new PipeReader(*teeSink);
2577 numCounterOffers = 0;
2578 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2579 ALOG_ASSERT(index == 0);
2580 mTeeSource = teeSource;
2581 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002582#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002583
2584 // create fast mixer and configure it initially with just one fast track for our submix
2585 mFastMixer = new FastMixer();
2586 FastMixerStateQueue *sq = mFastMixer->sq();
2587#ifdef STATE_QUEUE_DUMP
2588 sq->setObserverDump(&mStateQueueObserverDump);
2589 sq->setMutatorDump(&mStateQueueMutatorDump);
2590#endif
2591 FastMixerState *state = sq->begin();
2592 FastTrack *fastTrack = &state->mFastTracks[0];
2593 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2594 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2595 fastTrack->mVolumeProvider = NULL;
2596 fastTrack->mGeneration++;
2597 state->mFastTracksGen++;
2598 state->mTrackMask = 1;
2599 // fast mixer will use the HAL output sink
2600 state->mOutputSink = mOutputSink.get();
2601 state->mOutputSinkGen++;
2602 state->mFrameCount = mFrameCount;
2603 state->mCommand = FastMixerState::COLD_IDLE;
2604 // already done in constructor initialization list
2605 //mFastMixerFutex = 0;
2606 state->mColdFutexAddr = &mFastMixerFutex;
2607 state->mColdGen++;
2608 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002609#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002610 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002611#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002612 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2613 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002614 sq->end();
2615 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2616
2617 // start the fast mixer
2618 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2619 pid_t tid = mFastMixer->getTid();
2620 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2621 if (err != 0) {
2622 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2623 kPriorityFastMixer, getpid_cached, tid, err);
2624 }
2625
2626#ifdef AUDIO_WATCHDOG
2627 // create and start the watchdog
2628 mAudioWatchdog = new AudioWatchdog();
2629 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2630 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2631 tid = mAudioWatchdog->getTid();
2632 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2633 if (err != 0) {
2634 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2635 kPriorityFastMixer, getpid_cached, tid, err);
2636 }
2637#endif
2638
2639 } else {
2640 mFastMixer = NULL;
2641 }
2642
2643 switch (kUseFastMixer) {
2644 case FastMixer_Never:
2645 case FastMixer_Dynamic:
2646 mNormalSink = mOutputSink;
2647 break;
2648 case FastMixer_Always:
2649 mNormalSink = mPipeSink;
2650 break;
2651 case FastMixer_Static:
2652 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2653 break;
2654 }
2655}
2656
2657AudioFlinger::MixerThread::~MixerThread()
2658{
2659 if (mFastMixer != NULL) {
2660 FastMixerStateQueue *sq = mFastMixer->sq();
2661 FastMixerState *state = sq->begin();
2662 if (state->mCommand == FastMixerState::COLD_IDLE) {
2663 int32_t old = android_atomic_inc(&mFastMixerFutex);
2664 if (old == -1) {
2665 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2666 }
2667 }
2668 state->mCommand = FastMixerState::EXIT;
2669 sq->end();
2670 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2671 mFastMixer->join();
2672 // Though the fast mixer thread has exited, it's state queue is still valid.
2673 // We'll use that extract the final state which contains one remaining fast track
2674 // corresponding to our sub-mix.
2675 state = sq->begin();
2676 ALOG_ASSERT(state->mTrackMask == 1);
2677 FastTrack *fastTrack = &state->mFastTracks[0];
2678 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2679 delete fastTrack->mBufferProvider;
2680 sq->end(false /*didModify*/);
2681 delete mFastMixer;
2682#ifdef AUDIO_WATCHDOG
2683 if (mAudioWatchdog != 0) {
2684 mAudioWatchdog->requestExit();
2685 mAudioWatchdog->requestExitAndWait();
2686 mAudioWatchdog.clear();
2687 }
2688#endif
2689 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002690 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002691 delete mAudioMixer;
2692}
2693
2694
2695uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2696{
2697 if (mFastMixer != NULL) {
2698 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2699 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2700 }
2701 return latency;
2702}
2703
2704
2705void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2706{
2707 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2708}
2709
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002711{
2712 // FIXME we should only do one push per cycle; confirm this is true
2713 // Start the fast mixer if it's not already running
2714 if (mFastMixer != NULL) {
2715 FastMixerStateQueue *sq = mFastMixer->sq();
2716 FastMixerState *state = sq->begin();
2717 if (state->mCommand != FastMixerState::MIX_WRITE &&
2718 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2719 if (state->mCommand == FastMixerState::COLD_IDLE) {
2720 int32_t old = android_atomic_inc(&mFastMixerFutex);
2721 if (old == -1) {
2722 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2723 }
2724#ifdef AUDIO_WATCHDOG
2725 if (mAudioWatchdog != 0) {
2726 mAudioWatchdog->resume();
2727 }
2728#endif
2729 }
2730 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002731 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2732 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002733 sq->end();
2734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2735 if (kUseFastMixer == FastMixer_Dynamic) {
2736 mNormalSink = mPipeSink;
2737 }
2738 } else {
2739 sq->end(false /*didModify*/);
2740 }
2741 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002743}
2744
2745void AudioFlinger::MixerThread::threadLoop_standby()
2746{
2747 // Idle the fast mixer if it's currently running
2748 if (mFastMixer != NULL) {
2749 FastMixerStateQueue *sq = mFastMixer->sq();
2750 FastMixerState *state = sq->begin();
2751 if (!(state->mCommand & FastMixerState::IDLE)) {
2752 state->mCommand = FastMixerState::COLD_IDLE;
2753 state->mColdFutexAddr = &mFastMixerFutex;
2754 state->mColdGen++;
2755 mFastMixerFutex = 0;
2756 sq->end();
2757 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2758 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2759 if (kUseFastMixer == FastMixer_Dynamic) {
2760 mNormalSink = mOutputSink;
2761 }
2762#ifdef AUDIO_WATCHDOG
2763 if (mAudioWatchdog != 0) {
2764 mAudioWatchdog->pause();
2765 }
2766#endif
2767 } else {
2768 sq->end(false /*didModify*/);
2769 }
2770 }
2771 PlaybackThread::threadLoop_standby();
2772}
2773
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2775{
2776 return false;
2777}
2778
2779bool AudioFlinger::PlaybackThread::shouldStandby_l()
2780{
2781 return !mStandby;
2782}
2783
2784bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2785{
2786 Mutex::Autolock _l(mLock);
2787 return waitingAsyncCallback_l();
2788}
2789
Eric Laurent81784c32012-11-19 14:55:58 -08002790// shared by MIXER and DIRECT, overridden by DUPLICATING
2791void AudioFlinger::PlaybackThread::threadLoop_standby()
2792{
2793 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2794 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002796 // discard any pending drain or write ack by incrementing sequence
2797 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2798 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002800 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2801 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002802 }
Eric Laurent81784c32012-11-19 14:55:58 -08002803}
2804
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002805void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2806{
2807 ALOGV("signal playback thread");
2808 broadcast_l();
2809}
2810
Eric Laurent81784c32012-11-19 14:55:58 -08002811void AudioFlinger::MixerThread::threadLoop_mix()
2812{
2813 // obtain the presentation timestamp of the next output buffer
2814 int64_t pts;
2815 status_t status = INVALID_OPERATION;
2816
2817 if (mNormalSink != 0) {
2818 status = mNormalSink->getNextWriteTimestamp(&pts);
2819 } else {
2820 status = mOutputSink->getNextWriteTimestamp(&pts);
2821 }
2822
2823 if (status != NO_ERROR) {
2824 pts = AudioBufferProvider::kInvalidPTS;
2825 }
2826
2827 // mix buffers...
2828 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002830 // increase sleep time progressively when application underrun condition clears.
2831 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2832 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2833 // such that we would underrun the audio HAL.
2834 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2835 sleepTimeShift--;
2836 }
2837 sleepTime = 0;
2838 standbyTime = systemTime() + standbyDelay;
2839 //TODO: delay standby when effects have a tail
2840}
2841
2842void AudioFlinger::MixerThread::threadLoop_sleepTime()
2843{
2844 // If no tracks are ready, sleep once for the duration of an output
2845 // buffer size, then write 0s to the output
2846 if (sleepTime == 0) {
2847 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2848 sleepTime = activeSleepTime >> sleepTimeShift;
2849 if (sleepTime < kMinThreadSleepTimeUs) {
2850 sleepTime = kMinThreadSleepTimeUs;
2851 }
2852 // reduce sleep time in case of consecutive application underruns to avoid
2853 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2854 // duration we would end up writing less data than needed by the audio HAL if
2855 // the condition persists.
2856 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2857 sleepTimeShift++;
2858 }
2859 } else {
2860 sleepTime = idleSleepTime;
2861 }
2862 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002863 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002864 sleepTime = 0;
2865 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2866 "anticipated start");
2867 }
2868 // TODO add standby time extension fct of effect tail
2869}
2870
2871// prepareTracks_l() must be called with ThreadBase::mLock held
2872AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2873 Vector< sp<Track> > *tracksToRemove)
2874{
2875
2876 mixer_state mixerStatus = MIXER_IDLE;
2877 // find out which tracks need to be processed
2878 size_t count = mActiveTracks.size();
2879 size_t mixedTracks = 0;
2880 size_t tracksWithEffect = 0;
2881 // counts only _active_ fast tracks
2882 size_t fastTracks = 0;
2883 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2884
2885 float masterVolume = mMasterVolume;
2886 bool masterMute = mMasterMute;
2887
2888 if (masterMute) {
2889 masterVolume = 0;
2890 }
2891 // Delegate master volume control to effect in output mix effect chain if needed
2892 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2893 if (chain != 0) {
2894 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2895 chain->setVolume_l(&v, &v);
2896 masterVolume = (float)((v + (1 << 23)) >> 24);
2897 chain.clear();
2898 }
2899
2900 // prepare a new state to push
2901 FastMixerStateQueue *sq = NULL;
2902 FastMixerState *state = NULL;
2903 bool didModify = false;
2904 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2905 if (mFastMixer != NULL) {
2906 sq = mFastMixer->sq();
2907 state = sq->begin();
2908 }
2909
2910 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002911 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002912 if (t == 0) {
2913 continue;
2914 }
2915
2916 // this const just means the local variable doesn't change
2917 Track* const track = t.get();
2918
2919 // process fast tracks
2920 if (track->isFastTrack()) {
2921
2922 // It's theoretically possible (though unlikely) for a fast track to be created
2923 // and then removed within the same normal mix cycle. This is not a problem, as
2924 // the track never becomes active so it's fast mixer slot is never touched.
2925 // The converse, of removing an (active) track and then creating a new track
2926 // at the identical fast mixer slot within the same normal mix cycle,
2927 // is impossible because the slot isn't marked available until the end of each cycle.
2928 int j = track->mFastIndex;
2929 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2930 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2931 FastTrack *fastTrack = &state->mFastTracks[j];
2932
2933 // Determine whether the track is currently in underrun condition,
2934 // and whether it had a recent underrun.
2935 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2936 FastTrackUnderruns underruns = ftDump->mUnderruns;
2937 uint32_t recentFull = (underruns.mBitFields.mFull -
2938 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2939 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2940 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2941 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2942 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2943 uint32_t recentUnderruns = recentPartial + recentEmpty;
2944 track->mObservedUnderruns = underruns;
2945 // don't count underruns that occur while stopping or pausing
2946 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002947 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2948 recentUnderruns > 0) {
2949 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2950 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002951 }
2952
2953 // This is similar to the state machine for normal tracks,
2954 // with a few modifications for fast tracks.
2955 bool isActive = true;
2956 switch (track->mState) {
2957 case TrackBase::STOPPING_1:
2958 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002960 track->mState = TrackBase::STOPPING_2;
2961 }
2962 break;
2963 case TrackBase::PAUSING:
2964 // ramp down is not yet implemented
2965 track->setPaused();
2966 break;
2967 case TrackBase::RESUMING:
2968 // ramp up is not yet implemented
2969 track->mState = TrackBase::ACTIVE;
2970 break;
2971 case TrackBase::ACTIVE:
2972 if (recentFull > 0 || recentPartial > 0) {
2973 // track has provided at least some frames recently: reset retry count
2974 track->mRetryCount = kMaxTrackRetries;
2975 }
2976 if (recentUnderruns == 0) {
2977 // no recent underruns: stay active
2978 break;
2979 }
2980 // there has recently been an underrun of some kind
2981 if (track->sharedBuffer() == 0) {
2982 // were any of the recent underruns "empty" (no frames available)?
2983 if (recentEmpty == 0) {
2984 // no, then ignore the partial underruns as they are allowed indefinitely
2985 break;
2986 }
2987 // there has recently been an "empty" underrun: decrement the retry counter
2988 if (--(track->mRetryCount) > 0) {
2989 break;
2990 }
2991 // indicate to client process that the track was disabled because of underrun;
2992 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002993 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002994 // remove from active list, but state remains ACTIVE [confusing but true]
2995 isActive = false;
2996 break;
2997 }
2998 // fall through
2999 case TrackBase::STOPPING_2:
3000 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003001 case TrackBase::STOPPED:
3002 case TrackBase::FLUSHED: // flush() while active
3003 // Check for presentation complete if track is inactive
3004 // We have consumed all the buffers of this track.
3005 // This would be incomplete if we auto-paused on underrun
3006 {
3007 size_t audioHALFrames =
3008 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3009 size_t framesWritten = mBytesWritten / mFrameSize;
3010 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3011 // track stays in active list until presentation is complete
3012 break;
3013 }
3014 }
3015 if (track->isStopping_2()) {
3016 track->mState = TrackBase::STOPPED;
3017 }
3018 if (track->isStopped()) {
3019 // Can't reset directly, as fast mixer is still polling this track
3020 // track->reset();
3021 // So instead mark this track as needing to be reset after push with ack
3022 resetMask |= 1 << i;
3023 }
3024 isActive = false;
3025 break;
3026 case TrackBase::IDLE:
3027 default:
3028 LOG_FATAL("unexpected track state %d", track->mState);
3029 }
3030
3031 if (isActive) {
3032 // was it previously inactive?
3033 if (!(state->mTrackMask & (1 << j))) {
3034 ExtendedAudioBufferProvider *eabp = track;
3035 VolumeProvider *vp = track;
3036 fastTrack->mBufferProvider = eabp;
3037 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003038 fastTrack->mChannelMask = track->mChannelMask;
3039 fastTrack->mGeneration++;
3040 state->mTrackMask |= 1 << j;
3041 didModify = true;
3042 // no acknowledgement required for newly active tracks
3043 }
3044 // cache the combined master volume and stream type volume for fast mixer; this
3045 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003046 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003047 ++fastTracks;
3048 } else {
3049 // was it previously active?
3050 if (state->mTrackMask & (1 << j)) {
3051 fastTrack->mBufferProvider = NULL;
3052 fastTrack->mGeneration++;
3053 state->mTrackMask &= ~(1 << j);
3054 didModify = true;
3055 // If any fast tracks were removed, we must wait for acknowledgement
3056 // because we're about to decrement the last sp<> on those tracks.
3057 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3058 } else {
3059 LOG_FATAL("fast track %d should have been active", j);
3060 }
3061 tracksToRemove->add(track);
3062 // Avoids a misleading display in dumpsys
3063 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3064 }
3065 continue;
3066 }
3067
3068 { // local variable scope to avoid goto warning
3069
3070 audio_track_cblk_t* cblk = track->cblk();
3071
3072 // The first time a track is added we wait
3073 // for all its buffers to be filled before processing it
3074 int name = track->name();
3075 // make sure that we have enough frames to mix one full buffer.
3076 // enforce this condition only once to enable draining the buffer in case the client
3077 // app does not call stop() and relies on underrun to stop:
3078 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3079 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003080 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003081 uint32_t sr = track->sampleRate();
3082 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003083 desiredFrames = mNormalFrameCount;
3084 } else {
3085 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003086 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003087 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003088 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003089 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003090#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003091 // the minimum track buffer size is normally twice the number of frames necessary
3092 // to fill one buffer and the resampler should not leave more than one buffer worth
3093 // of unreleased frames after each pass, but just in case...
3094 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003095#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003096 }
Eric Laurent81784c32012-11-19 14:55:58 -08003097 uint32_t minFrames = 1;
3098 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3099 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003100 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003101 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003102
3103 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003104 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003105 !track->isPaused() && !track->isTerminated())
3106 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003107 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003108
3109 mixedTracks++;
3110
3111 // track->mainBuffer() != mMixBuffer means there is an effect chain
3112 // connected to the track
3113 chain.clear();
3114 if (track->mainBuffer() != mMixBuffer) {
3115 chain = getEffectChain_l(track->sessionId());
3116 // Delegate volume control to effect in track effect chain if needed
3117 if (chain != 0) {
3118 tracksWithEffect++;
3119 } else {
3120 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3121 "session %d",
3122 name, track->sessionId());
3123 }
3124 }
3125
3126
3127 int param = AudioMixer::VOLUME;
3128 if (track->mFillingUpStatus == Track::FS_FILLED) {
3129 // no ramp for the first volume setting
3130 track->mFillingUpStatus = Track::FS_ACTIVE;
3131 if (track->mState == TrackBase::RESUMING) {
3132 track->mState = TrackBase::ACTIVE;
3133 param = AudioMixer::RAMP_VOLUME;
3134 }
3135 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003136 // FIXME should not make a decision based on mServer
3137 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003138 // If the track is stopped before the first frame was mixed,
3139 // do not apply ramp
3140 param = AudioMixer::RAMP_VOLUME;
3141 }
3142
3143 // compute volume for this track
3144 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003145 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003146 vl = vr = va = 0;
3147 if (track->isPausing()) {
3148 track->setPaused();
3149 }
3150 } else {
3151
3152 // read original volumes with volume control
3153 float typeVolume = mStreamTypes[track->streamType()].volume;
3154 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003155 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003156 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003157 vl = vlr & 0xFFFF;
3158 vr = vlr >> 16;
3159 // track volumes come from shared memory, so can't be trusted and must be clamped
3160 if (vl > MAX_GAIN_INT) {
3161 ALOGV("Track left volume out of range: %04X", vl);
3162 vl = MAX_GAIN_INT;
3163 }
3164 if (vr > MAX_GAIN_INT) {
3165 ALOGV("Track right volume out of range: %04X", vr);
3166 vr = MAX_GAIN_INT;
3167 }
3168 // now apply the master volume and stream type volume
3169 vl = (uint32_t)(v * vl) << 12;
3170 vr = (uint32_t)(v * vr) << 12;
3171 // assuming master volume and stream type volume each go up to 1.0,
3172 // vl and vr are now in 8.24 format
3173
Glenn Kastene3aa6592012-12-04 12:22:46 -08003174 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003175 // send level comes from shared memory and so may be corrupt
3176 if (sendLevel > MAX_GAIN_INT) {
3177 ALOGV("Track send level out of range: %04X", sendLevel);
3178 sendLevel = MAX_GAIN_INT;
3179 }
3180 va = (uint32_t)(v * sendLevel);
3181 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182
Eric Laurent81784c32012-11-19 14:55:58 -08003183 // Delegate volume control to effect in track effect chain if needed
3184 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3185 // Do not ramp volume if volume is controlled by effect
3186 param = AudioMixer::VOLUME;
3187 track->mHasVolumeController = true;
3188 } else {
3189 // force no volume ramp when volume controller was just disabled or removed
3190 // from effect chain to avoid volume spike
3191 if (track->mHasVolumeController) {
3192 param = AudioMixer::VOLUME;
3193 }
3194 track->mHasVolumeController = false;
3195 }
3196
3197 // Convert volumes from 8.24 to 4.12 format
3198 // This additional clamping is needed in case chain->setVolume_l() overshot
3199 vl = (vl + (1 << 11)) >> 12;
3200 if (vl > MAX_GAIN_INT) {
3201 vl = MAX_GAIN_INT;
3202 }
3203 vr = (vr + (1 << 11)) >> 12;
3204 if (vr > MAX_GAIN_INT) {
3205 vr = MAX_GAIN_INT;
3206 }
3207
3208 if (va > MAX_GAIN_INT) {
3209 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3210 }
3211
3212 // XXX: these things DON'T need to be done each time
3213 mAudioMixer->setBufferProvider(name, track);
3214 mAudioMixer->enable(name);
3215
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003216 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3217 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3218 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003219 mAudioMixer->setParameter(
3220 name,
3221 AudioMixer::TRACK,
3222 AudioMixer::FORMAT, (void *)track->format());
3223 mAudioMixer->setParameter(
3224 name,
3225 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003226 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003227 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3228 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003229 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003230 if (reqSampleRate == 0) {
3231 reqSampleRate = mSampleRate;
3232 } else if (reqSampleRate > maxSampleRate) {
3233 reqSampleRate = maxSampleRate;
3234 }
Eric Laurent81784c32012-11-19 14:55:58 -08003235 mAudioMixer->setParameter(
3236 name,
3237 AudioMixer::RESAMPLE,
3238 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003239 (void *)(uintptr_t)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003240 mAudioMixer->setParameter(
3241 name,
3242 AudioMixer::TRACK,
3243 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3244 mAudioMixer->setParameter(
3245 name,
3246 AudioMixer::TRACK,
3247 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3248
3249 // reset retry count
3250 track->mRetryCount = kMaxTrackRetries;
3251
3252 // If one track is ready, set the mixer ready if:
3253 // - the mixer was not ready during previous round OR
3254 // - no other track is not ready
3255 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3256 mixerStatus != MIXER_TRACKS_ENABLED) {
3257 mixerStatus = MIXER_TRACKS_READY;
3258 }
3259 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003260 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003261 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003262 }
Eric Laurent81784c32012-11-19 14:55:58 -08003263 // clear effect chain input buffer if an active track underruns to avoid sending
3264 // previous audio buffer again to effects
3265 chain = getEffectChain_l(track->sessionId());
3266 if (chain != 0) {
3267 chain->clearInputBuffer();
3268 }
3269
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003270 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003271 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3272 track->isStopped() || track->isPaused()) {
3273 // We have consumed all the buffers of this track.
3274 // Remove it from the list of active tracks.
3275 // TODO: use actual buffer filling status instead of latency when available from
3276 // audio HAL
3277 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3278 size_t framesWritten = mBytesWritten / mFrameSize;
3279 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3280 if (track->isStopped()) {
3281 track->reset();
3282 }
3283 tracksToRemove->add(track);
3284 }
3285 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003286 // No buffers for this track. Give it a few chances to
3287 // fill a buffer, then remove it from active list.
3288 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003289 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003290 tracksToRemove->add(track);
3291 // indicate to client process that the track was disabled because of underrun;
3292 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003293 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003294 // If one track is not ready, mark the mixer also not ready if:
3295 // - the mixer was ready during previous round OR
3296 // - no other track is ready
3297 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3298 mixerStatus != MIXER_TRACKS_READY) {
3299 mixerStatus = MIXER_TRACKS_ENABLED;
3300 }
3301 }
3302 mAudioMixer->disable(name);
3303 }
3304
3305 } // local variable scope to avoid goto warning
3306track_is_ready: ;
3307
3308 }
3309
3310 // Push the new FastMixer state if necessary
3311 bool pauseAudioWatchdog = false;
3312 if (didModify) {
3313 state->mFastTracksGen++;
3314 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3315 if (kUseFastMixer == FastMixer_Dynamic &&
3316 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3317 state->mCommand = FastMixerState::COLD_IDLE;
3318 state->mColdFutexAddr = &mFastMixerFutex;
3319 state->mColdGen++;
3320 mFastMixerFutex = 0;
3321 if (kUseFastMixer == FastMixer_Dynamic) {
3322 mNormalSink = mOutputSink;
3323 }
3324 // If we go into cold idle, need to wait for acknowledgement
3325 // so that fast mixer stops doing I/O.
3326 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3327 pauseAudioWatchdog = true;
3328 }
Eric Laurent81784c32012-11-19 14:55:58 -08003329 }
3330 if (sq != NULL) {
3331 sq->end(didModify);
3332 sq->push(block);
3333 }
3334#ifdef AUDIO_WATCHDOG
3335 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3336 mAudioWatchdog->pause();
3337 }
3338#endif
3339
3340 // Now perform the deferred reset on fast tracks that have stopped
3341 while (resetMask != 0) {
3342 size_t i = __builtin_ctz(resetMask);
3343 ALOG_ASSERT(i < count);
3344 resetMask &= ~(1 << i);
3345 sp<Track> t = mActiveTracks[i].promote();
3346 if (t == 0) {
3347 continue;
3348 }
3349 Track* track = t.get();
3350 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3351 track->reset();
3352 }
3353
3354 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003356
3357 // mix buffer must be cleared if all tracks are connected to an
3358 // effect chain as in this case the mixer will not write to
3359 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3361 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003362 // FIXME as a performance optimization, should remember previous zero status
3363 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3364 }
3365
3366 // if any fast tracks, then status is ready
3367 mMixerStatusIgnoringFastTracks = mixerStatus;
3368 if (fastTracks > 0) {
3369 mixerStatus = MIXER_TRACKS_READY;
3370 }
3371 return mixerStatus;
3372}
3373
3374// getTrackName_l() must be called with ThreadBase::mLock held
3375int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3376{
3377 return mAudioMixer->getTrackName(channelMask, sessionId);
3378}
3379
3380// deleteTrackName_l() must be called with ThreadBase::mLock held
3381void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3382{
3383 ALOGV("remove track (%d) and delete from mixer", name);
3384 mAudioMixer->deleteTrackName(name);
3385}
3386
3387// checkForNewParameters_l() must be called with ThreadBase::mLock held
3388bool AudioFlinger::MixerThread::checkForNewParameters_l()
3389{
3390 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3391 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3392 bool reconfig = false;
3393
3394 while (!mNewParameters.isEmpty()) {
3395
3396 if (mFastMixer != NULL) {
3397 FastMixerStateQueue *sq = mFastMixer->sq();
3398 FastMixerState *state = sq->begin();
3399 if (!(state->mCommand & FastMixerState::IDLE)) {
3400 previousCommand = state->mCommand;
3401 state->mCommand = FastMixerState::HOT_IDLE;
3402 sq->end();
3403 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3404 } else {
3405 sq->end(false /*didModify*/);
3406 }
3407 }
3408
3409 status_t status = NO_ERROR;
3410 String8 keyValuePair = mNewParameters[0];
3411 AudioParameter param = AudioParameter(keyValuePair);
3412 int value;
3413
3414 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3415 reconfig = true;
3416 }
3417 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3418 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3419 status = BAD_VALUE;
3420 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003421 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003422 reconfig = true;
3423 }
3424 }
3425 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003426 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003427 status = BAD_VALUE;
3428 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003429 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003430 reconfig = true;
3431 }
3432 }
3433 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3434 // do not accept frame count changes if tracks are open as the track buffer
3435 // size depends on frame count and correct behavior would not be guaranteed
3436 // if frame count is changed after track creation
3437 if (!mTracks.isEmpty()) {
3438 status = INVALID_OPERATION;
3439 } else {
3440 reconfig = true;
3441 }
3442 }
3443 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3444#ifdef ADD_BATTERY_DATA
3445 // when changing the audio output device, call addBatteryData to notify
3446 // the change
3447 if (mOutDevice != value) {
3448 uint32_t params = 0;
3449 // check whether speaker is on
3450 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3451 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3452 }
3453
3454 audio_devices_t deviceWithoutSpeaker
3455 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3456 // check if any other device (except speaker) is on
3457 if (value & deviceWithoutSpeaker ) {
3458 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3459 }
3460
3461 if (params != 0) {
3462 addBatteryData(params);
3463 }
3464 }
3465#endif
3466
3467 // forward device change to effects that have requested to be
3468 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003469 if (value != AUDIO_DEVICE_NONE) {
3470 mOutDevice = value;
3471 for (size_t i = 0; i < mEffectChains.size(); i++) {
3472 mEffectChains[i]->setDevice_l(mOutDevice);
3473 }
Eric Laurent81784c32012-11-19 14:55:58 -08003474 }
3475 }
3476
3477 if (status == NO_ERROR) {
3478 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3479 keyValuePair.string());
3480 if (!mStandby && status == INVALID_OPERATION) {
3481 mOutput->stream->common.standby(&mOutput->stream->common);
3482 mStandby = true;
3483 mBytesWritten = 0;
3484 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3485 keyValuePair.string());
3486 }
3487 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003488 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003489 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003490 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3491 for (size_t i = 0; i < mTracks.size() ; i++) {
3492 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3493 if (name < 0) {
3494 break;
3495 }
3496 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003497 }
3498 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3499 }
3500 }
3501
3502 mNewParameters.removeAt(0);
3503
3504 mParamStatus = status;
3505 mParamCond.signal();
3506 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3507 // already timed out waiting for the status and will never signal the condition.
3508 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3509 }
3510
3511 if (!(previousCommand & FastMixerState::IDLE)) {
3512 ALOG_ASSERT(mFastMixer != NULL);
3513 FastMixerStateQueue *sq = mFastMixer->sq();
3514 FastMixerState *state = sq->begin();
3515 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3516 state->mCommand = previousCommand;
3517 sq->end();
3518 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3519 }
3520
3521 return reconfig;
3522}
3523
3524
3525void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3526{
3527 const size_t SIZE = 256;
3528 char buffer[SIZE];
3529 String8 result;
3530
3531 PlaybackThread::dumpInternals(fd, args);
3532
Marco Nelissenb2208842014-02-07 14:00:50 -08003533 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003534
3535 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003536 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 copy.dump(fd);
3538
3539#ifdef STATE_QUEUE_DUMP
3540 // Similar for state queue
3541 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3542 observerCopy.dump(fd);
3543 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3544 mutatorCopy.dump(fd);
3545#endif
3546
Glenn Kasten46909e72013-02-26 09:20:22 -08003547#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003548 // Write the tee output to a .wav file
3549 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003550#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003551
3552#ifdef AUDIO_WATCHDOG
3553 if (mAudioWatchdog != 0) {
3554 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3555 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3556 wdCopy.dump(fd);
3557 }
3558#endif
3559}
3560
3561uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3562{
3563 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3564}
3565
3566uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3567{
3568 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3569}
3570
3571void AudioFlinger::MixerThread::cacheParameters_l()
3572{
3573 PlaybackThread::cacheParameters_l();
3574
3575 // FIXME: Relaxed timing because of a certain device that can't meet latency
3576 // Should be reduced to 2x after the vendor fixes the driver issue
3577 // increase threshold again due to low power audio mode. The way this warning
3578 // threshold is calculated and its usefulness should be reconsidered anyway.
3579 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3580}
3581
3582// ----------------------------------------------------------------------------
3583
3584AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3585 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3586 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3587 // mLeftVolFloat, mRightVolFloat
3588{
3589}
3590
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3592 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3593 ThreadBase::type_t type)
3594 : PlaybackThread(audioFlinger, output, id, device, type)
3595 // mLeftVolFloat, mRightVolFloat
3596{
3597}
3598
Eric Laurent81784c32012-11-19 14:55:58 -08003599AudioFlinger::DirectOutputThread::~DirectOutputThread()
3600{
3601}
3602
Eric Laurentbfb1b832013-01-07 09:53:42 -08003603void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3604{
3605 audio_track_cblk_t* cblk = track->cblk();
3606 float left, right;
3607
3608 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3609 left = right = 0;
3610 } else {
3611 float typeVolume = mStreamTypes[track->streamType()].volume;
3612 float v = mMasterVolume * typeVolume;
3613 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3614 uint32_t vlr = proxy->getVolumeLR();
3615 float v_clamped = v * (vlr & 0xFFFF);
3616 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3617 left = v_clamped/MAX_GAIN;
3618 v_clamped = v * (vlr >> 16);
3619 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3620 right = v_clamped/MAX_GAIN;
3621 }
3622
3623 if (lastTrack) {
3624 if (left != mLeftVolFloat || right != mRightVolFloat) {
3625 mLeftVolFloat = left;
3626 mRightVolFloat = right;
3627
3628 // Convert volumes from float to 8.24
3629 uint32_t vl = (uint32_t)(left * (1 << 24));
3630 uint32_t vr = (uint32_t)(right * (1 << 24));
3631
3632 // Delegate volume control to effect in track effect chain if needed
3633 // only one effect chain can be present on DirectOutputThread, so if
3634 // there is one, the track is connected to it
3635 if (!mEffectChains.isEmpty()) {
3636 mEffectChains[0]->setVolume_l(&vl, &vr);
3637 left = (float)vl / (1 << 24);
3638 right = (float)vr / (1 << 24);
3639 }
3640 if (mOutput->stream->set_volume) {
3641 mOutput->stream->set_volume(mOutput->stream, left, right);
3642 }
3643 }
3644 }
3645}
3646
3647
Eric Laurent81784c32012-11-19 14:55:58 -08003648AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3649 Vector< sp<Track> > *tracksToRemove
3650)
3651{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003652 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003653 mixer_state mixerStatus = MIXER_IDLE;
3654
3655 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003656 for (size_t i = 0; i < count; i++) {
3657 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003658 // The track died recently
3659 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003660 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003661 }
3662
3663 Track* const track = t.get();
3664 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003665 // Only consider last track started for volume and mixer state control.
3666 // In theory an older track could underrun and restart after the new one starts
3667 // but as we only care about the transition phase between two tracks on a
3668 // direct output, it is not a problem to ignore the underrun case.
3669 sp<Track> l = mLatestActiveTrack.promote();
3670 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003671
3672 // The first time a track is added we wait
3673 // for all its buffers to be filled before processing it
3674 uint32_t minFrames;
3675 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3676 minFrames = mNormalFrameCount;
3677 } else {
3678 minFrames = 1;
3679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680
Eric Laurent81784c32012-11-19 14:55:58 -08003681 if ((track->framesReady() >= minFrames) && track->isReady() &&
3682 !track->isPaused() && !track->isTerminated())
3683 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003684 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003685
3686 if (track->mFillingUpStatus == Track::FS_FILLED) {
3687 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003688 // make sure processVolume_l() will apply new volume even if 0
3689 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 if (track->mState == TrackBase::RESUMING) {
3691 track->mState = TrackBase::ACTIVE;
3692 }
3693 }
3694
3695 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003696 processVolume_l(track, last);
3697 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003698 // reset retry count
3699 track->mRetryCount = kMaxTrackRetriesDirect;
3700 mActiveTrack = t;
3701 mixerStatus = MIXER_TRACKS_READY;
3702 }
Eric Laurent81784c32012-11-19 14:55:58 -08003703 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003704 // clear effect chain input buffer if the last active track started underruns
3705 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003706 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 mEffectChains[0]->clearInputBuffer();
3708 }
3709
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003710 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003711 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3712 track->isStopped() || track->isPaused()) {
3713 // We have consumed all the buffers of this track.
3714 // Remove it from the list of active tracks.
3715 // TODO: implement behavior for compressed audio
3716 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3717 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003718 if (mStandby || !last ||
3719 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003720 if (track->isStopped()) {
3721 track->reset();
3722 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003723 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003724 }
3725 } else {
3726 // No buffers for this track. Give it a few chances to
3727 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003728 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003729 if (--(track->mRetryCount) <= 0) {
3730 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003731 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003732 // indicate to client process that the track was disabled because of underrun;
3733 // it will then automatically call start() when data is available
3734 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003735 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003736 mixerStatus = MIXER_TRACKS_ENABLED;
3737 }
3738 }
3739 }
3740 }
3741
Eric Laurent81784c32012-11-19 14:55:58 -08003742 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003743 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003744
3745 return mixerStatus;
3746}
3747
3748void AudioFlinger::DirectOutputThread::threadLoop_mix()
3749{
Eric Laurent81784c32012-11-19 14:55:58 -08003750 size_t frameCount = mFrameCount;
3751 int8_t *curBuf = (int8_t *)mMixBuffer;
3752 // output audio to hardware
3753 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003754 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003755 buffer.frameCount = frameCount;
3756 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003757 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003758 memset(curBuf, 0, frameCount * mFrameSize);
3759 break;
3760 }
3761 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3762 frameCount -= buffer.frameCount;
3763 curBuf += buffer.frameCount * mFrameSize;
3764 mActiveTrack->releaseBuffer(&buffer);
3765 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003766 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003767 sleepTime = 0;
3768 standbyTime = systemTime() + standbyDelay;
3769 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003770}
3771
3772void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3773{
3774 if (sleepTime == 0) {
3775 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3776 sleepTime = activeSleepTime;
3777 } else {
3778 sleepTime = idleSleepTime;
3779 }
3780 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3781 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3782 sleepTime = 0;
3783 }
3784}
3785
3786// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003787int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3788 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003789{
3790 return 0;
3791}
3792
3793// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003794void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003795{
3796}
3797
3798// checkForNewParameters_l() must be called with ThreadBase::mLock held
3799bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3800{
3801 bool reconfig = false;
3802
3803 while (!mNewParameters.isEmpty()) {
3804 status_t status = NO_ERROR;
3805 String8 keyValuePair = mNewParameters[0];
3806 AudioParameter param = AudioParameter(keyValuePair);
3807 int value;
3808
3809 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3810 // do not accept frame count changes if tracks are open as the track buffer
3811 // size depends on frame count and correct behavior would not be garantied
3812 // if frame count is changed after track creation
3813 if (!mTracks.isEmpty()) {
3814 status = INVALID_OPERATION;
3815 } else {
3816 reconfig = true;
3817 }
3818 }
3819 if (status == NO_ERROR) {
3820 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3821 keyValuePair.string());
3822 if (!mStandby && status == INVALID_OPERATION) {
3823 mOutput->stream->common.standby(&mOutput->stream->common);
3824 mStandby = true;
3825 mBytesWritten = 0;
3826 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3827 keyValuePair.string());
3828 }
3829 if (status == NO_ERROR && reconfig) {
3830 readOutputParameters();
3831 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3832 }
3833 }
3834
3835 mNewParameters.removeAt(0);
3836
3837 mParamStatus = status;
3838 mParamCond.signal();
3839 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3840 // already timed out waiting for the status and will never signal the condition.
3841 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3842 }
3843 return reconfig;
3844}
3845
3846uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3847{
3848 uint32_t time;
3849 if (audio_is_linear_pcm(mFormat)) {
3850 time = PlaybackThread::activeSleepTimeUs();
3851 } else {
3852 time = 10000;
3853 }
3854 return time;
3855}
3856
3857uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3858{
3859 uint32_t time;
3860 if (audio_is_linear_pcm(mFormat)) {
3861 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3862 } else {
3863 time = 10000;
3864 }
3865 return time;
3866}
3867
3868uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3869{
3870 uint32_t time;
3871 if (audio_is_linear_pcm(mFormat)) {
3872 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3873 } else {
3874 time = 10000;
3875 }
3876 return time;
3877}
3878
3879void AudioFlinger::DirectOutputThread::cacheParameters_l()
3880{
3881 PlaybackThread::cacheParameters_l();
3882
3883 // use shorter standby delay as on normal output to release
3884 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003885 if (audio_is_linear_pcm(mFormat)) {
3886 standbyDelay = microseconds(activeSleepTime*2);
3887 } else {
3888 standbyDelay = kOffloadStandbyDelayNs;
3889 }
Eric Laurent81784c32012-11-19 14:55:58 -08003890}
3891
3892// ----------------------------------------------------------------------------
3893
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003895 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003897 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003898 mWriteAckSequence(0),
3899 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900{
3901}
3902
3903AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3904{
3905}
3906
3907void AudioFlinger::AsyncCallbackThread::onFirstRef()
3908{
3909 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3910}
3911
3912bool AudioFlinger::AsyncCallbackThread::threadLoop()
3913{
3914 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003915 uint32_t writeAckSequence;
3916 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003917
3918 {
3919 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003920 while (!((mWriteAckSequence & 1) ||
3921 (mDrainSequence & 1) ||
3922 exitPending())) {
3923 mWaitWorkCV.wait(mLock);
3924 }
3925
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 if (exitPending()) {
3927 break;
3928 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003929 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3930 mWriteAckSequence, mDrainSequence);
3931 writeAckSequence = mWriteAckSequence;
3932 mWriteAckSequence &= ~1;
3933 drainSequence = mDrainSequence;
3934 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003935 }
3936 {
Eric Laurent4de95592013-09-26 15:28:21 -07003937 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3938 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003939 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003940 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003942 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003943 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003944 }
3945 }
3946 }
3947 }
3948 return false;
3949}
3950
3951void AudioFlinger::AsyncCallbackThread::exit()
3952{
3953 ALOGV("AsyncCallbackThread::exit");
3954 Mutex::Autolock _l(mLock);
3955 requestExit();
3956 mWaitWorkCV.broadcast();
3957}
3958
Eric Laurent3b4529e2013-09-05 18:09:19 -07003959void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960{
3961 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003962 // bit 0 is cleared
3963 mWriteAckSequence = sequence << 1;
3964}
3965
3966void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3967{
3968 Mutex::Autolock _l(mLock);
3969 // ignore unexpected callbacks
3970 if (mWriteAckSequence & 2) {
3971 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003972 mWaitWorkCV.signal();
3973 }
3974}
3975
Eric Laurent3b4529e2013-09-05 18:09:19 -07003976void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977{
3978 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003979 // bit 0 is cleared
3980 mDrainSequence = sequence << 1;
3981}
3982
3983void AudioFlinger::AsyncCallbackThread::resetDraining()
3984{
3985 Mutex::Autolock _l(mLock);
3986 // ignore unexpected callbacks
3987 if (mDrainSequence & 2) {
3988 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003989 mWaitWorkCV.signal();
3990 }
3991}
3992
3993
3994// ----------------------------------------------------------------------------
3995AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3996 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3997 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3998 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003999 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004000 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004001{
Eric Laurentfd477972013-10-25 18:10:40 -07004002 //FIXME: mStandby should be set to true by ThreadBase constructor
4003 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004004}
4005
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006void AudioFlinger::OffloadThread::threadLoop_exit()
4007{
4008 if (mFlushPending || mHwPaused) {
4009 // If a flush is pending or track was paused, just discard buffered data
4010 flushHw_l();
4011 } else {
4012 mMixerStatus = MIXER_DRAIN_ALL;
4013 threadLoop_drain();
4014 }
4015 mCallbackThread->exit();
4016 PlaybackThread::threadLoop_exit();
4017}
4018
4019AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4020 Vector< sp<Track> > *tracksToRemove
4021)
4022{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004023 size_t count = mActiveTracks.size();
4024
4025 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004026 bool doHwPause = false;
4027 bool doHwResume = false;
4028
Eric Laurentede6c3b2013-09-19 14:37:46 -07004029 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4030
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 // find out which tracks need to be processed
4032 for (size_t i = 0; i < count; i++) {
4033 sp<Track> t = mActiveTracks[i].promote();
4034 // The track died recently
4035 if (t == 0) {
4036 continue;
4037 }
4038 Track* const track = t.get();
4039 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004040 // Only consider last track started for volume and mixer state control.
4041 // In theory an older track could underrun and restart after the new one starts
4042 // but as we only care about the transition phase between two tracks on a
4043 // direct output, it is not a problem to ignore the underrun case.
4044 sp<Track> l = mLatestActiveTrack.promote();
4045 bool last = l.get() == track;
4046
Haynes Mathew George7844f672014-01-15 12:32:55 -08004047 if (track->isInvalid()) {
4048 ALOGW("An invalidated track shouldn't be in active list");
4049 tracksToRemove->add(track);
4050 continue;
4051 }
4052
4053 if (track->mState == TrackBase::IDLE) {
4054 ALOGW("An idle track shouldn't be in active list");
4055 continue;
4056 }
4057
Eric Laurentbfb1b832013-01-07 09:53:42 -08004058 if (track->isPausing()) {
4059 track->setPaused();
4060 if (last) {
4061 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004062 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004063 mHwPaused = true;
4064 }
4065 // If we were part way through writing the mixbuffer to
4066 // the HAL we must save this until we resume
4067 // BUG - this will be wrong if a different track is made active,
4068 // in that case we want to discard the pending data in the
4069 // mixbuffer and tell the client to present it again when the
4070 // track is resumed
4071 mPausedWriteLength = mCurrentWriteLength;
4072 mPausedBytesRemaining = mBytesRemaining;
4073 mBytesRemaining = 0; // stop writing
4074 }
4075 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004076 } else if (track->isFlushPending()) {
4077 track->flushAck();
4078 if (last) {
4079 mFlushPending = true;
4080 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004082 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004083 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 if (track->mFillingUpStatus == Track::FS_FILLED) {
4085 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004086 // make sure processVolume_l() will apply new volume even if 0
4087 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004088 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004089 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004090 if (last) {
4091 if (mPausedBytesRemaining) {
4092 // Need to continue write that was interrupted
4093 mCurrentWriteLength = mPausedWriteLength;
4094 mBytesRemaining = mPausedBytesRemaining;
4095 mPausedBytesRemaining = 0;
4096 }
4097 if (mHwPaused) {
4098 doHwResume = true;
4099 mHwPaused = false;
4100 // threadLoop_mix() will handle the case that we need to
4101 // resume an interrupted write
4102 }
4103 // enable write to audio HAL
4104 sleepTime = 0;
4105 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004106 }
4107 }
4108
4109 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004110 sp<Track> previousTrack = mPreviousTrack.promote();
4111 if (previousTrack != 0) {
4112 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004113 // Flush any data still being written from last track
4114 mBytesRemaining = 0;
4115 if (mPausedBytesRemaining) {
4116 // Last track was paused so we also need to flush saved
4117 // mixbuffer state and invalidate track so that it will
4118 // re-submit that unwritten data when it is next resumed
4119 mPausedBytesRemaining = 0;
4120 // Invalidate is a bit drastic - would be more efficient
4121 // to have a flag to tell client that some of the
4122 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004123 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004124 }
4125 // flush data already sent to the DSP if changing audio session as audio
4126 // comes from a different source. Also invalidate previous track to force a
4127 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004128 if (previousTrack->sessionId() != track->sessionId()) {
4129 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004130 }
4131 }
4132 }
4133 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 // reset retry count
4135 track->mRetryCount = kMaxTrackRetriesOffload;
4136 mActiveTrack = t;
4137 mixerStatus = MIXER_TRACKS_READY;
4138 }
4139 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004140 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004141 if (track->isStopping_1()) {
4142 // Hardware buffer can hold a large amount of audio so we must
4143 // wait for all current track's data to drain before we say
4144 // that the track is stopped.
4145 if (mBytesRemaining == 0) {
4146 // Only start draining when all data in mixbuffer
4147 // has been written
4148 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4149 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004150 // do not drain if no data was ever sent to HAL (mStandby == true)
4151 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004152 // do not modify drain sequence if we are already draining. This happens
4153 // when resuming from pause after drain.
4154 if ((mDrainSequence & 1) == 0) {
4155 sleepTime = 0;
4156 standbyTime = systemTime() + standbyDelay;
4157 mixerStatus = MIXER_DRAIN_TRACK;
4158 mDrainSequence += 2;
4159 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004160 if (mHwPaused) {
4161 // It is possible to move from PAUSED to STOPPING_1 without
4162 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004163 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004164 mHwPaused = false;
4165 }
4166 }
4167 }
4168 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004169 // Drain has completed or we are in standby, signal presentation complete
4170 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 track->mState = TrackBase::STOPPED;
4172 size_t audioHALFrames =
4173 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4174 size_t framesWritten =
4175 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4176 track->presentationComplete(framesWritten, audioHALFrames);
4177 track->reset();
4178 tracksToRemove->add(track);
4179 }
4180 } else {
4181 // No buffers for this track. Give it a few chances to
4182 // fill a buffer, then remove it from active list.
4183 if (--(track->mRetryCount) <= 0) {
4184 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4185 track->name());
4186 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004187 // indicate to client process that the track was disabled because of underrun;
4188 // it will then automatically call start() when data is available
4189 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190 } else if (last){
4191 mixerStatus = MIXER_TRACKS_ENABLED;
4192 }
4193 }
4194 }
4195 // compute volume for this track
4196 processVolume_l(track, last);
4197 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004198
Eric Laurentea0fade2013-10-04 16:23:48 -07004199 // make sure the pause/flush/resume sequence is executed in the right order.
4200 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4201 // before flush and then resume HW. This can happen in case of pause/flush/resume
4202 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004203 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004204 mOutput->stream->pause(mOutput->stream);
4205 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004206 if (mFlushPending) {
4207 flushHw_l();
4208 mFlushPending = false;
4209 }
Eric Laurentfd477972013-10-25 18:10:40 -07004210 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004211 mOutput->stream->resume(mOutput->stream);
4212 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004213
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 // remove all the tracks that need to be...
4215 removeTracks_l(*tracksToRemove);
4216
4217 return mixerStatus;
4218}
4219
Eric Laurentbfb1b832013-01-07 09:53:42 -08004220// must be called with thread mutex locked
4221bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4222{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004223 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4224 mWriteAckSequence, mDrainSequence);
4225 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226 return true;
4227 }
4228 return false;
4229}
4230
4231// must be called with thread mutex locked
4232bool AudioFlinger::OffloadThread::shouldStandby_l()
4233{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004234 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004235
4236 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4237 // after a timeout and we will enter standby then.
4238 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004239 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240 }
4241
Glenn Kastene6f35b12013-08-19 09:58:50 -07004242 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243}
4244
4245
4246bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4247{
4248 Mutex::Autolock _l(mLock);
4249 return waitingAsyncCallback_l();
4250}
4251
4252void AudioFlinger::OffloadThread::flushHw_l()
4253{
4254 mOutput->stream->flush(mOutput->stream);
4255 // Flush anything still waiting in the mixbuffer
4256 mCurrentWriteLength = 0;
4257 mBytesRemaining = 0;
4258 mPausedWriteLength = 0;
4259 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004260 mHwPaused = false;
4261
Eric Laurentbfb1b832013-01-07 09:53:42 -08004262 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004263 // discard any pending drain or write ack by incrementing sequence
4264 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4265 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004266 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004267 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4268 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269 }
4270}
4271
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004272void AudioFlinger::OffloadThread::onAddNewTrack_l()
4273{
4274 sp<Track> previousTrack = mPreviousTrack.promote();
4275 sp<Track> latestTrack = mLatestActiveTrack.promote();
4276
4277 if (previousTrack != 0 && latestTrack != 0 &&
4278 (previousTrack->sessionId() != latestTrack->sessionId())) {
4279 mFlushPending = true;
4280 }
4281 PlaybackThread::onAddNewTrack_l();
4282}
4283
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284// ----------------------------------------------------------------------------
4285
Eric Laurent81784c32012-11-19 14:55:58 -08004286AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4287 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4288 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4289 DUPLICATING),
4290 mWaitTimeMs(UINT_MAX)
4291{
4292 addOutputTrack(mainThread);
4293}
4294
4295AudioFlinger::DuplicatingThread::~DuplicatingThread()
4296{
4297 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4298 mOutputTracks[i]->destroy();
4299 }
4300}
4301
4302void AudioFlinger::DuplicatingThread::threadLoop_mix()
4303{
4304 // mix buffers...
4305 if (outputsReady(outputTracks)) {
4306 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4307 } else {
4308 memset(mMixBuffer, 0, mixBufferSize);
4309 }
4310 sleepTime = 0;
4311 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004313 standbyTime = systemTime() + standbyDelay;
4314}
4315
4316void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4317{
4318 if (sleepTime == 0) {
4319 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4320 sleepTime = activeSleepTime;
4321 } else {
4322 sleepTime = idleSleepTime;
4323 }
4324 } else if (mBytesWritten != 0) {
4325 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4326 writeFrames = mNormalFrameCount;
4327 memset(mMixBuffer, 0, mixBufferSize);
4328 } else {
4329 // flush remaining overflow buffers in output tracks
4330 writeFrames = 0;
4331 }
4332 sleepTime = 0;
4333 }
4334}
4335
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004337{
4338 for (size_t i = 0; i < outputTracks.size(); i++) {
4339 outputTracks[i]->write(mMixBuffer, writeFrames);
4340 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004341 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004343}
4344
4345void AudioFlinger::DuplicatingThread::threadLoop_standby()
4346{
4347 // DuplicatingThread implements standby by stopping all tracks
4348 for (size_t i = 0; i < outputTracks.size(); i++) {
4349 outputTracks[i]->stop();
4350 }
4351}
4352
4353void AudioFlinger::DuplicatingThread::saveOutputTracks()
4354{
4355 outputTracks = mOutputTracks;
4356}
4357
4358void AudioFlinger::DuplicatingThread::clearOutputTracks()
4359{
4360 outputTracks.clear();
4361}
4362
4363void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4364{
4365 Mutex::Autolock _l(mLock);
4366 // FIXME explain this formula
4367 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4368 OutputTrack *outputTrack = new OutputTrack(thread,
4369 this,
4370 mSampleRate,
4371 mFormat,
4372 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004373 frameCount,
4374 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004375 if (outputTrack->cblk() != NULL) {
4376 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4377 mOutputTracks.add(outputTrack);
4378 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4379 updateWaitTime_l();
4380 }
4381}
4382
4383void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4384{
4385 Mutex::Autolock _l(mLock);
4386 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4387 if (mOutputTracks[i]->thread() == thread) {
4388 mOutputTracks[i]->destroy();
4389 mOutputTracks.removeAt(i);
4390 updateWaitTime_l();
4391 return;
4392 }
4393 }
4394 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4395}
4396
4397// caller must hold mLock
4398void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4399{
4400 mWaitTimeMs = UINT_MAX;
4401 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4402 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4403 if (strong != 0) {
4404 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4405 if (waitTimeMs < mWaitTimeMs) {
4406 mWaitTimeMs = waitTimeMs;
4407 }
4408 }
4409 }
4410}
4411
4412
4413bool AudioFlinger::DuplicatingThread::outputsReady(
4414 const SortedVector< sp<OutputTrack> > &outputTracks)
4415{
4416 for (size_t i = 0; i < outputTracks.size(); i++) {
4417 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4418 if (thread == 0) {
4419 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4420 outputTracks[i].get());
4421 return false;
4422 }
4423 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4424 // see note at standby() declaration
4425 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4426 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4427 thread.get());
4428 return false;
4429 }
4430 }
4431 return true;
4432}
4433
4434uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4435{
4436 return (mWaitTimeMs * 1000) / 2;
4437}
4438
4439void AudioFlinger::DuplicatingThread::cacheParameters_l()
4440{
4441 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4442 updateWaitTime_l();
4443
4444 MixerThread::cacheParameters_l();
4445}
4446
4447// ----------------------------------------------------------------------------
4448// Record
4449// ----------------------------------------------------------------------------
4450
4451AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4452 AudioStreamIn *input,
4453 uint32_t sampleRate,
4454 audio_channel_mask_t channelMask,
4455 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004456 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004457 audio_devices_t inDevice
4458#ifdef TEE_SINK
4459 , const sp<NBAIO_Sink>& teeSink
4460#endif
4461 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004462 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten2b806402013-11-20 16:37:38 -08004463 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten85948432013-08-19 12:09:05 -07004464 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear
4465 // are set by readInputParameters()
4466 // mRsmpInIndex LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08004467 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004468 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004469 // mBytesRead is only meaningful while active, and so is cleared in start()
4470 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004471#ifdef TEE_SINK
4472 , mTeeSink(teeSink)
4473#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004474{
4475 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004476 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004477
4478 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004479}
4480
4481
4482AudioFlinger::RecordThread::~RecordThread()
4483{
Glenn Kasten481fb672013-09-30 14:39:28 -07004484 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004485 delete[] mRsmpInBuffer;
4486 delete mResampler;
4487 delete[] mRsmpOutBuffer;
4488}
4489
4490void AudioFlinger::RecordThread::onFirstRef()
4491{
4492 run(mName, PRIORITY_URGENT_AUDIO);
4493}
4494
Eric Laurent81784c32012-11-19 14:55:58 -08004495bool AudioFlinger::RecordThread::threadLoop()
4496{
Eric Laurent81784c32012-11-19 14:55:58 -08004497 nsecs_t lastWarning = 0;
4498
4499 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004500
4501 // used to verify we've read at least once before evaluating how many bytes were read
4502 bool readOnce = false;
4503
Glenn Kasten5edadd42013-08-14 16:30:49 -07004504 // used to request a deferred sleep, to be executed later while mutex is unlocked
4505 bool doSleep = false;
4506
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004507reacquire_wakelock:
4508 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004509 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004510 {
4511 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004512 size_t size = mActiveTracks.size();
4513 activeTracksGen = mActiveTracksGen;
4514 if (size > 0) {
4515 // FIXME an arbitrary choice
4516 activeTrack = mActiveTracks[0];
4517 acquireWakeLock_l(activeTrack->uid());
4518 if (size > 1) {
4519 SortedVector<int> tmp;
4520 for (size_t i = 0; i < size; i++) {
4521 tmp.add(mActiveTracks[i]->uid());
4522 }
4523 updateWakeLockUids_l(tmp);
4524 }
4525 } else {
4526 acquireWakeLock_l(-1);
4527 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004528 }
4529
Eric Laurent81784c32012-11-19 14:55:58 -08004530 // start recording
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004531 for (;;) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004532 TrackBase::track_state activeTrackState;
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004533 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004534
Glenn Kasten5edadd42013-08-14 16:30:49 -07004535 // sleep with mutex unlocked
4536 if (doSleep) {
4537 doSleep = false;
4538 usleep(kRecordThreadSleepUs);
4539 }
4540
Eric Laurent81784c32012-11-19 14:55:58 -08004541 { // scope for mLock
4542 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004543
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004544 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004545 // return value 'reconfig' is currently unused
4546 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004547
Eric Laurent000a4192014-01-29 15:17:32 -08004548 // check exitPending here because checkForNewParameters_l() and
4549 // checkForNewParameters_l() can temporarily release mLock
4550 if (exitPending()) {
4551 break;
4552 }
4553
Glenn Kasten2b806402013-11-20 16:37:38 -08004554 // if no active track(s), then standby and release wakelock
4555 size_t size = mActiveTracks.size();
4556 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004557 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004558 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004559 releaseWakeLock_l();
4560 ALOGV("RecordThread: loop stopping");
4561 // go to sleep
4562 mWaitWorkCV.wait(mLock);
4563 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004564 goto reacquire_wakelock;
4565 }
4566
Glenn Kasten2b806402013-11-20 16:37:38 -08004567 if (mActiveTracksGen != activeTracksGen) {
4568 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004569 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004570 for (size_t i = 0; i < size; i++) {
4571 tmp.add(mActiveTracks[i]->uid());
4572 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004573 updateWakeLockUids_l(tmp);
Glenn Kasten2b806402013-11-20 16:37:38 -08004574 // FIXME an arbitrary choice
4575 activeTrack = mActiveTracks[0];
Eric Laurent81784c32012-11-19 14:55:58 -08004576 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004577
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004578 if (activeTrack->isTerminated()) {
4579 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004580 mActiveTracks.remove(activeTrack);
4581 mActiveTracksGen++;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004582 continue;
4583 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004584
Glenn Kastenb86432b2013-08-14 15:08:12 -07004585 activeTrackState = activeTrack->mState;
4586 switch (activeTrackState) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004587 case TrackBase::PAUSING:
Glenn Kasten93e471f2013-08-19 08:40:07 -07004588 standbyIfNotAlreadyInStandby();
Glenn Kasten2b806402013-11-20 16:37:38 -08004589 mActiveTracks.remove(activeTrack);
4590 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004591 mStartStopCond.broadcast();
4592 doSleep = true;
4593 continue;
4594
4595 case TrackBase::RESUMING:
4596 mStandby = false;
4597 if (mReqChannelCount != activeTrack->channelCount()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004598 mActiveTracks.remove(activeTrack);
4599 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004600 mStartStopCond.broadcast();
4601 continue;
4602 }
4603 if (readOnce) {
4604 mStartStopCond.broadcast();
4605 // record start succeeds only if first read from audio input succeeds
4606 if (mBytesRead < 0) {
Glenn Kasten2b806402013-11-20 16:37:38 -08004607 mActiveTracks.remove(activeTrack);
4608 mActiveTracksGen++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004609 continue;
4610 }
4611 activeTrack->mState = TrackBase::ACTIVE;
4612 }
4613 break;
4614
4615 case TrackBase::ACTIVE:
4616 break;
4617
4618 case TrackBase::IDLE:
Glenn Kasten71652682013-08-14 15:17:55 -07004619 doSleep = true;
4620 continue;
Glenn Kasten9e982352013-08-14 14:39:50 -07004621
4622 default:
Glenn Kastenb86432b2013-08-14 15:08:12 -07004623 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004624 }
4625
Eric Laurent81784c32012-11-19 14:55:58 -08004626 lockEffectChains_l(effectChains);
4627 }
4628
Glenn Kasten2b806402013-11-20 16:37:38 -08004629 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable
Glenn Kasten71652682013-08-14 15:17:55 -07004630 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4631
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004632 for (size_t i = 0; i < effectChains.size(); i ++) {
4633 // thread mutex is not locked, but effect chain is locked
4634 effectChains[i]->process_l();
4635 }
4636
Glenn Kastenb91aa632013-08-19 08:40:21 -07004637 AudioBufferProvider::Buffer buffer;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004638 buffer.frameCount = mFrameCount;
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004639 status_t status = activeTrack->getNextBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004640 if (status == NO_ERROR) {
4641 readOnce = true;
4642 size_t framesOut = buffer.frameCount;
4643 if (mResampler == NULL) {
4644 // no resampling
4645 while (framesOut) {
4646 size_t framesIn = mFrameCount - mRsmpInIndex;
4647 if (framesIn > 0) {
4648 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4649 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004650 activeTrack->mFrameSize;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004651 if (framesIn > framesOut) {
4652 framesIn = framesOut;
4653 }
4654 mRsmpInIndex += framesIn;
4655 framesOut -= framesIn;
4656 if (mChannelCount == mReqChannelCount) {
4657 memcpy(dst, src, framesIn * mFrameSize);
4658 } else {
4659 if (mChannelCount == 1) {
4660 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4661 (int16_t *)src, framesIn);
4662 } else {
4663 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4664 (int16_t *)src, framesIn);
4665 }
4666 }
4667 }
4668 if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4669 void *readInto;
4670 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4671 readInto = buffer.raw;
4672 framesOut = 0;
4673 } else {
4674 readInto = mRsmpInBuffer;
4675 mRsmpInIndex = 0;
4676 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07004677 mBytesRead = mInput->stream->read(mInput->stream, readInto, mBufferSize);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004678 if (mBytesRead <= 0) {
Glenn Kastenb86432b2013-08-14 15:08:12 -07004679 // TODO: verify that it's benign to use a stale track state
4680 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004681 {
4682 ALOGE("Error reading audio input");
4683 // Force input into standby so that it tries to
4684 // recover at next read attempt
4685 inputStandBy();
Glenn Kasten5edadd42013-08-14 16:30:49 -07004686 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004687 }
4688 mRsmpInIndex = mFrameCount;
4689 framesOut = 0;
4690 buffer.frameCount = 0;
4691 }
4692#ifdef TEE_SINK
4693 else if (mTeeSink != 0) {
4694 (void) mTeeSink->write(readInto,
4695 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4696 }
4697#endif
4698 }
4699 }
4700 } else {
4701 // resampling
4702
Glenn Kasten85948432013-08-19 12:09:05 -07004703 // avoid busy-waiting if client doesn't keep up
4704 bool madeProgress = false;
4705
4706 // keep mRsmpInBuffer full so resampler always has sufficient input
4707 for (;;) {
4708 int32_t rear = mRsmpInRear;
4709 ssize_t filled = rear - mRsmpInFront;
4710 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
4711 // exit once there is enough data in buffer for resampler
4712 if ((size_t) filled >= mRsmpInFrames) {
4713 break;
4714 }
4715 size_t avail = mRsmpInFramesP2 - filled;
4716 // Only try to read full HAL buffers.
4717 // But if the HAL read returns a partial buffer, use it.
4718 if (avail < mFrameCount) {
4719 ALOGE("insufficient space to read: avail %d < mFrameCount %d",
4720 avail, mFrameCount);
4721 break;
4722 }
4723 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then
4724 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
4725 rear &= mRsmpInFramesP2 - 1;
4726 mBytesRead = mInput->stream->read(mInput->stream,
4727 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4728 if (mBytesRead <= 0) {
4729 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize);
4730 break;
4731 }
4732 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize);
4733 size_t framesRead = mBytesRead / mFrameSize;
4734 ALOG_ASSERT(framesRead > 0);
4735 madeProgress = true;
4736 // If 'avail' was non-contiguous, we now correct for reading past end of buffer.
4737 size_t part1 = mRsmpInFramesP2 - rear;
4738 if (framesRead > part1) {
4739 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4740 (framesRead - part1) * mFrameSize);
4741 }
4742 mRsmpInRear += framesRead;
4743 }
4744
4745 if (!madeProgress) {
4746 ALOGV("Did not make progress");
4747 usleep(((mFrameCount * 1000) / mSampleRate) * 1000);
4748 }
4749
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004750 // resampler accumulates, but we only have one source track
4751 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004752 mResampler->resample(mRsmpOutBuffer, framesOut,
4753 this /* AudioBufferProvider* */);
4754 // ditherAndClamp() works as long as all buffers returned by
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004755 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten85948432013-08-19 12:09:05 -07004756 if (mReqChannelCount == 1) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004757 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4758 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4759 // the resampler always outputs stereo samples:
4760 // do post stereo to mono conversion
4761 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4762 framesOut);
4763 } else {
4764 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4765 }
4766 // now done with mRsmpOutBuffer
4767
4768 }
4769 if (mFramestoDrop == 0) {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004770 activeTrack->releaseBuffer(&buffer);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004771 } else {
4772 if (mFramestoDrop > 0) {
4773 mFramestoDrop -= buffer.frameCount;
4774 if (mFramestoDrop <= 0) {
4775 clearSyncStartEvent();
4776 }
4777 } else {
4778 mFramestoDrop += buffer.frameCount;
4779 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4780 mSyncStartEvent->isCancelled()) {
4781 ALOGW("Synced record %s, session %d, trigger session %d",
4782 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004783 activeTrack->sessionId(),
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004784 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4785 clearSyncStartEvent();
4786 }
4787 }
4788 }
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004789 activeTrack->clearOverflow();
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004790 }
4791 // client isn't retrieving buffers fast enough
4792 else {
Glenn Kastenad5bcc22013-08-14 14:21:34 -07004793 if (!activeTrack->setOverflow()) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004794 nsecs_t now = systemTime();
4795 if ((now - lastWarning) > kWarningThrottleNs) {
4796 ALOGW("RecordThread: buffer overflow");
4797 lastWarning = now;
4798 }
4799 }
4800 // Release the processor for a while before asking for a new buffer.
4801 // This will give the application more chance to read from the buffer and
4802 // clear the overflow.
Glenn Kasten5edadd42013-08-14 16:30:49 -07004803 doSleep = true;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004804 }
4805
Eric Laurent81784c32012-11-19 14:55:58 -08004806 // enable changes in effect chain
4807 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004808 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004809 }
4810
Glenn Kasten93e471f2013-08-19 08:40:07 -07004811 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004812
4813 {
4814 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004815 for (size_t i = 0; i < mTracks.size(); i++) {
4816 sp<RecordTrack> track = mTracks[i];
4817 track->invalidate();
4818 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004819 mActiveTracks.clear();
4820 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004821 mStartStopCond.broadcast();
4822 }
4823
4824 releaseWakeLock();
4825
4826 ALOGV("RecordThread %p exiting", this);
4827 return false;
4828}
4829
Glenn Kasten93e471f2013-08-19 08:40:07 -07004830void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004831{
4832 if (!mStandby) {
4833 inputStandBy();
4834 mStandby = true;
4835 }
4836}
4837
4838void AudioFlinger::RecordThread::inputStandBy()
4839{
4840 mInput->stream->common.standby(&mInput->stream->common);
4841}
4842
Glenn Kastene198c362013-08-13 09:13:36 -07004843sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004844 const sp<AudioFlinger::Client>& client,
4845 uint32_t sampleRate,
4846 audio_format_t format,
4847 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08004848 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08004849 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004850 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004851 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004852 pid_t tid,
4853 status_t *status)
4854{
Glenn Kasten74935e42013-12-19 08:56:45 -08004855 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004856 sp<RecordTrack> track;
4857 status_t lStatus;
4858
4859 lStatus = initCheck();
4860 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004861 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004862 goto Exit;
4863 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07004864
Glenn Kasten90e58b12013-07-31 16:16:02 -07004865 // client expresses a preference for FAST, but we get the final say
4866 if (*flags & IAudioFlinger::TRACK_FAST) {
4867 if (
4868 // use case: callback handler and frame count is default or at least as large as HAL
4869 (
4870 (tid != -1) &&
4871 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004872 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004873 ) &&
4874 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4875 // mono or stereo
4876 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4877 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4878 // hardware sample rate
4879 (sampleRate == mSampleRate) &&
4880 // record thread has an associated fast recorder
4881 hasFastRecorder()
4882 // FIXME test that RecordThread for this fast track has a capable output HAL
4883 // FIXME add a permission test also?
4884 ) {
4885 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4886 if (frameCount == 0) {
4887 frameCount = mFrameCount * kFastTrackMultiplier;
4888 }
4889 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4890 frameCount, mFrameCount);
4891 } else {
4892 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4893 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4894 "hasFastRecorder=%d tid=%d",
4895 frameCount, mFrameCount, format,
4896 audio_is_linear_pcm(format),
4897 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4898 *flags &= ~IAudioFlinger::TRACK_FAST;
4899 // For compatibility with AudioRecord calculation, buffer depth is forced
4900 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4901 // This is probably too conservative, but legacy application code may depend on it.
4902 // If you change this calculation, also review the start threshold which is related.
4903 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4904 size_t mNormalFrameCount = 2048; // FIXME
4905 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4906 if (minBufCount < 2) {
4907 minBufCount = 2;
4908 }
4909 size_t minFrameCount = mNormalFrameCount * minBufCount;
4910 if (frameCount < minFrameCount) {
4911 frameCount = minFrameCount;
4912 }
4913 }
4914 }
Glenn Kasten74935e42013-12-19 08:56:45 -08004915 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07004916
Eric Laurent81784c32012-11-19 14:55:58 -08004917 // FIXME use flags and tid similar to createTrack_l()
4918
4919 { // scope for mLock
4920 Mutex::Autolock _l(mLock);
4921
4922 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004923 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004924
Glenn Kasten03003332013-08-06 15:40:54 -07004925 lStatus = track->initCheck();
4926 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004927 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08004928 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004929 goto Exit;
4930 }
4931 mTracks.add(track);
4932
4933 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4934 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4935 mAudioFlinger->btNrecIsOff();
4936 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4937 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004938
4939 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4940 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4941 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4942 // so ask activity manager to do this on our behalf
4943 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4944 }
Eric Laurent81784c32012-11-19 14:55:58 -08004945 }
4946 lStatus = NO_ERROR;
4947
4948Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07004949 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08004950 return track;
4951}
4952
4953status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4954 AudioSystem::sync_event_t event,
4955 int triggerSession)
4956{
4957 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4958 sp<ThreadBase> strongMe = this;
4959 status_t status = NO_ERROR;
4960
4961 if (event == AudioSystem::SYNC_EVENT_NONE) {
4962 clearSyncStartEvent();
4963 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4964 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4965 triggerSession,
4966 recordTrack->sessionId(),
4967 syncStartEventCallback,
4968 this);
4969 // Sync event can be cancelled by the trigger session if the track is not in a
4970 // compatible state in which case we start record immediately
4971 if (mSyncStartEvent->isCancelled()) {
4972 clearSyncStartEvent();
4973 } else {
4974 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4975 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4976 }
4977 }
4978
4979 {
Glenn Kasten47c20702013-08-13 15:37:35 -07004980 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08004981 AutoMutex lock(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004982 if (mActiveTracks.size() > 0) {
4983 // FIXME does not work for multiple active tracks
4984 if (mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004985 status = -EBUSY;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004986 } else if (recordTrack->mState == TrackBase::PAUSING) {
4987 recordTrack->mState = TrackBase::ACTIVE;
Eric Laurent81784c32012-11-19 14:55:58 -08004988 }
4989 return status;
4990 }
4991
Glenn Kasten47c20702013-08-13 15:37:35 -07004992 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
Eric Laurent81784c32012-11-19 14:55:58 -08004993 recordTrack->mState = TrackBase::IDLE;
Glenn Kasten2b806402013-11-20 16:37:38 -08004994 mActiveTracks.add(recordTrack);
4995 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004996 mLock.unlock();
4997 status_t status = AudioSystem::startInput(mId);
4998 mLock.lock();
Glenn Kasten47c20702013-08-13 15:37:35 -07004999 // FIXME should verify that mActiveTrack is still == recordTrack
Eric Laurent81784c32012-11-19 14:55:58 -08005000 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005001 mActiveTracks.remove(recordTrack);
5002 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005003 clearSyncStartEvent();
5004 return status;
5005 }
Glenn Kasten85948432013-08-19 12:09:05 -07005006 // FIXME LEGACY
Eric Laurent81784c32012-11-19 14:55:58 -08005007 mRsmpInIndex = mFrameCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005008 mRsmpInFront = 0;
5009 mRsmpInRear = 0;
5010 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005011 mBytesRead = 0;
5012 if (mResampler != NULL) {
5013 mResampler->reset();
5014 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005015 // FIXME hijacking a playback track state name which was intended for start after pause;
5016 // here 'STARTING_2' would be more accurate
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005017 recordTrack->mState = TrackBase::RESUMING;
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // signal thread to start
5019 ALOGV("Signal record thread");
5020 mWaitWorkCV.broadcast();
5021 // do not wait for mStartStopCond if exiting
5022 if (exitPending()) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005023 mActiveTracks.remove(recordTrack);
5024 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005025 status = INVALID_OPERATION;
5026 goto startError;
5027 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005028 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005029 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005030 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005031 ALOGV("Record failed to start");
5032 status = BAD_VALUE;
5033 goto startError;
5034 }
5035 ALOGV("Record started OK");
5036 return status;
5037 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005038
Eric Laurent81784c32012-11-19 14:55:58 -08005039startError:
5040 AudioSystem::stopInput(mId);
5041 clearSyncStartEvent();
5042 return status;
5043}
5044
5045void AudioFlinger::RecordThread::clearSyncStartEvent()
5046{
5047 if (mSyncStartEvent != 0) {
5048 mSyncStartEvent->cancel();
5049 }
5050 mSyncStartEvent.clear();
5051 mFramestoDrop = 0;
5052}
5053
5054void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5055{
5056 sp<SyncEvent> strongEvent = event.promote();
5057
5058 if (strongEvent != 0) {
5059 RecordThread *me = (RecordThread *)strongEvent->cookie();
5060 me->handleSyncStartEvent(strongEvent);
5061 }
5062}
5063
5064void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5065{
5066 if (event == mSyncStartEvent) {
5067 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5068 // from audio HAL
5069 mFramestoDrop = mFrameCount * 2;
5070 }
5071}
5072
Glenn Kastena8356f62013-07-25 14:37:52 -07005073bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005074 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005075 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005076 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005077 return false;
5078 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005079 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005080 recordTrack->mState = TrackBase::PAUSING;
5081 // do not wait for mStartStopCond if exiting
5082 if (exitPending()) {
5083 return true;
5084 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005085 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005086 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005087 // if we have been restarted, recordTrack is in mActiveTracks here
5088 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 ALOGV("Record stopped OK");
5090 return true;
5091 }
5092 return false;
5093}
5094
Glenn Kasten0f11b512014-01-31 16:18:54 -08005095bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005096{
5097 return false;
5098}
5099
Glenn Kasten0f11b512014-01-31 16:18:54 -08005100status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005101{
5102#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5103 if (!isValidSyncEvent(event)) {
5104 return BAD_VALUE;
5105 }
5106
5107 int eventSession = event->triggerSession();
5108 status_t ret = NAME_NOT_FOUND;
5109
5110 Mutex::Autolock _l(mLock);
5111
5112 for (size_t i = 0; i < mTracks.size(); i++) {
5113 sp<RecordTrack> track = mTracks[i];
5114 if (eventSession == track->sessionId()) {
5115 (void) track->setSyncEvent(event);
5116 ret = NO_ERROR;
5117 }
5118 }
5119 return ret;
5120#else
5121 return BAD_VALUE;
5122#endif
5123}
5124
5125// destroyTrack_l() must be called with ThreadBase::mLock held
5126void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5127{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 track->terminate();
5129 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005130 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005131 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005132 removeTrack_l(track);
5133 }
5134}
5135
5136void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5137{
5138 mTracks.remove(track);
5139 // need anything related to effects here?
5140}
5141
5142void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5143{
5144 dumpInternals(fd, args);
5145 dumpTracks(fd, args);
5146 dumpEffectChains(fd, args);
5147}
5148
5149void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5150{
Marco Nelissenb2208842014-02-07 14:00:50 -08005151 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005152
Glenn Kasten2b806402013-11-20 16:37:38 -08005153 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005154 fdprintf(fd, " In index: %zu\n", mRsmpInIndex);
5155 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Marco Nelissenb2208842014-02-07 14:00:50 -08005156 fdprintf(fd, " Resampling: %d\n", (mResampler != NULL));
5157 fdprintf(fd, " Out channel count: %u\n", mReqChannelCount);
5158 fdprintf(fd, " Out sample rate: %u\n", mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005159 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -08005160 fdprintf(fd, " No active record client\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005161 }
5162
Eric Laurent81784c32012-11-19 14:55:58 -08005163 dumpBase(fd, args);
5164}
5165
Glenn Kasten0f11b512014-01-31 16:18:54 -08005166void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005167{
5168 const size_t SIZE = 256;
5169 char buffer[SIZE];
5170 String8 result;
5171
Marco Nelissenb2208842014-02-07 14:00:50 -08005172 size_t numtracks = mTracks.size();
5173 size_t numactive = mActiveTracks.size();
5174 size_t numactiveseen = 0;
5175 fdprintf(fd, " %d Tracks", numtracks);
5176 if (numtracks) {
5177 fdprintf(fd, " of which %d are active\n", numactive);
5178 RecordTrack::appendDumpHeader(result);
5179 for (size_t i = 0; i < numtracks ; ++i) {
5180 sp<RecordTrack> track = mTracks[i];
5181 if (track != 0) {
5182 bool active = mActiveTracks.indexOf(track) >= 0;
5183 if (active) {
5184 numactiveseen++;
5185 }
5186 track->dump(buffer, SIZE, active);
5187 result.append(buffer);
5188 }
Eric Laurent81784c32012-11-19 14:55:58 -08005189 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005190 } else {
5191 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005192 }
5193
Marco Nelissenb2208842014-02-07 14:00:50 -08005194 if (numactiveseen != numactive) {
5195 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5196 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005197 result.append(buffer);
5198 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005199 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005200 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005201 if (mTracks.indexOf(track) < 0) {
5202 track->dump(buffer, SIZE, true);
5203 result.append(buffer);
5204 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005205 }
Eric Laurent81784c32012-11-19 14:55:58 -08005206
5207 }
5208 write(fd, result.string(), result.size());
5209}
5210
5211// AudioBufferProvider interface
Glenn Kasten0f11b512014-01-31 16:18:54 -08005212status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005213{
Glenn Kasten85948432013-08-19 12:09:05 -07005214 int32_t rear = mRsmpInRear;
5215 int32_t front = mRsmpInFront;
5216 ssize_t filled = rear - front;
5217 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2);
5218 // 'filled' may be non-contiguous, so return only the first contiguous chunk
5219 front &= mRsmpInFramesP2 - 1;
5220 size_t part1 = mRsmpInFramesP2 - front;
5221 if (part1 > (size_t) filled) {
5222 part1 = filled;
5223 }
5224 size_t ask = buffer->frameCount;
5225 ALOG_ASSERT(ask > 0);
5226 if (part1 > ask) {
5227 part1 = ask;
5228 }
5229 if (part1 == 0) {
5230 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5231 ALOGE("RecordThread::getNextBuffer() starved");
5232 buffer->raw = NULL;
5233 buffer->frameCount = 0;
5234 mRsmpInUnrel = 0;
5235 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005236 }
5237
Glenn Kasten85948432013-08-19 12:09:05 -07005238 buffer->raw = mRsmpInBuffer + front * mChannelCount;
5239 buffer->frameCount = part1;
5240 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005241 return NO_ERROR;
5242}
5243
5244// AudioBufferProvider interface
5245void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5246{
Glenn Kasten85948432013-08-19 12:09:05 -07005247 size_t stepCount = buffer->frameCount;
5248 if (stepCount == 0) {
5249 return;
5250 }
5251 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
5252 mRsmpInUnrel -= stepCount;
5253 mRsmpInFront += stepCount;
5254 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005255 buffer->frameCount = 0;
5256}
5257
5258bool AudioFlinger::RecordThread::checkForNewParameters_l()
5259{
5260 bool reconfig = false;
5261
5262 while (!mNewParameters.isEmpty()) {
5263 status_t status = NO_ERROR;
5264 String8 keyValuePair = mNewParameters[0];
5265 AudioParameter param = AudioParameter(keyValuePair);
5266 int value;
5267 audio_format_t reqFormat = mFormat;
5268 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005269 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005270
5271 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5272 reqSamplingRate = value;
5273 reconfig = true;
5274 }
5275 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005276 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5277 status = BAD_VALUE;
5278 } else {
5279 reqFormat = (audio_format_t) value;
5280 reconfig = true;
5281 }
Eric Laurent81784c32012-11-19 14:55:58 -08005282 }
5283 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005284 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5285 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5286 status = BAD_VALUE;
5287 } else {
5288 reqChannelMask = mask;
5289 reconfig = true;
5290 }
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5293 // do not accept frame count changes if tracks are open as the track buffer
5294 // size depends on frame count and correct behavior would not be guaranteed
5295 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005296 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005297 status = INVALID_OPERATION;
5298 } else {
5299 reconfig = true;
5300 }
5301 }
5302 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5303 // forward device change to effects that have requested to be
5304 // aware of attached audio device.
5305 for (size_t i = 0; i < mEffectChains.size(); i++) {
5306 mEffectChains[i]->setDevice_l(value);
5307 }
5308
5309 // store input device and output device but do not forward output device to audio HAL.
5310 // Note that status is ignored by the caller for output device
5311 // (see AudioFlinger::setParameters()
5312 if (audio_is_output_devices(value)) {
5313 mOutDevice = value;
5314 status = BAD_VALUE;
5315 } else {
5316 mInDevice = value;
5317 // disable AEC and NS if the device is a BT SCO headset supporting those
5318 // pre processings
5319 if (mTracks.size() > 0) {
5320 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5321 mAudioFlinger->btNrecIsOff();
5322 for (size_t i = 0; i < mTracks.size(); i++) {
5323 sp<RecordTrack> track = mTracks[i];
5324 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5325 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5326 }
5327 }
5328 }
5329 }
5330 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5331 mAudioSource != (audio_source_t)value) {
5332 // forward device change to effects that have requested to be
5333 // aware of attached audio device.
5334 for (size_t i = 0; i < mEffectChains.size(); i++) {
5335 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5336 }
5337 mAudioSource = (audio_source_t)value;
5338 }
Glenn Kastene198c362013-08-13 09:13:36 -07005339
Eric Laurent81784c32012-11-19 14:55:58 -08005340 if (status == NO_ERROR) {
5341 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5342 keyValuePair.string());
5343 if (status == INVALID_OPERATION) {
5344 inputStandBy();
5345 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5346 keyValuePair.string());
5347 }
5348 if (reconfig) {
5349 if (status == BAD_VALUE &&
5350 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5351 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005352 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005353 <= (2 * reqSamplingRate)) &&
5354 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5355 <= FCC_2 &&
Glenn Kastenec3fb502013-07-17 07:30:58 -07005356 (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5357 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005358 status = NO_ERROR;
5359 }
5360 if (status == NO_ERROR) {
5361 readInputParameters();
5362 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5363 }
5364 }
5365 }
5366
5367 mNewParameters.removeAt(0);
5368
5369 mParamStatus = status;
5370 mParamCond.signal();
5371 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5372 // already timed out waiting for the status and will never signal the condition.
5373 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5374 }
5375 return reconfig;
5376}
5377
5378String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5379{
Eric Laurent81784c32012-11-19 14:55:58 -08005380 Mutex::Autolock _l(mLock);
5381 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005382 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
5384
Glenn Kastend8ea6992013-07-16 14:17:15 -07005385 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5386 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005387 free(s);
5388 return out_s8;
5389}
5390
Glenn Kasten0f11b512014-01-31 16:18:54 -08005391void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005392 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005393 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005394
5395 switch (event) {
5396 case AudioSystem::INPUT_OPENED:
5397 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005398 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005399 desc.samplingRate = mSampleRate;
5400 desc.format = mFormat;
5401 desc.frameCount = mFrameCount;
5402 desc.latency = 0;
5403 param2 = &desc;
5404 break;
5405
5406 case AudioSystem::INPUT_CLOSED:
5407 default:
5408 break;
5409 }
5410 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5411}
5412
5413void AudioFlinger::RecordThread::readInputParameters()
5414{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005415 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005416 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005417 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005418 mRsmpOutBuffer = NULL;
5419 delete mResampler;
5420 mResampler = NULL;
5421
5422 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5423 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005424 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005425 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005426 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005427 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005428 }
Eric Laurent81784c32012-11-19 14:55:58 -08005429 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005430 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5431 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07005432 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5433 // 1 full output buffer, regardless of the alignment of the available input.
5434 mRsmpInFrames = mFrameCount * 3;
5435 mRsmpInFramesP2 = roundup(mRsmpInFrames);
5436 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5437 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5438 mRsmpInFront = 0;
5439 mRsmpInRear = 0;
5440 mRsmpInUnrel = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005441
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07005442 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
Glenn Kasten579dd272013-11-08 14:26:14 -08005443 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08005444 mResampler->setSampleRate(mSampleRate);
5445 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten85948432013-08-19 12:09:05 -07005446 // resampler always outputs stereo
Glenn Kasten34af0262013-07-30 11:52:39 -07005447 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005448 }
5449 mRsmpInIndex = mFrameCount;
5450}
5451
Glenn Kasten5f972c02014-01-13 09:59:31 -08005452uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005453{
5454 Mutex::Autolock _l(mLock);
5455 if (initCheck() != NO_ERROR) {
5456 return 0;
5457 }
5458
5459 return mInput->stream->get_input_frames_lost(mInput->stream);
5460}
5461
5462uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5463{
5464 Mutex::Autolock _l(mLock);
5465 uint32_t result = 0;
5466 if (getEffectChain_l(sessionId) != 0) {
5467 result = EFFECT_SESSION;
5468 }
5469
5470 for (size_t i = 0; i < mTracks.size(); ++i) {
5471 if (sessionId == mTracks[i]->sessionId()) {
5472 result |= TRACK_SESSION;
5473 break;
5474 }
5475 }
5476
5477 return result;
5478}
5479
5480KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5481{
5482 KeyedVector<int, bool> ids;
5483 Mutex::Autolock _l(mLock);
5484 for (size_t j = 0; j < mTracks.size(); ++j) {
5485 sp<RecordThread::RecordTrack> track = mTracks[j];
5486 int sessionId = track->sessionId();
5487 if (ids.indexOfKey(sessionId) < 0) {
5488 ids.add(sessionId, true);
5489 }
5490 }
5491 return ids;
5492}
5493
5494AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5495{
5496 Mutex::Autolock _l(mLock);
5497 AudioStreamIn *input = mInput;
5498 mInput = NULL;
5499 return input;
5500}
5501
5502// this method must always be called either with ThreadBase mLock held or inside the thread loop
5503audio_stream_t* AudioFlinger::RecordThread::stream() const
5504{
5505 if (mInput == NULL) {
5506 return NULL;
5507 }
5508 return &mInput->stream->common;
5509}
5510
5511status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5512{
5513 // only one chain per input thread
5514 if (mEffectChains.size() != 0) {
5515 return INVALID_OPERATION;
5516 }
5517 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5518
5519 chain->setInBuffer(NULL);
5520 chain->setOutBuffer(NULL);
5521
5522 checkSuspendOnAddEffectChain_l(chain);
5523
5524 mEffectChains.add(chain);
5525
5526 return NO_ERROR;
5527}
5528
5529size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5530{
5531 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5532 ALOGW_IF(mEffectChains.size() != 1,
5533 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5534 chain.get(), mEffectChains.size(), this);
5535 if (mEffectChains.size() == 1) {
5536 mEffectChains.removeAt(0);
5537 }
5538 return 0;
5539}
5540
5541}; // namespace android