blob: 742163b92db34003cace5aaa6e33863a80c947a7 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080037#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039
40// NBAIO implementations
41#include <media/nbaio/AudioStreamOutSink.h>
42#include <media/nbaio/MonoPipe.h>
43#include <media/nbaio/MonoPipeReader.h>
44#include <media/nbaio/Pipe.h>
45#include <media/nbaio/PipeReader.h>
46#include <media/nbaio/SourceAudioBufferProvider.h>
47
48#include <powermanager/PowerManager.h>
49
50#include <common_time/cc_helper.h>
51#include <common_time/local_clock.h>
52
53#include "AudioFlinger.h"
54#include "AudioMixer.h"
55#include "FastMixer.h"
56#include "ServiceUtilities.h"
57#include "SchedulingPolicyService.h"
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef DEBUG_CPU_USAGE
65#include <cpustats/CentralTendencyStatistics.h>
66#include <cpustats/ThreadCpuUsage.h>
67#endif
68
69// ----------------------------------------------------------------------------
70
71// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
83
84namespace android {
85
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95// don't warn about blocked writes or record buffer overflows more often than this
96static const nsecs_t kWarningThrottleNs = seconds(5);
97
98// RecordThread loop sleep time upon application overrun or audio HAL read error
99static const int kRecordThreadSleepUs = 5000;
100
Eric Laurent10351942014-05-08 18:49:52 -0700101// maximum time to wait in sendConfigEvent_l() for a status to be received
102static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800103
104// minimum sleep time for the mixer thread loop when tracks are active but in underrun
105static const uint32_t kMinThreadSleepTimeUs = 5000;
106// maximum divider applied to the active sleep time in the mixer thread loop
107static const uint32_t kMaxThreadSleepTimeShift = 2;
108
Andy Hung09a50072014-02-27 14:30:47 -0800109// minimum normal sink buffer size, expressed in milliseconds rather than frames
110static const uint32_t kMinNormalSinkBufferSizeMs = 20;
111// maximum normal sink buffer size
112static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800113
Eric Laurent972a1732013-09-04 09:42:59 -0700114// Offloaded output thread standby delay: allows track transition without going to standby
115static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
116
Eric Laurent81784c32012-11-19 14:55:58 -0800117// Whether to use fast mixer
118static const enum {
119 FastMixer_Never, // never initialize or use: for debugging only
120 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
121 // normal mixer multiplier is 1
122 FastMixer_Static, // initialize if needed, then use all the time if initialized,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
125 // multiplier is calculated based on min & max normal mixer buffer size
126 // FIXME for FastMixer_Dynamic:
127 // Supporting this option will require fixing HALs that can't handle large writes.
128 // For example, one HAL implementation returns an error from a large write,
129 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
130 // We could either fix the HAL implementations, or provide a wrapper that breaks
131 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
132} kUseFastMixer = FastMixer_Static;
133
134// Priorities for requestPriority
135static const int kPriorityAudioApp = 2;
136static const int kPriorityFastMixer = 3;
137
138// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
139// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800140// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
141// So for now we just assume that client is double-buffered for fast tracks.
142// FIXME It would be better for client to tell AudioFlinger the value of N,
143// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800144// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700145
146// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800147static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800148
Glenn Kasten03490092014-05-27 12:30:54 -0700149// The minimum and maximum allowed values
150static const int kFastTrackMultiplierMin = 1;
151static const int kFastTrackMultiplierMax = 2;
152
153// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
154static int sFastTrackMultiplier = kFastTrackMultiplier;
155
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700156// See Thread::readOnlyHeap().
157// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
158// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
159// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
160static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
161
Eric Laurent81784c32012-11-19 14:55:58 -0800162// ----------------------------------------------------------------------------
163
Glenn Kasten03490092014-05-27 12:30:54 -0700164static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
165
166static void sFastTrackMultiplierInit()
167{
168 char value[PROPERTY_VALUE_MAX];
169 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
170 char *endptr;
171 unsigned long ul = strtoul(value, &endptr, 0);
172 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
173 sFastTrackMultiplier = (int) ul;
174 }
175 }
176}
177
178// ----------------------------------------------------------------------------
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180#ifdef ADD_BATTERY_DATA
181// To collect the amplifier usage
182static void addBatteryData(uint32_t params) {
183 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
184 if (service == NULL) {
185 // it already logged
186 return;
187 }
188
189 service->addBatteryData(params);
190}
191#endif
192
193
194// ----------------------------------------------------------------------------
195// CPU Stats
196// ----------------------------------------------------------------------------
197
198class CpuStats {
199public:
200 CpuStats();
201 void sample(const String8 &title);
202#ifdef DEBUG_CPU_USAGE
203private:
204 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
205 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
206
207 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
208
209 int mCpuNum; // thread's current CPU number
210 int mCpukHz; // frequency of thread's current CPU in kHz
211#endif
212};
213
214CpuStats::CpuStats()
215#ifdef DEBUG_CPU_USAGE
216 : mCpuNum(-1), mCpukHz(-1)
217#endif
218{
219}
220
Glenn Kasten0f11b512014-01-31 16:18:54 -0800221void CpuStats::sample(const String8 &title
222#ifndef DEBUG_CPU_USAGE
223 __unused
224#endif
225 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800226#ifdef DEBUG_CPU_USAGE
227 // get current thread's delta CPU time in wall clock ns
228 double wcNs;
229 bool valid = mCpuUsage.sampleAndEnable(wcNs);
230
231 // record sample for wall clock statistics
232 if (valid) {
233 mWcStats.sample(wcNs);
234 }
235
236 // get the current CPU number
237 int cpuNum = sched_getcpu();
238
239 // get the current CPU frequency in kHz
240 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
241
242 // check if either CPU number or frequency changed
243 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
244 mCpuNum = cpuNum;
245 mCpukHz = cpukHz;
246 // ignore sample for purposes of cycles
247 valid = false;
248 }
249
250 // if no change in CPU number or frequency, then record sample for cycle statistics
251 if (valid && mCpukHz > 0) {
252 double cycles = wcNs * cpukHz * 0.000001;
253 mHzStats.sample(cycles);
254 }
255
256 unsigned n = mWcStats.n();
257 // mCpuUsage.elapsed() is expensive, so don't call it every loop
258 if ((n & 127) == 1) {
259 long long elapsed = mCpuUsage.elapsed();
260 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
261 double perLoop = elapsed / (double) n;
262 double perLoop100 = perLoop * 0.01;
263 double perLoop1k = perLoop * 0.001;
264 double mean = mWcStats.mean();
265 double stddev = mWcStats.stddev();
266 double minimum = mWcStats.minimum();
267 double maximum = mWcStats.maximum();
268 double meanCycles = mHzStats.mean();
269 double stddevCycles = mHzStats.stddev();
270 double minCycles = mHzStats.minimum();
271 double maxCycles = mHzStats.maximum();
272 mCpuUsage.resetElapsed();
273 mWcStats.reset();
274 mHzStats.reset();
275 ALOGD("CPU usage for %s over past %.1f secs\n"
276 " (%u mixer loops at %.1f mean ms per loop):\n"
277 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
278 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
279 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
280 title.string(),
281 elapsed * .000000001, n, perLoop * .000001,
282 mean * .001,
283 stddev * .001,
284 minimum * .001,
285 maximum * .001,
286 mean / perLoop100,
287 stddev / perLoop100,
288 minimum / perLoop100,
289 maximum / perLoop100,
290 meanCycles / perLoop1k,
291 stddevCycles / perLoop1k,
292 minCycles / perLoop1k,
293 maxCycles / perLoop1k);
294
295 }
296 }
297#endif
298};
299
300// ----------------------------------------------------------------------------
301// ThreadBase
302// ----------------------------------------------------------------------------
303
304AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
305 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
306 : Thread(false /*canCallJava*/),
307 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700308 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700309 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800310 // are set by PlaybackThread::readOutputParameters_l() or
311 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700312 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800313 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
314 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
315 // mName will be set by concrete (non-virtual) subclass
316 mDeathRecipient(new PMDeathRecipient(this))
317{
318}
319
320AudioFlinger::ThreadBase::~ThreadBase()
321{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700322 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700323 mConfigEvents.clear();
324
Eric Laurent81784c32012-11-19 14:55:58 -0800325 // do not lock the mutex in destructor
326 releaseWakeLock_l();
327 if (mPowerManager != 0) {
328 sp<IBinder> binder = mPowerManager->asBinder();
329 binder->unlinkToDeath(mDeathRecipient);
330 }
331}
332
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700333status_t AudioFlinger::ThreadBase::readyToRun()
334{
335 status_t status = initCheck();
336 if (status == NO_ERROR) {
337 ALOGI("AudioFlinger's thread %p ready to run", this);
338 } else {
339 ALOGE("No working audio driver found.");
340 }
341 return status;
342}
343
Eric Laurent81784c32012-11-19 14:55:58 -0800344void AudioFlinger::ThreadBase::exit()
345{
346 ALOGV("ThreadBase::exit");
347 // do any cleanup required for exit to succeed
348 preExit();
349 {
350 // This lock prevents the following race in thread (uniprocessor for illustration):
351 // if (!exitPending()) {
352 // // context switch from here to exit()
353 // // exit() calls requestExit(), what exitPending() observes
354 // // exit() calls signal(), which is dropped since no waiters
355 // // context switch back from exit() to here
356 // mWaitWorkCV.wait(...);
357 // // now thread is hung
358 // }
359 AutoMutex lock(mLock);
360 requestExit();
361 mWaitWorkCV.broadcast();
362 }
363 // When Thread::requestExitAndWait is made virtual and this method is renamed to
364 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
365 requestExitAndWait();
366}
367
368status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
369{
370 status_t status;
371
372 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
373 Mutex::Autolock _l(mLock);
374
Eric Laurent10351942014-05-08 18:49:52 -0700375 return sendSetParameterConfigEvent_l(keyValuePairs);
376}
377
378// sendConfigEvent_l() must be called with ThreadBase::mLock held
379// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
380status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
381{
382 status_t status = NO_ERROR;
383
384 mConfigEvents.add(event);
385 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800386 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700387 mLock.unlock();
388 {
389 Mutex::Autolock _l(event->mLock);
390 while (event->mWaitStatus) {
391 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
392 event->mStatus = TIMED_OUT;
393 event->mWaitStatus = false;
394 }
395 }
396 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800397 }
Eric Laurent10351942014-05-08 18:49:52 -0700398 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800399 return status;
400}
401
402void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
403{
404 Mutex::Autolock _l(mLock);
405 sendIoConfigEvent_l(event, param);
406}
407
408// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
409void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
410{
Eric Laurent10351942014-05-08 18:49:52 -0700411 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
412 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800413}
414
415// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
416void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
417{
Eric Laurent10351942014-05-08 18:49:52 -0700418 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
419 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800420}
421
Eric Laurent10351942014-05-08 18:49:52 -0700422// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
423status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800424{
Eric Laurent10351942014-05-08 18:49:52 -0700425 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
426 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700427}
428
Eric Laurent1c333e22014-05-20 10:48:17 -0700429status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
430 const struct audio_patch *patch,
431 audio_patch_handle_t *handle)
432{
433 Mutex::Autolock _l(mLock);
434 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
435 status_t status = sendConfigEvent_l(configEvent);
436 if (status == NO_ERROR) {
437 CreateAudioPatchConfigEventData *data =
438 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
439 *handle = data->mHandle;
440 }
441 return status;
442}
443
444status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
445 const audio_patch_handle_t handle)
446{
447 Mutex::Autolock _l(mLock);
448 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
449 return sendConfigEvent_l(configEvent);
450}
451
452
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700453// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700454void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700455{
Eric Laurent10351942014-05-08 18:49:52 -0700456 bool configChanged = false;
457
Eric Laurent81784c32012-11-19 14:55:58 -0800458 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700459 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
460 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800461 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700462 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700463 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700464 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
465 // FIXME Need to understand why this has to be done asynchronously
466 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700467 true /*asynchronous*/);
468 if (err != 0) {
469 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700470 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700471 }
472 } break;
473 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700474 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700475 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700476 } break;
477 case CFG_EVENT_SET_PARAMETER: {
478 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
479 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
480 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700481 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700482 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700483 case CFG_EVENT_CREATE_AUDIO_PATCH: {
484 CreateAudioPatchConfigEventData *data =
485 (CreateAudioPatchConfigEventData *)event->mData.get();
486 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
487 } break;
488 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
489 ReleaseAudioPatchConfigEventData *data =
490 (ReleaseAudioPatchConfigEventData *)event->mData.get();
491 event->mStatus = releaseAudioPatch_l(data->mHandle);
492 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700493 default:
Eric Laurent10351942014-05-08 18:49:52 -0700494 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700495 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800496 }
Eric Laurent10351942014-05-08 18:49:52 -0700497 {
498 Mutex::Autolock _l(event->mLock);
499 if (event->mWaitStatus) {
500 event->mWaitStatus = false;
501 event->mCond.signal();
502 }
503 }
504 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
505 }
506
507 if (configChanged) {
508 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Eric Laurent81784c32012-11-19 14:55:58 -0800510}
511
Marco Nelissenb2208842014-02-07 14:00:50 -0800512String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
513 String8 s;
514 if (output) {
515 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
516 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
517 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
518 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
519 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
520 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
521 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
522 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
523 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
524 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
525 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
526 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
527 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
528 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
529 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
530 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
531 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
532 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
533 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
534 } else {
535 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
536 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
537 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
538 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
539 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
540 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
541 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
542 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
543 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
544 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
545 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
546 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
547 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
548 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
549 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
550 }
551 int len = s.length();
552 if (s.length() > 2) {
553 char *str = s.lockBuffer(len);
554 s.unlockBuffer(len - 2);
555 }
556 return s;
557}
558
Glenn Kasten0f11b512014-01-31 16:18:54 -0800559void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800560{
561 const size_t SIZE = 256;
562 char buffer[SIZE];
563 String8 result;
564
565 bool locked = AudioFlinger::dumpTryLock(mLock);
566 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700567 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800568 }
569
Elliott Hughes87cebad2014-05-22 10:14:43 -0700570 dprintf(fd, " I/O handle: %d\n", mId);
571 dprintf(fd, " TID: %d\n", getTid());
572 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
573 dprintf(fd, " Sample rate: %u\n", mSampleRate);
574 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
575 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
576 dprintf(fd, " Channel Count: %u\n", mChannelCount);
577 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800578 channelMaskToString(mChannelMask, mType != RECORD).string());
Elliott Hughes87cebad2014-05-22 10:14:43 -0700579 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
580 dprintf(fd, " Frame size: %zu\n", mFrameSize);
581 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800582 size_t numConfig = mConfigEvents.size();
583 if (numConfig) {
584 for (size_t i = 0; i < numConfig; i++) {
585 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700586 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800587 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700588 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800589 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700590 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800591 }
Eric Laurent81784c32012-11-19 14:55:58 -0800592
593 if (locked) {
594 mLock.unlock();
595 }
596}
597
598void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
599{
600 const size_t SIZE = 256;
601 char buffer[SIZE];
602 String8 result;
603
Marco Nelissenb2208842014-02-07 14:00:50 -0800604 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000605 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800606 write(fd, buffer, strlen(buffer));
607
Marco Nelissenb2208842014-02-07 14:00:50 -0800608 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800609 sp<EffectChain> chain = mEffectChains[i];
610 if (chain != 0) {
611 chain->dump(fd, args);
612 }
613 }
614}
615
Marco Nelissene14a5d62013-10-03 08:51:24 -0700616void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800617{
618 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700619 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800620}
621
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100622String16 AudioFlinger::ThreadBase::getWakeLockTag()
623{
624 switch (mType) {
625 case MIXER:
626 return String16("AudioMix");
627 case DIRECT:
628 return String16("AudioDirectOut");
629 case DUPLICATING:
630 return String16("AudioDup");
631 case RECORD:
632 return String16("AudioIn");
633 case OFFLOAD:
634 return String16("AudioOffload");
635 default:
636 ALOG_ASSERT(false);
637 return String16("AudioUnknown");
638 }
639}
640
Marco Nelissene14a5d62013-10-03 08:51:24 -0700641void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800642{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800643 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800644 if (mPowerManager != 0) {
645 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700646 status_t status;
647 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700648 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700649 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100650 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700651 String16("media"),
652 uid);
653 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700654 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700655 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100656 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700657 String16("media"));
658 }
Eric Laurent81784c32012-11-19 14:55:58 -0800659 if (status == NO_ERROR) {
660 mWakeLockToken = binder;
661 }
662 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
663 }
664}
665
666void AudioFlinger::ThreadBase::releaseWakeLock()
667{
668 Mutex::Autolock _l(mLock);
669 releaseWakeLock_l();
670}
671
672void AudioFlinger::ThreadBase::releaseWakeLock_l()
673{
674 if (mWakeLockToken != 0) {
675 ALOGV("releaseWakeLock_l() %s", mName);
676 if (mPowerManager != 0) {
677 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
678 }
679 mWakeLockToken.clear();
680 }
681}
682
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800683void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
684 Mutex::Autolock _l(mLock);
685 updateWakeLockUids_l(uids);
686}
687
688void AudioFlinger::ThreadBase::getPowerManager_l() {
689
690 if (mPowerManager == 0) {
691 // use checkService() to avoid blocking if power service is not up yet
692 sp<IBinder> binder =
693 defaultServiceManager()->checkService(String16("power"));
694 if (binder == 0) {
695 ALOGW("Thread %s cannot connect to the power manager service", mName);
696 } else {
697 mPowerManager = interface_cast<IPowerManager>(binder);
698 binder->linkToDeath(mDeathRecipient);
699 }
700 }
701}
702
703void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
704
705 getPowerManager_l();
706 if (mWakeLockToken == NULL) {
707 ALOGE("no wake lock to update!");
708 return;
709 }
710 if (mPowerManager != 0) {
711 sp<IBinder> binder = new BBinder();
712 status_t status;
713 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
714 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
715 }
716}
717
Eric Laurent81784c32012-11-19 14:55:58 -0800718void AudioFlinger::ThreadBase::clearPowerManager()
719{
720 Mutex::Autolock _l(mLock);
721 releaseWakeLock_l();
722 mPowerManager.clear();
723}
724
Glenn Kasten0f11b512014-01-31 16:18:54 -0800725void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800726{
727 sp<ThreadBase> thread = mThread.promote();
728 if (thread != 0) {
729 thread->clearPowerManager();
730 }
731 ALOGW("power manager service died !!!");
732}
733
734void AudioFlinger::ThreadBase::setEffectSuspended(
735 const effect_uuid_t *type, bool suspend, int sessionId)
736{
737 Mutex::Autolock _l(mLock);
738 setEffectSuspended_l(type, suspend, sessionId);
739}
740
741void AudioFlinger::ThreadBase::setEffectSuspended_l(
742 const effect_uuid_t *type, bool suspend, int sessionId)
743{
744 sp<EffectChain> chain = getEffectChain_l(sessionId);
745 if (chain != 0) {
746 if (type != NULL) {
747 chain->setEffectSuspended_l(type, suspend);
748 } else {
749 chain->setEffectSuspendedAll_l(suspend);
750 }
751 }
752
753 updateSuspendedSessions_l(type, suspend, sessionId);
754}
755
756void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
757{
758 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
759 if (index < 0) {
760 return;
761 }
762
763 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
764 mSuspendedSessions.valueAt(index);
765
766 for (size_t i = 0; i < sessionEffects.size(); i++) {
767 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
768 for (int j = 0; j < desc->mRefCount; j++) {
769 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
770 chain->setEffectSuspendedAll_l(true);
771 } else {
772 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
773 desc->mType.timeLow);
774 chain->setEffectSuspended_l(&desc->mType, true);
775 }
776 }
777 }
778}
779
780void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
781 bool suspend,
782 int sessionId)
783{
784 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
785
786 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
787
788 if (suspend) {
789 if (index >= 0) {
790 sessionEffects = mSuspendedSessions.valueAt(index);
791 } else {
792 mSuspendedSessions.add(sessionId, sessionEffects);
793 }
794 } else {
795 if (index < 0) {
796 return;
797 }
798 sessionEffects = mSuspendedSessions.valueAt(index);
799 }
800
801
802 int key = EffectChain::kKeyForSuspendAll;
803 if (type != NULL) {
804 key = type->timeLow;
805 }
806 index = sessionEffects.indexOfKey(key);
807
808 sp<SuspendedSessionDesc> desc;
809 if (suspend) {
810 if (index >= 0) {
811 desc = sessionEffects.valueAt(index);
812 } else {
813 desc = new SuspendedSessionDesc();
814 if (type != NULL) {
815 desc->mType = *type;
816 }
817 sessionEffects.add(key, desc);
818 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
819 }
820 desc->mRefCount++;
821 } else {
822 if (index < 0) {
823 return;
824 }
825 desc = sessionEffects.valueAt(index);
826 if (--desc->mRefCount == 0) {
827 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
828 sessionEffects.removeItemsAt(index);
829 if (sessionEffects.isEmpty()) {
830 ALOGV("updateSuspendedSessions_l() restore removing session %d",
831 sessionId);
832 mSuspendedSessions.removeItem(sessionId);
833 }
834 }
835 }
836 if (!sessionEffects.isEmpty()) {
837 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
838 }
839}
840
841void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
842 bool enabled,
843 int sessionId)
844{
845 Mutex::Autolock _l(mLock);
846 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
847}
848
849void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
850 bool enabled,
851 int sessionId)
852{
853 if (mType != RECORD) {
854 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
855 // another session. This gives the priority to well behaved effect control panels
856 // and applications not using global effects.
857 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
858 // global effects
859 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
860 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
861 }
862 }
863
864 sp<EffectChain> chain = getEffectChain_l(sessionId);
865 if (chain != 0) {
866 chain->checkSuspendOnEffectEnabled(effect, enabled);
867 }
868}
869
870// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
871sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
872 const sp<AudioFlinger::Client>& client,
873 const sp<IEffectClient>& effectClient,
874 int32_t priority,
875 int sessionId,
876 effect_descriptor_t *desc,
877 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700878 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800879{
880 sp<EffectModule> effect;
881 sp<EffectHandle> handle;
882 status_t lStatus;
883 sp<EffectChain> chain;
884 bool chainCreated = false;
885 bool effectCreated = false;
886 bool effectRegistered = false;
887
888 lStatus = initCheck();
889 if (lStatus != NO_ERROR) {
890 ALOGW("createEffect_l() Audio driver not initialized.");
891 goto Exit;
892 }
893
Andy Hung98ef9782014-03-04 14:46:50 -0800894 // Reject any effect on Direct output threads for now, since the format of
895 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
896 if (mType == DIRECT) {
897 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
898 desc->name, mName);
899 lStatus = BAD_VALUE;
900 goto Exit;
901 }
902
Eric Laurent5baf2af2013-09-12 17:37:00 -0700903 // Allow global effects only on offloaded and mixer threads
904 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
905 switch (mType) {
906 case MIXER:
907 case OFFLOAD:
908 break;
909 case DIRECT:
910 case DUPLICATING:
911 case RECORD:
912 default:
913 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
914 lStatus = BAD_VALUE;
915 goto Exit;
916 }
Eric Laurent81784c32012-11-19 14:55:58 -0800917 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700918
Eric Laurent81784c32012-11-19 14:55:58 -0800919 // Only Pre processor effects are allowed on input threads and only on input threads
920 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
921 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
922 desc->name, desc->flags, mType);
923 lStatus = BAD_VALUE;
924 goto Exit;
925 }
926
927 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
928
929 { // scope for mLock
930 Mutex::Autolock _l(mLock);
931
932 // check for existing effect chain with the requested audio session
933 chain = getEffectChain_l(sessionId);
934 if (chain == 0) {
935 // create a new chain for this session
936 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
937 chain = new EffectChain(this, sessionId);
938 addEffectChain_l(chain);
939 chain->setStrategy(getStrategyForSession_l(sessionId));
940 chainCreated = true;
941 } else {
942 effect = chain->getEffectFromDesc_l(desc);
943 }
944
945 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
946
947 if (effect == 0) {
948 int id = mAudioFlinger->nextUniqueId();
949 // Check CPU and memory usage
950 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
951 if (lStatus != NO_ERROR) {
952 goto Exit;
953 }
954 effectRegistered = true;
955 // create a new effect module if none present in the chain
956 effect = new EffectModule(this, chain, desc, id, sessionId);
957 lStatus = effect->status();
958 if (lStatus != NO_ERROR) {
959 goto Exit;
960 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700961 effect->setOffloaded(mType == OFFLOAD, mId);
962
Eric Laurent81784c32012-11-19 14:55:58 -0800963 lStatus = chain->addEffect_l(effect);
964 if (lStatus != NO_ERROR) {
965 goto Exit;
966 }
967 effectCreated = true;
968
969 effect->setDevice(mOutDevice);
970 effect->setDevice(mInDevice);
971 effect->setMode(mAudioFlinger->getMode());
972 effect->setAudioSource(mAudioSource);
973 }
974 // create effect handle and connect it to effect module
975 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800976 lStatus = handle->initCheck();
977 if (lStatus == OK) {
978 lStatus = effect->addHandle(handle.get());
979 }
Eric Laurent81784c32012-11-19 14:55:58 -0800980 if (enabled != NULL) {
981 *enabled = (int)effect->isEnabled();
982 }
983 }
984
985Exit:
986 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
987 Mutex::Autolock _l(mLock);
988 if (effectCreated) {
989 chain->removeEffect_l(effect);
990 }
991 if (effectRegistered) {
992 AudioSystem::unregisterEffect(effect->id());
993 }
994 if (chainCreated) {
995 removeEffectChain_l(chain);
996 }
997 handle.clear();
998 }
999
Glenn Kasten9156ef32013-08-06 15:39:08 -07001000 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001001 return handle;
1002}
1003
1004sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1005{
1006 Mutex::Autolock _l(mLock);
1007 return getEffect_l(sessionId, effectId);
1008}
1009
1010sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1011{
1012 sp<EffectChain> chain = getEffectChain_l(sessionId);
1013 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1014}
1015
1016// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1017// PlaybackThread::mLock held
1018status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1019{
1020 // check for existing effect chain with the requested audio session
1021 int sessionId = effect->sessionId();
1022 sp<EffectChain> chain = getEffectChain_l(sessionId);
1023 bool chainCreated = false;
1024
Eric Laurent5baf2af2013-09-12 17:37:00 -07001025 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1026 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1027 this, effect->desc().name, effect->desc().flags);
1028
Eric Laurent81784c32012-11-19 14:55:58 -08001029 if (chain == 0) {
1030 // create a new chain for this session
1031 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1032 chain = new EffectChain(this, sessionId);
1033 addEffectChain_l(chain);
1034 chain->setStrategy(getStrategyForSession_l(sessionId));
1035 chainCreated = true;
1036 }
1037 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1038
1039 if (chain->getEffectFromId_l(effect->id()) != 0) {
1040 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1041 this, effect->desc().name, chain.get());
1042 return BAD_VALUE;
1043 }
1044
Eric Laurent5baf2af2013-09-12 17:37:00 -07001045 effect->setOffloaded(mType == OFFLOAD, mId);
1046
Eric Laurent81784c32012-11-19 14:55:58 -08001047 status_t status = chain->addEffect_l(effect);
1048 if (status != NO_ERROR) {
1049 if (chainCreated) {
1050 removeEffectChain_l(chain);
1051 }
1052 return status;
1053 }
1054
1055 effect->setDevice(mOutDevice);
1056 effect->setDevice(mInDevice);
1057 effect->setMode(mAudioFlinger->getMode());
1058 effect->setAudioSource(mAudioSource);
1059 return NO_ERROR;
1060}
1061
1062void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1063
1064 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1065 effect_descriptor_t desc = effect->desc();
1066 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1067 detachAuxEffect_l(effect->id());
1068 }
1069
1070 sp<EffectChain> chain = effect->chain().promote();
1071 if (chain != 0) {
1072 // remove effect chain if removing last effect
1073 if (chain->removeEffect_l(effect) == 0) {
1074 removeEffectChain_l(chain);
1075 }
1076 } else {
1077 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1078 }
1079}
1080
1081void AudioFlinger::ThreadBase::lockEffectChains_l(
1082 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1083{
1084 effectChains = mEffectChains;
1085 for (size_t i = 0; i < mEffectChains.size(); i++) {
1086 mEffectChains[i]->lock();
1087 }
1088}
1089
1090void AudioFlinger::ThreadBase::unlockEffectChains(
1091 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1092{
1093 for (size_t i = 0; i < effectChains.size(); i++) {
1094 effectChains[i]->unlock();
1095 }
1096}
1097
1098sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1099{
1100 Mutex::Autolock _l(mLock);
1101 return getEffectChain_l(sessionId);
1102}
1103
1104sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1105{
1106 size_t size = mEffectChains.size();
1107 for (size_t i = 0; i < size; i++) {
1108 if (mEffectChains[i]->sessionId() == sessionId) {
1109 return mEffectChains[i];
1110 }
1111 }
1112 return 0;
1113}
1114
1115void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1116{
1117 Mutex::Autolock _l(mLock);
1118 size_t size = mEffectChains.size();
1119 for (size_t i = 0; i < size; i++) {
1120 mEffectChains[i]->setMode_l(mode);
1121 }
1122}
1123
1124void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1125 EffectHandle *handle,
1126 bool unpinIfLast) {
1127
1128 Mutex::Autolock _l(mLock);
1129 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1130 // delete the effect module if removing last handle on it
1131 if (effect->removeHandle(handle) == 0) {
1132 if (!effect->isPinned() || unpinIfLast) {
1133 removeEffect_l(effect);
1134 AudioSystem::unregisterEffect(effect->id());
1135 }
1136 }
1137}
1138
1139// ----------------------------------------------------------------------------
1140// Playback
1141// ----------------------------------------------------------------------------
1142
1143AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1144 AudioStreamOut* output,
1145 audio_io_handle_t id,
1146 audio_devices_t device,
1147 type_t type)
1148 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001149 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001150 mMixerBufferEnabled(false),
1151 mMixerBuffer(NULL),
1152 mMixerBufferSize(0),
1153 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1154 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001155 mEffectBufferEnabled(false),
1156 mEffectBuffer(NULL),
1157 mEffectBufferSize(0),
1158 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1159 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001160 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001161 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001162 // mStreamTypes[] initialized in constructor body
1163 mOutput(output),
1164 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1165 mMixerStatus(MIXER_IDLE),
1166 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1167 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001168 mBytesRemaining(0),
1169 mCurrentWriteLength(0),
1170 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001171 mWriteAckSequence(0),
1172 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001173 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001174 mScreenState(AudioFlinger::mScreenState),
1175 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001176 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1177 // mLatchD, mLatchQ,
1178 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001179{
1180 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001181 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001182
1183 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1184 // it would be safer to explicitly pass initial masterVolume/masterMute as
1185 // parameter.
1186 //
1187 // If the HAL we are using has support for master volume or master mute,
1188 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1189 // and the mute set to false).
1190 mMasterVolume = audioFlinger->masterVolume_l();
1191 mMasterMute = audioFlinger->masterMute_l();
1192 if (mOutput && mOutput->audioHwDev) {
1193 if (mOutput->audioHwDev->canSetMasterVolume()) {
1194 mMasterVolume = 1.0;
1195 }
1196
1197 if (mOutput->audioHwDev->canSetMasterMute()) {
1198 mMasterMute = false;
1199 }
1200 }
1201
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001202 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001203
1204 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1205 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001206 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001207 stream = (audio_stream_type_t) (stream + 1)) {
1208 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1209 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1210 }
1211 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1212 // because mAudioFlinger doesn't have one to copy from
1213}
1214
1215AudioFlinger::PlaybackThread::~PlaybackThread()
1216{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001217 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001218 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001219 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001220 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001221}
1222
1223void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1224{
1225 dumpInternals(fd, args);
1226 dumpTracks(fd, args);
1227 dumpEffectChains(fd, args);
1228}
1229
Glenn Kasten0f11b512014-01-31 16:18:54 -08001230void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
1232 const size_t SIZE = 256;
1233 char buffer[SIZE];
1234 String8 result;
1235
Marco Nelissenb2208842014-02-07 14:00:50 -08001236 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001237 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1238 const stream_type_t *st = &mStreamTypes[i];
1239 if (i > 0) {
1240 result.appendFormat(", ");
1241 }
1242 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1243 if (st->mute) {
1244 result.append("M");
1245 }
1246 }
1247 result.append("\n");
1248 write(fd, result.string(), result.length());
1249 result.clear();
1250
Eric Laurent81784c32012-11-19 14:55:58 -08001251 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1252 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001253 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001254 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001255
1256 size_t numtracks = mTracks.size();
1257 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001258 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001259 size_t numactiveseen = 0;
1260 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001261 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001262 Track::appendDumpHeader(result);
1263 for (size_t i = 0; i < numtracks; ++i) {
1264 sp<Track> track = mTracks[i];
1265 if (track != 0) {
1266 bool active = mActiveTracks.indexOf(track) >= 0;
1267 if (active) {
1268 numactiveseen++;
1269 }
1270 track->dump(buffer, SIZE, active);
1271 result.append(buffer);
1272 }
1273 }
1274 } else {
1275 result.append("\n");
1276 }
1277 if (numactiveseen != numactive) {
1278 // some tracks in the active list were not in the tracks list
1279 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1280 " not in the track list\n");
1281 result.append(buffer);
1282 Track::appendDumpHeader(result);
1283 for (size_t i = 0; i < numactive; ++i) {
1284 sp<Track> track = mActiveTracks[i].promote();
1285 if (track != 0 && mTracks.indexOf(track) < 0) {
1286 track->dump(buffer, SIZE, true);
1287 result.append(buffer);
1288 }
1289 }
1290 }
1291
1292 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001293}
1294
1295void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1296{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001297 dprintf(fd, "\nOutput thread %p:\n", this);
1298 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1299 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1300 dprintf(fd, " Total writes: %d\n", mNumWrites);
1301 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1302 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1303 dprintf(fd, " Suspend count: %d\n", mSuspended);
1304 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1305 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1306 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1307 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001308
1309 dumpBase(fd, args);
1310}
1311
1312// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001313
1314void AudioFlinger::PlaybackThread::onFirstRef()
1315{
1316 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1317}
1318
1319// ThreadBase virtuals
1320void AudioFlinger::PlaybackThread::preExit()
1321{
1322 ALOGV(" preExit()");
1323 // FIXME this is using hard-coded strings but in the future, this functionality will be
1324 // converted to use audio HAL extensions required to support tunneling
1325 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1326}
1327
1328// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1329sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1330 const sp<AudioFlinger::Client>& client,
1331 audio_stream_type_t streamType,
1332 uint32_t sampleRate,
1333 audio_format_t format,
1334 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001335 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001336 const sp<IMemory>& sharedBuffer,
1337 int sessionId,
1338 IAudioFlinger::track_flags_t *flags,
1339 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001340 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001341 status_t *status)
1342{
Glenn Kasten74935e42013-12-19 08:56:45 -08001343 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001344 sp<Track> track;
1345 status_t lStatus;
1346
1347 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1348
1349 // client expresses a preference for FAST, but we get the final say
1350 if (*flags & IAudioFlinger::TRACK_FAST) {
1351 if (
1352 // not timed
1353 (!isTimed) &&
1354 // either of these use cases:
1355 (
1356 // use case 1: shared buffer with any frame count
1357 (
1358 (sharedBuffer != 0)
1359 ) ||
1360 // use case 2: callback handler and frame count is default or at least as large as HAL
1361 (
1362 (tid != -1) &&
1363 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001364 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001365 )
1366 ) &&
1367 // PCM data
1368 audio_is_linear_pcm(format) &&
1369 // mono or stereo
1370 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1371 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001372 // hardware sample rate
1373 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001374 // normal mixer has an associated fast mixer
1375 hasFastMixer() &&
1376 // there are sufficient fast track slots available
1377 (mFastTrackAvailMask != 0)
1378 // FIXME test that MixerThread for this fast track has a capable output HAL
1379 // FIXME add a permission test also?
1380 ) {
1381 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1382 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001383 // read the fast track multiplier property the first time it is needed
1384 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1385 if (ok != 0) {
1386 ALOGE("%s pthread_once failed: %d", __func__, ok);
1387 }
1388 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001389 }
1390 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1391 frameCount, mFrameCount);
1392 } else {
1393 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1394 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1395 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1396 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1397 audio_is_linear_pcm(format),
1398 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1399 *flags &= ~IAudioFlinger::TRACK_FAST;
1400 // For compatibility with AudioTrack calculation, buffer depth is forced
1401 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1402 // This is probably too conservative, but legacy application code may depend on it.
1403 // If you change this calculation, also review the start threshold which is related.
1404 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1405 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1406 if (minBufCount < 2) {
1407 minBufCount = 2;
1408 }
1409 size_t minFrameCount = mNormalFrameCount * minBufCount;
1410 if (frameCount < minFrameCount) {
1411 frameCount = minFrameCount;
1412 }
1413 }
1414 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001415 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001416
Glenn Kastenc3df8382014-03-13 15:05:25 -07001417 switch (mType) {
1418
1419 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001420 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001421 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001422 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1423 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001424 sampleRate, format, channelMask, mOutput, mFormat);
1425 lStatus = BAD_VALUE;
1426 goto Exit;
1427 }
1428 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001429 break;
1430
1431 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001432 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001433 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1434 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001435 sampleRate, format, channelMask, mOutput, mFormat);
1436 lStatus = BAD_VALUE;
1437 goto Exit;
1438 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001439 break;
1440
1441 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001442 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001443 ALOGE("createTrack_l() Bad parameter: format %#x \""
1444 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001445 format, mOutput, mFormat);
1446 lStatus = BAD_VALUE;
1447 goto Exit;
1448 }
Eric Laurent81784c32012-11-19 14:55:58 -08001449 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1450 if (sampleRate > mSampleRate*2) {
1451 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1452 lStatus = BAD_VALUE;
1453 goto Exit;
1454 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001455 break;
1456
Eric Laurent81784c32012-11-19 14:55:58 -08001457 }
1458
1459 lStatus = initCheck();
1460 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001461 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001462 goto Exit;
1463 }
1464
1465 { // scope for mLock
1466 Mutex::Autolock _l(mLock);
1467
1468 // all tracks in same audio session must share the same routing strategy otherwise
1469 // conflicts will happen when tracks are moved from one output to another by audio policy
1470 // manager
1471 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1472 for (size_t i = 0; i < mTracks.size(); ++i) {
1473 sp<Track> t = mTracks[i];
1474 if (t != 0 && !t->isOutputTrack()) {
1475 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1476 if (sessionId == t->sessionId() && strategy != actual) {
1477 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1478 strategy, actual);
1479 lStatus = BAD_VALUE;
1480 goto Exit;
1481 }
1482 }
1483 }
1484
1485 if (!isTimed) {
1486 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001487 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001488 } else {
1489 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001490 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001491 }
Glenn Kasten03003332013-08-06 15:40:54 -07001492
1493 // new Track always returns non-NULL,
1494 // but TimedTrack::create() is a factory that could fail by returning NULL
1495 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1496 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001497 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001498 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001499 goto Exit;
1500 }
1501 mTracks.add(track);
1502
1503 sp<EffectChain> chain = getEffectChain_l(sessionId);
1504 if (chain != 0) {
1505 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1506 track->setMainBuffer(chain->inBuffer());
1507 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1508 chain->incTrackCnt();
1509 }
1510
1511 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1512 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1513 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1514 // so ask activity manager to do this on our behalf
1515 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1516 }
1517 }
1518
1519 lStatus = NO_ERROR;
1520
1521Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001522 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001523 return track;
1524}
1525
1526uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1527{
1528 return latency;
1529}
1530
1531uint32_t AudioFlinger::PlaybackThread::latency() const
1532{
1533 Mutex::Autolock _l(mLock);
1534 return latency_l();
1535}
1536uint32_t AudioFlinger::PlaybackThread::latency_l() const
1537{
1538 if (initCheck() == NO_ERROR) {
1539 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1540 } else {
1541 return 0;
1542 }
1543}
1544
1545void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1546{
1547 Mutex::Autolock _l(mLock);
1548 // Don't apply master volume in SW if our HAL can do it for us.
1549 if (mOutput && mOutput->audioHwDev &&
1550 mOutput->audioHwDev->canSetMasterVolume()) {
1551 mMasterVolume = 1.0;
1552 } else {
1553 mMasterVolume = value;
1554 }
1555}
1556
1557void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1558{
1559 Mutex::Autolock _l(mLock);
1560 // Don't apply master mute in SW if our HAL can do it for us.
1561 if (mOutput && mOutput->audioHwDev &&
1562 mOutput->audioHwDev->canSetMasterMute()) {
1563 mMasterMute = false;
1564 } else {
1565 mMasterMute = muted;
1566 }
1567}
1568
1569void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1570{
1571 Mutex::Autolock _l(mLock);
1572 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001573 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001574}
1575
1576void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1577{
1578 Mutex::Autolock _l(mLock);
1579 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001580 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001581}
1582
1583float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1584{
1585 Mutex::Autolock _l(mLock);
1586 return mStreamTypes[stream].volume;
1587}
1588
1589// addTrack_l() must be called with ThreadBase::mLock held
1590status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1591{
1592 status_t status = ALREADY_EXISTS;
1593
1594 // set retry count for buffer fill
1595 track->mRetryCount = kMaxTrackStartupRetries;
1596 if (mActiveTracks.indexOf(track) < 0) {
1597 // the track is newly added, make sure it fills up all its
1598 // buffers before playing. This is to ensure the client will
1599 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600 if (!track->isOutputTrack()) {
1601 TrackBase::track_state state = track->mState;
1602 mLock.unlock();
1603 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1604 mLock.lock();
1605 // abort track was stopped/paused while we released the lock
1606 if (state != track->mState) {
1607 if (status == NO_ERROR) {
1608 mLock.unlock();
1609 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1610 mLock.lock();
1611 }
1612 return INVALID_OPERATION;
1613 }
1614 // abort if start is rejected by audio policy manager
1615 if (status != NO_ERROR) {
1616 return PERMISSION_DENIED;
1617 }
1618#ifdef ADD_BATTERY_DATA
1619 // to track the speaker usage
1620 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1621#endif
1622 }
1623
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001624 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001625 track->mResetDone = false;
1626 track->mPresentationCompleteFrames = 0;
1627 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001628 mWakeLockUids.add(track->uid());
1629 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001630 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001631 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1632 if (chain != 0) {
1633 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1634 track->sessionId());
1635 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001636 }
1637
1638 status = NO_ERROR;
1639 }
1640
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001641 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001642 return status;
1643}
1644
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001646{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001647 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001648 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001649 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1650 track->mState = TrackBase::STOPPED;
1651 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001652 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653 } else if (track->isFastTrack() || track->isOffloaded()) {
1654 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001655 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656
1657 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001658}
1659
1660void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1661{
1662 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1663 mTracks.remove(track);
1664 deleteTrackName_l(track->name());
1665 // redundant as track is about to be destroyed, for dumpsys only
1666 track->mName = -1;
1667 if (track->isFastTrack()) {
1668 int index = track->mFastIndex;
1669 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1670 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1671 mFastTrackAvailMask |= 1 << index;
1672 // redundant as track is about to be destroyed, for dumpsys only
1673 track->mFastIndex = -1;
1674 }
1675 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1676 if (chain != 0) {
1677 chain->decTrackCnt();
1678 }
1679}
1680
Eric Laurentede6c3b2013-09-19 14:37:46 -07001681void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001682{
1683 // Thread could be blocked waiting for async
1684 // so signal it to handle state changes immediately
1685 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1686 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1687 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001688 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689}
1690
Eric Laurent81784c32012-11-19 14:55:58 -08001691String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1692{
Eric Laurent81784c32012-11-19 14:55:58 -08001693 Mutex::Autolock _l(mLock);
1694 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001695 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001696 }
1697
Glenn Kastend8ea6992013-07-16 14:17:15 -07001698 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1699 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001700 free(s);
1701 return out_s8;
1702}
1703
Eric Laurent021cf962014-05-13 10:18:14 -07001704void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001705 AudioSystem::OutputDescriptor desc;
1706 void *param2 = NULL;
1707
Eric Laurent021cf962014-05-13 10:18:14 -07001708 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001709 param);
1710
1711 switch (event) {
1712 case AudioSystem::OUTPUT_OPENED:
1713 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001714 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001715 desc.samplingRate = mSampleRate;
1716 desc.format = mFormat;
1717 desc.frameCount = mNormalFrameCount; // FIXME see
1718 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001719 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001720 param2 = &desc;
1721 break;
1722
1723 case AudioSystem::STREAM_CONFIG_CHANGED:
1724 param2 = &param;
1725 case AudioSystem::OUTPUT_CLOSED:
1726 default:
1727 break;
1728 }
Eric Laurent021cf962014-05-13 10:18:14 -07001729 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001730}
1731
Eric Laurentbfb1b832013-01-07 09:53:42 -08001732void AudioFlinger::PlaybackThread::writeCallback()
1733{
1734 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001735 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001736}
1737
1738void AudioFlinger::PlaybackThread::drainCallback()
1739{
1740 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001741 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742}
1743
Eric Laurent3b4529e2013-09-05 18:09:19 -07001744void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001745{
1746 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001747 // reject out of sequence requests
1748 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1749 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001750 mWaitWorkCV.signal();
1751 }
1752}
1753
Eric Laurent3b4529e2013-09-05 18:09:19 -07001754void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001755{
1756 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001757 // reject out of sequence requests
1758 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1759 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001760 mWaitWorkCV.signal();
1761 }
1762}
1763
1764// static
1765int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001766 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767 void *cookie)
1768{
1769 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1770 ALOGV("asyncCallback() event %d", event);
1771 switch (event) {
1772 case STREAM_CBK_EVENT_WRITE_READY:
1773 me->writeCallback();
1774 break;
1775 case STREAM_CBK_EVENT_DRAIN_READY:
1776 me->drainCallback();
1777 break;
1778 default:
1779 ALOGW("asyncCallback() unknown event %d", event);
1780 break;
1781 }
1782 return 0;
1783}
1784
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001785void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001787 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001788 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1789 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001790 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001791 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001792 }
1793 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001794 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001795 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1796 }
Andy Hunge5412692014-05-16 11:25:07 -07001797 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001798 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001799 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001800 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001801 }
1802 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001803 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1804 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001805 }
Eric Laurent81784c32012-11-19 14:55:58 -08001806 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001807 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1808 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001809 if (mFrameCount & 15) {
1810 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1811 mFrameCount);
1812 }
1813
Eric Laurentbfb1b832013-01-07 09:53:42 -08001814 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1815 (mOutput->stream->set_callback != NULL)) {
1816 if (mOutput->stream->set_callback(mOutput->stream,
1817 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1818 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001819 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001820 }
1821 }
1822
Andy Hung09a50072014-02-27 14:30:47 -08001823 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001824 double multiplier = 1.0;
1825 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1826 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001827 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1828 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001829 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1830 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1831 maxNormalFrameCount = maxNormalFrameCount & ~15;
1832 if (maxNormalFrameCount < minNormalFrameCount) {
1833 maxNormalFrameCount = minNormalFrameCount;
1834 }
1835 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1836 if (multiplier <= 1.0) {
1837 multiplier = 1.0;
1838 } else if (multiplier <= 2.0) {
1839 if (2 * mFrameCount <= maxNormalFrameCount) {
1840 multiplier = 2.0;
1841 } else {
1842 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1843 }
1844 } else {
1845 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001846 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08001847 // track, but we sometimes have to do this to satisfy the maximum frame count
1848 // constraint)
1849 // FIXME this rounding up should not be done if no HAL SRC
1850 uint32_t truncMult = (uint32_t) multiplier;
1851 if ((truncMult & 1)) {
1852 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1853 ++truncMult;
1854 }
1855 }
1856 multiplier = (double) truncMult;
1857 }
1858 }
1859 mNormalFrameCount = multiplier * mFrameCount;
1860 // round up to nearest 16 frames to satisfy AudioMixer
1861 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001862 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001863 mNormalFrameCount);
1864
Andy Hung010a1a12014-03-13 13:57:33 -07001865 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1866 // Originally this was int16_t[] array, need to remove legacy implications.
1867 free(mSinkBuffer);
1868 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001869 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1870 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1871 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001872 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001873
Andy Hung69aed5f2014-02-25 17:24:40 -08001874 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1875 // drives the output.
1876 free(mMixerBuffer);
1877 mMixerBuffer = NULL;
1878 if (mMixerBufferEnabled) {
1879 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1880 mMixerBufferSize = mNormalFrameCount * mChannelCount
1881 * audio_bytes_per_sample(mMixerBufferFormat);
1882 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1883 }
Andy Hung98ef9782014-03-04 14:46:50 -08001884 free(mEffectBuffer);
1885 mEffectBuffer = NULL;
1886 if (mEffectBufferEnabled) {
1887 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1888 mEffectBufferSize = mNormalFrameCount * mChannelCount
1889 * audio_bytes_per_sample(mEffectBufferFormat);
1890 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1891 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001892
Eric Laurent81784c32012-11-19 14:55:58 -08001893 // force reconfiguration of effect chains and engines to take new buffer size and audio
1894 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001895 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001896 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1897 // matter.
1898 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1899 Vector< sp<EffectChain> > effectChains = mEffectChains;
1900 for (size_t i = 0; i < effectChains.size(); i ++) {
1901 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1902 }
1903}
1904
1905
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001906status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001907{
1908 if (halFrames == NULL || dspFrames == NULL) {
1909 return BAD_VALUE;
1910 }
1911 Mutex::Autolock _l(mLock);
1912 if (initCheck() != NO_ERROR) {
1913 return INVALID_OPERATION;
1914 }
1915 size_t framesWritten = mBytesWritten / mFrameSize;
1916 *halFrames = framesWritten;
1917
1918 if (isSuspended()) {
1919 // return an estimation of rendered frames when the output is suspended
1920 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1921 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1922 return NO_ERROR;
1923 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001924 status_t status;
1925 uint32_t frames;
1926 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1927 *dspFrames = (size_t)frames;
1928 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001929 }
1930}
1931
1932uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1933{
1934 Mutex::Autolock _l(mLock);
1935 uint32_t result = 0;
1936 if (getEffectChain_l(sessionId) != 0) {
1937 result = EFFECT_SESSION;
1938 }
1939
1940 for (size_t i = 0; i < mTracks.size(); ++i) {
1941 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001942 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001943 result |= TRACK_SESSION;
1944 break;
1945 }
1946 }
1947
1948 return result;
1949}
1950
1951uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1952{
1953 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1954 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1955 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1956 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1957 }
1958 for (size_t i = 0; i < mTracks.size(); i++) {
1959 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001960 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001961 return AudioSystem::getStrategyForStream(track->streamType());
1962 }
1963 }
1964 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1965}
1966
1967
1968AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1969{
1970 Mutex::Autolock _l(mLock);
1971 return mOutput;
1972}
1973
1974AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1975{
1976 Mutex::Autolock _l(mLock);
1977 AudioStreamOut *output = mOutput;
1978 mOutput = NULL;
1979 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1980 // must push a NULL and wait for ack
1981 mOutputSink.clear();
1982 mPipeSink.clear();
1983 mNormalSink.clear();
1984 return output;
1985}
1986
1987// this method must always be called either with ThreadBase mLock held or inside the thread loop
1988audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1989{
1990 if (mOutput == NULL) {
1991 return NULL;
1992 }
1993 return &mOutput->stream->common;
1994}
1995
1996uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1997{
1998 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1999}
2000
2001status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2002{
2003 if (!isValidSyncEvent(event)) {
2004 return BAD_VALUE;
2005 }
2006
2007 Mutex::Autolock _l(mLock);
2008
2009 for (size_t i = 0; i < mTracks.size(); ++i) {
2010 sp<Track> track = mTracks[i];
2011 if (event->triggerSession() == track->sessionId()) {
2012 (void) track->setSyncEvent(event);
2013 return NO_ERROR;
2014 }
2015 }
2016
2017 return NAME_NOT_FOUND;
2018}
2019
2020bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2021{
2022 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2023}
2024
2025void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2026 const Vector< sp<Track> >& tracksToRemove)
2027{
2028 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002029 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 for (size_t i = 0 ; i < count ; i++) {
2031 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002033 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002034#ifdef ADD_BATTERY_DATA
2035 // to track the speaker usage
2036 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2037#endif
2038 if (track->isTerminated()) {
2039 AudioSystem::releaseOutput(mId);
2040 }
Eric Laurent81784c32012-11-19 14:55:58 -08002041 }
2042 }
2043 }
Eric Laurent81784c32012-11-19 14:55:58 -08002044}
2045
2046void AudioFlinger::PlaybackThread::checkSilentMode_l()
2047{
2048 if (!mMasterMute) {
2049 char value[PROPERTY_VALUE_MAX];
2050 if (property_get("ro.audio.silent", value, "0") > 0) {
2051 char *endptr;
2052 unsigned long ul = strtoul(value, &endptr, 0);
2053 if (*endptr == '\0' && ul != 0) {
2054 ALOGD("Silence is golden");
2055 // The setprop command will not allow a property to be changed after
2056 // the first time it is set, so we don't have to worry about un-muting.
2057 setMasterMute_l(true);
2058 }
2059 }
2060 }
2061}
2062
2063// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002065{
2066 // FIXME rewrite to reduce number of system calls
2067 mLastWriteTime = systemTime();
2068 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002069 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002070 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002071
2072 // If an NBAIO sink is present, use it to write the normal mixer's submix
2073 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002074 const size_t count = mBytesRemaining / mFrameSize;
2075
Simon Wilson2d590962012-11-29 15:18:50 -08002076 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002077 // update the setpoint when AudioFlinger::mScreenState changes
2078 uint32_t screenState = AudioFlinger::mScreenState;
2079 if (screenState != mScreenState) {
2080 mScreenState = screenState;
2081 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2082 if (pipe != NULL) {
2083 pipe->setAvgFrames((mScreenState & 1) ?
2084 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2085 }
2086 }
Andy Hung010a1a12014-03-13 13:57:33 -07002087 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002088 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002089 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002090 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002091 } else {
2092 bytesWritten = framesWritten;
2093 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002094 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002095 if (status == NO_ERROR) {
2096 size_t totalFramesWritten = mNormalSink->framesWritten();
2097 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2098 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2099 mLatchDValid = true;
2100 }
2101 }
Eric Laurent81784c32012-11-19 14:55:58 -08002102 // otherwise use the HAL / AudioStreamOut directly
2103 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002105
Eric Laurentbfb1b832013-01-07 09:53:42 -08002106 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002107 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2108 mWriteAckSequence += 2;
2109 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002111 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002113 // FIXME We should have an implementation of timestamps for direct output threads.
2114 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002116 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117 if (mUseAsyncWrite &&
2118 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2119 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002120 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002121 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002122 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002123 }
Eric Laurent81784c32012-11-19 14:55:58 -08002124 }
2125
Eric Laurent81784c32012-11-19 14:55:58 -08002126 mNumWrites++;
2127 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002128 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129 return bytesWritten;
2130}
2131
2132void AudioFlinger::PlaybackThread::threadLoop_drain()
2133{
2134 if (mOutput->stream->drain) {
2135 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2136 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002137 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2138 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002140 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 }
2142 mOutput->stream->drain(mOutput->stream,
2143 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2144 : AUDIO_DRAIN_ALL);
2145 }
2146}
2147
2148void AudioFlinger::PlaybackThread::threadLoop_exit()
2149{
2150 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002151}
2152
2153/*
2154The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002155 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002156 - activeSleepTime from activeSleepTimeUs()
2157 - idleSleepTime from idleSleepTimeUs()
2158 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2159 - maxPeriod from frame count and sample rate (MIXER only)
2160
2161The parameters that affect these derived values are:
2162 - frame count
2163 - frame size
2164 - sample rate
2165 - device type: A2DP or not
2166 - device latency
2167 - format: PCM or not
2168 - active sleep time
2169 - idle sleep time
2170*/
2171
2172void AudioFlinger::PlaybackThread::cacheParameters_l()
2173{
Andy Hung25c2dac2014-02-27 14:56:00 -08002174 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002175 activeSleepTime = activeSleepTimeUs();
2176 idleSleepTime = idleSleepTimeUs();
2177}
2178
2179void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2180{
Glenn Kasten7c027242012-12-26 14:43:16 -08002181 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002182 this, streamType, mTracks.size());
2183 Mutex::Autolock _l(mLock);
2184
2185 size_t size = mTracks.size();
2186 for (size_t i = 0; i < size; i++) {
2187 sp<Track> t = mTracks[i];
2188 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002189 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002190 }
2191 }
2192}
2193
2194status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2195{
2196 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002197 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2198 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002199 bool ownsBuffer = false;
2200
2201 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2202 if (session > 0) {
2203 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002204 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002205 if (mType != DIRECT) {
2206 size_t numSamples = mNormalFrameCount * mChannelCount;
2207 buffer = new int16_t[numSamples];
2208 memset(buffer, 0, numSamples * sizeof(int16_t));
2209 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2210 ownsBuffer = true;
2211 }
2212
2213 // Attach all tracks with same session ID to this chain.
2214 for (size_t i = 0; i < mTracks.size(); ++i) {
2215 sp<Track> track = mTracks[i];
2216 if (session == track->sessionId()) {
2217 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2218 buffer);
2219 track->setMainBuffer(buffer);
2220 chain->incTrackCnt();
2221 }
2222 }
2223
2224 // indicate all active tracks in the chain
2225 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2226 sp<Track> track = mActiveTracks[i].promote();
2227 if (track == 0) {
2228 continue;
2229 }
2230 if (session == track->sessionId()) {
2231 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2232 chain->incActiveTrackCnt();
2233 }
2234 }
2235 }
2236
2237 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002238 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2239 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002240 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2241 // chains list in order to be processed last as it contains output stage effects
2242 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2243 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2244 // after track specific effects and before output stage
2245 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2246 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2247 // Effect chain for other sessions are inserted at beginning of effect
2248 // chains list to be processed before output mix effects. Relative order between other
2249 // sessions is not important
2250 size_t size = mEffectChains.size();
2251 size_t i = 0;
2252 for (i = 0; i < size; i++) {
2253 if (mEffectChains[i]->sessionId() < session) {
2254 break;
2255 }
2256 }
2257 mEffectChains.insertAt(chain, i);
2258 checkSuspendOnAddEffectChain_l(chain);
2259
2260 return NO_ERROR;
2261}
2262
2263size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2264{
2265 int session = chain->sessionId();
2266
2267 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2268
2269 for (size_t i = 0; i < mEffectChains.size(); i++) {
2270 if (chain == mEffectChains[i]) {
2271 mEffectChains.removeAt(i);
2272 // detach all active tracks from the chain
2273 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2274 sp<Track> track = mActiveTracks[i].promote();
2275 if (track == 0) {
2276 continue;
2277 }
2278 if (session == track->sessionId()) {
2279 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2280 chain.get(), session);
2281 chain->decActiveTrackCnt();
2282 }
2283 }
2284
2285 // detach all tracks with same session ID from this chain
2286 for (size_t i = 0; i < mTracks.size(); ++i) {
2287 sp<Track> track = mTracks[i];
2288 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002289 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002290 chain->decTrackCnt();
2291 }
2292 }
2293 break;
2294 }
2295 }
2296 return mEffectChains.size();
2297}
2298
2299status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2300 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2301{
2302 Mutex::Autolock _l(mLock);
2303 return attachAuxEffect_l(track, EffectId);
2304}
2305
2306status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2307 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2308{
2309 status_t status = NO_ERROR;
2310
2311 if (EffectId == 0) {
2312 track->setAuxBuffer(0, NULL);
2313 } else {
2314 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2315 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2316 if (effect != 0) {
2317 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2318 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2319 } else {
2320 status = INVALID_OPERATION;
2321 }
2322 } else {
2323 status = BAD_VALUE;
2324 }
2325 }
2326 return status;
2327}
2328
2329void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2330{
2331 for (size_t i = 0; i < mTracks.size(); ++i) {
2332 sp<Track> track = mTracks[i];
2333 if (track->auxEffectId() == effectId) {
2334 attachAuxEffect_l(track, 0);
2335 }
2336 }
2337}
2338
2339bool AudioFlinger::PlaybackThread::threadLoop()
2340{
2341 Vector< sp<Track> > tracksToRemove;
2342
2343 standbyTime = systemTime();
2344
2345 // MIXER
2346 nsecs_t lastWarning = 0;
2347
2348 // DUPLICATING
2349 // FIXME could this be made local to while loop?
2350 writeFrames = 0;
2351
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002352 int lastGeneration = 0;
2353
Eric Laurent81784c32012-11-19 14:55:58 -08002354 cacheParameters_l();
2355 sleepTime = idleSleepTime;
2356
2357 if (mType == MIXER) {
2358 sleepTimeShift = 0;
2359 }
2360
2361 CpuStats cpuStats;
2362 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2363
2364 acquireWakeLock();
2365
Glenn Kasten9e58b552013-01-18 15:09:48 -08002366 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2367 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2368 // and then that string will be logged at the next convenient opportunity.
2369 const char *logString = NULL;
2370
Eric Laurent664539d2013-09-23 18:24:31 -07002371 checkSilentMode_l();
2372
Eric Laurent81784c32012-11-19 14:55:58 -08002373 while (!exitPending())
2374 {
2375 cpuStats.sample(myName);
2376
2377 Vector< sp<EffectChain> > effectChains;
2378
Eric Laurent81784c32012-11-19 14:55:58 -08002379 { // scope for mLock
2380
2381 Mutex::Autolock _l(mLock);
2382
Eric Laurent021cf962014-05-13 10:18:14 -07002383 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002384
Glenn Kasten9e58b552013-01-18 15:09:48 -08002385 if (logString != NULL) {
2386 mNBLogWriter->logTimestamp();
2387 mNBLogWriter->log(logString);
2388 logString = NULL;
2389 }
2390
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002391 if (mLatchDValid) {
2392 mLatchQ = mLatchD;
2393 mLatchDValid = false;
2394 mLatchQValid = true;
2395 }
2396
Eric Laurent81784c32012-11-19 14:55:58 -08002397 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398 if (mSignalPending) {
2399 // A signal was raised while we were unlocked
2400 mSignalPending = false;
2401 } else if (waitingAsyncCallback_l()) {
2402 if (exitPending()) {
2403 break;
2404 }
2405 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002406 mWakeLockUids.clear();
2407 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002408 ALOGV("wait async completion");
2409 mWaitWorkCV.wait(mLock);
2410 ALOGV("async completion/wake");
2411 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002412 standbyTime = systemTime() + standbyDelay;
2413 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002414
2415 continue;
2416 }
2417 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002418 isSuspended()) {
2419 // put audio hardware into standby after short delay
2420 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002421
2422 threadLoop_standby();
2423
2424 mStandby = true;
2425 }
2426
2427 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2428 // we're about to wait, flush the binder command buffer
2429 IPCThreadState::self()->flushCommands();
2430
2431 clearOutputTracks();
2432
2433 if (exitPending()) {
2434 break;
2435 }
2436
2437 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002438 mWakeLockUids.clear();
2439 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002440 // wait until we have something to do...
2441 ALOGV("%s going to sleep", myName.string());
2442 mWaitWorkCV.wait(mLock);
2443 ALOGV("%s waking up", myName.string());
2444 acquireWakeLock_l();
2445
2446 mMixerStatus = MIXER_IDLE;
2447 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2448 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002450 checkSilentMode_l();
2451
2452 standbyTime = systemTime() + standbyDelay;
2453 sleepTime = idleSleepTime;
2454 if (mType == MIXER) {
2455 sleepTimeShift = 0;
2456 }
2457
2458 continue;
2459 }
2460 }
Eric Laurent81784c32012-11-19 14:55:58 -08002461 // mMixerStatusIgnoringFastTracks is also updated internally
2462 mMixerStatus = prepareTracks_l(&tracksToRemove);
2463
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002464 // compare with previously applied list
2465 if (lastGeneration != mActiveTracksGeneration) {
2466 // update wakelock
2467 updateWakeLockUids_l(mWakeLockUids);
2468 lastGeneration = mActiveTracksGeneration;
2469 }
2470
Eric Laurent81784c32012-11-19 14:55:58 -08002471 // prevent any changes in effect chain list and in each effect chain
2472 // during mixing and effect process as the audio buffers could be deleted
2473 // or modified if an effect is created or deleted
2474 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002475 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002476
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477 if (mBytesRemaining == 0) {
2478 mCurrentWriteLength = 0;
2479 if (mMixerStatus == MIXER_TRACKS_READY) {
2480 // threadLoop_mix() sets mCurrentWriteLength
2481 threadLoop_mix();
2482 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2483 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2484 // threadLoop_sleepTime sets sleepTime to 0 if data
2485 // must be written to HAL
2486 threadLoop_sleepTime();
2487 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002488 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002489 }
2490 }
Andy Hung98ef9782014-03-04 14:46:50 -08002491 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2492 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2493 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2494 // or mSinkBuffer (if there are no effects).
2495 //
2496 // This is done pre-effects computation; if effects change to
2497 // support higher precision, this needs to move.
2498 //
2499 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2500 // TODO use sleepTime == 0 as an additional condition.
2501 if (mMixerBufferValid) {
2502 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2503 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2504
2505 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2506 mNormalFrameCount * mChannelCount);
2507 }
2508
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 mBytesRemaining = mCurrentWriteLength;
2510 if (isSuspended()) {
2511 sleepTime = suspendSleepTimeUs();
2512 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002513 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 mBytesRemaining = 0;
2515 }
Eric Laurent81784c32012-11-19 14:55:58 -08002516
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002518 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002519 for (size_t i = 0; i < effectChains.size(); i ++) {
2520 effectChains[i]->process_l();
2521 }
Eric Laurent81784c32012-11-19 14:55:58 -08002522 }
2523 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002524 // Process effect chains for offloaded thread even if no audio
2525 // was read from audio track: process only updates effect state
2526 // and thus does have to be synchronized with audio writes but may have
2527 // to be called while waiting for async write callback
2528 if (mType == OFFLOAD) {
2529 for (size_t i = 0; i < effectChains.size(); i ++) {
2530 effectChains[i]->process_l();
2531 }
2532 }
Eric Laurent81784c32012-11-19 14:55:58 -08002533
Andy Hung98ef9782014-03-04 14:46:50 -08002534 // Only if the Effects buffer is enabled and there is data in the
2535 // Effects buffer (buffer valid), we need to
2536 // copy into the sink buffer.
2537 // TODO use sleepTime == 0 as an additional condition.
2538 if (mEffectBufferValid) {
2539 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2540 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2541 mNormalFrameCount * mChannelCount);
2542 }
2543
Eric Laurent81784c32012-11-19 14:55:58 -08002544 // enable changes in effect chain
2545 unlockEffectChains(effectChains);
2546
Eric Laurentbfb1b832013-01-07 09:53:42 -08002547 if (!waitingAsyncCallback()) {
2548 // sleepTime == 0 means we must write to audio hardware
2549 if (sleepTime == 0) {
2550 if (mBytesRemaining) {
2551 ssize_t ret = threadLoop_write();
2552 if (ret < 0) {
2553 mBytesRemaining = 0;
2554 } else {
2555 mBytesWritten += ret;
2556 mBytesRemaining -= ret;
2557 }
2558 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2559 (mMixerStatus == MIXER_DRAIN_ALL)) {
2560 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002561 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002562 if (mType == MIXER) {
2563 // write blocked detection
2564 nsecs_t now = systemTime();
2565 nsecs_t delta = now - mLastWriteTime;
2566 if (!mStandby && delta > maxPeriod) {
2567 mNumDelayedWrites++;
2568 if ((now - lastWarning) > kWarningThrottleNs) {
2569 ATRACE_NAME("underrun");
2570 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2571 ns2ms(delta), mNumDelayedWrites, this);
2572 lastWarning = now;
2573 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 }
2575 }
Eric Laurent81784c32012-11-19 14:55:58 -08002576
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 } else {
2578 usleep(sleepTime);
2579 }
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
2581
2582 // Finally let go of removed track(s), without the lock held
2583 // since we can't guarantee the destructors won't acquire that
2584 // same lock. This will also mutate and push a new fast mixer state.
2585 threadLoop_removeTracks(tracksToRemove);
2586 tracksToRemove.clear();
2587
2588 // FIXME I don't understand the need for this here;
2589 // it was in the original code but maybe the
2590 // assignment in saveOutputTracks() makes this unnecessary?
2591 clearOutputTracks();
2592
2593 // Effect chains will be actually deleted here if they were removed from
2594 // mEffectChains list during mixing or effects processing
2595 effectChains.clear();
2596
2597 // FIXME Note that the above .clear() is no longer necessary since effectChains
2598 // is now local to this block, but will keep it for now (at least until merge done).
2599 }
2600
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 threadLoop_exit();
2602
Eric Laurent81784c32012-11-19 14:55:58 -08002603 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002605 // put output stream into standby mode
2606 if (!mStandby) {
2607 mOutput->stream->common.standby(&mOutput->stream->common);
2608 }
2609 }
2610
2611 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002612 mWakeLockUids.clear();
2613 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002614
2615 ALOGV("Thread %p type %d exiting", this, mType);
2616 return false;
2617}
2618
Eric Laurentbfb1b832013-01-07 09:53:42 -08002619// removeTracks_l() must be called with ThreadBase::mLock held
2620void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2621{
2622 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002623 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002624 for (size_t i=0 ; i<count ; i++) {
2625 const sp<Track>& track = tracksToRemove.itemAt(i);
2626 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002627 mWakeLockUids.remove(track->uid());
2628 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2630 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2631 if (chain != 0) {
2632 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2633 track->sessionId());
2634 chain->decActiveTrackCnt();
2635 }
2636 if (track->isTerminated()) {
2637 removeTrack_l(track);
2638 }
2639 }
2640 }
2641
2642}
Eric Laurent81784c32012-11-19 14:55:58 -08002643
Eric Laurentaccc1472013-09-20 09:36:34 -07002644status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2645{
2646 if (mNormalSink != 0) {
2647 return mNormalSink->getTimestamp(timestamp);
2648 }
2649 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2650 uint64_t position64;
2651 int ret = mOutput->stream->get_presentation_position(
2652 mOutput->stream, &position64, &timestamp.mTime);
2653 if (ret == 0) {
2654 timestamp.mPosition = (uint32_t)position64;
2655 return NO_ERROR;
2656 }
2657 }
2658 return INVALID_OPERATION;
2659}
Eric Laurent1c333e22014-05-20 10:48:17 -07002660
2661status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2662 audio_patch_handle_t *handle)
2663{
2664 status_t status = NO_ERROR;
2665 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2666 // store new device and send to effects
2667 audio_devices_t type = AUDIO_DEVICE_NONE;
2668 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2669 type |= patch->sinks[i].ext.device.type;
2670 }
2671 mOutDevice = type;
2672 for (size_t i = 0; i < mEffectChains.size(); i++) {
2673 mEffectChains[i]->setDevice_l(mOutDevice);
2674 }
2675
2676 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2677 status = hwDevice->create_audio_patch(hwDevice,
2678 patch->num_sources,
2679 patch->sources,
2680 patch->num_sinks,
2681 patch->sinks,
2682 handle);
2683 } else {
2684 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2685 }
2686 return status;
2687}
2688
2689status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2690{
2691 status_t status = NO_ERROR;
2692 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2693 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2694 status = hwDevice->release_audio_patch(hwDevice, handle);
2695 } else {
2696 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2697 }
2698 return status;
2699}
2700
Eric Laurent81784c32012-11-19 14:55:58 -08002701// ----------------------------------------------------------------------------
2702
2703AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2704 audio_io_handle_t id, audio_devices_t device, type_t type)
2705 : PlaybackThread(audioFlinger, output, id, device, type),
2706 // mAudioMixer below
2707 // mFastMixer below
2708 mFastMixerFutex(0)
2709 // mOutputSink below
2710 // mPipeSink below
2711 // mNormalSink below
2712{
2713 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002714 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002715 "mFrameCount=%d, mNormalFrameCount=%d",
2716 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2717 mNormalFrameCount);
2718 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2719
2720 // FIXME - Current mixer implementation only supports stereo output
2721 if (mChannelCount != FCC_2) {
2722 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2723 }
2724
2725 // create an NBAIO sink for the HAL output stream, and negotiate
2726 mOutputSink = new AudioStreamOutSink(output->stream);
2727 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002728 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002729 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2730 ALOG_ASSERT(index == 0);
2731
2732 // initialize fast mixer depending on configuration
2733 bool initFastMixer;
2734 switch (kUseFastMixer) {
2735 case FastMixer_Never:
2736 initFastMixer = false;
2737 break;
2738 case FastMixer_Always:
2739 initFastMixer = true;
2740 break;
2741 case FastMixer_Static:
2742 case FastMixer_Dynamic:
2743 initFastMixer = mFrameCount < mNormalFrameCount;
2744 break;
2745 }
2746 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002747 audio_format_t fastMixerFormat;
2748 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2749 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2750 } else {
2751 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2752 }
2753 if (mFormat != fastMixerFormat) {
2754 // change our Sink format to accept our intermediate precision
2755 mFormat = fastMixerFormat;
2756 free(mSinkBuffer);
2757 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2758 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2759 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2760 }
Eric Laurent81784c32012-11-19 14:55:58 -08002761
2762 // create a MonoPipe to connect our submix to FastMixer
2763 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002764 // adjust format to match that of the Fast Mixer
2765 format.mFormat = fastMixerFormat;
2766 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2767
Eric Laurent81784c32012-11-19 14:55:58 -08002768 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2769 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2770 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2771 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2772 const NBAIO_Format offers[1] = {format};
2773 size_t numCounterOffers = 0;
2774 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2775 ALOG_ASSERT(index == 0);
2776 monoPipe->setAvgFrames((mScreenState & 1) ?
2777 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2778 mPipeSink = monoPipe;
2779
Glenn Kasten46909e72013-02-26 09:20:22 -08002780#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002781 if (mTeeSinkOutputEnabled) {
2782 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2783 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2784 numCounterOffers = 0;
2785 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2786 ALOG_ASSERT(index == 0);
2787 mTeeSink = teeSink;
2788 PipeReader *teeSource = new PipeReader(*teeSink);
2789 numCounterOffers = 0;
2790 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2791 ALOG_ASSERT(index == 0);
2792 mTeeSource = teeSource;
2793 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002794#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002795
2796 // create fast mixer and configure it initially with just one fast track for our submix
2797 mFastMixer = new FastMixer();
2798 FastMixerStateQueue *sq = mFastMixer->sq();
2799#ifdef STATE_QUEUE_DUMP
2800 sq->setObserverDump(&mStateQueueObserverDump);
2801 sq->setMutatorDump(&mStateQueueMutatorDump);
2802#endif
2803 FastMixerState *state = sq->begin();
2804 FastTrack *fastTrack = &state->mFastTracks[0];
2805 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2806 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2807 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002808 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2809 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002810 fastTrack->mGeneration++;
2811 state->mFastTracksGen++;
2812 state->mTrackMask = 1;
2813 // fast mixer will use the HAL output sink
2814 state->mOutputSink = mOutputSink.get();
2815 state->mOutputSinkGen++;
2816 state->mFrameCount = mFrameCount;
2817 state->mCommand = FastMixerState::COLD_IDLE;
2818 // already done in constructor initialization list
2819 //mFastMixerFutex = 0;
2820 state->mColdFutexAddr = &mFastMixerFutex;
2821 state->mColdGen++;
2822 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002823#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002824 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002825#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002826 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2827 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002828 sq->end();
2829 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2830
2831 // start the fast mixer
2832 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2833 pid_t tid = mFastMixer->getTid();
2834 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2835 if (err != 0) {
2836 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2837 kPriorityFastMixer, getpid_cached, tid, err);
2838 }
2839
2840#ifdef AUDIO_WATCHDOG
2841 // create and start the watchdog
2842 mAudioWatchdog = new AudioWatchdog();
2843 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2844 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2845 tid = mAudioWatchdog->getTid();
2846 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2847 if (err != 0) {
2848 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2849 kPriorityFastMixer, getpid_cached, tid, err);
2850 }
2851#endif
2852
2853 } else {
2854 mFastMixer = NULL;
2855 }
2856
2857 switch (kUseFastMixer) {
2858 case FastMixer_Never:
2859 case FastMixer_Dynamic:
2860 mNormalSink = mOutputSink;
2861 break;
2862 case FastMixer_Always:
2863 mNormalSink = mPipeSink;
2864 break;
2865 case FastMixer_Static:
2866 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2867 break;
2868 }
2869}
2870
2871AudioFlinger::MixerThread::~MixerThread()
2872{
2873 if (mFastMixer != NULL) {
2874 FastMixerStateQueue *sq = mFastMixer->sq();
2875 FastMixerState *state = sq->begin();
2876 if (state->mCommand == FastMixerState::COLD_IDLE) {
2877 int32_t old = android_atomic_inc(&mFastMixerFutex);
2878 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002879 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002880 }
2881 }
2882 state->mCommand = FastMixerState::EXIT;
2883 sq->end();
2884 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2885 mFastMixer->join();
2886 // Though the fast mixer thread has exited, it's state queue is still valid.
2887 // We'll use that extract the final state which contains one remaining fast track
2888 // corresponding to our sub-mix.
2889 state = sq->begin();
2890 ALOG_ASSERT(state->mTrackMask == 1);
2891 FastTrack *fastTrack = &state->mFastTracks[0];
2892 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2893 delete fastTrack->mBufferProvider;
2894 sq->end(false /*didModify*/);
2895 delete mFastMixer;
2896#ifdef AUDIO_WATCHDOG
2897 if (mAudioWatchdog != 0) {
2898 mAudioWatchdog->requestExit();
2899 mAudioWatchdog->requestExitAndWait();
2900 mAudioWatchdog.clear();
2901 }
2902#endif
2903 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002904 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002905 delete mAudioMixer;
2906}
2907
2908
2909uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2910{
2911 if (mFastMixer != NULL) {
2912 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2913 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2914 }
2915 return latency;
2916}
2917
2918
2919void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2920{
2921 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2922}
2923
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002925{
2926 // FIXME we should only do one push per cycle; confirm this is true
2927 // Start the fast mixer if it's not already running
2928 if (mFastMixer != NULL) {
2929 FastMixerStateQueue *sq = mFastMixer->sq();
2930 FastMixerState *state = sq->begin();
2931 if (state->mCommand != FastMixerState::MIX_WRITE &&
2932 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2933 if (state->mCommand == FastMixerState::COLD_IDLE) {
2934 int32_t old = android_atomic_inc(&mFastMixerFutex);
2935 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002936 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002937 }
2938#ifdef AUDIO_WATCHDOG
2939 if (mAudioWatchdog != 0) {
2940 mAudioWatchdog->resume();
2941 }
2942#endif
2943 }
2944 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002945 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2946 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002947 sq->end();
2948 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2949 if (kUseFastMixer == FastMixer_Dynamic) {
2950 mNormalSink = mPipeSink;
2951 }
2952 } else {
2953 sq->end(false /*didModify*/);
2954 }
2955 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002957}
2958
2959void AudioFlinger::MixerThread::threadLoop_standby()
2960{
2961 // Idle the fast mixer if it's currently running
2962 if (mFastMixer != NULL) {
2963 FastMixerStateQueue *sq = mFastMixer->sq();
2964 FastMixerState *state = sq->begin();
2965 if (!(state->mCommand & FastMixerState::IDLE)) {
2966 state->mCommand = FastMixerState::COLD_IDLE;
2967 state->mColdFutexAddr = &mFastMixerFutex;
2968 state->mColdGen++;
2969 mFastMixerFutex = 0;
2970 sq->end();
2971 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2972 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2973 if (kUseFastMixer == FastMixer_Dynamic) {
2974 mNormalSink = mOutputSink;
2975 }
2976#ifdef AUDIO_WATCHDOG
2977 if (mAudioWatchdog != 0) {
2978 mAudioWatchdog->pause();
2979 }
2980#endif
2981 } else {
2982 sq->end(false /*didModify*/);
2983 }
2984 }
2985 PlaybackThread::threadLoop_standby();
2986}
2987
Eric Laurentbfb1b832013-01-07 09:53:42 -08002988bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2989{
2990 return false;
2991}
2992
2993bool AudioFlinger::PlaybackThread::shouldStandby_l()
2994{
2995 return !mStandby;
2996}
2997
2998bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2999{
3000 Mutex::Autolock _l(mLock);
3001 return waitingAsyncCallback_l();
3002}
3003
Eric Laurent81784c32012-11-19 14:55:58 -08003004// shared by MIXER and DIRECT, overridden by DUPLICATING
3005void AudioFlinger::PlaybackThread::threadLoop_standby()
3006{
3007 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3008 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003010 // discard any pending drain or write ack by incrementing sequence
3011 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3012 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003014 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3015 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003016 }
Eric Laurent81784c32012-11-19 14:55:58 -08003017}
3018
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003019void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3020{
3021 ALOGV("signal playback thread");
3022 broadcast_l();
3023}
3024
Eric Laurent81784c32012-11-19 14:55:58 -08003025void AudioFlinger::MixerThread::threadLoop_mix()
3026{
3027 // obtain the presentation timestamp of the next output buffer
3028 int64_t pts;
3029 status_t status = INVALID_OPERATION;
3030
3031 if (mNormalSink != 0) {
3032 status = mNormalSink->getNextWriteTimestamp(&pts);
3033 } else {
3034 status = mOutputSink->getNextWriteTimestamp(&pts);
3035 }
3036
3037 if (status != NO_ERROR) {
3038 pts = AudioBufferProvider::kInvalidPTS;
3039 }
3040
3041 // mix buffers...
3042 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003043 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003044 // increase sleep time progressively when application underrun condition clears.
3045 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3046 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3047 // such that we would underrun the audio HAL.
3048 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3049 sleepTimeShift--;
3050 }
3051 sleepTime = 0;
3052 standbyTime = systemTime() + standbyDelay;
3053 //TODO: delay standby when effects have a tail
3054}
3055
3056void AudioFlinger::MixerThread::threadLoop_sleepTime()
3057{
3058 // If no tracks are ready, sleep once for the duration of an output
3059 // buffer size, then write 0s to the output
3060 if (sleepTime == 0) {
3061 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3062 sleepTime = activeSleepTime >> sleepTimeShift;
3063 if (sleepTime < kMinThreadSleepTimeUs) {
3064 sleepTime = kMinThreadSleepTimeUs;
3065 }
3066 // reduce sleep time in case of consecutive application underruns to avoid
3067 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3068 // duration we would end up writing less data than needed by the audio HAL if
3069 // the condition persists.
3070 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3071 sleepTimeShift++;
3072 }
3073 } else {
3074 sleepTime = idleSleepTime;
3075 }
3076 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003077 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3078 // before effects processing or output.
3079 if (mMixerBufferValid) {
3080 memset(mMixerBuffer, 0, mMixerBufferSize);
3081 } else {
3082 memset(mSinkBuffer, 0, mSinkBufferSize);
3083 }
Eric Laurent81784c32012-11-19 14:55:58 -08003084 sleepTime = 0;
3085 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3086 "anticipated start");
3087 }
3088 // TODO add standby time extension fct of effect tail
3089}
3090
3091// prepareTracks_l() must be called with ThreadBase::mLock held
3092AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3093 Vector< sp<Track> > *tracksToRemove)
3094{
3095
3096 mixer_state mixerStatus = MIXER_IDLE;
3097 // find out which tracks need to be processed
3098 size_t count = mActiveTracks.size();
3099 size_t mixedTracks = 0;
3100 size_t tracksWithEffect = 0;
3101 // counts only _active_ fast tracks
3102 size_t fastTracks = 0;
3103 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3104
3105 float masterVolume = mMasterVolume;
3106 bool masterMute = mMasterMute;
3107
3108 if (masterMute) {
3109 masterVolume = 0;
3110 }
3111 // Delegate master volume control to effect in output mix effect chain if needed
3112 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3113 if (chain != 0) {
3114 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3115 chain->setVolume_l(&v, &v);
3116 masterVolume = (float)((v + (1 << 23)) >> 24);
3117 chain.clear();
3118 }
3119
3120 // prepare a new state to push
3121 FastMixerStateQueue *sq = NULL;
3122 FastMixerState *state = NULL;
3123 bool didModify = false;
3124 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3125 if (mFastMixer != NULL) {
3126 sq = mFastMixer->sq();
3127 state = sq->begin();
3128 }
3129
Andy Hung69aed5f2014-02-25 17:24:40 -08003130 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003131 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003132
Eric Laurent81784c32012-11-19 14:55:58 -08003133 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003134 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003135 if (t == 0) {
3136 continue;
3137 }
3138
3139 // this const just means the local variable doesn't change
3140 Track* const track = t.get();
3141
3142 // process fast tracks
3143 if (track->isFastTrack()) {
3144
3145 // It's theoretically possible (though unlikely) for a fast track to be created
3146 // and then removed within the same normal mix cycle. This is not a problem, as
3147 // the track never becomes active so it's fast mixer slot is never touched.
3148 // The converse, of removing an (active) track and then creating a new track
3149 // at the identical fast mixer slot within the same normal mix cycle,
3150 // is impossible because the slot isn't marked available until the end of each cycle.
3151 int j = track->mFastIndex;
3152 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3153 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3154 FastTrack *fastTrack = &state->mFastTracks[j];
3155
3156 // Determine whether the track is currently in underrun condition,
3157 // and whether it had a recent underrun.
3158 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3159 FastTrackUnderruns underruns = ftDump->mUnderruns;
3160 uint32_t recentFull = (underruns.mBitFields.mFull -
3161 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3162 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3163 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3164 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3165 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3166 uint32_t recentUnderruns = recentPartial + recentEmpty;
3167 track->mObservedUnderruns = underruns;
3168 // don't count underruns that occur while stopping or pausing
3169 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003170 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3171 recentUnderruns > 0) {
3172 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3173 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003174 }
3175
3176 // This is similar to the state machine for normal tracks,
3177 // with a few modifications for fast tracks.
3178 bool isActive = true;
3179 switch (track->mState) {
3180 case TrackBase::STOPPING_1:
3181 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003183 track->mState = TrackBase::STOPPING_2;
3184 }
3185 break;
3186 case TrackBase::PAUSING:
3187 // ramp down is not yet implemented
3188 track->setPaused();
3189 break;
3190 case TrackBase::RESUMING:
3191 // ramp up is not yet implemented
3192 track->mState = TrackBase::ACTIVE;
3193 break;
3194 case TrackBase::ACTIVE:
3195 if (recentFull > 0 || recentPartial > 0) {
3196 // track has provided at least some frames recently: reset retry count
3197 track->mRetryCount = kMaxTrackRetries;
3198 }
3199 if (recentUnderruns == 0) {
3200 // no recent underruns: stay active
3201 break;
3202 }
3203 // there has recently been an underrun of some kind
3204 if (track->sharedBuffer() == 0) {
3205 // were any of the recent underruns "empty" (no frames available)?
3206 if (recentEmpty == 0) {
3207 // no, then ignore the partial underruns as they are allowed indefinitely
3208 break;
3209 }
3210 // there has recently been an "empty" underrun: decrement the retry counter
3211 if (--(track->mRetryCount) > 0) {
3212 break;
3213 }
3214 // indicate to client process that the track was disabled because of underrun;
3215 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003216 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 // remove from active list, but state remains ACTIVE [confusing but true]
3218 isActive = false;
3219 break;
3220 }
3221 // fall through
3222 case TrackBase::STOPPING_2:
3223 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003224 case TrackBase::STOPPED:
3225 case TrackBase::FLUSHED: // flush() while active
3226 // Check for presentation complete if track is inactive
3227 // We have consumed all the buffers of this track.
3228 // This would be incomplete if we auto-paused on underrun
3229 {
3230 size_t audioHALFrames =
3231 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3232 size_t framesWritten = mBytesWritten / mFrameSize;
3233 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3234 // track stays in active list until presentation is complete
3235 break;
3236 }
3237 }
3238 if (track->isStopping_2()) {
3239 track->mState = TrackBase::STOPPED;
3240 }
3241 if (track->isStopped()) {
3242 // Can't reset directly, as fast mixer is still polling this track
3243 // track->reset();
3244 // So instead mark this track as needing to be reset after push with ack
3245 resetMask |= 1 << i;
3246 }
3247 isActive = false;
3248 break;
3249 case TrackBase::IDLE:
3250 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003251 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003252 }
3253
3254 if (isActive) {
3255 // was it previously inactive?
3256 if (!(state->mTrackMask & (1 << j))) {
3257 ExtendedAudioBufferProvider *eabp = track;
3258 VolumeProvider *vp = track;
3259 fastTrack->mBufferProvider = eabp;
3260 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003261 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003262 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003263 fastTrack->mGeneration++;
3264 state->mTrackMask |= 1 << j;
3265 didModify = true;
3266 // no acknowledgement required for newly active tracks
3267 }
3268 // cache the combined master volume and stream type volume for fast mixer; this
3269 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003270 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003271 ++fastTracks;
3272 } else {
3273 // was it previously active?
3274 if (state->mTrackMask & (1 << j)) {
3275 fastTrack->mBufferProvider = NULL;
3276 fastTrack->mGeneration++;
3277 state->mTrackMask &= ~(1 << j);
3278 didModify = true;
3279 // If any fast tracks were removed, we must wait for acknowledgement
3280 // because we're about to decrement the last sp<> on those tracks.
3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3282 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003283 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003284 }
3285 tracksToRemove->add(track);
3286 // Avoids a misleading display in dumpsys
3287 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3288 }
3289 continue;
3290 }
3291
3292 { // local variable scope to avoid goto warning
3293
3294 audio_track_cblk_t* cblk = track->cblk();
3295
3296 // The first time a track is added we wait
3297 // for all its buffers to be filled before processing it
3298 int name = track->name();
3299 // make sure that we have enough frames to mix one full buffer.
3300 // enforce this condition only once to enable draining the buffer in case the client
3301 // app does not call stop() and relies on underrun to stop:
3302 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3303 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003304 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003305 uint32_t sr = track->sampleRate();
3306 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003307 desiredFrames = mNormalFrameCount;
3308 } else {
3309 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003310 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003311 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003312 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003313 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003314#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003315 // the minimum track buffer size is normally twice the number of frames necessary
3316 // to fill one buffer and the resampler should not leave more than one buffer worth
3317 // of unreleased frames after each pass, but just in case...
3318 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003319#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003320 }
Eric Laurent81784c32012-11-19 14:55:58 -08003321 uint32_t minFrames = 1;
3322 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3323 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003324 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003325 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003326
3327 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003328 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003329 !track->isPaused() && !track->isTerminated())
3330 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003331 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003332
3333 mixedTracks++;
3334
Andy Hung69aed5f2014-02-25 17:24:40 -08003335 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3336 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003337 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003338 if (track->mainBuffer() != mSinkBuffer &&
3339 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003340 if (mEffectBufferEnabled) {
3341 mEffectBufferValid = true; // Later can set directly.
3342 }
Eric Laurent81784c32012-11-19 14:55:58 -08003343 chain = getEffectChain_l(track->sessionId());
3344 // Delegate volume control to effect in track effect chain if needed
3345 if (chain != 0) {
3346 tracksWithEffect++;
3347 } else {
3348 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3349 "session %d",
3350 name, track->sessionId());
3351 }
3352 }
3353
3354
3355 int param = AudioMixer::VOLUME;
3356 if (track->mFillingUpStatus == Track::FS_FILLED) {
3357 // no ramp for the first volume setting
3358 track->mFillingUpStatus = Track::FS_ACTIVE;
3359 if (track->mState == TrackBase::RESUMING) {
3360 track->mState = TrackBase::ACTIVE;
3361 param = AudioMixer::RAMP_VOLUME;
3362 }
3363 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003364 // FIXME should not make a decision based on mServer
3365 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003366 // If the track is stopped before the first frame was mixed,
3367 // do not apply ramp
3368 param = AudioMixer::RAMP_VOLUME;
3369 }
3370
3371 // compute volume for this track
3372 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003373 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003374 vl = vr = va = 0;
3375 if (track->isPausing()) {
3376 track->setPaused();
3377 }
3378 } else {
3379
3380 // read original volumes with volume control
3381 float typeVolume = mStreamTypes[track->streamType()].volume;
3382 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003383 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003384 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3385 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3386 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003387 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003388 if (vlf > GAIN_FLOAT_UNITY) {
3389 ALOGV("Track left volume out of range: %.3g", vlf);
3390 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003391 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003392 if (vrf > GAIN_FLOAT_UNITY) {
3393 ALOGV("Track right volume out of range: %.3g", vrf);
3394 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003395 }
3396 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003397 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3398 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3399 vl = (uint32_t) (v8_24 * vlf);
3400 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003401 // assuming master volume and stream type volume each go up to 1.0,
3402 // vl and vr are now in 8.24 format
3403
Glenn Kastene3aa6592012-12-04 12:22:46 -08003404 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003405 // send level comes from shared memory and so may be corrupt
3406 if (sendLevel > MAX_GAIN_INT) {
3407 ALOGV("Track send level out of range: %04X", sendLevel);
3408 sendLevel = MAX_GAIN_INT;
3409 }
3410 va = (uint32_t)(v * sendLevel);
3411 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412
Eric Laurent81784c32012-11-19 14:55:58 -08003413 // Delegate volume control to effect in track effect chain if needed
3414 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3415 // Do not ramp volume if volume is controlled by effect
3416 param = AudioMixer::VOLUME;
3417 track->mHasVolumeController = true;
3418 } else {
3419 // force no volume ramp when volume controller was just disabled or removed
3420 // from effect chain to avoid volume spike
3421 if (track->mHasVolumeController) {
3422 param = AudioMixer::VOLUME;
3423 }
3424 track->mHasVolumeController = false;
3425 }
3426
Glenn Kastenc56f3422014-03-21 17:53:17 -07003427 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003428 // Convert volumes from 8.24 to 4.12 format
3429 // This additional clamping is needed in case chain->setVolume_l() overshot
3430 vl = (vl + (1 << 11)) >> 12;
3431 if (vl > MAX_GAIN_INT) {
3432 vl = MAX_GAIN_INT;
3433 }
3434 vr = (vr + (1 << 11)) >> 12;
3435 if (vr > MAX_GAIN_INT) {
3436 vr = MAX_GAIN_INT;
3437 }
3438
3439 if (va > MAX_GAIN_INT) {
3440 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3441 }
3442
3443 // XXX: these things DON'T need to be done each time
3444 mAudioMixer->setBufferProvider(name, track);
3445 mAudioMixer->enable(name);
3446
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003447 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3448 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3449 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003450 mAudioMixer->setParameter(
3451 name,
3452 AudioMixer::TRACK,
3453 AudioMixer::FORMAT, (void *)track->format());
3454 mAudioMixer->setParameter(
3455 name,
3456 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003457 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003458 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3459 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003460 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003461 if (reqSampleRate == 0) {
3462 reqSampleRate = mSampleRate;
3463 } else if (reqSampleRate > maxSampleRate) {
3464 reqSampleRate = maxSampleRate;
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 mAudioMixer->setParameter(
3467 name,
3468 AudioMixer::RESAMPLE,
3469 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003470 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003471 /*
3472 * Select the appropriate output buffer for the track.
3473 *
Andy Hung98ef9782014-03-04 14:46:50 -08003474 * Tracks with effects go into their own effects chain buffer
3475 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003476 *
3477 * Other tracks can use mMixerBuffer for higher precision
3478 * channel accumulation. If this buffer is enabled
3479 * (mMixerBufferEnabled true), then selected tracks will accumulate
3480 * into it.
3481 *
3482 */
3483 if (mMixerBufferEnabled
3484 && (track->mainBuffer() == mSinkBuffer
3485 || track->mainBuffer() == mMixerBuffer)) {
3486 mAudioMixer->setParameter(
3487 name,
3488 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003489 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003490 mAudioMixer->setParameter(
3491 name,
3492 AudioMixer::TRACK,
3493 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3494 // TODO: override track->mainBuffer()?
3495 mMixerBufferValid = true;
3496 } else {
3497 mAudioMixer->setParameter(
3498 name,
3499 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003500 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003501 mAudioMixer->setParameter(
3502 name,
3503 AudioMixer::TRACK,
3504 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3505 }
Eric Laurent81784c32012-11-19 14:55:58 -08003506 mAudioMixer->setParameter(
3507 name,
3508 AudioMixer::TRACK,
3509 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3510
3511 // reset retry count
3512 track->mRetryCount = kMaxTrackRetries;
3513
3514 // If one track is ready, set the mixer ready if:
3515 // - the mixer was not ready during previous round OR
3516 // - no other track is not ready
3517 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3518 mixerStatus != MIXER_TRACKS_ENABLED) {
3519 mixerStatus = MIXER_TRACKS_READY;
3520 }
3521 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003522 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003523 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003524 }
Eric Laurent81784c32012-11-19 14:55:58 -08003525 // clear effect chain input buffer if an active track underruns to avoid sending
3526 // previous audio buffer again to effects
3527 chain = getEffectChain_l(track->sessionId());
3528 if (chain != 0) {
3529 chain->clearInputBuffer();
3530 }
3531
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003532 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003533 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3534 track->isStopped() || track->isPaused()) {
3535 // We have consumed all the buffers of this track.
3536 // Remove it from the list of active tracks.
3537 // TODO: use actual buffer filling status instead of latency when available from
3538 // audio HAL
3539 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3540 size_t framesWritten = mBytesWritten / mFrameSize;
3541 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3542 if (track->isStopped()) {
3543 track->reset();
3544 }
3545 tracksToRemove->add(track);
3546 }
3547 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003548 // No buffers for this track. Give it a few chances to
3549 // fill a buffer, then remove it from active list.
3550 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003551 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003552 tracksToRemove->add(track);
3553 // indicate to client process that the track was disabled because of underrun;
3554 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003555 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003556 // If one track is not ready, mark the mixer also not ready if:
3557 // - the mixer was ready during previous round OR
3558 // - no other track is ready
3559 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3560 mixerStatus != MIXER_TRACKS_READY) {
3561 mixerStatus = MIXER_TRACKS_ENABLED;
3562 }
3563 }
3564 mAudioMixer->disable(name);
3565 }
3566
3567 } // local variable scope to avoid goto warning
3568track_is_ready: ;
3569
3570 }
3571
3572 // Push the new FastMixer state if necessary
3573 bool pauseAudioWatchdog = false;
3574 if (didModify) {
3575 state->mFastTracksGen++;
3576 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3577 if (kUseFastMixer == FastMixer_Dynamic &&
3578 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3579 state->mCommand = FastMixerState::COLD_IDLE;
3580 state->mColdFutexAddr = &mFastMixerFutex;
3581 state->mColdGen++;
3582 mFastMixerFutex = 0;
3583 if (kUseFastMixer == FastMixer_Dynamic) {
3584 mNormalSink = mOutputSink;
3585 }
3586 // If we go into cold idle, need to wait for acknowledgement
3587 // so that fast mixer stops doing I/O.
3588 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3589 pauseAudioWatchdog = true;
3590 }
Eric Laurent81784c32012-11-19 14:55:58 -08003591 }
3592 if (sq != NULL) {
3593 sq->end(didModify);
3594 sq->push(block);
3595 }
3596#ifdef AUDIO_WATCHDOG
3597 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3598 mAudioWatchdog->pause();
3599 }
3600#endif
3601
3602 // Now perform the deferred reset on fast tracks that have stopped
3603 while (resetMask != 0) {
3604 size_t i = __builtin_ctz(resetMask);
3605 ALOG_ASSERT(i < count);
3606 resetMask &= ~(1 << i);
3607 sp<Track> t = mActiveTracks[i].promote();
3608 if (t == 0) {
3609 continue;
3610 }
3611 Track* track = t.get();
3612 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3613 track->reset();
3614 }
3615
3616 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003618
Andy Hung69aed5f2014-02-25 17:24:40 -08003619 // sink or mix buffer must be cleared if all tracks are connected to an
3620 // effect chain as in this case the mixer will not write to the sink or mix buffer
3621 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3623 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003624 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003625 if (mMixerBufferValid) {
3626 memset(mMixerBuffer, 0, mMixerBufferSize);
3627 // TODO: In testing, mSinkBuffer below need not be cleared because
3628 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3629 // after mixing.
3630 //
3631 // To enforce this guarantee:
3632 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3633 // (mixedTracks == 0 && fastTracks > 0))
3634 // must imply MIXER_TRACKS_READY.
3635 // Later, we may clear buffers regardless, and skip much of this logic.
3636 }
Andy Hung98ef9782014-03-04 14:46:50 -08003637 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3638 if (mEffectBufferValid) {
3639 memset(mEffectBuffer, 0, mEffectBufferSize);
3640 }
3641 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003642 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003643 }
3644
3645 // if any fast tracks, then status is ready
3646 mMixerStatusIgnoringFastTracks = mixerStatus;
3647 if (fastTracks > 0) {
3648 mixerStatus = MIXER_TRACKS_READY;
3649 }
3650 return mixerStatus;
3651}
3652
3653// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003654int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3655 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003656{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003657 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003658}
3659
3660// deleteTrackName_l() must be called with ThreadBase::mLock held
3661void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3662{
3663 ALOGV("remove track (%d) and delete from mixer", name);
3664 mAudioMixer->deleteTrackName(name);
3665}
3666
Eric Laurent10351942014-05-08 18:49:52 -07003667// checkForNewParameter_l() must be called with ThreadBase::mLock held
3668bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3669 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003670{
Eric Laurent81784c32012-11-19 14:55:58 -08003671 bool reconfig = false;
3672
Eric Laurent10351942014-05-08 18:49:52 -07003673 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003674
Eric Laurent10351942014-05-08 18:49:52 -07003675 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3676 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3677 if (mFastMixer != NULL) {
3678 FastMixerStateQueue *sq = mFastMixer->sq();
3679 FastMixerState *state = sq->begin();
3680 if (!(state->mCommand & FastMixerState::IDLE)) {
3681 previousCommand = state->mCommand;
3682 state->mCommand = FastMixerState::HOT_IDLE;
3683 sq->end();
3684 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3685 } else {
3686 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003687 }
Eric Laurent10351942014-05-08 18:49:52 -07003688 }
Eric Laurent81784c32012-11-19 14:55:58 -08003689
Eric Laurent10351942014-05-08 18:49:52 -07003690 AudioParameter param = AudioParameter(keyValuePair);
3691 int value;
3692 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3693 reconfig = true;
3694 }
3695 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3696 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3697 status = BAD_VALUE;
3698 } else {
3699 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003700 reconfig = true;
3701 }
Eric Laurent10351942014-05-08 18:49:52 -07003702 }
3703 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3704 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3705 status = BAD_VALUE;
3706 } else {
3707 // no need to save value, since it's constant
3708 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003709 }
Eric Laurent10351942014-05-08 18:49:52 -07003710 }
3711 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3712 // do not accept frame count changes if tracks are open as the track buffer
3713 // size depends on frame count and correct behavior would not be guaranteed
3714 // if frame count is changed after track creation
3715 if (!mTracks.isEmpty()) {
3716 status = INVALID_OPERATION;
3717 } else {
3718 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003719 }
Eric Laurent10351942014-05-08 18:49:52 -07003720 }
3721 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003722#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003723 // when changing the audio output device, call addBatteryData to notify
3724 // the change
3725 if (mOutDevice != value) {
3726 uint32_t params = 0;
3727 // check whether speaker is on
3728 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3729 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003730 }
Eric Laurent10351942014-05-08 18:49:52 -07003731
3732 audio_devices_t deviceWithoutSpeaker
3733 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3734 // check if any other device (except speaker) is on
3735 if (value & deviceWithoutSpeaker ) {
3736 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3737 }
3738
3739 if (params != 0) {
3740 addBatteryData(params);
3741 }
3742 }
Eric Laurent81784c32012-11-19 14:55:58 -08003743#endif
3744
Eric Laurent10351942014-05-08 18:49:52 -07003745 // forward device change to effects that have requested to be
3746 // aware of attached audio device.
3747 if (value != AUDIO_DEVICE_NONE) {
3748 mOutDevice = value;
3749 for (size_t i = 0; i < mEffectChains.size(); i++) {
3750 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003751 }
3752 }
Eric Laurent10351942014-05-08 18:49:52 -07003753 }
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Eric Laurent10351942014-05-08 18:49:52 -07003755 if (status == NO_ERROR) {
3756 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3757 keyValuePair.string());
3758 if (!mStandby && status == INVALID_OPERATION) {
3759 mOutput->stream->common.standby(&mOutput->stream->common);
3760 mStandby = true;
3761 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003762 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003763 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003764 }
Eric Laurent10351942014-05-08 18:49:52 -07003765 if (status == NO_ERROR && reconfig) {
3766 readOutputParameters_l();
3767 delete mAudioMixer;
3768 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3769 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003770 int name = getTrackName_l(mTracks[i]->mChannelMask,
3771 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003772 if (name < 0) {
3773 break;
3774 }
3775 mTracks[i]->mName = name;
3776 }
3777 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3778 }
Eric Laurent81784c32012-11-19 14:55:58 -08003779 }
3780
3781 if (!(previousCommand & FastMixerState::IDLE)) {
3782 ALOG_ASSERT(mFastMixer != NULL);
3783 FastMixerStateQueue *sq = mFastMixer->sq();
3784 FastMixerState *state = sq->begin();
3785 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3786 state->mCommand = previousCommand;
3787 sq->end();
3788 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3789 }
3790
3791 return reconfig;
3792}
3793
3794
3795void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3796{
3797 const size_t SIZE = 256;
3798 char buffer[SIZE];
3799 String8 result;
3800
3801 PlaybackThread::dumpInternals(fd, args);
3802
Elliott Hughes87cebad2014-05-22 10:14:43 -07003803 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003804
3805 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003806 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003807 copy.dump(fd);
3808
3809#ifdef STATE_QUEUE_DUMP
3810 // Similar for state queue
3811 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3812 observerCopy.dump(fd);
3813 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3814 mutatorCopy.dump(fd);
3815#endif
3816
Glenn Kasten46909e72013-02-26 09:20:22 -08003817#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003818 // Write the tee output to a .wav file
3819 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003820#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003821
3822#ifdef AUDIO_WATCHDOG
3823 if (mAudioWatchdog != 0) {
3824 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3825 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3826 wdCopy.dump(fd);
3827 }
3828#endif
3829}
3830
3831uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3832{
3833 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3834}
3835
3836uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3837{
3838 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3839}
3840
3841void AudioFlinger::MixerThread::cacheParameters_l()
3842{
3843 PlaybackThread::cacheParameters_l();
3844
3845 // FIXME: Relaxed timing because of a certain device that can't meet latency
3846 // Should be reduced to 2x after the vendor fixes the driver issue
3847 // increase threshold again due to low power audio mode. The way this warning
3848 // threshold is calculated and its usefulness should be reconsidered anyway.
3849 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3850}
3851
3852// ----------------------------------------------------------------------------
3853
3854AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3855 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3856 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3857 // mLeftVolFloat, mRightVolFloat
3858{
3859}
3860
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3862 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3863 ThreadBase::type_t type)
3864 : PlaybackThread(audioFlinger, output, id, device, type)
3865 // mLeftVolFloat, mRightVolFloat
3866{
3867}
3868
Eric Laurent81784c32012-11-19 14:55:58 -08003869AudioFlinger::DirectOutputThread::~DirectOutputThread()
3870{
3871}
3872
Eric Laurentbfb1b832013-01-07 09:53:42 -08003873void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3874{
3875 audio_track_cblk_t* cblk = track->cblk();
3876 float left, right;
3877
3878 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3879 left = right = 0;
3880 } else {
3881 float typeVolume = mStreamTypes[track->streamType()].volume;
3882 float v = mMasterVolume * typeVolume;
3883 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003884 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3885 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3886 if (left > GAIN_FLOAT_UNITY) {
3887 left = GAIN_FLOAT_UNITY;
3888 }
3889 left *= v;
3890 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3891 if (right > GAIN_FLOAT_UNITY) {
3892 right = GAIN_FLOAT_UNITY;
3893 }
3894 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895 }
3896
3897 if (lastTrack) {
3898 if (left != mLeftVolFloat || right != mRightVolFloat) {
3899 mLeftVolFloat = left;
3900 mRightVolFloat = right;
3901
3902 // Convert volumes from float to 8.24
3903 uint32_t vl = (uint32_t)(left * (1 << 24));
3904 uint32_t vr = (uint32_t)(right * (1 << 24));
3905
3906 // Delegate volume control to effect in track effect chain if needed
3907 // only one effect chain can be present on DirectOutputThread, so if
3908 // there is one, the track is connected to it
3909 if (!mEffectChains.isEmpty()) {
3910 mEffectChains[0]->setVolume_l(&vl, &vr);
3911 left = (float)vl / (1 << 24);
3912 right = (float)vr / (1 << 24);
3913 }
3914 if (mOutput->stream->set_volume) {
3915 mOutput->stream->set_volume(mOutput->stream, left, right);
3916 }
3917 }
3918 }
3919}
3920
3921
Eric Laurent81784c32012-11-19 14:55:58 -08003922AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3923 Vector< sp<Track> > *tracksToRemove
3924)
3925{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003926 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003927 mixer_state mixerStatus = MIXER_IDLE;
3928
3929 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003930 for (size_t i = 0; i < count; i++) {
3931 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003932 // The track died recently
3933 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003934 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003935 }
3936
3937 Track* const track = t.get();
3938 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003939 // Only consider last track started for volume and mixer state control.
3940 // In theory an older track could underrun and restart after the new one starts
3941 // but as we only care about the transition phase between two tracks on a
3942 // direct output, it is not a problem to ignore the underrun case.
3943 sp<Track> l = mLatestActiveTrack.promote();
3944 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003945
3946 // The first time a track is added we wait
3947 // for all its buffers to be filled before processing it
3948 uint32_t minFrames;
3949 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3950 minFrames = mNormalFrameCount;
3951 } else {
3952 minFrames = 1;
3953 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003954
Eric Laurent81784c32012-11-19 14:55:58 -08003955 if ((track->framesReady() >= minFrames) && track->isReady() &&
3956 !track->isPaused() && !track->isTerminated())
3957 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003958 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003959
3960 if (track->mFillingUpStatus == Track::FS_FILLED) {
3961 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003962 // make sure processVolume_l() will apply new volume even if 0
3963 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003964 if (track->mState == TrackBase::RESUMING) {
3965 track->mState = TrackBase::ACTIVE;
3966 }
3967 }
3968
3969 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970 processVolume_l(track, last);
3971 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003972 // reset retry count
3973 track->mRetryCount = kMaxTrackRetriesDirect;
3974 mActiveTrack = t;
3975 mixerStatus = MIXER_TRACKS_READY;
3976 }
Eric Laurent81784c32012-11-19 14:55:58 -08003977 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003978 // clear effect chain input buffer if the last active track started underruns
3979 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003980 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003981 mEffectChains[0]->clearInputBuffer();
3982 }
3983
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003984 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003985 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3986 track->isStopped() || track->isPaused()) {
3987 // We have consumed all the buffers of this track.
3988 // Remove it from the list of active tracks.
3989 // TODO: implement behavior for compressed audio
3990 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3991 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003992 if (mStandby || !last ||
3993 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003994 if (track->isStopped()) {
3995 track->reset();
3996 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003997 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
3999 } else {
4000 // No buffers for this track. Give it a few chances to
4001 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004002 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004003 if (--(track->mRetryCount) <= 0) {
4004 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004005 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004006 // indicate to client process that the track was disabled because of underrun;
4007 // it will then automatically call start() when data is available
4008 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004009 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004010 mixerStatus = MIXER_TRACKS_ENABLED;
4011 }
4012 }
4013 }
4014 }
4015
Eric Laurent81784c32012-11-19 14:55:58 -08004016 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004017 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004018
4019 return mixerStatus;
4020}
4021
4022void AudioFlinger::DirectOutputThread::threadLoop_mix()
4023{
Eric Laurent81784c32012-11-19 14:55:58 -08004024 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004025 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004026 // output audio to hardware
4027 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004028 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004029 buffer.frameCount = frameCount;
4030 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004031 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004032 memset(curBuf, 0, frameCount * mFrameSize);
4033 break;
4034 }
4035 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4036 frameCount -= buffer.frameCount;
4037 curBuf += buffer.frameCount * mFrameSize;
4038 mActiveTrack->releaseBuffer(&buffer);
4039 }
Andy Hung2098f272014-02-27 14:00:06 -08004040 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004041 sleepTime = 0;
4042 standbyTime = systemTime() + standbyDelay;
4043 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004044}
4045
4046void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4047{
4048 if (sleepTime == 0) {
4049 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4050 sleepTime = activeSleepTime;
4051 } else {
4052 sleepTime = idleSleepTime;
4053 }
4054 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004055 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004056 sleepTime = 0;
4057 }
4058}
4059
4060// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004061int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004062 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004063{
4064 return 0;
4065}
4066
4067// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004068void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004069{
4070}
4071
Eric Laurent10351942014-05-08 18:49:52 -07004072// checkForNewParameter_l() must be called with ThreadBase::mLock held
4073bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4074 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004075{
4076 bool reconfig = false;
4077
Eric Laurent10351942014-05-08 18:49:52 -07004078 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004079
Eric Laurent10351942014-05-08 18:49:52 -07004080 AudioParameter param = AudioParameter(keyValuePair);
4081 int value;
4082 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4083 // forward device change to effects that have requested to be
4084 // aware of attached audio device.
4085 if (value != AUDIO_DEVICE_NONE) {
4086 mOutDevice = value;
4087 for (size_t i = 0; i < mEffectChains.size(); i++) {
4088 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004089 }
4090 }
Eric Laurent81784c32012-11-19 14:55:58 -08004091 }
Eric Laurent10351942014-05-08 18:49:52 -07004092 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4093 // do not accept frame count changes if tracks are open as the track buffer
4094 // size depends on frame count and correct behavior would not be garantied
4095 // if frame count is changed after track creation
4096 if (!mTracks.isEmpty()) {
4097 status = INVALID_OPERATION;
4098 } else {
4099 reconfig = true;
4100 }
4101 }
4102 if (status == NO_ERROR) {
4103 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4104 keyValuePair.string());
4105 if (!mStandby && status == INVALID_OPERATION) {
4106 mOutput->stream->common.standby(&mOutput->stream->common);
4107 mStandby = true;
4108 mBytesWritten = 0;
4109 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4110 keyValuePair.string());
4111 }
4112 if (status == NO_ERROR && reconfig) {
4113 readOutputParameters_l();
4114 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4115 }
4116 }
4117
Eric Laurent81784c32012-11-19 14:55:58 -08004118 return reconfig;
4119}
4120
4121uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4122{
4123 uint32_t time;
4124 if (audio_is_linear_pcm(mFormat)) {
4125 time = PlaybackThread::activeSleepTimeUs();
4126 } else {
4127 time = 10000;
4128 }
4129 return time;
4130}
4131
4132uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4133{
4134 uint32_t time;
4135 if (audio_is_linear_pcm(mFormat)) {
4136 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4137 } else {
4138 time = 10000;
4139 }
4140 return time;
4141}
4142
4143uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4144{
4145 uint32_t time;
4146 if (audio_is_linear_pcm(mFormat)) {
4147 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4148 } else {
4149 time = 10000;
4150 }
4151 return time;
4152}
4153
4154void AudioFlinger::DirectOutputThread::cacheParameters_l()
4155{
4156 PlaybackThread::cacheParameters_l();
4157
4158 // use shorter standby delay as on normal output to release
4159 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004160 if (audio_is_linear_pcm(mFormat)) {
4161 standbyDelay = microseconds(activeSleepTime*2);
4162 } else {
4163 standbyDelay = kOffloadStandbyDelayNs;
4164 }
Eric Laurent81784c32012-11-19 14:55:58 -08004165}
4166
4167// ----------------------------------------------------------------------------
4168
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004170 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004172 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004173 mWriteAckSequence(0),
4174 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175{
4176}
4177
4178AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4179{
4180}
4181
4182void AudioFlinger::AsyncCallbackThread::onFirstRef()
4183{
4184 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4185}
4186
4187bool AudioFlinger::AsyncCallbackThread::threadLoop()
4188{
4189 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004190 uint32_t writeAckSequence;
4191 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192
4193 {
4194 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004195 while (!((mWriteAckSequence & 1) ||
4196 (mDrainSequence & 1) ||
4197 exitPending())) {
4198 mWaitWorkCV.wait(mLock);
4199 }
4200
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 if (exitPending()) {
4202 break;
4203 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004204 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4205 mWriteAckSequence, mDrainSequence);
4206 writeAckSequence = mWriteAckSequence;
4207 mWriteAckSequence &= ~1;
4208 drainSequence = mDrainSequence;
4209 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004210 }
4211 {
Eric Laurent4de95592013-09-26 15:28:21 -07004212 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4213 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004214 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004215 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004217 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004218 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 }
4220 }
4221 }
4222 }
4223 return false;
4224}
4225
4226void AudioFlinger::AsyncCallbackThread::exit()
4227{
4228 ALOGV("AsyncCallbackThread::exit");
4229 Mutex::Autolock _l(mLock);
4230 requestExit();
4231 mWaitWorkCV.broadcast();
4232}
4233
Eric Laurent3b4529e2013-09-05 18:09:19 -07004234void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004235{
4236 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004237 // bit 0 is cleared
4238 mWriteAckSequence = sequence << 1;
4239}
4240
4241void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4242{
4243 Mutex::Autolock _l(mLock);
4244 // ignore unexpected callbacks
4245 if (mWriteAckSequence & 2) {
4246 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004247 mWaitWorkCV.signal();
4248 }
4249}
4250
Eric Laurent3b4529e2013-09-05 18:09:19 -07004251void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004252{
4253 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004254 // bit 0 is cleared
4255 mDrainSequence = sequence << 1;
4256}
4257
4258void AudioFlinger::AsyncCallbackThread::resetDraining()
4259{
4260 Mutex::Autolock _l(mLock);
4261 // ignore unexpected callbacks
4262 if (mDrainSequence & 2) {
4263 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 mWaitWorkCV.signal();
4265 }
4266}
4267
4268
4269// ----------------------------------------------------------------------------
4270AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4271 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4272 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4273 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004274 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004275 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276{
Eric Laurentfd477972013-10-25 18:10:40 -07004277 //FIXME: mStandby should be set to true by ThreadBase constructor
4278 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004279}
4280
Eric Laurentbfb1b832013-01-07 09:53:42 -08004281void AudioFlinger::OffloadThread::threadLoop_exit()
4282{
4283 if (mFlushPending || mHwPaused) {
4284 // If a flush is pending or track was paused, just discard buffered data
4285 flushHw_l();
4286 } else {
4287 mMixerStatus = MIXER_DRAIN_ALL;
4288 threadLoop_drain();
4289 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004290 if (mUseAsyncWrite) {
4291 ALOG_ASSERT(mCallbackThread != 0);
4292 mCallbackThread->exit();
4293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 PlaybackThread::threadLoop_exit();
4295}
4296
4297AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4298 Vector< sp<Track> > *tracksToRemove
4299)
4300{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301 size_t count = mActiveTracks.size();
4302
4303 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004304 bool doHwPause = false;
4305 bool doHwResume = false;
4306
Eric Laurentede6c3b2013-09-19 14:37:46 -07004307 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4308
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309 // find out which tracks need to be processed
4310 for (size_t i = 0; i < count; i++) {
4311 sp<Track> t = mActiveTracks[i].promote();
4312 // The track died recently
4313 if (t == 0) {
4314 continue;
4315 }
4316 Track* const track = t.get();
4317 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004318 // Only consider last track started for volume and mixer state control.
4319 // In theory an older track could underrun and restart after the new one starts
4320 // but as we only care about the transition phase between two tracks on a
4321 // direct output, it is not a problem to ignore the underrun case.
4322 sp<Track> l = mLatestActiveTrack.promote();
4323 bool last = l.get() == track;
4324
Haynes Mathew George7844f672014-01-15 12:32:55 -08004325 if (track->isInvalid()) {
4326 ALOGW("An invalidated track shouldn't be in active list");
4327 tracksToRemove->add(track);
4328 continue;
4329 }
4330
4331 if (track->mState == TrackBase::IDLE) {
4332 ALOGW("An idle track shouldn't be in active list");
4333 continue;
4334 }
4335
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 if (track->isPausing()) {
4337 track->setPaused();
4338 if (last) {
4339 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004340 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 mHwPaused = true;
4342 }
4343 // If we were part way through writing the mixbuffer to
4344 // the HAL we must save this until we resume
4345 // BUG - this will be wrong if a different track is made active,
4346 // in that case we want to discard the pending data in the
4347 // mixbuffer and tell the client to present it again when the
4348 // track is resumed
4349 mPausedWriteLength = mCurrentWriteLength;
4350 mPausedBytesRemaining = mBytesRemaining;
4351 mBytesRemaining = 0; // stop writing
4352 }
4353 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004354 } else if (track->isFlushPending()) {
4355 track->flushAck();
4356 if (last) {
4357 mFlushPending = true;
4358 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004359 } else if (track->isResumePending()){
4360 track->resumeAck();
4361 if (last) {
4362 if (mPausedBytesRemaining) {
4363 // Need to continue write that was interrupted
4364 mCurrentWriteLength = mPausedWriteLength;
4365 mBytesRemaining = mPausedBytesRemaining;
4366 mPausedBytesRemaining = 0;
4367 }
4368 if (mHwPaused) {
4369 doHwResume = true;
4370 mHwPaused = false;
4371 // threadLoop_mix() will handle the case that we need to
4372 // resume an interrupted write
4373 }
4374 // enable write to audio HAL
4375 sleepTime = 0;
4376
4377 // Do not handle new data in this iteration even if track->framesReady()
4378 mixerStatus = MIXER_TRACKS_ENABLED;
4379 }
4380 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004381 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004382 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 if (track->mFillingUpStatus == Track::FS_FILLED) {
4384 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004385 // make sure processVolume_l() will apply new volume even if 0
4386 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 }
4388
4389 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004390 sp<Track> previousTrack = mPreviousTrack.promote();
4391 if (previousTrack != 0) {
4392 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004393 // Flush any data still being written from last track
4394 mBytesRemaining = 0;
4395 if (mPausedBytesRemaining) {
4396 // Last track was paused so we also need to flush saved
4397 // mixbuffer state and invalidate track so that it will
4398 // re-submit that unwritten data when it is next resumed
4399 mPausedBytesRemaining = 0;
4400 // Invalidate is a bit drastic - would be more efficient
4401 // to have a flag to tell client that some of the
4402 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004403 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004404 }
4405 // flush data already sent to the DSP if changing audio session as audio
4406 // comes from a different source. Also invalidate previous track to force a
4407 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004408 if (previousTrack->sessionId() != track->sessionId()) {
4409 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004410 }
4411 }
4412 }
4413 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414 // reset retry count
4415 track->mRetryCount = kMaxTrackRetriesOffload;
4416 mActiveTrack = t;
4417 mixerStatus = MIXER_TRACKS_READY;
4418 }
4419 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004420 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004421 if (track->isStopping_1()) {
4422 // Hardware buffer can hold a large amount of audio so we must
4423 // wait for all current track's data to drain before we say
4424 // that the track is stopped.
4425 if (mBytesRemaining == 0) {
4426 // Only start draining when all data in mixbuffer
4427 // has been written
4428 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4429 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004430 // do not drain if no data was ever sent to HAL (mStandby == true)
4431 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004432 // do not modify drain sequence if we are already draining. This happens
4433 // when resuming from pause after drain.
4434 if ((mDrainSequence & 1) == 0) {
4435 sleepTime = 0;
4436 standbyTime = systemTime() + standbyDelay;
4437 mixerStatus = MIXER_DRAIN_TRACK;
4438 mDrainSequence += 2;
4439 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440 if (mHwPaused) {
4441 // It is possible to move from PAUSED to STOPPING_1 without
4442 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004443 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 mHwPaused = false;
4445 }
4446 }
4447 }
4448 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004449 // Drain has completed or we are in standby, signal presentation complete
4450 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004451 track->mState = TrackBase::STOPPED;
4452 size_t audioHALFrames =
4453 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4454 size_t framesWritten =
4455 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4456 track->presentationComplete(framesWritten, audioHALFrames);
4457 track->reset();
4458 tracksToRemove->add(track);
4459 }
4460 } else {
4461 // No buffers for this track. Give it a few chances to
4462 // fill a buffer, then remove it from active list.
4463 if (--(track->mRetryCount) <= 0) {
4464 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4465 track->name());
4466 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004467 // indicate to client process that the track was disabled because of underrun;
4468 // it will then automatically call start() when data is available
4469 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 } else if (last){
4471 mixerStatus = MIXER_TRACKS_ENABLED;
4472 }
4473 }
4474 }
4475 // compute volume for this track
4476 processVolume_l(track, last);
4477 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004478
Eric Laurentea0fade2013-10-04 16:23:48 -07004479 // make sure the pause/flush/resume sequence is executed in the right order.
4480 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4481 // before flush and then resume HW. This can happen in case of pause/flush/resume
4482 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004483 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004484 mOutput->stream->pause(mOutput->stream);
4485 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004486 if (mFlushPending) {
4487 flushHw_l();
4488 mFlushPending = false;
4489 }
Eric Laurentfd477972013-10-25 18:10:40 -07004490 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004491 mOutput->stream->resume(mOutput->stream);
4492 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004493
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 // remove all the tracks that need to be...
4495 removeTracks_l(*tracksToRemove);
4496
4497 return mixerStatus;
4498}
4499
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500// must be called with thread mutex locked
4501bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4502{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004503 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4504 mWriteAckSequence, mDrainSequence);
4505 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 return true;
4507 }
4508 return false;
4509}
4510
4511// must be called with thread mutex locked
4512bool AudioFlinger::OffloadThread::shouldStandby_l()
4513{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004514 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004515
4516 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4517 // after a timeout and we will enter standby then.
4518 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004519 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004520 }
4521
Glenn Kastene6f35b12013-08-19 09:58:50 -07004522 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523}
4524
4525
4526bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4527{
4528 Mutex::Autolock _l(mLock);
4529 return waitingAsyncCallback_l();
4530}
4531
4532void AudioFlinger::OffloadThread::flushHw_l()
4533{
4534 mOutput->stream->flush(mOutput->stream);
4535 // Flush anything still waiting in the mixbuffer
4536 mCurrentWriteLength = 0;
4537 mBytesRemaining = 0;
4538 mPausedWriteLength = 0;
4539 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004540 mHwPaused = false;
4541
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004543 // discard any pending drain or write ack by incrementing sequence
4544 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4545 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004546 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004547 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4548 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004549 }
4550}
4551
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004552void AudioFlinger::OffloadThread::onAddNewTrack_l()
4553{
4554 sp<Track> previousTrack = mPreviousTrack.promote();
4555 sp<Track> latestTrack = mLatestActiveTrack.promote();
4556
4557 if (previousTrack != 0 && latestTrack != 0 &&
4558 (previousTrack->sessionId() != latestTrack->sessionId())) {
4559 mFlushPending = true;
4560 }
4561 PlaybackThread::onAddNewTrack_l();
4562}
4563
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564// ----------------------------------------------------------------------------
4565
Eric Laurent81784c32012-11-19 14:55:58 -08004566AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4567 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4568 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4569 DUPLICATING),
4570 mWaitTimeMs(UINT_MAX)
4571{
4572 addOutputTrack(mainThread);
4573}
4574
4575AudioFlinger::DuplicatingThread::~DuplicatingThread()
4576{
4577 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4578 mOutputTracks[i]->destroy();
4579 }
4580}
4581
4582void AudioFlinger::DuplicatingThread::threadLoop_mix()
4583{
4584 // mix buffers...
4585 if (outputsReady(outputTracks)) {
4586 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4587 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004588 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004589 }
4590 sleepTime = 0;
4591 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004592 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004593 standbyTime = systemTime() + standbyDelay;
4594}
4595
4596void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4597{
4598 if (sleepTime == 0) {
4599 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4600 sleepTime = activeSleepTime;
4601 } else {
4602 sleepTime = idleSleepTime;
4603 }
4604 } else if (mBytesWritten != 0) {
4605 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4606 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004607 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004608 } else {
4609 // flush remaining overflow buffers in output tracks
4610 writeFrames = 0;
4611 }
4612 sleepTime = 0;
4613 }
4614}
4615
Eric Laurentbfb1b832013-01-07 09:53:42 -08004616ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004617{
4618 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004619 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4620 // for delivery downstream as needed. This in-place conversion is safe as
4621 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4622 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4623 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4624 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4625 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4626 }
4627 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004628 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004629 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004630 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004631}
4632
4633void AudioFlinger::DuplicatingThread::threadLoop_standby()
4634{
4635 // DuplicatingThread implements standby by stopping all tracks
4636 for (size_t i = 0; i < outputTracks.size(); i++) {
4637 outputTracks[i]->stop();
4638 }
4639}
4640
4641void AudioFlinger::DuplicatingThread::saveOutputTracks()
4642{
4643 outputTracks = mOutputTracks;
4644}
4645
4646void AudioFlinger::DuplicatingThread::clearOutputTracks()
4647{
4648 outputTracks.clear();
4649}
4650
4651void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4652{
4653 Mutex::Autolock _l(mLock);
4654 // FIXME explain this formula
4655 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004656 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4657 // due to current usage case and restrictions on the AudioBufferProvider.
4658 // Actual buffer conversion is done in threadLoop_write().
4659 //
4660 // TODO: This may change in the future, depending on multichannel
4661 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004662 OutputTrack *outputTrack = new OutputTrack(thread,
4663 this,
4664 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004665 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004666 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004667 frameCount,
4668 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004669 if (outputTrack->cblk() != NULL) {
4670 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4671 mOutputTracks.add(outputTrack);
4672 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4673 updateWaitTime_l();
4674 }
4675}
4676
4677void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4678{
4679 Mutex::Autolock _l(mLock);
4680 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4681 if (mOutputTracks[i]->thread() == thread) {
4682 mOutputTracks[i]->destroy();
4683 mOutputTracks.removeAt(i);
4684 updateWaitTime_l();
4685 return;
4686 }
4687 }
4688 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4689}
4690
4691// caller must hold mLock
4692void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4693{
4694 mWaitTimeMs = UINT_MAX;
4695 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4696 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4697 if (strong != 0) {
4698 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4699 if (waitTimeMs < mWaitTimeMs) {
4700 mWaitTimeMs = waitTimeMs;
4701 }
4702 }
4703 }
4704}
4705
4706
4707bool AudioFlinger::DuplicatingThread::outputsReady(
4708 const SortedVector< sp<OutputTrack> > &outputTracks)
4709{
4710 for (size_t i = 0; i < outputTracks.size(); i++) {
4711 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4712 if (thread == 0) {
4713 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4714 outputTracks[i].get());
4715 return false;
4716 }
4717 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4718 // see note at standby() declaration
4719 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4720 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4721 thread.get());
4722 return false;
4723 }
4724 }
4725 return true;
4726}
4727
4728uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4729{
4730 return (mWaitTimeMs * 1000) / 2;
4731}
4732
4733void AudioFlinger::DuplicatingThread::cacheParameters_l()
4734{
4735 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4736 updateWaitTime_l();
4737
4738 MixerThread::cacheParameters_l();
4739}
4740
4741// ----------------------------------------------------------------------------
4742// Record
4743// ----------------------------------------------------------------------------
4744
4745AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4746 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004747 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004748 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004749 audio_devices_t inDevice
4750#ifdef TEE_SINK
4751 , const sp<NBAIO_Sink>& teeSink
4752#endif
4753 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004754 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004755 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004756 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004757 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004758#ifdef TEE_SINK
4759 , mTeeSink(teeSink)
4760#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004761 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4762 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004763{
4764 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004765 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004766
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004767 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004768}
4769
4770
4771AudioFlinger::RecordThread::~RecordThread()
4772{
Glenn Kasten481fb672013-09-30 14:39:28 -07004773 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004774 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004775}
4776
4777void AudioFlinger::RecordThread::onFirstRef()
4778{
4779 run(mName, PRIORITY_URGENT_AUDIO);
4780}
4781
Eric Laurent81784c32012-11-19 14:55:58 -08004782bool AudioFlinger::RecordThread::threadLoop()
4783{
Eric Laurent81784c32012-11-19 14:55:58 -08004784 nsecs_t lastWarning = 0;
4785
4786 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004787
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004788reacquire_wakelock:
4789 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004790 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004791 {
4792 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004793 size_t size = mActiveTracks.size();
4794 activeTracksGen = mActiveTracksGen;
4795 if (size > 0) {
4796 // FIXME an arbitrary choice
4797 activeTrack = mActiveTracks[0];
4798 acquireWakeLock_l(activeTrack->uid());
4799 if (size > 1) {
4800 SortedVector<int> tmp;
4801 for (size_t i = 0; i < size; i++) {
4802 tmp.add(mActiveTracks[i]->uid());
4803 }
4804 updateWakeLockUids_l(tmp);
4805 }
4806 } else {
4807 acquireWakeLock_l(-1);
4808 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004809 }
4810
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004811 // used to request a deferred sleep, to be executed later while mutex is unlocked
4812 uint32_t sleepUs = 0;
4813
4814 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004815 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004816 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004817
Glenn Kasten5edadd42013-08-14 16:30:49 -07004818 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004819 if (sleepUs > 0) {
4820 usleep(sleepUs);
4821 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004822 }
4823
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004824 // activeTracks accumulates a copy of a subset of mActiveTracks
4825 Vector< sp<RecordTrack> > activeTracks;
4826
Eric Laurent10351942014-05-08 18:49:52 -07004827
Eric Laurent81784c32012-11-19 14:55:58 -08004828 { // scope for mLock
4829 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004830
Eric Laurent021cf962014-05-13 10:18:14 -07004831 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004832
Eric Laurent000a4192014-01-29 15:17:32 -08004833 // check exitPending here because checkForNewParameters_l() and
4834 // checkForNewParameters_l() can temporarily release mLock
4835 if (exitPending()) {
4836 break;
4837 }
4838
Glenn Kasten2b806402013-11-20 16:37:38 -08004839 // if no active track(s), then standby and release wakelock
4840 size_t size = mActiveTracks.size();
4841 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004842 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004843 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004844 releaseWakeLock_l();
4845 ALOGV("RecordThread: loop stopping");
4846 // go to sleep
4847 mWaitWorkCV.wait(mLock);
4848 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004849 goto reacquire_wakelock;
4850 }
4851
Glenn Kasten2b806402013-11-20 16:37:38 -08004852 if (mActiveTracksGen != activeTracksGen) {
4853 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004854 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004855 for (size_t i = 0; i < size; i++) {
4856 tmp.add(mActiveTracks[i]->uid());
4857 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004858 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004859 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004860
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004861 bool doBroadcast = false;
4862 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004863
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004864 activeTrack = mActiveTracks[i];
4865 if (activeTrack->isTerminated()) {
4866 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004867 mActiveTracks.remove(activeTrack);
4868 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004869 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004870 continue;
4871 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004872
4873 TrackBase::track_state activeTrackState = activeTrack->mState;
4874 switch (activeTrackState) {
4875
4876 case TrackBase::PAUSING:
4877 mActiveTracks.remove(activeTrack);
4878 mActiveTracksGen++;
4879 doBroadcast = true;
4880 size--;
4881 continue;
4882
4883 case TrackBase::STARTING_1:
4884 sleepUs = 10000;
4885 i++;
4886 continue;
4887
4888 case TrackBase::STARTING_2:
4889 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004890 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004891 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004892 break;
4893
4894 case TrackBase::ACTIVE:
4895 break;
4896
4897 case TrackBase::IDLE:
4898 i++;
4899 continue;
4900
4901 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004902 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004903 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004904
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004905 activeTracks.add(activeTrack);
4906 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004907
Glenn Kasten9e982352013-08-14 14:39:50 -07004908 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004909 if (doBroadcast) {
4910 mStartStopCond.broadcast();
4911 }
4912
4913 // sleep if there are no active tracks to process
4914 if (activeTracks.size() == 0) {
4915 if (sleepUs == 0) {
4916 sleepUs = kRecordThreadSleepUs;
4917 }
4918 continue;
4919 }
4920 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004921
Eric Laurent81784c32012-11-19 14:55:58 -08004922 lockEffectChains_l(effectChains);
4923 }
4924
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004925 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004926
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004927 size_t size = effectChains.size();
4928 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004929 // thread mutex is not locked, but effect chain is locked
4930 effectChains[i]->process_l();
4931 }
4932
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004933 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4934 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4935 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4936 // If destination is non-contiguous, first read past the nominal end of buffer, then
4937 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004938
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004939 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4940 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4941 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4942 if (bytesRead <= 0) {
4943 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4944 // Force input into standby so that it tries to recover at next read attempt
4945 inputStandBy();
4946 sleepUs = kRecordThreadSleepUs;
4947 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004948 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004949 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4950 size_t framesRead = bytesRead / mFrameSize;
4951 ALOG_ASSERT(framesRead > 0);
4952 if (mTeeSink != 0) {
4953 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4954 }
4955 // If destination is non-contiguous, we now correct for reading past end of buffer.
4956 size_t part1 = mRsmpInFramesP2 - rear;
4957 if (framesRead > part1) {
4958 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4959 (framesRead - part1) * mFrameSize);
4960 }
4961 rear = mRsmpInRear += framesRead;
4962
4963 size = activeTracks.size();
4964 // loop over each active track
4965 for (size_t i = 0; i < size; i++) {
4966 activeTrack = activeTracks[i];
4967
4968 enum {
4969 OVERRUN_UNKNOWN,
4970 OVERRUN_TRUE,
4971 OVERRUN_FALSE
4972 } overrun = OVERRUN_UNKNOWN;
4973
4974 // loop over getNextBuffer to handle circular sink
4975 for (;;) {
4976
4977 activeTrack->mSink.frameCount = ~0;
4978 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4979 size_t framesOut = activeTrack->mSink.frameCount;
4980 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4981
4982 int32_t front = activeTrack->mRsmpInFront;
4983 ssize_t filled = rear - front;
4984 size_t framesIn;
4985
4986 if (filled < 0) {
4987 // should not happen, but treat like a massive overrun and re-sync
4988 framesIn = 0;
4989 activeTrack->mRsmpInFront = rear;
4990 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004991 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004992 framesIn = (size_t) filled;
4993 } else {
4994 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004995 framesIn = mRsmpInFrames;
4996 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004997 overrun = OVERRUN_TRUE;
4998 }
4999
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005000 if (framesOut == 0 || framesIn == 0) {
5001 break;
5002 }
5003
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005004 if (activeTrack->mResampler == NULL) {
5005 // no resampling
5006 if (framesIn > framesOut) {
5007 framesIn = framesOut;
5008 } else {
5009 framesOut = framesIn;
5010 }
5011 int8_t *dst = activeTrack->mSink.i8;
5012 while (framesIn > 0) {
5013 front &= mRsmpInFramesP2 - 1;
5014 size_t part1 = mRsmpInFramesP2 - front;
5015 if (part1 > framesIn) {
5016 part1 = framesIn;
5017 }
5018 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005019 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005020 memcpy(dst, src, part1 * mFrameSize);
5021 } else if (mChannelCount == 1) {
5022 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
5023 part1);
5024 } else {
5025 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
5026 part1);
5027 }
5028 dst += part1 * activeTrack->mFrameSize;
5029 front += part1;
5030 framesIn -= part1;
5031 }
5032 activeTrack->mRsmpInFront += framesOut;
5033
5034 } else {
5035 // resampling
5036 // FIXME framesInNeeded should really be part of resampler API, and should
5037 // depend on the SRC ratio
5038 // to keep mRsmpInBuffer full so resampler always has sufficient input
5039 size_t framesInNeeded;
5040 // FIXME only re-calculate when it changes, and optimize for common ratios
5041 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
5042 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005043 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005044 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
5045 framesInNeeded, framesOut, inOverOut);
5046 // Although we theoretically have framesIn in circular buffer, some of those are
5047 // unreleased frames, and thus must be discounted for purpose of budgeting.
5048 size_t unreleased = activeTrack->mRsmpInUnrel;
5049 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005050 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005051 ALOGV("not enough to resample: have %u frames in but need %u in to "
5052 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005053 framesIn, framesInNeeded, framesOut, inOverOut);
5054 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005055 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5056 if (newFramesOut == 0) {
5057 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005058 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005059 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5060 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5061 framesInNeeded, newFramesOut, outOverIn);
5062 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5063 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5064 "given in/out ratio of %.4g",
5065 framesIn, framesInNeeded, newFramesOut, inOverOut);
5066 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005067 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005068 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005069 "given in/out ratio of %.4g",
5070 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005071 }
5072
5073 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5074 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005075 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005076 delete[] activeTrack->mRsmpOutBuffer;
5077 // resampler always outputs stereo
5078 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5079 activeTrack->mRsmpOutFrameCount = framesOut;
5080 }
5081
5082 // resampler accumulates, but we only have one source track
5083 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5084 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005085 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005086 activeTrack->mResamplerBufferProvider
5087 /*this*/ /* AudioBufferProvider* */);
5088 // ditherAndClamp() works as long as all buffers returned by
5089 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005090 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005091 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005092 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5093 framesOut);
5094 // the resampler always outputs stereo samples:
5095 // do post stereo to mono conversion
5096 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
5097 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
5098 } else {
5099 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5100 activeTrack->mRsmpOutBuffer, framesOut);
5101 }
5102 // now done with mRsmpOutBuffer
5103
5104 }
5105
5106 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5107 overrun = OVERRUN_FALSE;
5108 }
5109
5110 if (activeTrack->mFramesToDrop == 0) {
5111 if (framesOut > 0) {
5112 activeTrack->mSink.frameCount = framesOut;
5113 activeTrack->releaseBuffer(&activeTrack->mSink);
5114 }
5115 } else {
5116 // FIXME could do a partial drop of framesOut
5117 if (activeTrack->mFramesToDrop > 0) {
5118 activeTrack->mFramesToDrop -= framesOut;
5119 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005120 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005121 }
5122 } else {
5123 activeTrack->mFramesToDrop += framesOut;
5124 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5125 activeTrack->mSyncStartEvent->isCancelled()) {
5126 ALOGW("Synced record %s, session %d, trigger session %d",
5127 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5128 activeTrack->sessionId(),
5129 (activeTrack->mSyncStartEvent != 0) ?
5130 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005131 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005132 }
5133 }
5134 }
5135
5136 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005137 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005138 }
5139 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005140
5141 switch (overrun) {
5142 case OVERRUN_TRUE:
5143 // client isn't retrieving buffers fast enough
5144 if (!activeTrack->setOverflow()) {
5145 nsecs_t now = systemTime();
5146 // FIXME should lastWarning per track?
5147 if ((now - lastWarning) > kWarningThrottleNs) {
5148 ALOGW("RecordThread: buffer overflow");
5149 lastWarning = now;
5150 }
5151 }
5152 break;
5153 case OVERRUN_FALSE:
5154 activeTrack->clearOverflow();
5155 break;
5156 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005157 break;
5158 }
5159
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005160 }
5161
Eric Laurent81784c32012-11-19 14:55:58 -08005162 // enable changes in effect chain
5163 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005164 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005165 }
5166
Glenn Kasten93e471f2013-08-19 08:40:07 -07005167 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005168
5169 {
5170 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005171 for (size_t i = 0; i < mTracks.size(); i++) {
5172 sp<RecordTrack> track = mTracks[i];
5173 track->invalidate();
5174 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005175 mActiveTracks.clear();
5176 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005177 mStartStopCond.broadcast();
5178 }
5179
5180 releaseWakeLock();
5181
5182 ALOGV("RecordThread %p exiting", this);
5183 return false;
5184}
5185
Glenn Kasten93e471f2013-08-19 08:40:07 -07005186void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005187{
5188 if (!mStandby) {
5189 inputStandBy();
5190 mStandby = true;
5191 }
5192}
5193
5194void AudioFlinger::RecordThread::inputStandBy()
5195{
5196 mInput->stream->common.standby(&mInput->stream->common);
5197}
5198
Glenn Kasten05997e22014-03-13 15:08:33 -07005199// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005200sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005201 const sp<AudioFlinger::Client>& client,
5202 uint32_t sampleRate,
5203 audio_format_t format,
5204 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005205 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005206 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005207 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005208 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005209 pid_t tid,
5210 status_t *status)
5211{
Glenn Kasten74935e42013-12-19 08:56:45 -08005212 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005213 sp<RecordTrack> track;
5214 status_t lStatus;
5215
Glenn Kasten90e58b12013-07-31 16:16:02 -07005216 // client expresses a preference for FAST, but we get the final say
5217 if (*flags & IAudioFlinger::TRACK_FAST) {
5218 if (
5219 // use case: callback handler and frame count is default or at least as large as HAL
5220 (
5221 (tid != -1) &&
5222 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005223 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005224 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005225 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005226 // PCM data
5227 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005228 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005229 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5230 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005231 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005232 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005233 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005234 // record thread has an associated fast capture
5235 hasFastCapture()
5236 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005237 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005238 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005239 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005240 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005241 frameCount = mFrameCount * kFastTrackMultiplier;
5242 }
5243 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5244 frameCount, mFrameCount);
5245 } else {
5246 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5247 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005248 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005249 frameCount, mFrameCount, format,
5250 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005251 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005252 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005253 // FIXME It's not clear that we need to enforce this any more, since we have a pipe.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005254 // For compatibility with AudioRecord calculation, buffer depth is forced
5255 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5256 // This is probably too conservative, but legacy application code may depend on it.
5257 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005258 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005259 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5260 size_t mNormalFrameCount = 2048; // FIXME
5261 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5262 if (minBufCount < 2) {
5263 minBufCount = 2;
5264 }
5265 size_t minFrameCount = mNormalFrameCount * minBufCount;
5266 if (frameCount < minFrameCount) {
5267 frameCount = minFrameCount;
5268 }
5269 }
5270 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005271 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005272
Glenn Kasten15e57982013-09-24 11:52:37 -07005273 lStatus = initCheck();
5274 if (lStatus != NO_ERROR) {
5275 ALOGE("createRecordTrack_l() audio driver not initialized");
5276 goto Exit;
5277 }
Eric Laurent81784c32012-11-19 14:55:58 -08005278
5279 { // scope for mLock
5280 Mutex::Autolock _l(mLock);
5281
5282 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005283 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005284 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005285
Glenn Kasten03003332013-08-06 15:40:54 -07005286 lStatus = track->initCheck();
5287 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005288 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005289 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005290 goto Exit;
5291 }
5292 mTracks.add(track);
5293
5294 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5295 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5296 mAudioFlinger->btNrecIsOff();
5297 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5298 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005299
5300 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5301 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5302 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5303 // so ask activity manager to do this on our behalf
5304 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5305 }
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005307
Eric Laurent81784c32012-11-19 14:55:58 -08005308 lStatus = NO_ERROR;
5309
5310Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005311 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005312 return track;
5313}
5314
5315status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5316 AudioSystem::sync_event_t event,
5317 int triggerSession)
5318{
5319 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5320 sp<ThreadBase> strongMe = this;
5321 status_t status = NO_ERROR;
5322
5323 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005324 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005325 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005326 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005327 triggerSession,
5328 recordTrack->sessionId(),
5329 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005330 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // Sync event can be cancelled by the trigger session if the track is not in a
5332 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005333 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005334 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005335 } else {
5336 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005337 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005338 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005339 }
5340 }
5341
5342 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005343 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005344 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005345 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5346 if (recordTrack->mState == TrackBase::PAUSING) {
5347 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005348 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 } else {
5350 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005351 }
5352 return status;
5353 }
5354
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005355 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5356 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5357 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005358 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005359 mActiveTracks.add(recordTrack);
5360 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005361 mLock.unlock();
5362 status_t status = AudioSystem::startInput(mId);
5363 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005364 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005365 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005366 mActiveTracks.remove(recordTrack);
5367 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005368 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005369 return status;
5370 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005371 // Catch up with current buffer indices if thread is already running.
5372 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5373 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5374 // see previously buffered data before it called start(), but with greater risk of overrun.
5375
5376 recordTrack->mRsmpInFront = mRsmpInRear;
5377 recordTrack->mRsmpInUnrel = 0;
5378 // FIXME why reset?
5379 if (recordTrack->mResampler != NULL) {
5380 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005382 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005383 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005384 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005385 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005386 ALOGV("Record failed to start");
5387 status = BAD_VALUE;
5388 goto startError;
5389 }
Eric Laurent81784c32012-11-19 14:55:58 -08005390 return status;
5391 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005392
Eric Laurent81784c32012-11-19 14:55:58 -08005393startError:
5394 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005395 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005396 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005397 return status;
5398}
5399
Eric Laurent81784c32012-11-19 14:55:58 -08005400void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5401{
5402 sp<SyncEvent> strongEvent = event.promote();
5403
5404 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005405 sp<RefBase> ptr = strongEvent->cookie().promote();
5406 if (ptr != 0) {
5407 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5408 recordTrack->handleSyncStartEvent(strongEvent);
5409 }
Eric Laurent81784c32012-11-19 14:55:58 -08005410 }
5411}
5412
Glenn Kastena8356f62013-07-25 14:37:52 -07005413bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005414 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005415 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005416 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005417 return false;
5418 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005419 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005420 recordTrack->mState = TrackBase::PAUSING;
5421 // do not wait for mStartStopCond if exiting
5422 if (exitPending()) {
5423 return true;
5424 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005425 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005426 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005427 // if we have been restarted, recordTrack is in mActiveTracks here
5428 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005429 ALOGV("Record stopped OK");
5430 return true;
5431 }
5432 return false;
5433}
5434
Glenn Kasten0f11b512014-01-31 16:18:54 -08005435bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005436{
5437 return false;
5438}
5439
Glenn Kasten0f11b512014-01-31 16:18:54 -08005440status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005441{
5442#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5443 if (!isValidSyncEvent(event)) {
5444 return BAD_VALUE;
5445 }
5446
5447 int eventSession = event->triggerSession();
5448 status_t ret = NAME_NOT_FOUND;
5449
5450 Mutex::Autolock _l(mLock);
5451
5452 for (size_t i = 0; i < mTracks.size(); i++) {
5453 sp<RecordTrack> track = mTracks[i];
5454 if (eventSession == track->sessionId()) {
5455 (void) track->setSyncEvent(event);
5456 ret = NO_ERROR;
5457 }
5458 }
5459 return ret;
5460#else
5461 return BAD_VALUE;
5462#endif
5463}
5464
5465// destroyTrack_l() must be called with ThreadBase::mLock held
5466void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5467{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 track->terminate();
5469 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005470 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005471 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005472 removeTrack_l(track);
5473 }
5474}
5475
5476void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5477{
5478 mTracks.remove(track);
5479 // need anything related to effects here?
5480}
5481
5482void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5483{
5484 dumpInternals(fd, args);
5485 dumpTracks(fd, args);
5486 dumpEffectChains(fd, args);
5487}
5488
5489void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5490{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005491 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005492
Glenn Kasten2b806402013-11-20 16:37:38 -08005493 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005494 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005495 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005496 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005497 }
5498
Eric Laurent81784c32012-11-19 14:55:58 -08005499 dumpBase(fd, args);
5500}
5501
Glenn Kasten0f11b512014-01-31 16:18:54 -08005502void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005503{
5504 const size_t SIZE = 256;
5505 char buffer[SIZE];
5506 String8 result;
5507
Marco Nelissenb2208842014-02-07 14:00:50 -08005508 size_t numtracks = mTracks.size();
5509 size_t numactive = mActiveTracks.size();
5510 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005511 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005512 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005513 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005514 RecordTrack::appendDumpHeader(result);
5515 for (size_t i = 0; i < numtracks ; ++i) {
5516 sp<RecordTrack> track = mTracks[i];
5517 if (track != 0) {
5518 bool active = mActiveTracks.indexOf(track) >= 0;
5519 if (active) {
5520 numactiveseen++;
5521 }
5522 track->dump(buffer, SIZE, active);
5523 result.append(buffer);
5524 }
Eric Laurent81784c32012-11-19 14:55:58 -08005525 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005526 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005527 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005528 }
5529
Marco Nelissenb2208842014-02-07 14:00:50 -08005530 if (numactiveseen != numactive) {
5531 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5532 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005533 result.append(buffer);
5534 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005535 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005536 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005537 if (mTracks.indexOf(track) < 0) {
5538 track->dump(buffer, SIZE, true);
5539 result.append(buffer);
5540 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005541 }
Eric Laurent81784c32012-11-19 14:55:58 -08005542
5543 }
5544 write(fd, result.string(), result.size());
5545}
5546
5547// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005548status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5549 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005550{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005551 RecordTrack *activeTrack = mRecordTrack;
5552 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5553 if (threadBase == 0) {
5554 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005555 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005556 return NOT_ENOUGH_DATA;
5557 }
5558 RecordThread *recordThread = (RecordThread *) threadBase.get();
5559 int32_t rear = recordThread->mRsmpInRear;
5560 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005561 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005562 // FIXME should not be P2 (don't want to increase latency)
5563 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005564 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005565 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005566 front &= recordThread->mRsmpInFramesP2 - 1;
5567 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005568 if (part1 > (size_t) filled) {
5569 part1 = filled;
5570 }
5571 size_t ask = buffer->frameCount;
5572 ALOG_ASSERT(ask > 0);
5573 if (part1 > ask) {
5574 part1 = ask;
5575 }
5576 if (part1 == 0) {
5577 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005578 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005579 buffer->raw = NULL;
5580 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005581 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005582 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005583 }
5584
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005585 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005586 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005587 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 return NO_ERROR;
5589}
5590
5591// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005592void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5593 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005594{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005595 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005596 size_t stepCount = buffer->frameCount;
5597 if (stepCount == 0) {
5598 return;
5599 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005600 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5601 activeTrack->mRsmpInUnrel -= stepCount;
5602 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005603 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 buffer->frameCount = 0;
5605}
5606
Eric Laurent10351942014-05-08 18:49:52 -07005607bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5608 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005609{
5610 bool reconfig = false;
5611
Eric Laurent10351942014-05-08 18:49:52 -07005612 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005613
Eric Laurent10351942014-05-08 18:49:52 -07005614 audio_format_t reqFormat = mFormat;
5615 uint32_t samplingRate = mSampleRate;
5616 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5617
5618 AudioParameter param = AudioParameter(keyValuePair);
5619 int value;
5620 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5621 // channel count change can be requested. Do we mandate the first client defines the
5622 // HAL sampling rate and channel count or do we allow changes on the fly?
5623 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5624 samplingRate = value;
5625 reconfig = true;
5626 }
5627 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5628 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5629 status = BAD_VALUE;
5630 } else {
5631 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005632 reconfig = true;
5633 }
Eric Laurent10351942014-05-08 18:49:52 -07005634 }
5635 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5636 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5637 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5638 status = BAD_VALUE;
5639 } else {
5640 channelMask = mask;
5641 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005642 }
Eric Laurent10351942014-05-08 18:49:52 -07005643 }
5644 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5645 // do not accept frame count changes if tracks are open as the track buffer
5646 // size depends on frame count and correct behavior would not be guaranteed
5647 // if frame count is changed after track creation
5648 if (mActiveTracks.size() > 0) {
5649 status = INVALID_OPERATION;
5650 } else {
5651 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005652 }
Eric Laurent10351942014-05-08 18:49:52 -07005653 }
5654 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5655 // forward device change to effects that have requested to be
5656 // aware of attached audio device.
5657 for (size_t i = 0; i < mEffectChains.size(); i++) {
5658 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005659 }
Eric Laurent81784c32012-11-19 14:55:58 -08005660
Eric Laurent10351942014-05-08 18:49:52 -07005661 // store input device and output device but do not forward output device to audio HAL.
5662 // Note that status is ignored by the caller for output device
5663 // (see AudioFlinger::setParameters()
5664 if (audio_is_output_devices(value)) {
5665 mOutDevice = value;
5666 status = BAD_VALUE;
5667 } else {
5668 mInDevice = value;
5669 // disable AEC and NS if the device is a BT SCO headset supporting those
5670 // pre processings
5671 if (mTracks.size() > 0) {
5672 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5673 mAudioFlinger->btNrecIsOff();
5674 for (size_t i = 0; i < mTracks.size(); i++) {
5675 sp<RecordTrack> track = mTracks[i];
5676 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5677 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005678 }
5679 }
5680 }
Eric Laurent10351942014-05-08 18:49:52 -07005681 }
5682 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5683 mAudioSource != (audio_source_t)value) {
5684 // forward device change to effects that have requested to be
5685 // aware of attached audio device.
5686 for (size_t i = 0; i < mEffectChains.size(); i++) {
5687 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005688 }
Eric Laurent10351942014-05-08 18:49:52 -07005689 mAudioSource = (audio_source_t)value;
5690 }
Glenn Kastene198c362013-08-13 09:13:36 -07005691
Eric Laurent10351942014-05-08 18:49:52 -07005692 if (status == NO_ERROR) {
5693 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5694 keyValuePair.string());
5695 if (status == INVALID_OPERATION) {
5696 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005697 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5698 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005699 }
5700 if (reconfig) {
5701 if (status == BAD_VALUE &&
5702 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5703 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5704 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5705 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005706 audio_channel_count_from_in_mask(
5707 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005708 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5709 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5710 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
Eric Laurent10351942014-05-08 18:49:52 -07005712 if (status == NO_ERROR) {
5713 readInputParameters_l();
5714 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
Eric Laurent10351942014-05-08 18:49:52 -07005718
Eric Laurent81784c32012-11-19 14:55:58 -08005719 return reconfig;
5720}
5721
5722String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5723{
Eric Laurent81784c32012-11-19 14:55:58 -08005724 Mutex::Autolock _l(mLock);
5725 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005726 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005727 }
5728
Glenn Kastend8ea6992013-07-16 14:17:15 -07005729 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5730 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005731 free(s);
5732 return out_s8;
5733}
5734
Eric Laurent021cf962014-05-13 10:18:14 -07005735void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005736 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005737 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005738
5739 switch (event) {
5740 case AudioSystem::INPUT_OPENED:
5741 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005742 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005743 desc.samplingRate = mSampleRate;
5744 desc.format = mFormat;
5745 desc.frameCount = mFrameCount;
5746 desc.latency = 0;
5747 param2 = &desc;
5748 break;
5749
5750 case AudioSystem::INPUT_CLOSED:
5751 default:
5752 break;
5753 }
Eric Laurent021cf962014-05-13 10:18:14 -07005754 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005755}
5756
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005757void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005758{
Eric Laurent81784c32012-11-19 14:55:58 -08005759 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5760 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005761 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005762 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005763 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005764 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005767 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5768 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005769 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005770 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07005771 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005772 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005773 // A larger value should allow more old data to be read after a track calls start(),
5774 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005775 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005776 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005777 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005778 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5779 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005780
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005781 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5782 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005783}
5784
Glenn Kasten5f972c02014-01-13 09:59:31 -08005785uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005786{
5787 Mutex::Autolock _l(mLock);
5788 if (initCheck() != NO_ERROR) {
5789 return 0;
5790 }
5791
5792 return mInput->stream->get_input_frames_lost(mInput->stream);
5793}
5794
5795uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5796{
5797 Mutex::Autolock _l(mLock);
5798 uint32_t result = 0;
5799 if (getEffectChain_l(sessionId) != 0) {
5800 result = EFFECT_SESSION;
5801 }
5802
5803 for (size_t i = 0; i < mTracks.size(); ++i) {
5804 if (sessionId == mTracks[i]->sessionId()) {
5805 result |= TRACK_SESSION;
5806 break;
5807 }
5808 }
5809
5810 return result;
5811}
5812
5813KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5814{
5815 KeyedVector<int, bool> ids;
5816 Mutex::Autolock _l(mLock);
5817 for (size_t j = 0; j < mTracks.size(); ++j) {
5818 sp<RecordThread::RecordTrack> track = mTracks[j];
5819 int sessionId = track->sessionId();
5820 if (ids.indexOfKey(sessionId) < 0) {
5821 ids.add(sessionId, true);
5822 }
5823 }
5824 return ids;
5825}
5826
5827AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5828{
5829 Mutex::Autolock _l(mLock);
5830 AudioStreamIn *input = mInput;
5831 mInput = NULL;
5832 return input;
5833}
5834
5835// this method must always be called either with ThreadBase mLock held or inside the thread loop
5836audio_stream_t* AudioFlinger::RecordThread::stream() const
5837{
5838 if (mInput == NULL) {
5839 return NULL;
5840 }
5841 return &mInput->stream->common;
5842}
5843
5844status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5845{
5846 // only one chain per input thread
5847 if (mEffectChains.size() != 0) {
5848 return INVALID_OPERATION;
5849 }
5850 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5851
5852 chain->setInBuffer(NULL);
5853 chain->setOutBuffer(NULL);
5854
5855 checkSuspendOnAddEffectChain_l(chain);
5856
5857 mEffectChains.add(chain);
5858
5859 return NO_ERROR;
5860}
5861
5862size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5863{
5864 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5865 ALOGW_IF(mEffectChains.size() != 1,
5866 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5867 chain.get(), mEffectChains.size(), this);
5868 if (mEffectChains.size() == 1) {
5869 mEffectChains.removeAt(0);
5870 }
5871 return 0;
5872}
5873
Eric Laurent1c333e22014-05-20 10:48:17 -07005874status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
5875 audio_patch_handle_t *handle)
5876{
5877 status_t status = NO_ERROR;
5878 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5879 // store new device and send to effects
5880 mInDevice = patch->sources[0].ext.device.type;
5881 for (size_t i = 0; i < mEffectChains.size(); i++) {
5882 mEffectChains[i]->setDevice_l(mInDevice);
5883 }
5884
5885 // disable AEC and NS if the device is a BT SCO headset supporting those
5886 // pre processings
5887 if (mTracks.size() > 0) {
5888 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5889 mAudioFlinger->btNrecIsOff();
5890 for (size_t i = 0; i < mTracks.size(); i++) {
5891 sp<RecordTrack> track = mTracks[i];
5892 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5893 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5894 }
5895 }
5896
5897 // store new source and send to effects
5898 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
5899 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
5900 for (size_t i = 0; i < mEffectChains.size(); i++) {
5901 mEffectChains[i]->setAudioSource_l(mAudioSource);
5902 }
5903 }
5904
5905 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5906 status = hwDevice->create_audio_patch(hwDevice,
5907 patch->num_sources,
5908 patch->sources,
5909 patch->num_sinks,
5910 patch->sinks,
5911 handle);
5912 } else {
5913 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
5914 }
5915 return status;
5916}
5917
5918status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
5919{
5920 status_t status = NO_ERROR;
5921 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5922 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5923 status = hwDevice->release_audio_patch(hwDevice, handle);
5924 } else {
5925 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
5926 }
5927 return status;
5928}
5929
5930
Eric Laurent81784c32012-11-19 14:55:58 -08005931}; // namespace android