blob: 7a2a773a53682749a46f811c5d2f71aaf0dc0084 [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
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070041#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042#include <media/nbaio/AudioStreamOutSink.h>
43#include <media/nbaio/MonoPipe.h>
44#include <media/nbaio/MonoPipeReader.h>
45#include <media/nbaio/Pipe.h>
46#include <media/nbaio/PipeReader.h>
47#include <media/nbaio/SourceAudioBufferProvider.h>
48
49#include <powermanager/PowerManager.h>
50
51#include <common_time/cc_helper.h>
52#include <common_time/local_clock.h>
53
54#include "AudioFlinger.h"
55#include "AudioMixer.h"
56#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070057#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "ServiceUtilities.h"
59#include "SchedulingPolicyService.h"
60
Eric Laurent81784c32012-11-19 14:55:58 -080061#ifdef ADD_BATTERY_DATA
62#include <media/IMediaPlayerService.h>
63#include <media/IMediaDeathNotifier.h>
64#endif
65
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef DEBUG_CPU_USAGE
67#include <cpustats/CentralTendencyStatistics.h>
68#include <cpustats/ThreadCpuUsage.h>
69#endif
70
71// ----------------------------------------------------------------------------
72
73// Note: the following macro is used for extremely verbose logging message. In
74// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
75// 0; but one side effect of this is to turn all LOGV's as well. Some messages
76// are so verbose that we want to suppress them even when we have ALOG_ASSERT
77// turned on. Do not uncomment the #def below unless you really know what you
78// are doing and want to see all of the extremely verbose messages.
79//#define VERY_VERY_VERBOSE_LOGGING
80#ifdef VERY_VERY_VERBOSE_LOGGING
81#define ALOGVV ALOGV
82#else
83#define ALOGVV(a...) do { } while(0)
84#endif
85
86namespace android {
87
88// retry counts for buffer fill timeout
89// 50 * ~20msecs = 1 second
90static const int8_t kMaxTrackRetries = 50;
91static const int8_t kMaxTrackStartupRetries = 50;
92// allow less retry attempts on direct output thread.
93// direct outputs can be a scarce resource in audio hardware and should
94// be released as quickly as possible.
95static const int8_t kMaxTrackRetriesDirect = 2;
96
97// don't warn about blocked writes or record buffer overflows more often than this
98static const nsecs_t kWarningThrottleNs = seconds(5);
99
100// RecordThread loop sleep time upon application overrun or audio HAL read error
101static const int kRecordThreadSleepUs = 5000;
102
Eric Laurent10351942014-05-08 18:49:52 -0700103// maximum time to wait in sendConfigEvent_l() for a status to be received
104static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800105
106// minimum sleep time for the mixer thread loop when tracks are active but in underrun
107static const uint32_t kMinThreadSleepTimeUs = 5000;
108// maximum divider applied to the active sleep time in the mixer thread loop
109static const uint32_t kMaxThreadSleepTimeShift = 2;
110
Andy Hung09a50072014-02-27 14:30:47 -0800111// minimum normal sink buffer size, expressed in milliseconds rather than frames
112static const uint32_t kMinNormalSinkBufferSizeMs = 20;
113// maximum normal sink buffer size
114static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800115
Eric Laurent972a1732013-09-04 09:42:59 -0700116// Offloaded output thread standby delay: allows track transition without going to standby
117static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
118
Eric Laurent81784c32012-11-19 14:55:58 -0800119// Whether to use fast mixer
120static const enum {
121 FastMixer_Never, // never initialize or use: for debugging only
122 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
123 // normal mixer multiplier is 1
124 FastMixer_Static, // initialize if needed, then use all the time if initialized,
125 // multiplier is calculated based on min & max normal mixer buffer size
126 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
127 // multiplier is calculated based on min & max normal mixer buffer size
128 // FIXME for FastMixer_Dynamic:
129 // Supporting this option will require fixing HALs that can't handle large writes.
130 // For example, one HAL implementation returns an error from a large write,
131 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
132 // We could either fix the HAL implementations, or provide a wrapper that breaks
133 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
134} kUseFastMixer = FastMixer_Static;
135
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700136// Whether to use fast capture
137static const enum {
138 FastCapture_Never, // never initialize or use: for debugging only
139 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
140 FastCapture_Static, // initialize if needed, then use all the time if initialized
141} kUseFastCapture = FastCapture_Static;
142
Eric Laurent81784c32012-11-19 14:55:58 -0800143// Priorities for requestPriority
144static const int kPriorityAudioApp = 2;
145static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700146static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800147
148// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
149// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800150// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
151// So for now we just assume that client is double-buffered for fast tracks.
152// FIXME It would be better for client to tell AudioFlinger the value of N,
153// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800154// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700155
156// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800157static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800158
Glenn Kasten03490092014-05-27 12:30:54 -0700159// The minimum and maximum allowed values
160static const int kFastTrackMultiplierMin = 1;
161static const int kFastTrackMultiplierMax = 2;
162
163// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
164static int sFastTrackMultiplier = kFastTrackMultiplier;
165
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700166// See Thread::readOnlyHeap().
167// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
168// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
169// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
170static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
171
Eric Laurent81784c32012-11-19 14:55:58 -0800172// ----------------------------------------------------------------------------
173
Glenn Kasten03490092014-05-27 12:30:54 -0700174static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
175
176static void sFastTrackMultiplierInit()
177{
178 char value[PROPERTY_VALUE_MAX];
179 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
180 char *endptr;
181 unsigned long ul = strtoul(value, &endptr, 0);
182 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
183 sFastTrackMultiplier = (int) ul;
184 }
185 }
186}
187
188// ----------------------------------------------------------------------------
189
Eric Laurent81784c32012-11-19 14:55:58 -0800190#ifdef ADD_BATTERY_DATA
191// To collect the amplifier usage
192static void addBatteryData(uint32_t params) {
193 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
194 if (service == NULL) {
195 // it already logged
196 return;
197 }
198
199 service->addBatteryData(params);
200}
201#endif
202
203
204// ----------------------------------------------------------------------------
205// CPU Stats
206// ----------------------------------------------------------------------------
207
208class CpuStats {
209public:
210 CpuStats();
211 void sample(const String8 &title);
212#ifdef DEBUG_CPU_USAGE
213private:
214 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
215 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
216
217 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
218
219 int mCpuNum; // thread's current CPU number
220 int mCpukHz; // frequency of thread's current CPU in kHz
221#endif
222};
223
224CpuStats::CpuStats()
225#ifdef DEBUG_CPU_USAGE
226 : mCpuNum(-1), mCpukHz(-1)
227#endif
228{
229}
230
Glenn Kasten0f11b512014-01-31 16:18:54 -0800231void CpuStats::sample(const String8 &title
232#ifndef DEBUG_CPU_USAGE
233 __unused
234#endif
235 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800236#ifdef DEBUG_CPU_USAGE
237 // get current thread's delta CPU time in wall clock ns
238 double wcNs;
239 bool valid = mCpuUsage.sampleAndEnable(wcNs);
240
241 // record sample for wall clock statistics
242 if (valid) {
243 mWcStats.sample(wcNs);
244 }
245
246 // get the current CPU number
247 int cpuNum = sched_getcpu();
248
249 // get the current CPU frequency in kHz
250 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
251
252 // check if either CPU number or frequency changed
253 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
254 mCpuNum = cpuNum;
255 mCpukHz = cpukHz;
256 // ignore sample for purposes of cycles
257 valid = false;
258 }
259
260 // if no change in CPU number or frequency, then record sample for cycle statistics
261 if (valid && mCpukHz > 0) {
262 double cycles = wcNs * cpukHz * 0.000001;
263 mHzStats.sample(cycles);
264 }
265
266 unsigned n = mWcStats.n();
267 // mCpuUsage.elapsed() is expensive, so don't call it every loop
268 if ((n & 127) == 1) {
269 long long elapsed = mCpuUsage.elapsed();
270 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
271 double perLoop = elapsed / (double) n;
272 double perLoop100 = perLoop * 0.01;
273 double perLoop1k = perLoop * 0.001;
274 double mean = mWcStats.mean();
275 double stddev = mWcStats.stddev();
276 double minimum = mWcStats.minimum();
277 double maximum = mWcStats.maximum();
278 double meanCycles = mHzStats.mean();
279 double stddevCycles = mHzStats.stddev();
280 double minCycles = mHzStats.minimum();
281 double maxCycles = mHzStats.maximum();
282 mCpuUsage.resetElapsed();
283 mWcStats.reset();
284 mHzStats.reset();
285 ALOGD("CPU usage for %s over past %.1f secs\n"
286 " (%u mixer loops at %.1f mean ms per loop):\n"
287 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
288 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
289 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
290 title.string(),
291 elapsed * .000000001, n, perLoop * .000001,
292 mean * .001,
293 stddev * .001,
294 minimum * .001,
295 maximum * .001,
296 mean / perLoop100,
297 stddev / perLoop100,
298 minimum / perLoop100,
299 maximum / perLoop100,
300 meanCycles / perLoop1k,
301 stddevCycles / perLoop1k,
302 minCycles / perLoop1k,
303 maxCycles / perLoop1k);
304
305 }
306 }
307#endif
308};
309
310// ----------------------------------------------------------------------------
311// ThreadBase
312// ----------------------------------------------------------------------------
313
314AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
315 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
316 : Thread(false /*canCallJava*/),
317 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700318 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700319 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800320 // are set by PlaybackThread::readOutputParameters_l() or
321 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700322 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800323 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
324 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
325 // mName will be set by concrete (non-virtual) subclass
326 mDeathRecipient(new PMDeathRecipient(this))
327{
328}
329
330AudioFlinger::ThreadBase::~ThreadBase()
331{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700332 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700333 mConfigEvents.clear();
334
Eric Laurent81784c32012-11-19 14:55:58 -0800335 // do not lock the mutex in destructor
336 releaseWakeLock_l();
337 if (mPowerManager != 0) {
338 sp<IBinder> binder = mPowerManager->asBinder();
339 binder->unlinkToDeath(mDeathRecipient);
340 }
341}
342
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700343status_t AudioFlinger::ThreadBase::readyToRun()
344{
345 status_t status = initCheck();
346 if (status == NO_ERROR) {
347 ALOGI("AudioFlinger's thread %p ready to run", this);
348 } else {
349 ALOGE("No working audio driver found.");
350 }
351 return status;
352}
353
Eric Laurent81784c32012-11-19 14:55:58 -0800354void AudioFlinger::ThreadBase::exit()
355{
356 ALOGV("ThreadBase::exit");
357 // do any cleanup required for exit to succeed
358 preExit();
359 {
360 // This lock prevents the following race in thread (uniprocessor for illustration):
361 // if (!exitPending()) {
362 // // context switch from here to exit()
363 // // exit() calls requestExit(), what exitPending() observes
364 // // exit() calls signal(), which is dropped since no waiters
365 // // context switch back from exit() to here
366 // mWaitWorkCV.wait(...);
367 // // now thread is hung
368 // }
369 AutoMutex lock(mLock);
370 requestExit();
371 mWaitWorkCV.broadcast();
372 }
373 // When Thread::requestExitAndWait is made virtual and this method is renamed to
374 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
375 requestExitAndWait();
376}
377
378status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
379{
380 status_t status;
381
382 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
383 Mutex::Autolock _l(mLock);
384
Eric Laurent10351942014-05-08 18:49:52 -0700385 return sendSetParameterConfigEvent_l(keyValuePairs);
386}
387
388// sendConfigEvent_l() must be called with ThreadBase::mLock held
389// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
390status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
391{
392 status_t status = NO_ERROR;
393
394 mConfigEvents.add(event);
395 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800396 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700397 mLock.unlock();
398 {
399 Mutex::Autolock _l(event->mLock);
400 while (event->mWaitStatus) {
401 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
402 event->mStatus = TIMED_OUT;
403 event->mWaitStatus = false;
404 }
405 }
406 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800407 }
Eric Laurent10351942014-05-08 18:49:52 -0700408 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800409 return status;
410}
411
412void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
413{
414 Mutex::Autolock _l(mLock);
415 sendIoConfigEvent_l(event, param);
416}
417
418// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
419void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
420{
Eric Laurent10351942014-05-08 18:49:52 -0700421 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
422 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800423}
424
425// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
426void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
427{
Eric Laurent10351942014-05-08 18:49:52 -0700428 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
429 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800430}
431
Eric Laurent10351942014-05-08 18:49:52 -0700432// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
433status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800434{
Eric Laurent10351942014-05-08 18:49:52 -0700435 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
436 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700437}
438
Eric Laurent1c333e22014-05-20 10:48:17 -0700439status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
440 const struct audio_patch *patch,
441 audio_patch_handle_t *handle)
442{
443 Mutex::Autolock _l(mLock);
444 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
445 status_t status = sendConfigEvent_l(configEvent);
446 if (status == NO_ERROR) {
447 CreateAudioPatchConfigEventData *data =
448 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
449 *handle = data->mHandle;
450 }
451 return status;
452}
453
454status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
455 const audio_patch_handle_t handle)
456{
457 Mutex::Autolock _l(mLock);
458 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
459 return sendConfigEvent_l(configEvent);
460}
461
462
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700463// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700464void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700465{
Eric Laurent10351942014-05-08 18:49:52 -0700466 bool configChanged = false;
467
Eric Laurent81784c32012-11-19 14:55:58 -0800468 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700469 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
470 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800471 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700472 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700473 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700474 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
475 // FIXME Need to understand why this has to be done asynchronously
476 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700477 true /*asynchronous*/);
478 if (err != 0) {
479 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700480 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700481 }
482 } break;
483 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700484 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700485 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700486 } break;
487 case CFG_EVENT_SET_PARAMETER: {
488 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
489 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
490 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700491 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700492 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700493 case CFG_EVENT_CREATE_AUDIO_PATCH: {
494 CreateAudioPatchConfigEventData *data =
495 (CreateAudioPatchConfigEventData *)event->mData.get();
496 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
497 } break;
498 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
499 ReleaseAudioPatchConfigEventData *data =
500 (ReleaseAudioPatchConfigEventData *)event->mData.get();
501 event->mStatus = releaseAudioPatch_l(data->mHandle);
502 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700503 default:
Eric Laurent10351942014-05-08 18:49:52 -0700504 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700505 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800506 }
Eric Laurent10351942014-05-08 18:49:52 -0700507 {
508 Mutex::Autolock _l(event->mLock);
509 if (event->mWaitStatus) {
510 event->mWaitStatus = false;
511 event->mCond.signal();
512 }
513 }
514 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
515 }
516
517 if (configChanged) {
518 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800519 }
Eric Laurent81784c32012-11-19 14:55:58 -0800520}
521
Marco Nelissenb2208842014-02-07 14:00:50 -0800522String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
523 String8 s;
524 if (output) {
525 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
526 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
527 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
528 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
529 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
530 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
531 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
532 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
533 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
534 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
535 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
536 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
537 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
538 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
539 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
540 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
541 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
542 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
543 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
544 } else {
545 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
546 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
547 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
548 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
549 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
550 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
551 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
552 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
553 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
554 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
555 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
556 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
557 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
558 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
559 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
560 }
561 int len = s.length();
562 if (s.length() > 2) {
563 char *str = s.lockBuffer(len);
564 s.unlockBuffer(len - 2);
565 }
566 return s;
567}
568
Glenn Kasten0f11b512014-01-31 16:18:54 -0800569void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800570{
571 const size_t SIZE = 256;
572 char buffer[SIZE];
573 String8 result;
574
575 bool locked = AudioFlinger::dumpTryLock(mLock);
576 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700577 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800578 }
579
Elliott Hughes87cebad2014-05-22 10:14:43 -0700580 dprintf(fd, " I/O handle: %d\n", mId);
581 dprintf(fd, " TID: %d\n", getTid());
582 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
583 dprintf(fd, " Sample rate: %u\n", mSampleRate);
584 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
585 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
586 dprintf(fd, " Channel Count: %u\n", mChannelCount);
587 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800588 channelMaskToString(mChannelMask, mType != RECORD).string());
Elliott Hughes87cebad2014-05-22 10:14:43 -0700589 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
590 dprintf(fd, " Frame size: %zu\n", mFrameSize);
591 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800592 size_t numConfig = mConfigEvents.size();
593 if (numConfig) {
594 for (size_t i = 0; i < numConfig; i++) {
595 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700596 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800597 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700598 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800599 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700600 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800601 }
Eric Laurent81784c32012-11-19 14:55:58 -0800602
603 if (locked) {
604 mLock.unlock();
605 }
606}
607
608void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
609{
610 const size_t SIZE = 256;
611 char buffer[SIZE];
612 String8 result;
613
Marco Nelissenb2208842014-02-07 14:00:50 -0800614 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000615 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800616 write(fd, buffer, strlen(buffer));
617
Marco Nelissenb2208842014-02-07 14:00:50 -0800618 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800619 sp<EffectChain> chain = mEffectChains[i];
620 if (chain != 0) {
621 chain->dump(fd, args);
622 }
623 }
624}
625
Marco Nelissene14a5d62013-10-03 08:51:24 -0700626void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
628 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700629 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100632String16 AudioFlinger::ThreadBase::getWakeLockTag()
633{
634 switch (mType) {
635 case MIXER:
636 return String16("AudioMix");
637 case DIRECT:
638 return String16("AudioDirectOut");
639 case DUPLICATING:
640 return String16("AudioDup");
641 case RECORD:
642 return String16("AudioIn");
643 case OFFLOAD:
644 return String16("AudioOffload");
645 default:
646 ALOG_ASSERT(false);
647 return String16("AudioUnknown");
648 }
649}
650
Marco Nelissene14a5d62013-10-03 08:51:24 -0700651void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800653 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800654 if (mPowerManager != 0) {
655 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700656 status_t status;
657 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700658 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700659 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100660 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700661 String16("media"),
662 uid);
663 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700664 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700665 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100666 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700667 String16("media"));
668 }
Eric Laurent81784c32012-11-19 14:55:58 -0800669 if (status == NO_ERROR) {
670 mWakeLockToken = binder;
671 }
672 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
673 }
674}
675
676void AudioFlinger::ThreadBase::releaseWakeLock()
677{
678 Mutex::Autolock _l(mLock);
679 releaseWakeLock_l();
680}
681
682void AudioFlinger::ThreadBase::releaseWakeLock_l()
683{
684 if (mWakeLockToken != 0) {
685 ALOGV("releaseWakeLock_l() %s", mName);
686 if (mPowerManager != 0) {
687 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
688 }
689 mWakeLockToken.clear();
690 }
691}
692
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800693void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
694 Mutex::Autolock _l(mLock);
695 updateWakeLockUids_l(uids);
696}
697
698void AudioFlinger::ThreadBase::getPowerManager_l() {
699
700 if (mPowerManager == 0) {
701 // use checkService() to avoid blocking if power service is not up yet
702 sp<IBinder> binder =
703 defaultServiceManager()->checkService(String16("power"));
704 if (binder == 0) {
705 ALOGW("Thread %s cannot connect to the power manager service", mName);
706 } else {
707 mPowerManager = interface_cast<IPowerManager>(binder);
708 binder->linkToDeath(mDeathRecipient);
709 }
710 }
711}
712
713void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
714
715 getPowerManager_l();
716 if (mWakeLockToken == NULL) {
717 ALOGE("no wake lock to update!");
718 return;
719 }
720 if (mPowerManager != 0) {
721 sp<IBinder> binder = new BBinder();
722 status_t status;
723 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
724 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
725 }
726}
727
Eric Laurent81784c32012-11-19 14:55:58 -0800728void AudioFlinger::ThreadBase::clearPowerManager()
729{
730 Mutex::Autolock _l(mLock);
731 releaseWakeLock_l();
732 mPowerManager.clear();
733}
734
Glenn Kasten0f11b512014-01-31 16:18:54 -0800735void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800736{
737 sp<ThreadBase> thread = mThread.promote();
738 if (thread != 0) {
739 thread->clearPowerManager();
740 }
741 ALOGW("power manager service died !!!");
742}
743
744void AudioFlinger::ThreadBase::setEffectSuspended(
745 const effect_uuid_t *type, bool suspend, int sessionId)
746{
747 Mutex::Autolock _l(mLock);
748 setEffectSuspended_l(type, suspend, sessionId);
749}
750
751void AudioFlinger::ThreadBase::setEffectSuspended_l(
752 const effect_uuid_t *type, bool suspend, int sessionId)
753{
754 sp<EffectChain> chain = getEffectChain_l(sessionId);
755 if (chain != 0) {
756 if (type != NULL) {
757 chain->setEffectSuspended_l(type, suspend);
758 } else {
759 chain->setEffectSuspendedAll_l(suspend);
760 }
761 }
762
763 updateSuspendedSessions_l(type, suspend, sessionId);
764}
765
766void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
767{
768 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
769 if (index < 0) {
770 return;
771 }
772
773 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
774 mSuspendedSessions.valueAt(index);
775
776 for (size_t i = 0; i < sessionEffects.size(); i++) {
777 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
778 for (int j = 0; j < desc->mRefCount; j++) {
779 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
780 chain->setEffectSuspendedAll_l(true);
781 } else {
782 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
783 desc->mType.timeLow);
784 chain->setEffectSuspended_l(&desc->mType, true);
785 }
786 }
787 }
788}
789
790void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
791 bool suspend,
792 int sessionId)
793{
794 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
795
796 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
797
798 if (suspend) {
799 if (index >= 0) {
800 sessionEffects = mSuspendedSessions.valueAt(index);
801 } else {
802 mSuspendedSessions.add(sessionId, sessionEffects);
803 }
804 } else {
805 if (index < 0) {
806 return;
807 }
808 sessionEffects = mSuspendedSessions.valueAt(index);
809 }
810
811
812 int key = EffectChain::kKeyForSuspendAll;
813 if (type != NULL) {
814 key = type->timeLow;
815 }
816 index = sessionEffects.indexOfKey(key);
817
818 sp<SuspendedSessionDesc> desc;
819 if (suspend) {
820 if (index >= 0) {
821 desc = sessionEffects.valueAt(index);
822 } else {
823 desc = new SuspendedSessionDesc();
824 if (type != NULL) {
825 desc->mType = *type;
826 }
827 sessionEffects.add(key, desc);
828 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
829 }
830 desc->mRefCount++;
831 } else {
832 if (index < 0) {
833 return;
834 }
835 desc = sessionEffects.valueAt(index);
836 if (--desc->mRefCount == 0) {
837 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
838 sessionEffects.removeItemsAt(index);
839 if (sessionEffects.isEmpty()) {
840 ALOGV("updateSuspendedSessions_l() restore removing session %d",
841 sessionId);
842 mSuspendedSessions.removeItem(sessionId);
843 }
844 }
845 }
846 if (!sessionEffects.isEmpty()) {
847 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
848 }
849}
850
851void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
852 bool enabled,
853 int sessionId)
854{
855 Mutex::Autolock _l(mLock);
856 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
857}
858
859void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
860 bool enabled,
861 int sessionId)
862{
863 if (mType != RECORD) {
864 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
865 // another session. This gives the priority to well behaved effect control panels
866 // and applications not using global effects.
867 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
868 // global effects
869 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
870 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
871 }
872 }
873
874 sp<EffectChain> chain = getEffectChain_l(sessionId);
875 if (chain != 0) {
876 chain->checkSuspendOnEffectEnabled(effect, enabled);
877 }
878}
879
880// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
881sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
882 const sp<AudioFlinger::Client>& client,
883 const sp<IEffectClient>& effectClient,
884 int32_t priority,
885 int sessionId,
886 effect_descriptor_t *desc,
887 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700888 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800889{
890 sp<EffectModule> effect;
891 sp<EffectHandle> handle;
892 status_t lStatus;
893 sp<EffectChain> chain;
894 bool chainCreated = false;
895 bool effectCreated = false;
896 bool effectRegistered = false;
897
898 lStatus = initCheck();
899 if (lStatus != NO_ERROR) {
900 ALOGW("createEffect_l() Audio driver not initialized.");
901 goto Exit;
902 }
903
Andy Hung98ef9782014-03-04 14:46:50 -0800904 // Reject any effect on Direct output threads for now, since the format of
905 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
906 if (mType == DIRECT) {
907 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
908 desc->name, mName);
909 lStatus = BAD_VALUE;
910 goto Exit;
911 }
912
Eric Laurent5baf2af2013-09-12 17:37:00 -0700913 // Allow global effects only on offloaded and mixer threads
914 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
915 switch (mType) {
916 case MIXER:
917 case OFFLOAD:
918 break;
919 case DIRECT:
920 case DUPLICATING:
921 case RECORD:
922 default:
923 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
924 lStatus = BAD_VALUE;
925 goto Exit;
926 }
Eric Laurent81784c32012-11-19 14:55:58 -0800927 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700928
Eric Laurent81784c32012-11-19 14:55:58 -0800929 // Only Pre processor effects are allowed on input threads and only on input threads
930 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
931 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
932 desc->name, desc->flags, mType);
933 lStatus = BAD_VALUE;
934 goto Exit;
935 }
936
937 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
938
939 { // scope for mLock
940 Mutex::Autolock _l(mLock);
941
942 // check for existing effect chain with the requested audio session
943 chain = getEffectChain_l(sessionId);
944 if (chain == 0) {
945 // create a new chain for this session
946 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
947 chain = new EffectChain(this, sessionId);
948 addEffectChain_l(chain);
949 chain->setStrategy(getStrategyForSession_l(sessionId));
950 chainCreated = true;
951 } else {
952 effect = chain->getEffectFromDesc_l(desc);
953 }
954
955 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
956
957 if (effect == 0) {
958 int id = mAudioFlinger->nextUniqueId();
959 // Check CPU and memory usage
960 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
961 if (lStatus != NO_ERROR) {
962 goto Exit;
963 }
964 effectRegistered = true;
965 // create a new effect module if none present in the chain
966 effect = new EffectModule(this, chain, desc, id, sessionId);
967 lStatus = effect->status();
968 if (lStatus != NO_ERROR) {
969 goto Exit;
970 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700971 effect->setOffloaded(mType == OFFLOAD, mId);
972
Eric Laurent81784c32012-11-19 14:55:58 -0800973 lStatus = chain->addEffect_l(effect);
974 if (lStatus != NO_ERROR) {
975 goto Exit;
976 }
977 effectCreated = true;
978
979 effect->setDevice(mOutDevice);
980 effect->setDevice(mInDevice);
981 effect->setMode(mAudioFlinger->getMode());
982 effect->setAudioSource(mAudioSource);
983 }
984 // create effect handle and connect it to effect module
985 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800986 lStatus = handle->initCheck();
987 if (lStatus == OK) {
988 lStatus = effect->addHandle(handle.get());
989 }
Eric Laurent81784c32012-11-19 14:55:58 -0800990 if (enabled != NULL) {
991 *enabled = (int)effect->isEnabled();
992 }
993 }
994
995Exit:
996 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
997 Mutex::Autolock _l(mLock);
998 if (effectCreated) {
999 chain->removeEffect_l(effect);
1000 }
1001 if (effectRegistered) {
1002 AudioSystem::unregisterEffect(effect->id());
1003 }
1004 if (chainCreated) {
1005 removeEffectChain_l(chain);
1006 }
1007 handle.clear();
1008 }
1009
Glenn Kasten9156ef32013-08-06 15:39:08 -07001010 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001011 return handle;
1012}
1013
1014sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1015{
1016 Mutex::Autolock _l(mLock);
1017 return getEffect_l(sessionId, effectId);
1018}
1019
1020sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1021{
1022 sp<EffectChain> chain = getEffectChain_l(sessionId);
1023 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1024}
1025
1026// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1027// PlaybackThread::mLock held
1028status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1029{
1030 // check for existing effect chain with the requested audio session
1031 int sessionId = effect->sessionId();
1032 sp<EffectChain> chain = getEffectChain_l(sessionId);
1033 bool chainCreated = false;
1034
Eric Laurent5baf2af2013-09-12 17:37:00 -07001035 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1036 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1037 this, effect->desc().name, effect->desc().flags);
1038
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (chain == 0) {
1040 // create a new chain for this session
1041 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1042 chain = new EffectChain(this, sessionId);
1043 addEffectChain_l(chain);
1044 chain->setStrategy(getStrategyForSession_l(sessionId));
1045 chainCreated = true;
1046 }
1047 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1048
1049 if (chain->getEffectFromId_l(effect->id()) != 0) {
1050 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1051 this, effect->desc().name, chain.get());
1052 return BAD_VALUE;
1053 }
1054
Eric Laurent5baf2af2013-09-12 17:37:00 -07001055 effect->setOffloaded(mType == OFFLOAD, mId);
1056
Eric Laurent81784c32012-11-19 14:55:58 -08001057 status_t status = chain->addEffect_l(effect);
1058 if (status != NO_ERROR) {
1059 if (chainCreated) {
1060 removeEffectChain_l(chain);
1061 }
1062 return status;
1063 }
1064
1065 effect->setDevice(mOutDevice);
1066 effect->setDevice(mInDevice);
1067 effect->setMode(mAudioFlinger->getMode());
1068 effect->setAudioSource(mAudioSource);
1069 return NO_ERROR;
1070}
1071
1072void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1073
1074 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1075 effect_descriptor_t desc = effect->desc();
1076 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1077 detachAuxEffect_l(effect->id());
1078 }
1079
1080 sp<EffectChain> chain = effect->chain().promote();
1081 if (chain != 0) {
1082 // remove effect chain if removing last effect
1083 if (chain->removeEffect_l(effect) == 0) {
1084 removeEffectChain_l(chain);
1085 }
1086 } else {
1087 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1088 }
1089}
1090
1091void AudioFlinger::ThreadBase::lockEffectChains_l(
1092 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1093{
1094 effectChains = mEffectChains;
1095 for (size_t i = 0; i < mEffectChains.size(); i++) {
1096 mEffectChains[i]->lock();
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::unlockEffectChains(
1101 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1102{
1103 for (size_t i = 0; i < effectChains.size(); i++) {
1104 effectChains[i]->unlock();
1105 }
1106}
1107
1108sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1109{
1110 Mutex::Autolock _l(mLock);
1111 return getEffectChain_l(sessionId);
1112}
1113
1114sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1115{
1116 size_t size = mEffectChains.size();
1117 for (size_t i = 0; i < size; i++) {
1118 if (mEffectChains[i]->sessionId() == sessionId) {
1119 return mEffectChains[i];
1120 }
1121 }
1122 return 0;
1123}
1124
1125void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1126{
1127 Mutex::Autolock _l(mLock);
1128 size_t size = mEffectChains.size();
1129 for (size_t i = 0; i < size; i++) {
1130 mEffectChains[i]->setMode_l(mode);
1131 }
1132}
1133
1134void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1135 EffectHandle *handle,
1136 bool unpinIfLast) {
1137
1138 Mutex::Autolock _l(mLock);
1139 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1140 // delete the effect module if removing last handle on it
1141 if (effect->removeHandle(handle) == 0) {
1142 if (!effect->isPinned() || unpinIfLast) {
1143 removeEffect_l(effect);
1144 AudioSystem::unregisterEffect(effect->id());
1145 }
1146 }
1147}
1148
1149// ----------------------------------------------------------------------------
1150// Playback
1151// ----------------------------------------------------------------------------
1152
1153AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1154 AudioStreamOut* output,
1155 audio_io_handle_t id,
1156 audio_devices_t device,
1157 type_t type)
1158 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001159 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001160 mMixerBufferEnabled(false),
1161 mMixerBuffer(NULL),
1162 mMixerBufferSize(0),
1163 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1164 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001165 mEffectBufferEnabled(false),
1166 mEffectBuffer(NULL),
1167 mEffectBufferSize(0),
1168 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1169 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001170 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001171 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001172 // mStreamTypes[] initialized in constructor body
1173 mOutput(output),
1174 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1175 mMixerStatus(MIXER_IDLE),
1176 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1177 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001178 mBytesRemaining(0),
1179 mCurrentWriteLength(0),
1180 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001181 mWriteAckSequence(0),
1182 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001183 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001184 mScreenState(AudioFlinger::mScreenState),
1185 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001186 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1187 // mLatchD, mLatchQ,
1188 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001189{
1190 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001191 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001192
1193 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1194 // it would be safer to explicitly pass initial masterVolume/masterMute as
1195 // parameter.
1196 //
1197 // If the HAL we are using has support for master volume or master mute,
1198 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1199 // and the mute set to false).
1200 mMasterVolume = audioFlinger->masterVolume_l();
1201 mMasterMute = audioFlinger->masterMute_l();
1202 if (mOutput && mOutput->audioHwDev) {
1203 if (mOutput->audioHwDev->canSetMasterVolume()) {
1204 mMasterVolume = 1.0;
1205 }
1206
1207 if (mOutput->audioHwDev->canSetMasterMute()) {
1208 mMasterMute = false;
1209 }
1210 }
1211
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001212 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001213
1214 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1215 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001216 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001217 stream = (audio_stream_type_t) (stream + 1)) {
1218 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1219 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1220 }
1221 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1222 // because mAudioFlinger doesn't have one to copy from
1223}
1224
1225AudioFlinger::PlaybackThread::~PlaybackThread()
1226{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001227 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001228 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001229 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001230 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001231}
1232
1233void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1234{
1235 dumpInternals(fd, args);
1236 dumpTracks(fd, args);
1237 dumpEffectChains(fd, args);
1238}
1239
Glenn Kasten0f11b512014-01-31 16:18:54 -08001240void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242 const size_t SIZE = 256;
1243 char buffer[SIZE];
1244 String8 result;
1245
Marco Nelissenb2208842014-02-07 14:00:50 -08001246 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001247 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1248 const stream_type_t *st = &mStreamTypes[i];
1249 if (i > 0) {
1250 result.appendFormat(", ");
1251 }
1252 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1253 if (st->mute) {
1254 result.append("M");
1255 }
1256 }
1257 result.append("\n");
1258 write(fd, result.string(), result.length());
1259 result.clear();
1260
Eric Laurent81784c32012-11-19 14:55:58 -08001261 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1262 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001263 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001264 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001265
1266 size_t numtracks = mTracks.size();
1267 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001268 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001269 size_t numactiveseen = 0;
1270 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001271 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001272 Track::appendDumpHeader(result);
1273 for (size_t i = 0; i < numtracks; ++i) {
1274 sp<Track> track = mTracks[i];
1275 if (track != 0) {
1276 bool active = mActiveTracks.indexOf(track) >= 0;
1277 if (active) {
1278 numactiveseen++;
1279 }
1280 track->dump(buffer, SIZE, active);
1281 result.append(buffer);
1282 }
1283 }
1284 } else {
1285 result.append("\n");
1286 }
1287 if (numactiveseen != numactive) {
1288 // some tracks in the active list were not in the tracks list
1289 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1290 " not in the track list\n");
1291 result.append(buffer);
1292 Track::appendDumpHeader(result);
1293 for (size_t i = 0; i < numactive; ++i) {
1294 sp<Track> track = mActiveTracks[i].promote();
1295 if (track != 0 && mTracks.indexOf(track) < 0) {
1296 track->dump(buffer, SIZE, true);
1297 result.append(buffer);
1298 }
1299 }
1300 }
1301
1302 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001303}
1304
1305void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1306{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001307 dprintf(fd, "\nOutput thread %p:\n", this);
1308 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1309 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1310 dprintf(fd, " Total writes: %d\n", mNumWrites);
1311 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1312 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1313 dprintf(fd, " Suspend count: %d\n", mSuspended);
1314 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1315 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1316 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1317 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001318
1319 dumpBase(fd, args);
1320}
1321
1322// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001323
1324void AudioFlinger::PlaybackThread::onFirstRef()
1325{
1326 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1327}
1328
1329// ThreadBase virtuals
1330void AudioFlinger::PlaybackThread::preExit()
1331{
1332 ALOGV(" preExit()");
1333 // FIXME this is using hard-coded strings but in the future, this functionality will be
1334 // converted to use audio HAL extensions required to support tunneling
1335 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1336}
1337
1338// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1339sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1340 const sp<AudioFlinger::Client>& client,
1341 audio_stream_type_t streamType,
1342 uint32_t sampleRate,
1343 audio_format_t format,
1344 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001345 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001346 const sp<IMemory>& sharedBuffer,
1347 int sessionId,
1348 IAudioFlinger::track_flags_t *flags,
1349 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001350 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001351 status_t *status)
1352{
Glenn Kasten74935e42013-12-19 08:56:45 -08001353 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001354 sp<Track> track;
1355 status_t lStatus;
1356
1357 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1358
1359 // client expresses a preference for FAST, but we get the final say
1360 if (*flags & IAudioFlinger::TRACK_FAST) {
1361 if (
1362 // not timed
1363 (!isTimed) &&
1364 // either of these use cases:
1365 (
1366 // use case 1: shared buffer with any frame count
1367 (
1368 (sharedBuffer != 0)
1369 ) ||
1370 // use case 2: callback handler and frame count is default or at least as large as HAL
1371 (
1372 (tid != -1) &&
1373 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001374 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001375 )
1376 ) &&
1377 // PCM data
1378 audio_is_linear_pcm(format) &&
1379 // mono or stereo
1380 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1381 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001382 // hardware sample rate
1383 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001384 // normal mixer has an associated fast mixer
1385 hasFastMixer() &&
1386 // there are sufficient fast track slots available
1387 (mFastTrackAvailMask != 0)
1388 // FIXME test that MixerThread for this fast track has a capable output HAL
1389 // FIXME add a permission test also?
1390 ) {
1391 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1392 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001393 // read the fast track multiplier property the first time it is needed
1394 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1395 if (ok != 0) {
1396 ALOGE("%s pthread_once failed: %d", __func__, ok);
1397 }
1398 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001399 }
1400 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1401 frameCount, mFrameCount);
1402 } else {
1403 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1404 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1405 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1406 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1407 audio_is_linear_pcm(format),
1408 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1409 *flags &= ~IAudioFlinger::TRACK_FAST;
1410 // For compatibility with AudioTrack calculation, buffer depth is forced
1411 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1412 // This is probably too conservative, but legacy application code may depend on it.
1413 // If you change this calculation, also review the start threshold which is related.
1414 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1415 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1416 if (minBufCount < 2) {
1417 minBufCount = 2;
1418 }
1419 size_t minFrameCount = mNormalFrameCount * minBufCount;
1420 if (frameCount < minFrameCount) {
1421 frameCount = minFrameCount;
1422 }
1423 }
1424 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001425 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001426
Glenn Kastenc3df8382014-03-13 15:05:25 -07001427 switch (mType) {
1428
1429 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001430 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001431 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001432 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1433 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001434 sampleRate, format, channelMask, mOutput, mFormat);
1435 lStatus = BAD_VALUE;
1436 goto Exit;
1437 }
1438 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001439 break;
1440
1441 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001442 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001443 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1444 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001445 sampleRate, format, channelMask, mOutput, mFormat);
1446 lStatus = BAD_VALUE;
1447 goto Exit;
1448 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001449 break;
1450
1451 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001452 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001453 ALOGE("createTrack_l() Bad parameter: format %#x \""
1454 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001455 format, mOutput, mFormat);
1456 lStatus = BAD_VALUE;
1457 goto Exit;
1458 }
Eric Laurent81784c32012-11-19 14:55:58 -08001459 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1460 if (sampleRate > mSampleRate*2) {
1461 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1462 lStatus = BAD_VALUE;
1463 goto Exit;
1464 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001465 break;
1466
Eric Laurent81784c32012-11-19 14:55:58 -08001467 }
1468
1469 lStatus = initCheck();
1470 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001471 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001472 goto Exit;
1473 }
1474
1475 { // scope for mLock
1476 Mutex::Autolock _l(mLock);
1477
1478 // all tracks in same audio session must share the same routing strategy otherwise
1479 // conflicts will happen when tracks are moved from one output to another by audio policy
1480 // manager
1481 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1482 for (size_t i = 0; i < mTracks.size(); ++i) {
1483 sp<Track> t = mTracks[i];
1484 if (t != 0 && !t->isOutputTrack()) {
1485 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1486 if (sessionId == t->sessionId() && strategy != actual) {
1487 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1488 strategy, actual);
1489 lStatus = BAD_VALUE;
1490 goto Exit;
1491 }
1492 }
1493 }
1494
1495 if (!isTimed) {
1496 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001497 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001498 } else {
1499 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001500 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001501 }
Glenn Kasten03003332013-08-06 15:40:54 -07001502
1503 // new Track always returns non-NULL,
1504 // but TimedTrack::create() is a factory that could fail by returning NULL
1505 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1506 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001507 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001508 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001509 goto Exit;
1510 }
1511 mTracks.add(track);
1512
1513 sp<EffectChain> chain = getEffectChain_l(sessionId);
1514 if (chain != 0) {
1515 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1516 track->setMainBuffer(chain->inBuffer());
1517 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1518 chain->incTrackCnt();
1519 }
1520
1521 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1522 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1523 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1524 // so ask activity manager to do this on our behalf
1525 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1526 }
1527 }
1528
1529 lStatus = NO_ERROR;
1530
1531Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001532 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001533 return track;
1534}
1535
1536uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1537{
1538 return latency;
1539}
1540
1541uint32_t AudioFlinger::PlaybackThread::latency() const
1542{
1543 Mutex::Autolock _l(mLock);
1544 return latency_l();
1545}
1546uint32_t AudioFlinger::PlaybackThread::latency_l() const
1547{
1548 if (initCheck() == NO_ERROR) {
1549 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1550 } else {
1551 return 0;
1552 }
1553}
1554
1555void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1556{
1557 Mutex::Autolock _l(mLock);
1558 // Don't apply master volume in SW if our HAL can do it for us.
1559 if (mOutput && mOutput->audioHwDev &&
1560 mOutput->audioHwDev->canSetMasterVolume()) {
1561 mMasterVolume = 1.0;
1562 } else {
1563 mMasterVolume = value;
1564 }
1565}
1566
1567void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1568{
1569 Mutex::Autolock _l(mLock);
1570 // Don't apply master mute in SW if our HAL can do it for us.
1571 if (mOutput && mOutput->audioHwDev &&
1572 mOutput->audioHwDev->canSetMasterMute()) {
1573 mMasterMute = false;
1574 } else {
1575 mMasterMute = muted;
1576 }
1577}
1578
1579void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1580{
1581 Mutex::Autolock _l(mLock);
1582 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001583 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001584}
1585
1586void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1587{
1588 Mutex::Autolock _l(mLock);
1589 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001590 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001591}
1592
1593float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1594{
1595 Mutex::Autolock _l(mLock);
1596 return mStreamTypes[stream].volume;
1597}
1598
1599// addTrack_l() must be called with ThreadBase::mLock held
1600status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1601{
1602 status_t status = ALREADY_EXISTS;
1603
1604 // set retry count for buffer fill
1605 track->mRetryCount = kMaxTrackStartupRetries;
1606 if (mActiveTracks.indexOf(track) < 0) {
1607 // the track is newly added, make sure it fills up all its
1608 // buffers before playing. This is to ensure the client will
1609 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001610 if (!track->isOutputTrack()) {
1611 TrackBase::track_state state = track->mState;
1612 mLock.unlock();
1613 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1614 mLock.lock();
1615 // abort track was stopped/paused while we released the lock
1616 if (state != track->mState) {
1617 if (status == NO_ERROR) {
1618 mLock.unlock();
1619 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1620 mLock.lock();
1621 }
1622 return INVALID_OPERATION;
1623 }
1624 // abort if start is rejected by audio policy manager
1625 if (status != NO_ERROR) {
1626 return PERMISSION_DENIED;
1627 }
1628#ifdef ADD_BATTERY_DATA
1629 // to track the speaker usage
1630 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1631#endif
1632 }
1633
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001634 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 track->mResetDone = false;
1636 track->mPresentationCompleteFrames = 0;
1637 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001638 mWakeLockUids.add(track->uid());
1639 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001640 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001641 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1642 if (chain != 0) {
1643 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1644 track->sessionId());
1645 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001646 }
1647
1648 status = NO_ERROR;
1649 }
1650
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001651 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001652 return status;
1653}
1654
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001656{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001657 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001658 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001659 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1660 track->mState = TrackBase::STOPPED;
1661 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001662 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001663 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001666
1667 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001668}
1669
1670void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1671{
1672 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1673 mTracks.remove(track);
1674 deleteTrackName_l(track->name());
1675 // redundant as track is about to be destroyed, for dumpsys only
1676 track->mName = -1;
1677 if (track->isFastTrack()) {
1678 int index = track->mFastIndex;
1679 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1680 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1681 mFastTrackAvailMask |= 1 << index;
1682 // redundant as track is about to be destroyed, for dumpsys only
1683 track->mFastIndex = -1;
1684 }
1685 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1686 if (chain != 0) {
1687 chain->decTrackCnt();
1688 }
1689}
1690
Eric Laurentede6c3b2013-09-19 14:37:46 -07001691void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692{
1693 // Thread could be blocked waiting for async
1694 // so signal it to handle state changes immediately
1695 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1696 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1697 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001698 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001699}
1700
Eric Laurent81784c32012-11-19 14:55:58 -08001701String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1702{
Eric Laurent81784c32012-11-19 14:55:58 -08001703 Mutex::Autolock _l(mLock);
1704 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001705 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001706 }
1707
Glenn Kastend8ea6992013-07-16 14:17:15 -07001708 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1709 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001710 free(s);
1711 return out_s8;
1712}
1713
Eric Laurent021cf962014-05-13 10:18:14 -07001714void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001715 AudioSystem::OutputDescriptor desc;
1716 void *param2 = NULL;
1717
Eric Laurent021cf962014-05-13 10:18:14 -07001718 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001719 param);
1720
1721 switch (event) {
1722 case AudioSystem::OUTPUT_OPENED:
1723 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001724 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001725 desc.samplingRate = mSampleRate;
1726 desc.format = mFormat;
1727 desc.frameCount = mNormalFrameCount; // FIXME see
1728 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001729 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001730 param2 = &desc;
1731 break;
1732
1733 case AudioSystem::STREAM_CONFIG_CHANGED:
1734 param2 = &param;
1735 case AudioSystem::OUTPUT_CLOSED:
1736 default:
1737 break;
1738 }
Eric Laurent021cf962014-05-13 10:18:14 -07001739 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001740}
1741
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742void AudioFlinger::PlaybackThread::writeCallback()
1743{
1744 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001745 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001746}
1747
1748void AudioFlinger::PlaybackThread::drainCallback()
1749{
1750 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001751 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001752}
1753
Eric Laurent3b4529e2013-09-05 18:09:19 -07001754void AudioFlinger::PlaybackThread::resetWriteBlocked(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 ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1759 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001760 mWaitWorkCV.signal();
1761 }
1762}
1763
Eric Laurent3b4529e2013-09-05 18:09:19 -07001764void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001765{
1766 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001767 // reject out of sequence requests
1768 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1769 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001770 mWaitWorkCV.signal();
1771 }
1772}
1773
1774// static
1775int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001776 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777 void *cookie)
1778{
1779 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1780 ALOGV("asyncCallback() event %d", event);
1781 switch (event) {
1782 case STREAM_CBK_EVENT_WRITE_READY:
1783 me->writeCallback();
1784 break;
1785 case STREAM_CBK_EVENT_DRAIN_READY:
1786 me->drainCallback();
1787 break;
1788 default:
1789 ALOGW("asyncCallback() unknown event %d", event);
1790 break;
1791 }
1792 return 0;
1793}
1794
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001795void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001796{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001797 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001798 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1799 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001800 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001801 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001802 }
1803 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001804 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001805 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1806 }
Andy Hunge5412692014-05-16 11:25:07 -07001807 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001808 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001809 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001810 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001811 }
1812 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001813 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1814 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001815 }
Eric Laurent81784c32012-11-19 14:55:58 -08001816 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001817 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1818 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 if (mFrameCount & 15) {
1820 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1821 mFrameCount);
1822 }
1823
Eric Laurentbfb1b832013-01-07 09:53:42 -08001824 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1825 (mOutput->stream->set_callback != NULL)) {
1826 if (mOutput->stream->set_callback(mOutput->stream,
1827 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1828 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001829 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001830 }
1831 }
1832
Andy Hung09a50072014-02-27 14:30:47 -08001833 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001834 double multiplier = 1.0;
1835 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1836 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001837 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1838 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001839 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1840 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1841 maxNormalFrameCount = maxNormalFrameCount & ~15;
1842 if (maxNormalFrameCount < minNormalFrameCount) {
1843 maxNormalFrameCount = minNormalFrameCount;
1844 }
1845 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1846 if (multiplier <= 1.0) {
1847 multiplier = 1.0;
1848 } else if (multiplier <= 2.0) {
1849 if (2 * mFrameCount <= maxNormalFrameCount) {
1850 multiplier = 2.0;
1851 } else {
1852 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1853 }
1854 } else {
1855 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001856 // 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 -08001857 // track, but we sometimes have to do this to satisfy the maximum frame count
1858 // constraint)
1859 // FIXME this rounding up should not be done if no HAL SRC
1860 uint32_t truncMult = (uint32_t) multiplier;
1861 if ((truncMult & 1)) {
1862 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1863 ++truncMult;
1864 }
1865 }
1866 multiplier = (double) truncMult;
1867 }
1868 }
1869 mNormalFrameCount = multiplier * mFrameCount;
1870 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001871 if (mType == MIXER || mType == DUPLICATING) {
1872 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1873 }
Andy Hung09a50072014-02-27 14:30:47 -08001874 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001875 mNormalFrameCount);
1876
Andy Hung010a1a12014-03-13 13:57:33 -07001877 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1878 // Originally this was int16_t[] array, need to remove legacy implications.
1879 free(mSinkBuffer);
1880 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001881 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1882 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1883 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001884 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001885
Andy Hung69aed5f2014-02-25 17:24:40 -08001886 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1887 // drives the output.
1888 free(mMixerBuffer);
1889 mMixerBuffer = NULL;
1890 if (mMixerBufferEnabled) {
1891 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1892 mMixerBufferSize = mNormalFrameCount * mChannelCount
1893 * audio_bytes_per_sample(mMixerBufferFormat);
1894 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1895 }
Andy Hung98ef9782014-03-04 14:46:50 -08001896 free(mEffectBuffer);
1897 mEffectBuffer = NULL;
1898 if (mEffectBufferEnabled) {
1899 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1900 mEffectBufferSize = mNormalFrameCount * mChannelCount
1901 * audio_bytes_per_sample(mEffectBufferFormat);
1902 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1903 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001904
Eric Laurent81784c32012-11-19 14:55:58 -08001905 // force reconfiguration of effect chains and engines to take new buffer size and audio
1906 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001907 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001908 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1909 // matter.
1910 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1911 Vector< sp<EffectChain> > effectChains = mEffectChains;
1912 for (size_t i = 0; i < effectChains.size(); i ++) {
1913 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1914 }
1915}
1916
1917
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001918status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001919{
1920 if (halFrames == NULL || dspFrames == NULL) {
1921 return BAD_VALUE;
1922 }
1923 Mutex::Autolock _l(mLock);
1924 if (initCheck() != NO_ERROR) {
1925 return INVALID_OPERATION;
1926 }
1927 size_t framesWritten = mBytesWritten / mFrameSize;
1928 *halFrames = framesWritten;
1929
1930 if (isSuspended()) {
1931 // return an estimation of rendered frames when the output is suspended
1932 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1933 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1934 return NO_ERROR;
1935 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001936 status_t status;
1937 uint32_t frames;
1938 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1939 *dspFrames = (size_t)frames;
1940 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001941 }
1942}
1943
1944uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1945{
1946 Mutex::Autolock _l(mLock);
1947 uint32_t result = 0;
1948 if (getEffectChain_l(sessionId) != 0) {
1949 result = EFFECT_SESSION;
1950 }
1951
1952 for (size_t i = 0; i < mTracks.size(); ++i) {
1953 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001954 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001955 result |= TRACK_SESSION;
1956 break;
1957 }
1958 }
1959
1960 return result;
1961}
1962
1963uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1964{
1965 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1966 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1967 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1968 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1969 }
1970 for (size_t i = 0; i < mTracks.size(); i++) {
1971 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001972 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001973 return AudioSystem::getStrategyForStream(track->streamType());
1974 }
1975 }
1976 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1977}
1978
1979
1980AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1981{
1982 Mutex::Autolock _l(mLock);
1983 return mOutput;
1984}
1985
1986AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1987{
1988 Mutex::Autolock _l(mLock);
1989 AudioStreamOut *output = mOutput;
1990 mOutput = NULL;
1991 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1992 // must push a NULL and wait for ack
1993 mOutputSink.clear();
1994 mPipeSink.clear();
1995 mNormalSink.clear();
1996 return output;
1997}
1998
1999// this method must always be called either with ThreadBase mLock held or inside the thread loop
2000audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2001{
2002 if (mOutput == NULL) {
2003 return NULL;
2004 }
2005 return &mOutput->stream->common;
2006}
2007
2008uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2009{
2010 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2011}
2012
2013status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2014{
2015 if (!isValidSyncEvent(event)) {
2016 return BAD_VALUE;
2017 }
2018
2019 Mutex::Autolock _l(mLock);
2020
2021 for (size_t i = 0; i < mTracks.size(); ++i) {
2022 sp<Track> track = mTracks[i];
2023 if (event->triggerSession() == track->sessionId()) {
2024 (void) track->setSyncEvent(event);
2025 return NO_ERROR;
2026 }
2027 }
2028
2029 return NAME_NOT_FOUND;
2030}
2031
2032bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2033{
2034 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2035}
2036
2037void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2038 const Vector< sp<Track> >& tracksToRemove)
2039{
2040 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002041 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002042 for (size_t i = 0 ; i < count ; i++) {
2043 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002044 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002045 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046#ifdef ADD_BATTERY_DATA
2047 // to track the speaker usage
2048 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2049#endif
2050 if (track->isTerminated()) {
2051 AudioSystem::releaseOutput(mId);
2052 }
Eric Laurent81784c32012-11-19 14:55:58 -08002053 }
2054 }
2055 }
Eric Laurent81784c32012-11-19 14:55:58 -08002056}
2057
2058void AudioFlinger::PlaybackThread::checkSilentMode_l()
2059{
2060 if (!mMasterMute) {
2061 char value[PROPERTY_VALUE_MAX];
2062 if (property_get("ro.audio.silent", value, "0") > 0) {
2063 char *endptr;
2064 unsigned long ul = strtoul(value, &endptr, 0);
2065 if (*endptr == '\0' && ul != 0) {
2066 ALOGD("Silence is golden");
2067 // The setprop command will not allow a property to be changed after
2068 // the first time it is set, so we don't have to worry about un-muting.
2069 setMasterMute_l(true);
2070 }
2071 }
2072 }
2073}
2074
2075// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002076ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002077{
2078 // FIXME rewrite to reduce number of system calls
2079 mLastWriteTime = systemTime();
2080 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002081 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002082 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002083
2084 // If an NBAIO sink is present, use it to write the normal mixer's submix
2085 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002086 const size_t count = mBytesRemaining / mFrameSize;
2087
Simon Wilson2d590962012-11-29 15:18:50 -08002088 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002089 // update the setpoint when AudioFlinger::mScreenState changes
2090 uint32_t screenState = AudioFlinger::mScreenState;
2091 if (screenState != mScreenState) {
2092 mScreenState = screenState;
2093 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2094 if (pipe != NULL) {
2095 pipe->setAvgFrames((mScreenState & 1) ?
2096 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2097 }
2098 }
Andy Hung010a1a12014-03-13 13:57:33 -07002099 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002100 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002101 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002102 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002103 } else {
2104 bytesWritten = framesWritten;
2105 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002106 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002107 if (status == NO_ERROR) {
2108 size_t totalFramesWritten = mNormalSink->framesWritten();
2109 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2110 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2111 mLatchDValid = true;
2112 }
2113 }
Eric Laurent81784c32012-11-19 14:55:58 -08002114 // otherwise use the HAL / AudioStreamOut directly
2115 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002116 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002117
Eric Laurentbfb1b832013-01-07 09:53:42 -08002118 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002119 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2120 mWriteAckSequence += 2;
2121 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002122 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002123 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002125 // FIXME We should have an implementation of timestamps for direct output threads.
2126 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002128 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129 if (mUseAsyncWrite &&
2130 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2131 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002132 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002134 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 }
Eric Laurent81784c32012-11-19 14:55:58 -08002136 }
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138 mNumWrites++;
2139 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002140 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 return bytesWritten;
2142}
2143
2144void AudioFlinger::PlaybackThread::threadLoop_drain()
2145{
2146 if (mOutput->stream->drain) {
2147 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2148 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002149 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2150 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002152 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 }
2154 mOutput->stream->drain(mOutput->stream,
2155 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2156 : AUDIO_DRAIN_ALL);
2157 }
2158}
2159
2160void AudioFlinger::PlaybackThread::threadLoop_exit()
2161{
2162 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002163}
2164
2165/*
2166The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002167 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002168 - activeSleepTime from activeSleepTimeUs()
2169 - idleSleepTime from idleSleepTimeUs()
2170 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2171 - maxPeriod from frame count and sample rate (MIXER only)
2172
2173The parameters that affect these derived values are:
2174 - frame count
2175 - frame size
2176 - sample rate
2177 - device type: A2DP or not
2178 - device latency
2179 - format: PCM or not
2180 - active sleep time
2181 - idle sleep time
2182*/
2183
2184void AudioFlinger::PlaybackThread::cacheParameters_l()
2185{
Andy Hung25c2dac2014-02-27 14:56:00 -08002186 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002187 activeSleepTime = activeSleepTimeUs();
2188 idleSleepTime = idleSleepTimeUs();
2189}
2190
2191void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2192{
Glenn Kasten7c027242012-12-26 14:43:16 -08002193 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002194 this, streamType, mTracks.size());
2195 Mutex::Autolock _l(mLock);
2196
2197 size_t size = mTracks.size();
2198 for (size_t i = 0; i < size; i++) {
2199 sp<Track> t = mTracks[i];
2200 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002201 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002202 }
2203 }
2204}
2205
2206status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2207{
2208 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002209 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2210 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002211 bool ownsBuffer = false;
2212
2213 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2214 if (session > 0) {
2215 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002216 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002217 if (mType != DIRECT) {
2218 size_t numSamples = mNormalFrameCount * mChannelCount;
2219 buffer = new int16_t[numSamples];
2220 memset(buffer, 0, numSamples * sizeof(int16_t));
2221 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2222 ownsBuffer = true;
2223 }
2224
2225 // Attach all tracks with same session ID to this chain.
2226 for (size_t i = 0; i < mTracks.size(); ++i) {
2227 sp<Track> track = mTracks[i];
2228 if (session == track->sessionId()) {
2229 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2230 buffer);
2231 track->setMainBuffer(buffer);
2232 chain->incTrackCnt();
2233 }
2234 }
2235
2236 // indicate all active tracks in the chain
2237 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2238 sp<Track> track = mActiveTracks[i].promote();
2239 if (track == 0) {
2240 continue;
2241 }
2242 if (session == track->sessionId()) {
2243 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2244 chain->incActiveTrackCnt();
2245 }
2246 }
2247 }
2248
2249 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002250 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2251 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002252 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2253 // chains list in order to be processed last as it contains output stage effects
2254 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2255 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2256 // after track specific effects and before output stage
2257 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2258 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2259 // Effect chain for other sessions are inserted at beginning of effect
2260 // chains list to be processed before output mix effects. Relative order between other
2261 // sessions is not important
2262 size_t size = mEffectChains.size();
2263 size_t i = 0;
2264 for (i = 0; i < size; i++) {
2265 if (mEffectChains[i]->sessionId() < session) {
2266 break;
2267 }
2268 }
2269 mEffectChains.insertAt(chain, i);
2270 checkSuspendOnAddEffectChain_l(chain);
2271
2272 return NO_ERROR;
2273}
2274
2275size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2276{
2277 int session = chain->sessionId();
2278
2279 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2280
2281 for (size_t i = 0; i < mEffectChains.size(); i++) {
2282 if (chain == mEffectChains[i]) {
2283 mEffectChains.removeAt(i);
2284 // detach all active tracks from the chain
2285 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2286 sp<Track> track = mActiveTracks[i].promote();
2287 if (track == 0) {
2288 continue;
2289 }
2290 if (session == track->sessionId()) {
2291 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2292 chain.get(), session);
2293 chain->decActiveTrackCnt();
2294 }
2295 }
2296
2297 // detach all tracks with same session ID from this chain
2298 for (size_t i = 0; i < mTracks.size(); ++i) {
2299 sp<Track> track = mTracks[i];
2300 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002301 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002302 chain->decTrackCnt();
2303 }
2304 }
2305 break;
2306 }
2307 }
2308 return mEffectChains.size();
2309}
2310
2311status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2312 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2313{
2314 Mutex::Autolock _l(mLock);
2315 return attachAuxEffect_l(track, EffectId);
2316}
2317
2318status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2319 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2320{
2321 status_t status = NO_ERROR;
2322
2323 if (EffectId == 0) {
2324 track->setAuxBuffer(0, NULL);
2325 } else {
2326 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2327 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2328 if (effect != 0) {
2329 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2330 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2331 } else {
2332 status = INVALID_OPERATION;
2333 }
2334 } else {
2335 status = BAD_VALUE;
2336 }
2337 }
2338 return status;
2339}
2340
2341void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2342{
2343 for (size_t i = 0; i < mTracks.size(); ++i) {
2344 sp<Track> track = mTracks[i];
2345 if (track->auxEffectId() == effectId) {
2346 attachAuxEffect_l(track, 0);
2347 }
2348 }
2349}
2350
2351bool AudioFlinger::PlaybackThread::threadLoop()
2352{
2353 Vector< sp<Track> > tracksToRemove;
2354
2355 standbyTime = systemTime();
2356
2357 // MIXER
2358 nsecs_t lastWarning = 0;
2359
2360 // DUPLICATING
2361 // FIXME could this be made local to while loop?
2362 writeFrames = 0;
2363
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002364 int lastGeneration = 0;
2365
Eric Laurent81784c32012-11-19 14:55:58 -08002366 cacheParameters_l();
2367 sleepTime = idleSleepTime;
2368
2369 if (mType == MIXER) {
2370 sleepTimeShift = 0;
2371 }
2372
2373 CpuStats cpuStats;
2374 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2375
2376 acquireWakeLock();
2377
Glenn Kasten9e58b552013-01-18 15:09:48 -08002378 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2379 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2380 // and then that string will be logged at the next convenient opportunity.
2381 const char *logString = NULL;
2382
Eric Laurent664539d2013-09-23 18:24:31 -07002383 checkSilentMode_l();
2384
Eric Laurent81784c32012-11-19 14:55:58 -08002385 while (!exitPending())
2386 {
2387 cpuStats.sample(myName);
2388
2389 Vector< sp<EffectChain> > effectChains;
2390
Eric Laurent81784c32012-11-19 14:55:58 -08002391 { // scope for mLock
2392
2393 Mutex::Autolock _l(mLock);
2394
Eric Laurent021cf962014-05-13 10:18:14 -07002395 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002396
Glenn Kasten9e58b552013-01-18 15:09:48 -08002397 if (logString != NULL) {
2398 mNBLogWriter->logTimestamp();
2399 mNBLogWriter->log(logString);
2400 logString = NULL;
2401 }
2402
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002403 if (mLatchDValid) {
2404 mLatchQ = mLatchD;
2405 mLatchDValid = false;
2406 mLatchQValid = true;
2407 }
2408
Eric Laurent81784c32012-11-19 14:55:58 -08002409 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 if (mSignalPending) {
2411 // A signal was raised while we were unlocked
2412 mSignalPending = false;
2413 } else if (waitingAsyncCallback_l()) {
2414 if (exitPending()) {
2415 break;
2416 }
2417 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002418 mWakeLockUids.clear();
2419 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420 ALOGV("wait async completion");
2421 mWaitWorkCV.wait(mLock);
2422 ALOGV("async completion/wake");
2423 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002424 standbyTime = systemTime() + standbyDelay;
2425 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002426
2427 continue;
2428 }
2429 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002430 isSuspended()) {
2431 // put audio hardware into standby after short delay
2432 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002433
2434 threadLoop_standby();
2435
2436 mStandby = true;
2437 }
2438
2439 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2440 // we're about to wait, flush the binder command buffer
2441 IPCThreadState::self()->flushCommands();
2442
2443 clearOutputTracks();
2444
2445 if (exitPending()) {
2446 break;
2447 }
2448
2449 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002450 mWakeLockUids.clear();
2451 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // wait until we have something to do...
2453 ALOGV("%s going to sleep", myName.string());
2454 mWaitWorkCV.wait(mLock);
2455 ALOGV("%s waking up", myName.string());
2456 acquireWakeLock_l();
2457
2458 mMixerStatus = MIXER_IDLE;
2459 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2460 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002462 checkSilentMode_l();
2463
2464 standbyTime = systemTime() + standbyDelay;
2465 sleepTime = idleSleepTime;
2466 if (mType == MIXER) {
2467 sleepTimeShift = 0;
2468 }
2469
2470 continue;
2471 }
2472 }
Eric Laurent81784c32012-11-19 14:55:58 -08002473 // mMixerStatusIgnoringFastTracks is also updated internally
2474 mMixerStatus = prepareTracks_l(&tracksToRemove);
2475
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002476 // compare with previously applied list
2477 if (lastGeneration != mActiveTracksGeneration) {
2478 // update wakelock
2479 updateWakeLockUids_l(mWakeLockUids);
2480 lastGeneration = mActiveTracksGeneration;
2481 }
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 // prevent any changes in effect chain list and in each effect chain
2484 // during mixing and effect process as the audio buffers could be deleted
2485 // or modified if an effect is created or deleted
2486 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002487 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002488
Eric Laurentbfb1b832013-01-07 09:53:42 -08002489 if (mBytesRemaining == 0) {
2490 mCurrentWriteLength = 0;
2491 if (mMixerStatus == MIXER_TRACKS_READY) {
2492 // threadLoop_mix() sets mCurrentWriteLength
2493 threadLoop_mix();
2494 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2495 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2496 // threadLoop_sleepTime sets sleepTime to 0 if data
2497 // must be written to HAL
2498 threadLoop_sleepTime();
2499 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002500 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002501 }
2502 }
Andy Hung98ef9782014-03-04 14:46:50 -08002503 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2504 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2505 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2506 // or mSinkBuffer (if there are no effects).
2507 //
2508 // This is done pre-effects computation; if effects change to
2509 // support higher precision, this needs to move.
2510 //
2511 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2512 // TODO use sleepTime == 0 as an additional condition.
2513 if (mMixerBufferValid) {
2514 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2515 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2516
2517 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2518 mNormalFrameCount * mChannelCount);
2519 }
2520
Eric Laurentbfb1b832013-01-07 09:53:42 -08002521 mBytesRemaining = mCurrentWriteLength;
2522 if (isSuspended()) {
2523 sleepTime = suspendSleepTimeUs();
2524 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002525 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002526 mBytesRemaining = 0;
2527 }
Eric Laurent81784c32012-11-19 14:55:58 -08002528
Eric Laurentbfb1b832013-01-07 09:53:42 -08002529 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002530 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002531 for (size_t i = 0; i < effectChains.size(); i ++) {
2532 effectChains[i]->process_l();
2533 }
Eric Laurent81784c32012-11-19 14:55:58 -08002534 }
2535 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002536 // Process effect chains for offloaded thread even if no audio
2537 // was read from audio track: process only updates effect state
2538 // and thus does have to be synchronized with audio writes but may have
2539 // to be called while waiting for async write callback
2540 if (mType == OFFLOAD) {
2541 for (size_t i = 0; i < effectChains.size(); i ++) {
2542 effectChains[i]->process_l();
2543 }
2544 }
Eric Laurent81784c32012-11-19 14:55:58 -08002545
Andy Hung98ef9782014-03-04 14:46:50 -08002546 // Only if the Effects buffer is enabled and there is data in the
2547 // Effects buffer (buffer valid), we need to
2548 // copy into the sink buffer.
2549 // TODO use sleepTime == 0 as an additional condition.
2550 if (mEffectBufferValid) {
2551 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2552 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2553 mNormalFrameCount * mChannelCount);
2554 }
2555
Eric Laurent81784c32012-11-19 14:55:58 -08002556 // enable changes in effect chain
2557 unlockEffectChains(effectChains);
2558
Eric Laurentbfb1b832013-01-07 09:53:42 -08002559 if (!waitingAsyncCallback()) {
2560 // sleepTime == 0 means we must write to audio hardware
2561 if (sleepTime == 0) {
2562 if (mBytesRemaining) {
2563 ssize_t ret = threadLoop_write();
2564 if (ret < 0) {
2565 mBytesRemaining = 0;
2566 } else {
2567 mBytesWritten += ret;
2568 mBytesRemaining -= ret;
2569 }
2570 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2571 (mMixerStatus == MIXER_DRAIN_ALL)) {
2572 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002573 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002574 if (mType == MIXER) {
2575 // write blocked detection
2576 nsecs_t now = systemTime();
2577 nsecs_t delta = now - mLastWriteTime;
2578 if (!mStandby && delta > maxPeriod) {
2579 mNumDelayedWrites++;
2580 if ((now - lastWarning) > kWarningThrottleNs) {
2581 ATRACE_NAME("underrun");
2582 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2583 ns2ms(delta), mNumDelayedWrites, this);
2584 lastWarning = now;
2585 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 }
2587 }
Eric Laurent81784c32012-11-19 14:55:58 -08002588
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589 } else {
2590 usleep(sleepTime);
2591 }
Eric Laurent81784c32012-11-19 14:55:58 -08002592 }
2593
2594 // Finally let go of removed track(s), without the lock held
2595 // since we can't guarantee the destructors won't acquire that
2596 // same lock. This will also mutate and push a new fast mixer state.
2597 threadLoop_removeTracks(tracksToRemove);
2598 tracksToRemove.clear();
2599
2600 // FIXME I don't understand the need for this here;
2601 // it was in the original code but maybe the
2602 // assignment in saveOutputTracks() makes this unnecessary?
2603 clearOutputTracks();
2604
2605 // Effect chains will be actually deleted here if they were removed from
2606 // mEffectChains list during mixing or effects processing
2607 effectChains.clear();
2608
2609 // FIXME Note that the above .clear() is no longer necessary since effectChains
2610 // is now local to this block, but will keep it for now (at least until merge done).
2611 }
2612
Eric Laurentbfb1b832013-01-07 09:53:42 -08002613 threadLoop_exit();
2614
Eric Laurent81784c32012-11-19 14:55:58 -08002615 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002617 // put output stream into standby mode
2618 if (!mStandby) {
2619 mOutput->stream->common.standby(&mOutput->stream->common);
2620 }
2621 }
2622
2623 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002624 mWakeLockUids.clear();
2625 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002626
2627 ALOGV("Thread %p type %d exiting", this, mType);
2628 return false;
2629}
2630
Eric Laurentbfb1b832013-01-07 09:53:42 -08002631// removeTracks_l() must be called with ThreadBase::mLock held
2632void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2633{
2634 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002635 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636 for (size_t i=0 ; i<count ; i++) {
2637 const sp<Track>& track = tracksToRemove.itemAt(i);
2638 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002639 mWakeLockUids.remove(track->uid());
2640 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2642 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2643 if (chain != 0) {
2644 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2645 track->sessionId());
2646 chain->decActiveTrackCnt();
2647 }
2648 if (track->isTerminated()) {
2649 removeTrack_l(track);
2650 }
2651 }
2652 }
2653
2654}
Eric Laurent81784c32012-11-19 14:55:58 -08002655
Eric Laurentaccc1472013-09-20 09:36:34 -07002656status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2657{
2658 if (mNormalSink != 0) {
2659 return mNormalSink->getTimestamp(timestamp);
2660 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002661 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002662 uint64_t position64;
2663 int ret = mOutput->stream->get_presentation_position(
2664 mOutput->stream, &position64, &timestamp.mTime);
2665 if (ret == 0) {
2666 timestamp.mPosition = (uint32_t)position64;
2667 return NO_ERROR;
2668 }
2669 }
2670 return INVALID_OPERATION;
2671}
Eric Laurent1c333e22014-05-20 10:48:17 -07002672
2673status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2674 audio_patch_handle_t *handle)
2675{
2676 status_t status = NO_ERROR;
2677 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2678 // store new device and send to effects
2679 audio_devices_t type = AUDIO_DEVICE_NONE;
2680 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2681 type |= patch->sinks[i].ext.device.type;
2682 }
2683 mOutDevice = type;
2684 for (size_t i = 0; i < mEffectChains.size(); i++) {
2685 mEffectChains[i]->setDevice_l(mOutDevice);
2686 }
2687
2688 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2689 status = hwDevice->create_audio_patch(hwDevice,
2690 patch->num_sources,
2691 patch->sources,
2692 patch->num_sinks,
2693 patch->sinks,
2694 handle);
2695 } else {
2696 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2697 }
2698 return status;
2699}
2700
2701status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2702{
2703 status_t status = NO_ERROR;
2704 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2705 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2706 status = hwDevice->release_audio_patch(hwDevice, handle);
2707 } else {
2708 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2709 }
2710 return status;
2711}
2712
Eric Laurent81784c32012-11-19 14:55:58 -08002713// ----------------------------------------------------------------------------
2714
2715AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2716 audio_io_handle_t id, audio_devices_t device, type_t type)
2717 : PlaybackThread(audioFlinger, output, id, device, type),
2718 // mAudioMixer below
2719 // mFastMixer below
2720 mFastMixerFutex(0)
2721 // mOutputSink below
2722 // mPipeSink below
2723 // mNormalSink below
2724{
2725 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002726 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002727 "mFrameCount=%d, mNormalFrameCount=%d",
2728 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2729 mNormalFrameCount);
2730 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2731
2732 // FIXME - Current mixer implementation only supports stereo output
2733 if (mChannelCount != FCC_2) {
2734 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2735 }
2736
2737 // create an NBAIO sink for the HAL output stream, and negotiate
2738 mOutputSink = new AudioStreamOutSink(output->stream);
2739 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002740 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002741 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2742 ALOG_ASSERT(index == 0);
2743
2744 // initialize fast mixer depending on configuration
2745 bool initFastMixer;
2746 switch (kUseFastMixer) {
2747 case FastMixer_Never:
2748 initFastMixer = false;
2749 break;
2750 case FastMixer_Always:
2751 initFastMixer = true;
2752 break;
2753 case FastMixer_Static:
2754 case FastMixer_Dynamic:
2755 initFastMixer = mFrameCount < mNormalFrameCount;
2756 break;
2757 }
2758 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002759 audio_format_t fastMixerFormat;
2760 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2761 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2762 } else {
2763 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2764 }
2765 if (mFormat != fastMixerFormat) {
2766 // change our Sink format to accept our intermediate precision
2767 mFormat = fastMixerFormat;
2768 free(mSinkBuffer);
2769 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2770 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2771 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2772 }
Eric Laurent81784c32012-11-19 14:55:58 -08002773
2774 // create a MonoPipe to connect our submix to FastMixer
2775 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002776 // adjust format to match that of the Fast Mixer
2777 format.mFormat = fastMixerFormat;
2778 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2779
Eric Laurent81784c32012-11-19 14:55:58 -08002780 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2781 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2782 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2783 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2784 const NBAIO_Format offers[1] = {format};
2785 size_t numCounterOffers = 0;
2786 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2787 ALOG_ASSERT(index == 0);
2788 monoPipe->setAvgFrames((mScreenState & 1) ?
2789 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2790 mPipeSink = monoPipe;
2791
Glenn Kasten46909e72013-02-26 09:20:22 -08002792#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002793 if (mTeeSinkOutputEnabled) {
2794 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2795 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2796 numCounterOffers = 0;
2797 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2798 ALOG_ASSERT(index == 0);
2799 mTeeSink = teeSink;
2800 PipeReader *teeSource = new PipeReader(*teeSink);
2801 numCounterOffers = 0;
2802 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2803 ALOG_ASSERT(index == 0);
2804 mTeeSource = teeSource;
2805 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002806#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002807
2808 // create fast mixer and configure it initially with just one fast track for our submix
2809 mFastMixer = new FastMixer();
2810 FastMixerStateQueue *sq = mFastMixer->sq();
2811#ifdef STATE_QUEUE_DUMP
2812 sq->setObserverDump(&mStateQueueObserverDump);
2813 sq->setMutatorDump(&mStateQueueMutatorDump);
2814#endif
2815 FastMixerState *state = sq->begin();
2816 FastTrack *fastTrack = &state->mFastTracks[0];
2817 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2818 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2819 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002820 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2821 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002822 fastTrack->mGeneration++;
2823 state->mFastTracksGen++;
2824 state->mTrackMask = 1;
2825 // fast mixer will use the HAL output sink
2826 state->mOutputSink = mOutputSink.get();
2827 state->mOutputSinkGen++;
2828 state->mFrameCount = mFrameCount;
2829 state->mCommand = FastMixerState::COLD_IDLE;
2830 // already done in constructor initialization list
2831 //mFastMixerFutex = 0;
2832 state->mColdFutexAddr = &mFastMixerFutex;
2833 state->mColdGen++;
2834 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002835#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002836 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002837#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002838 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2839 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002840 sq->end();
2841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2842
2843 // start the fast mixer
2844 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2845 pid_t tid = mFastMixer->getTid();
2846 int 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
2852#ifdef AUDIO_WATCHDOG
2853 // create and start the watchdog
2854 mAudioWatchdog = new AudioWatchdog();
2855 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2856 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2857 tid = mAudioWatchdog->getTid();
2858 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2859 if (err != 0) {
2860 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2861 kPriorityFastMixer, getpid_cached, tid, err);
2862 }
2863#endif
2864
Eric Laurent81784c32012-11-19 14:55:58 -08002865 }
2866
2867 switch (kUseFastMixer) {
2868 case FastMixer_Never:
2869 case FastMixer_Dynamic:
2870 mNormalSink = mOutputSink;
2871 break;
2872 case FastMixer_Always:
2873 mNormalSink = mPipeSink;
2874 break;
2875 case FastMixer_Static:
2876 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2877 break;
2878 }
2879}
2880
2881AudioFlinger::MixerThread::~MixerThread()
2882{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002883 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002884 FastMixerStateQueue *sq = mFastMixer->sq();
2885 FastMixerState *state = sq->begin();
2886 if (state->mCommand == FastMixerState::COLD_IDLE) {
2887 int32_t old = android_atomic_inc(&mFastMixerFutex);
2888 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002889 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002890 }
2891 }
2892 state->mCommand = FastMixerState::EXIT;
2893 sq->end();
2894 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2895 mFastMixer->join();
2896 // Though the fast mixer thread has exited, it's state queue is still valid.
2897 // We'll use that extract the final state which contains one remaining fast track
2898 // corresponding to our sub-mix.
2899 state = sq->begin();
2900 ALOG_ASSERT(state->mTrackMask == 1);
2901 FastTrack *fastTrack = &state->mFastTracks[0];
2902 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2903 delete fastTrack->mBufferProvider;
2904 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002905 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002906#ifdef AUDIO_WATCHDOG
2907 if (mAudioWatchdog != 0) {
2908 mAudioWatchdog->requestExit();
2909 mAudioWatchdog->requestExitAndWait();
2910 mAudioWatchdog.clear();
2911 }
2912#endif
2913 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002914 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002915 delete mAudioMixer;
2916}
2917
2918
2919uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2920{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002921 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002922 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2923 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2924 }
2925 return latency;
2926}
2927
2928
2929void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2930{
2931 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2932}
2933
Eric Laurentbfb1b832013-01-07 09:53:42 -08002934ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002935{
2936 // FIXME we should only do one push per cycle; confirm this is true
2937 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002938 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002939 FastMixerStateQueue *sq = mFastMixer->sq();
2940 FastMixerState *state = sq->begin();
2941 if (state->mCommand != FastMixerState::MIX_WRITE &&
2942 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2943 if (state->mCommand == FastMixerState::COLD_IDLE) {
2944 int32_t old = android_atomic_inc(&mFastMixerFutex);
2945 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002946 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002947 }
2948#ifdef AUDIO_WATCHDOG
2949 if (mAudioWatchdog != 0) {
2950 mAudioWatchdog->resume();
2951 }
2952#endif
2953 }
2954 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002955 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2956 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002957 sq->end();
2958 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2959 if (kUseFastMixer == FastMixer_Dynamic) {
2960 mNormalSink = mPipeSink;
2961 }
2962 } else {
2963 sq->end(false /*didModify*/);
2964 }
2965 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002966 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002967}
2968
2969void AudioFlinger::MixerThread::threadLoop_standby()
2970{
2971 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002972 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002973 FastMixerStateQueue *sq = mFastMixer->sq();
2974 FastMixerState *state = sq->begin();
2975 if (!(state->mCommand & FastMixerState::IDLE)) {
2976 state->mCommand = FastMixerState::COLD_IDLE;
2977 state->mColdFutexAddr = &mFastMixerFutex;
2978 state->mColdGen++;
2979 mFastMixerFutex = 0;
2980 sq->end();
2981 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2982 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2983 if (kUseFastMixer == FastMixer_Dynamic) {
2984 mNormalSink = mOutputSink;
2985 }
2986#ifdef AUDIO_WATCHDOG
2987 if (mAudioWatchdog != 0) {
2988 mAudioWatchdog->pause();
2989 }
2990#endif
2991 } else {
2992 sq->end(false /*didModify*/);
2993 }
2994 }
2995 PlaybackThread::threadLoop_standby();
2996}
2997
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2999{
3000 return false;
3001}
3002
3003bool AudioFlinger::PlaybackThread::shouldStandby_l()
3004{
3005 return !mStandby;
3006}
3007
3008bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3009{
3010 Mutex::Autolock _l(mLock);
3011 return waitingAsyncCallback_l();
3012}
3013
Eric Laurent81784c32012-11-19 14:55:58 -08003014// shared by MIXER and DIRECT, overridden by DUPLICATING
3015void AudioFlinger::PlaybackThread::threadLoop_standby()
3016{
3017 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3018 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003019 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003020 // discard any pending drain or write ack by incrementing sequence
3021 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3022 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003024 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3025 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 }
Eric Laurent81784c32012-11-19 14:55:58 -08003027}
3028
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003029void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3030{
3031 ALOGV("signal playback thread");
3032 broadcast_l();
3033}
3034
Eric Laurent81784c32012-11-19 14:55:58 -08003035void AudioFlinger::MixerThread::threadLoop_mix()
3036{
3037 // obtain the presentation timestamp of the next output buffer
3038 int64_t pts;
3039 status_t status = INVALID_OPERATION;
3040
3041 if (mNormalSink != 0) {
3042 status = mNormalSink->getNextWriteTimestamp(&pts);
3043 } else {
3044 status = mOutputSink->getNextWriteTimestamp(&pts);
3045 }
3046
3047 if (status != NO_ERROR) {
3048 pts = AudioBufferProvider::kInvalidPTS;
3049 }
3050
3051 // mix buffers...
3052 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003053 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003054 // increase sleep time progressively when application underrun condition clears.
3055 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3056 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3057 // such that we would underrun the audio HAL.
3058 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3059 sleepTimeShift--;
3060 }
3061 sleepTime = 0;
3062 standbyTime = systemTime() + standbyDelay;
3063 //TODO: delay standby when effects have a tail
3064}
3065
3066void AudioFlinger::MixerThread::threadLoop_sleepTime()
3067{
3068 // If no tracks are ready, sleep once for the duration of an output
3069 // buffer size, then write 0s to the output
3070 if (sleepTime == 0) {
3071 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3072 sleepTime = activeSleepTime >> sleepTimeShift;
3073 if (sleepTime < kMinThreadSleepTimeUs) {
3074 sleepTime = kMinThreadSleepTimeUs;
3075 }
3076 // reduce sleep time in case of consecutive application underruns to avoid
3077 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3078 // duration we would end up writing less data than needed by the audio HAL if
3079 // the condition persists.
3080 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3081 sleepTimeShift++;
3082 }
3083 } else {
3084 sleepTime = idleSleepTime;
3085 }
3086 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003087 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3088 // before effects processing or output.
3089 if (mMixerBufferValid) {
3090 memset(mMixerBuffer, 0, mMixerBufferSize);
3091 } else {
3092 memset(mSinkBuffer, 0, mSinkBufferSize);
3093 }
Eric Laurent81784c32012-11-19 14:55:58 -08003094 sleepTime = 0;
3095 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3096 "anticipated start");
3097 }
3098 // TODO add standby time extension fct of effect tail
3099}
3100
3101// prepareTracks_l() must be called with ThreadBase::mLock held
3102AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3103 Vector< sp<Track> > *tracksToRemove)
3104{
3105
3106 mixer_state mixerStatus = MIXER_IDLE;
3107 // find out which tracks need to be processed
3108 size_t count = mActiveTracks.size();
3109 size_t mixedTracks = 0;
3110 size_t tracksWithEffect = 0;
3111 // counts only _active_ fast tracks
3112 size_t fastTracks = 0;
3113 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3114
3115 float masterVolume = mMasterVolume;
3116 bool masterMute = mMasterMute;
3117
3118 if (masterMute) {
3119 masterVolume = 0;
3120 }
3121 // Delegate master volume control to effect in output mix effect chain if needed
3122 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3123 if (chain != 0) {
3124 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3125 chain->setVolume_l(&v, &v);
3126 masterVolume = (float)((v + (1 << 23)) >> 24);
3127 chain.clear();
3128 }
3129
3130 // prepare a new state to push
3131 FastMixerStateQueue *sq = NULL;
3132 FastMixerState *state = NULL;
3133 bool didModify = false;
3134 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003135 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003136 sq = mFastMixer->sq();
3137 state = sq->begin();
3138 }
3139
Andy Hung69aed5f2014-02-25 17:24:40 -08003140 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003141 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003142
Eric Laurent81784c32012-11-19 14:55:58 -08003143 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003144 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003145 if (t == 0) {
3146 continue;
3147 }
3148
3149 // this const just means the local variable doesn't change
3150 Track* const track = t.get();
3151
3152 // process fast tracks
3153 if (track->isFastTrack()) {
3154
3155 // It's theoretically possible (though unlikely) for a fast track to be created
3156 // and then removed within the same normal mix cycle. This is not a problem, as
3157 // the track never becomes active so it's fast mixer slot is never touched.
3158 // The converse, of removing an (active) track and then creating a new track
3159 // at the identical fast mixer slot within the same normal mix cycle,
3160 // is impossible because the slot isn't marked available until the end of each cycle.
3161 int j = track->mFastIndex;
3162 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3163 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3164 FastTrack *fastTrack = &state->mFastTracks[j];
3165
3166 // Determine whether the track is currently in underrun condition,
3167 // and whether it had a recent underrun.
3168 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3169 FastTrackUnderruns underruns = ftDump->mUnderruns;
3170 uint32_t recentFull = (underruns.mBitFields.mFull -
3171 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3172 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3173 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3174 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3175 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3176 uint32_t recentUnderruns = recentPartial + recentEmpty;
3177 track->mObservedUnderruns = underruns;
3178 // don't count underruns that occur while stopping or pausing
3179 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003180 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3181 recentUnderruns > 0) {
3182 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3183 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003184 }
3185
3186 // This is similar to the state machine for normal tracks,
3187 // with a few modifications for fast tracks.
3188 bool isActive = true;
3189 switch (track->mState) {
3190 case TrackBase::STOPPING_1:
3191 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003193 track->mState = TrackBase::STOPPING_2;
3194 }
3195 break;
3196 case TrackBase::PAUSING:
3197 // ramp down is not yet implemented
3198 track->setPaused();
3199 break;
3200 case TrackBase::RESUMING:
3201 // ramp up is not yet implemented
3202 track->mState = TrackBase::ACTIVE;
3203 break;
3204 case TrackBase::ACTIVE:
3205 if (recentFull > 0 || recentPartial > 0) {
3206 // track has provided at least some frames recently: reset retry count
3207 track->mRetryCount = kMaxTrackRetries;
3208 }
3209 if (recentUnderruns == 0) {
3210 // no recent underruns: stay active
3211 break;
3212 }
3213 // there has recently been an underrun of some kind
3214 if (track->sharedBuffer() == 0) {
3215 // were any of the recent underruns "empty" (no frames available)?
3216 if (recentEmpty == 0) {
3217 // no, then ignore the partial underruns as they are allowed indefinitely
3218 break;
3219 }
3220 // there has recently been an "empty" underrun: decrement the retry counter
3221 if (--(track->mRetryCount) > 0) {
3222 break;
3223 }
3224 // indicate to client process that the track was disabled because of underrun;
3225 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003226 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003227 // remove from active list, but state remains ACTIVE [confusing but true]
3228 isActive = false;
3229 break;
3230 }
3231 // fall through
3232 case TrackBase::STOPPING_2:
3233 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003234 case TrackBase::STOPPED:
3235 case TrackBase::FLUSHED: // flush() while active
3236 // Check for presentation complete if track is inactive
3237 // We have consumed all the buffers of this track.
3238 // This would be incomplete if we auto-paused on underrun
3239 {
3240 size_t audioHALFrames =
3241 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3242 size_t framesWritten = mBytesWritten / mFrameSize;
3243 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3244 // track stays in active list until presentation is complete
3245 break;
3246 }
3247 }
3248 if (track->isStopping_2()) {
3249 track->mState = TrackBase::STOPPED;
3250 }
3251 if (track->isStopped()) {
3252 // Can't reset directly, as fast mixer is still polling this track
3253 // track->reset();
3254 // So instead mark this track as needing to be reset after push with ack
3255 resetMask |= 1 << i;
3256 }
3257 isActive = false;
3258 break;
3259 case TrackBase::IDLE:
3260 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003261 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003262 }
3263
3264 if (isActive) {
3265 // was it previously inactive?
3266 if (!(state->mTrackMask & (1 << j))) {
3267 ExtendedAudioBufferProvider *eabp = track;
3268 VolumeProvider *vp = track;
3269 fastTrack->mBufferProvider = eabp;
3270 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003271 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003272 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003273 fastTrack->mGeneration++;
3274 state->mTrackMask |= 1 << j;
3275 didModify = true;
3276 // no acknowledgement required for newly active tracks
3277 }
3278 // cache the combined master volume and stream type volume for fast mixer; this
3279 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003280 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003281 ++fastTracks;
3282 } else {
3283 // was it previously active?
3284 if (state->mTrackMask & (1 << j)) {
3285 fastTrack->mBufferProvider = NULL;
3286 fastTrack->mGeneration++;
3287 state->mTrackMask &= ~(1 << j);
3288 didModify = true;
3289 // If any fast tracks were removed, we must wait for acknowledgement
3290 // because we're about to decrement the last sp<> on those tracks.
3291 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3292 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003293 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003294 }
3295 tracksToRemove->add(track);
3296 // Avoids a misleading display in dumpsys
3297 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3298 }
3299 continue;
3300 }
3301
3302 { // local variable scope to avoid goto warning
3303
3304 audio_track_cblk_t* cblk = track->cblk();
3305
3306 // The first time a track is added we wait
3307 // for all its buffers to be filled before processing it
3308 int name = track->name();
3309 // make sure that we have enough frames to mix one full buffer.
3310 // enforce this condition only once to enable draining the buffer in case the client
3311 // app does not call stop() and relies on underrun to stop:
3312 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3313 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003314 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003315 uint32_t sr = track->sampleRate();
3316 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003317 desiredFrames = mNormalFrameCount;
3318 } else {
3319 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003320 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003321 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003322 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003323 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003324#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003325 // the minimum track buffer size is normally twice the number of frames necessary
3326 // to fill one buffer and the resampler should not leave more than one buffer worth
3327 // of unreleased frames after each pass, but just in case...
3328 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003329#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003330 }
Eric Laurent81784c32012-11-19 14:55:58 -08003331 uint32_t minFrames = 1;
3332 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3333 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003334 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003335 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003336
3337 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003338 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003339 !track->isPaused() && !track->isTerminated())
3340 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003341 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003342
3343 mixedTracks++;
3344
Andy Hung69aed5f2014-02-25 17:24:40 -08003345 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3346 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003347 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003348 if (track->mainBuffer() != mSinkBuffer &&
3349 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003350 if (mEffectBufferEnabled) {
3351 mEffectBufferValid = true; // Later can set directly.
3352 }
Eric Laurent81784c32012-11-19 14:55:58 -08003353 chain = getEffectChain_l(track->sessionId());
3354 // Delegate volume control to effect in track effect chain if needed
3355 if (chain != 0) {
3356 tracksWithEffect++;
3357 } else {
3358 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3359 "session %d",
3360 name, track->sessionId());
3361 }
3362 }
3363
3364
3365 int param = AudioMixer::VOLUME;
3366 if (track->mFillingUpStatus == Track::FS_FILLED) {
3367 // no ramp for the first volume setting
3368 track->mFillingUpStatus = Track::FS_ACTIVE;
3369 if (track->mState == TrackBase::RESUMING) {
3370 track->mState = TrackBase::ACTIVE;
3371 param = AudioMixer::RAMP_VOLUME;
3372 }
3373 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003374 // FIXME should not make a decision based on mServer
3375 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003376 // If the track is stopped before the first frame was mixed,
3377 // do not apply ramp
3378 param = AudioMixer::RAMP_VOLUME;
3379 }
3380
3381 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003382 uint32_t vl, vr; // in U8.24 integer format
3383 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003384 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003385 vl = vr = 0;
3386 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003387 if (track->isPausing()) {
3388 track->setPaused();
3389 }
3390 } else {
3391
3392 // read original volumes with volume control
3393 float typeVolume = mStreamTypes[track->streamType()].volume;
3394 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003395 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003396 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003397 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3398 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003399 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003400 if (vlf > GAIN_FLOAT_UNITY) {
3401 ALOGV("Track left volume out of range: %.3g", vlf);
3402 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003403 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003404 if (vrf > GAIN_FLOAT_UNITY) {
3405 ALOGV("Track right volume out of range: %.3g", vrf);
3406 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003407 }
3408 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003409 vlf *= v;
3410 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003411 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003412 // then derive vl and vr as U8.24 versions for the effect chain
3413 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3414 vl = (uint32_t) (scaleto8_24 * vlf);
3415 vr = (uint32_t) (scaleto8_24 * vrf);
3416 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003417 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003418 // send level comes from shared memory and so may be corrupt
3419 if (sendLevel > MAX_GAIN_INT) {
3420 ALOGV("Track send level out of range: %04X", sendLevel);
3421 sendLevel = MAX_GAIN_INT;
3422 }
Andy Hung6be49402014-05-30 10:42:03 -07003423 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3424 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003425 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003426
Eric Laurent81784c32012-11-19 14:55:58 -08003427 // Delegate volume control to effect in track effect chain if needed
3428 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3429 // Do not ramp volume if volume is controlled by effect
3430 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003431 // Update remaining floating point volume levels
3432 vlf = (float)vl / (1 << 24);
3433 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003434 track->mHasVolumeController = true;
3435 } else {
3436 // force no volume ramp when volume controller was just disabled or removed
3437 // from effect chain to avoid volume spike
3438 if (track->mHasVolumeController) {
3439 param = AudioMixer::VOLUME;
3440 }
3441 track->mHasVolumeController = false;
3442 }
3443
Eric Laurent81784c32012-11-19 14:55:58 -08003444 // XXX: these things DON'T need to be done each time
3445 mAudioMixer->setBufferProvider(name, track);
3446 mAudioMixer->enable(name);
3447
Andy Hung6be49402014-05-30 10:42:03 -07003448 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3449 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3450 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003451 mAudioMixer->setParameter(
3452 name,
3453 AudioMixer::TRACK,
3454 AudioMixer::FORMAT, (void *)track->format());
3455 mAudioMixer->setParameter(
3456 name,
3457 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003458 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003459 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3460 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003461 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003462 if (reqSampleRate == 0) {
3463 reqSampleRate = mSampleRate;
3464 } else if (reqSampleRate > maxSampleRate) {
3465 reqSampleRate = maxSampleRate;
3466 }
Eric Laurent81784c32012-11-19 14:55:58 -08003467 mAudioMixer->setParameter(
3468 name,
3469 AudioMixer::RESAMPLE,
3470 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003471 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003472 /*
3473 * Select the appropriate output buffer for the track.
3474 *
Andy Hung98ef9782014-03-04 14:46:50 -08003475 * Tracks with effects go into their own effects chain buffer
3476 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003477 *
3478 * Other tracks can use mMixerBuffer for higher precision
3479 * channel accumulation. If this buffer is enabled
3480 * (mMixerBufferEnabled true), then selected tracks will accumulate
3481 * into it.
3482 *
3483 */
3484 if (mMixerBufferEnabled
3485 && (track->mainBuffer() == mSinkBuffer
3486 || track->mainBuffer() == mMixerBuffer)) {
3487 mAudioMixer->setParameter(
3488 name,
3489 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003490 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003491 mAudioMixer->setParameter(
3492 name,
3493 AudioMixer::TRACK,
3494 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3495 // TODO: override track->mainBuffer()?
3496 mMixerBufferValid = true;
3497 } else {
3498 mAudioMixer->setParameter(
3499 name,
3500 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003501 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003502 mAudioMixer->setParameter(
3503 name,
3504 AudioMixer::TRACK,
3505 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3506 }
Eric Laurent81784c32012-11-19 14:55:58 -08003507 mAudioMixer->setParameter(
3508 name,
3509 AudioMixer::TRACK,
3510 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3511
3512 // reset retry count
3513 track->mRetryCount = kMaxTrackRetries;
3514
3515 // If one track is ready, set the mixer ready if:
3516 // - the mixer was not ready during previous round OR
3517 // - no other track is not ready
3518 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3519 mixerStatus != MIXER_TRACKS_ENABLED) {
3520 mixerStatus = MIXER_TRACKS_READY;
3521 }
3522 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003523 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003524 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003525 }
Eric Laurent81784c32012-11-19 14:55:58 -08003526 // clear effect chain input buffer if an active track underruns to avoid sending
3527 // previous audio buffer again to effects
3528 chain = getEffectChain_l(track->sessionId());
3529 if (chain != 0) {
3530 chain->clearInputBuffer();
3531 }
3532
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003533 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003534 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3535 track->isStopped() || track->isPaused()) {
3536 // We have consumed all the buffers of this track.
3537 // Remove it from the list of active tracks.
3538 // TODO: use actual buffer filling status instead of latency when available from
3539 // audio HAL
3540 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3541 size_t framesWritten = mBytesWritten / mFrameSize;
3542 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3543 if (track->isStopped()) {
3544 track->reset();
3545 }
3546 tracksToRemove->add(track);
3547 }
3548 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003549 // No buffers for this track. Give it a few chances to
3550 // fill a buffer, then remove it from active list.
3551 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003552 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003553 tracksToRemove->add(track);
3554 // indicate to client process that the track was disabled because of underrun;
3555 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003556 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003557 // If one track is not ready, mark the mixer also not ready if:
3558 // - the mixer was ready during previous round OR
3559 // - no other track is ready
3560 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3561 mixerStatus != MIXER_TRACKS_READY) {
3562 mixerStatus = MIXER_TRACKS_ENABLED;
3563 }
3564 }
3565 mAudioMixer->disable(name);
3566 }
3567
3568 } // local variable scope to avoid goto warning
3569track_is_ready: ;
3570
3571 }
3572
3573 // Push the new FastMixer state if necessary
3574 bool pauseAudioWatchdog = false;
3575 if (didModify) {
3576 state->mFastTracksGen++;
3577 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3578 if (kUseFastMixer == FastMixer_Dynamic &&
3579 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3580 state->mCommand = FastMixerState::COLD_IDLE;
3581 state->mColdFutexAddr = &mFastMixerFutex;
3582 state->mColdGen++;
3583 mFastMixerFutex = 0;
3584 if (kUseFastMixer == FastMixer_Dynamic) {
3585 mNormalSink = mOutputSink;
3586 }
3587 // If we go into cold idle, need to wait for acknowledgement
3588 // so that fast mixer stops doing I/O.
3589 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3590 pauseAudioWatchdog = true;
3591 }
Eric Laurent81784c32012-11-19 14:55:58 -08003592 }
3593 if (sq != NULL) {
3594 sq->end(didModify);
3595 sq->push(block);
3596 }
3597#ifdef AUDIO_WATCHDOG
3598 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3599 mAudioWatchdog->pause();
3600 }
3601#endif
3602
3603 // Now perform the deferred reset on fast tracks that have stopped
3604 while (resetMask != 0) {
3605 size_t i = __builtin_ctz(resetMask);
3606 ALOG_ASSERT(i < count);
3607 resetMask &= ~(1 << i);
3608 sp<Track> t = mActiveTracks[i].promote();
3609 if (t == 0) {
3610 continue;
3611 }
3612 Track* track = t.get();
3613 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3614 track->reset();
3615 }
3616
3617 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003619
Andy Hung69aed5f2014-02-25 17:24:40 -08003620 // sink or mix buffer must be cleared if all tracks are connected to an
3621 // effect chain as in this case the mixer will not write to the sink or mix buffer
3622 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3624 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003625 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003626 if (mMixerBufferValid) {
3627 memset(mMixerBuffer, 0, mMixerBufferSize);
3628 // TODO: In testing, mSinkBuffer below need not be cleared because
3629 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3630 // after mixing.
3631 //
3632 // To enforce this guarantee:
3633 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3634 // (mixedTracks == 0 && fastTracks > 0))
3635 // must imply MIXER_TRACKS_READY.
3636 // Later, we may clear buffers regardless, and skip much of this logic.
3637 }
Andy Hung98ef9782014-03-04 14:46:50 -08003638 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3639 if (mEffectBufferValid) {
3640 memset(mEffectBuffer, 0, mEffectBufferSize);
3641 }
3642 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003643 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003644 }
3645
3646 // if any fast tracks, then status is ready
3647 mMixerStatusIgnoringFastTracks = mixerStatus;
3648 if (fastTracks > 0) {
3649 mixerStatus = MIXER_TRACKS_READY;
3650 }
3651 return mixerStatus;
3652}
3653
3654// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003655int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3656 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003657{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003658 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003659}
3660
3661// deleteTrackName_l() must be called with ThreadBase::mLock held
3662void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3663{
3664 ALOGV("remove track (%d) and delete from mixer", name);
3665 mAudioMixer->deleteTrackName(name);
3666}
3667
Eric Laurent10351942014-05-08 18:49:52 -07003668// checkForNewParameter_l() must be called with ThreadBase::mLock held
3669bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3670 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003671{
Eric Laurent81784c32012-11-19 14:55:58 -08003672 bool reconfig = false;
3673
Eric Laurent10351942014-05-08 18:49:52 -07003674 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003675
Eric Laurent10351942014-05-08 18:49:52 -07003676 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3677 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003678 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003679 FastMixerStateQueue *sq = mFastMixer->sq();
3680 FastMixerState *state = sq->begin();
3681 if (!(state->mCommand & FastMixerState::IDLE)) {
3682 previousCommand = state->mCommand;
3683 state->mCommand = FastMixerState::HOT_IDLE;
3684 sq->end();
3685 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3686 } else {
3687 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
Eric Laurent10351942014-05-08 18:49:52 -07003689 }
Eric Laurent81784c32012-11-19 14:55:58 -08003690
Eric Laurent10351942014-05-08 18:49:52 -07003691 AudioParameter param = AudioParameter(keyValuePair);
3692 int value;
3693 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3694 reconfig = true;
3695 }
3696 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3697 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3698 status = BAD_VALUE;
3699 } else {
3700 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003701 reconfig = true;
3702 }
Eric Laurent10351942014-05-08 18:49:52 -07003703 }
3704 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3705 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3706 status = BAD_VALUE;
3707 } else {
3708 // no need to save value, since it's constant
3709 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003710 }
Eric Laurent10351942014-05-08 18:49:52 -07003711 }
3712 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3713 // do not accept frame count changes if tracks are open as the track buffer
3714 // size depends on frame count and correct behavior would not be guaranteed
3715 // if frame count is changed after track creation
3716 if (!mTracks.isEmpty()) {
3717 status = INVALID_OPERATION;
3718 } else {
3719 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003720 }
Eric Laurent10351942014-05-08 18:49:52 -07003721 }
3722 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003723#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003724 // when changing the audio output device, call addBatteryData to notify
3725 // the change
3726 if (mOutDevice != value) {
3727 uint32_t params = 0;
3728 // check whether speaker is on
3729 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3730 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003731 }
Eric Laurent10351942014-05-08 18:49:52 -07003732
3733 audio_devices_t deviceWithoutSpeaker
3734 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3735 // check if any other device (except speaker) is on
3736 if (value & deviceWithoutSpeaker ) {
3737 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3738 }
3739
3740 if (params != 0) {
3741 addBatteryData(params);
3742 }
3743 }
Eric Laurent81784c32012-11-19 14:55:58 -08003744#endif
3745
Eric Laurent10351942014-05-08 18:49:52 -07003746 // forward device change to effects that have requested to be
3747 // aware of attached audio device.
3748 if (value != AUDIO_DEVICE_NONE) {
3749 mOutDevice = value;
3750 for (size_t i = 0; i < mEffectChains.size(); i++) {
3751 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003752 }
3753 }
Eric Laurent10351942014-05-08 18:49:52 -07003754 }
Eric Laurent81784c32012-11-19 14:55:58 -08003755
Eric Laurent10351942014-05-08 18:49:52 -07003756 if (status == NO_ERROR) {
3757 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3758 keyValuePair.string());
3759 if (!mStandby && status == INVALID_OPERATION) {
3760 mOutput->stream->common.standby(&mOutput->stream->common);
3761 mStandby = true;
3762 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003763 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003764 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
Eric Laurent10351942014-05-08 18:49:52 -07003766 if (status == NO_ERROR && reconfig) {
3767 readOutputParameters_l();
3768 delete mAudioMixer;
3769 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3770 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003771 int name = getTrackName_l(mTracks[i]->mChannelMask,
3772 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003773 if (name < 0) {
3774 break;
3775 }
3776 mTracks[i]->mName = name;
3777 }
3778 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3779 }
Eric Laurent81784c32012-11-19 14:55:58 -08003780 }
3781
3782 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003783 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 FastMixerStateQueue *sq = mFastMixer->sq();
3785 FastMixerState *state = sq->begin();
3786 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3787 state->mCommand = previousCommand;
3788 sq->end();
3789 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3790 }
3791
3792 return reconfig;
3793}
3794
3795
3796void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3797{
3798 const size_t SIZE = 256;
3799 char buffer[SIZE];
3800 String8 result;
3801
3802 PlaybackThread::dumpInternals(fd, args);
3803
Elliott Hughes87cebad2014-05-22 10:14:43 -07003804 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003805
3806 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003807 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003808 copy.dump(fd);
3809
3810#ifdef STATE_QUEUE_DUMP
3811 // Similar for state queue
3812 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3813 observerCopy.dump(fd);
3814 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3815 mutatorCopy.dump(fd);
3816#endif
3817
Glenn Kasten46909e72013-02-26 09:20:22 -08003818#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003819 // Write the tee output to a .wav file
3820 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003821#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003822
3823#ifdef AUDIO_WATCHDOG
3824 if (mAudioWatchdog != 0) {
3825 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3826 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3827 wdCopy.dump(fd);
3828 }
3829#endif
3830}
3831
3832uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3833{
3834 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3835}
3836
3837uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3838{
3839 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3840}
3841
3842void AudioFlinger::MixerThread::cacheParameters_l()
3843{
3844 PlaybackThread::cacheParameters_l();
3845
3846 // FIXME: Relaxed timing because of a certain device that can't meet latency
3847 // Should be reduced to 2x after the vendor fixes the driver issue
3848 // increase threshold again due to low power audio mode. The way this warning
3849 // threshold is calculated and its usefulness should be reconsidered anyway.
3850 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3851}
3852
3853// ----------------------------------------------------------------------------
3854
3855AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3856 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3857 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3858 // mLeftVolFloat, mRightVolFloat
3859{
3860}
3861
Eric Laurentbfb1b832013-01-07 09:53:42 -08003862AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3863 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3864 ThreadBase::type_t type)
3865 : PlaybackThread(audioFlinger, output, id, device, type)
3866 // mLeftVolFloat, mRightVolFloat
3867{
3868}
3869
Eric Laurent81784c32012-11-19 14:55:58 -08003870AudioFlinger::DirectOutputThread::~DirectOutputThread()
3871{
3872}
3873
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3875{
3876 audio_track_cblk_t* cblk = track->cblk();
3877 float left, right;
3878
3879 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3880 left = right = 0;
3881 } else {
3882 float typeVolume = mStreamTypes[track->streamType()].volume;
3883 float v = mMasterVolume * typeVolume;
3884 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003885 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3886 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3887 if (left > GAIN_FLOAT_UNITY) {
3888 left = GAIN_FLOAT_UNITY;
3889 }
3890 left *= v;
3891 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3892 if (right > GAIN_FLOAT_UNITY) {
3893 right = GAIN_FLOAT_UNITY;
3894 }
3895 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 }
3897
3898 if (lastTrack) {
3899 if (left != mLeftVolFloat || right != mRightVolFloat) {
3900 mLeftVolFloat = left;
3901 mRightVolFloat = right;
3902
3903 // Convert volumes from float to 8.24
3904 uint32_t vl = (uint32_t)(left * (1 << 24));
3905 uint32_t vr = (uint32_t)(right * (1 << 24));
3906
3907 // Delegate volume control to effect in track effect chain if needed
3908 // only one effect chain can be present on DirectOutputThread, so if
3909 // there is one, the track is connected to it
3910 if (!mEffectChains.isEmpty()) {
3911 mEffectChains[0]->setVolume_l(&vl, &vr);
3912 left = (float)vl / (1 << 24);
3913 right = (float)vr / (1 << 24);
3914 }
3915 if (mOutput->stream->set_volume) {
3916 mOutput->stream->set_volume(mOutput->stream, left, right);
3917 }
3918 }
3919 }
3920}
3921
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3924 Vector< sp<Track> > *tracksToRemove
3925)
3926{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003927 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003928 mixer_state mixerStatus = MIXER_IDLE;
3929
3930 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003931 for (size_t i = 0; i < count; i++) {
3932 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003933 // The track died recently
3934 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003935 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003936 }
3937
3938 Track* const track = t.get();
3939 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003940 // Only consider last track started for volume and mixer state control.
3941 // In theory an older track could underrun and restart after the new one starts
3942 // but as we only care about the transition phase between two tracks on a
3943 // direct output, it is not a problem to ignore the underrun case.
3944 sp<Track> l = mLatestActiveTrack.promote();
3945 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003946
3947 // The first time a track is added we wait
3948 // for all its buffers to be filled before processing it
3949 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07003950 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003951 minFrames = mNormalFrameCount;
3952 } else {
3953 minFrames = 1;
3954 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003955
Eric Laurentab5cdba2014-06-09 17:22:27 -07003956 ALOGI("prepareTracks_l minFrames %d state %d frames ready %d, ",
3957 minFrames, track->mState, track->framesReady());
3958 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
3959 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08003960 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003961 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003962
3963 if (track->mFillingUpStatus == Track::FS_FILLED) {
3964 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003965 // make sure processVolume_l() will apply new volume even if 0
3966 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003967 if (track->mState == TrackBase::RESUMING) {
3968 track->mState = TrackBase::ACTIVE;
3969 }
3970 }
3971
3972 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973 processVolume_l(track, last);
3974 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003975 // reset retry count
3976 track->mRetryCount = kMaxTrackRetriesDirect;
3977 mActiveTrack = t;
3978 mixerStatus = MIXER_TRACKS_READY;
3979 }
Eric Laurent81784c32012-11-19 14:55:58 -08003980 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003981 // clear effect chain input buffer if the last active track started underruns
3982 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003983 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003984 mEffectChains[0]->clearInputBuffer();
3985 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07003986 if (track->isStopping_1()) {
3987 track->mState = TrackBase::STOPPING_2;
3988 }
3989 if ((track->sharedBuffer() != 0) || track->isStopped() ||
3990 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003991 // We have consumed all the buffers of this track.
3992 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07003993 size_t audioHALFrames;
3994 if (audio_is_linear_pcm(mFormat)) {
3995 audioHALFrames = (latency_l() * mSampleRate) / 1000;
3996 } else {
3997 audioHALFrames = 0;
3998 }
3999
Eric Laurent81784c32012-11-19 14:55:58 -08004000 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004001 if (mStandby || !last ||
4002 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004003 if (track->isStopping_2()) {
4004 track->mState = TrackBase::STOPPED;
4005 }
Eric Laurent81784c32012-11-19 14:55:58 -08004006 if (track->isStopped()) {
4007 track->reset();
4008 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004009 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004010 }
4011 } else {
4012 // No buffers for this track. Give it a few chances to
4013 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004014 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004015 if (--(track->mRetryCount) <= 0) {
4016 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004017 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004018 // indicate to client process that the track was disabled because of underrun;
4019 // it will then automatically call start() when data is available
4020 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004021 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004022 mixerStatus = MIXER_TRACKS_ENABLED;
4023 }
4024 }
4025 }
4026 }
4027
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004029 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004030
4031 return mixerStatus;
4032}
4033
4034void AudioFlinger::DirectOutputThread::threadLoop_mix()
4035{
Eric Laurent81784c32012-11-19 14:55:58 -08004036 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004037 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004038 // output audio to hardware
4039 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004040 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004041 buffer.frameCount = frameCount;
4042 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004043 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004044 memset(curBuf, 0, frameCount * mFrameSize);
4045 break;
4046 }
4047 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4048 frameCount -= buffer.frameCount;
4049 curBuf += buffer.frameCount * mFrameSize;
4050 mActiveTrack->releaseBuffer(&buffer);
4051 }
Andy Hung2098f272014-02-27 14:00:06 -08004052 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004053 sleepTime = 0;
4054 standbyTime = systemTime() + standbyDelay;
4055 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004056}
4057
4058void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4059{
4060 if (sleepTime == 0) {
4061 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4062 sleepTime = activeSleepTime;
4063 } else {
4064 sleepTime = idleSleepTime;
4065 }
4066 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004067 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004068 sleepTime = 0;
4069 }
4070}
4071
4072// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004073int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004074 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004075{
4076 return 0;
4077}
4078
4079// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004080void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004081{
4082}
4083
Eric Laurent10351942014-05-08 18:49:52 -07004084// checkForNewParameter_l() must be called with ThreadBase::mLock held
4085bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4086 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004087{
4088 bool reconfig = false;
4089
Eric Laurent10351942014-05-08 18:49:52 -07004090 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004091
Eric Laurent10351942014-05-08 18:49:52 -07004092 AudioParameter param = AudioParameter(keyValuePair);
4093 int value;
4094 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4095 // forward device change to effects that have requested to be
4096 // aware of attached audio device.
4097 if (value != AUDIO_DEVICE_NONE) {
4098 mOutDevice = value;
4099 for (size_t i = 0; i < mEffectChains.size(); i++) {
4100 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004101 }
4102 }
Eric Laurent81784c32012-11-19 14:55:58 -08004103 }
Eric Laurent10351942014-05-08 18:49:52 -07004104 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4105 // do not accept frame count changes if tracks are open as the track buffer
4106 // size depends on frame count and correct behavior would not be garantied
4107 // if frame count is changed after track creation
4108 if (!mTracks.isEmpty()) {
4109 status = INVALID_OPERATION;
4110 } else {
4111 reconfig = true;
4112 }
4113 }
4114 if (status == NO_ERROR) {
4115 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4116 keyValuePair.string());
4117 if (!mStandby && status == INVALID_OPERATION) {
4118 mOutput->stream->common.standby(&mOutput->stream->common);
4119 mStandby = true;
4120 mBytesWritten = 0;
4121 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4122 keyValuePair.string());
4123 }
4124 if (status == NO_ERROR && reconfig) {
4125 readOutputParameters_l();
4126 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4127 }
4128 }
4129
Eric Laurent81784c32012-11-19 14:55:58 -08004130 return reconfig;
4131}
4132
4133uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4134{
4135 uint32_t time;
4136 if (audio_is_linear_pcm(mFormat)) {
4137 time = PlaybackThread::activeSleepTimeUs();
4138 } else {
4139 time = 10000;
4140 }
4141 return time;
4142}
4143
4144uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4145{
4146 uint32_t time;
4147 if (audio_is_linear_pcm(mFormat)) {
4148 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4149 } else {
4150 time = 10000;
4151 }
4152 return time;
4153}
4154
4155uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4156{
4157 uint32_t time;
4158 if (audio_is_linear_pcm(mFormat)) {
4159 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4160 } else {
4161 time = 10000;
4162 }
4163 return time;
4164}
4165
4166void AudioFlinger::DirectOutputThread::cacheParameters_l()
4167{
4168 PlaybackThread::cacheParameters_l();
4169
4170 // use shorter standby delay as on normal output to release
4171 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004172 if (audio_is_linear_pcm(mFormat)) {
4173 standbyDelay = microseconds(activeSleepTime*2);
4174 } else {
4175 standbyDelay = kOffloadStandbyDelayNs;
4176 }
Eric Laurent81784c32012-11-19 14:55:58 -08004177}
4178
4179// ----------------------------------------------------------------------------
4180
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004182 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004184 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004185 mWriteAckSequence(0),
4186 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187{
4188}
4189
4190AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4191{
4192}
4193
4194void AudioFlinger::AsyncCallbackThread::onFirstRef()
4195{
4196 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4197}
4198
4199bool AudioFlinger::AsyncCallbackThread::threadLoop()
4200{
4201 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004202 uint32_t writeAckSequence;
4203 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204
4205 {
4206 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004207 while (!((mWriteAckSequence & 1) ||
4208 (mDrainSequence & 1) ||
4209 exitPending())) {
4210 mWaitWorkCV.wait(mLock);
4211 }
4212
Eric Laurentbfb1b832013-01-07 09:53:42 -08004213 if (exitPending()) {
4214 break;
4215 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004216 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4217 mWriteAckSequence, mDrainSequence);
4218 writeAckSequence = mWriteAckSequence;
4219 mWriteAckSequence &= ~1;
4220 drainSequence = mDrainSequence;
4221 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004222 }
4223 {
Eric Laurent4de95592013-09-26 15:28:21 -07004224 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4225 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004226 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004227 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004228 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004229 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004230 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004231 }
4232 }
4233 }
4234 }
4235 return false;
4236}
4237
4238void AudioFlinger::AsyncCallbackThread::exit()
4239{
4240 ALOGV("AsyncCallbackThread::exit");
4241 Mutex::Autolock _l(mLock);
4242 requestExit();
4243 mWaitWorkCV.broadcast();
4244}
4245
Eric Laurent3b4529e2013-09-05 18:09:19 -07004246void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004247{
4248 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004249 // bit 0 is cleared
4250 mWriteAckSequence = sequence << 1;
4251}
4252
4253void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4254{
4255 Mutex::Autolock _l(mLock);
4256 // ignore unexpected callbacks
4257 if (mWriteAckSequence & 2) {
4258 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004259 mWaitWorkCV.signal();
4260 }
4261}
4262
Eric Laurent3b4529e2013-09-05 18:09:19 -07004263void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264{
4265 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004266 // bit 0 is cleared
4267 mDrainSequence = sequence << 1;
4268}
4269
4270void AudioFlinger::AsyncCallbackThread::resetDraining()
4271{
4272 Mutex::Autolock _l(mLock);
4273 // ignore unexpected callbacks
4274 if (mDrainSequence & 2) {
4275 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276 mWaitWorkCV.signal();
4277 }
4278}
4279
4280
4281// ----------------------------------------------------------------------------
4282AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4283 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4284 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4285 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004286 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004287 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288{
Eric Laurentfd477972013-10-25 18:10:40 -07004289 //FIXME: mStandby should be set to true by ThreadBase constructor
4290 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291}
4292
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293void AudioFlinger::OffloadThread::threadLoop_exit()
4294{
4295 if (mFlushPending || mHwPaused) {
4296 // If a flush is pending or track was paused, just discard buffered data
4297 flushHw_l();
4298 } else {
4299 mMixerStatus = MIXER_DRAIN_ALL;
4300 threadLoop_drain();
4301 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004302 if (mUseAsyncWrite) {
4303 ALOG_ASSERT(mCallbackThread != 0);
4304 mCallbackThread->exit();
4305 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 PlaybackThread::threadLoop_exit();
4307}
4308
4309AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4310 Vector< sp<Track> > *tracksToRemove
4311)
4312{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004313 size_t count = mActiveTracks.size();
4314
4315 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004316 bool doHwPause = false;
4317 bool doHwResume = false;
4318
Eric Laurentede6c3b2013-09-19 14:37:46 -07004319 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4320
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 // find out which tracks need to be processed
4322 for (size_t i = 0; i < count; i++) {
4323 sp<Track> t = mActiveTracks[i].promote();
4324 // The track died recently
4325 if (t == 0) {
4326 continue;
4327 }
4328 Track* const track = t.get();
4329 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004330 // Only consider last track started for volume and mixer state control.
4331 // In theory an older track could underrun and restart after the new one starts
4332 // but as we only care about the transition phase between two tracks on a
4333 // direct output, it is not a problem to ignore the underrun case.
4334 sp<Track> l = mLatestActiveTrack.promote();
4335 bool last = l.get() == track;
4336
Haynes Mathew George7844f672014-01-15 12:32:55 -08004337 if (track->isInvalid()) {
4338 ALOGW("An invalidated track shouldn't be in active list");
4339 tracksToRemove->add(track);
4340 continue;
4341 }
4342
4343 if (track->mState == TrackBase::IDLE) {
4344 ALOGW("An idle track shouldn't be in active list");
4345 continue;
4346 }
4347
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348 if (track->isPausing()) {
4349 track->setPaused();
4350 if (last) {
4351 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004352 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004353 mHwPaused = true;
4354 }
4355 // If we were part way through writing the mixbuffer to
4356 // the HAL we must save this until we resume
4357 // BUG - this will be wrong if a different track is made active,
4358 // in that case we want to discard the pending data in the
4359 // mixbuffer and tell the client to present it again when the
4360 // track is resumed
4361 mPausedWriteLength = mCurrentWriteLength;
4362 mPausedBytesRemaining = mBytesRemaining;
4363 mBytesRemaining = 0; // stop writing
4364 }
4365 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004366 } else if (track->isFlushPending()) {
4367 track->flushAck();
4368 if (last) {
4369 mFlushPending = true;
4370 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004371 } else if (track->isResumePending()){
4372 track->resumeAck();
4373 if (last) {
4374 if (mPausedBytesRemaining) {
4375 // Need to continue write that was interrupted
4376 mCurrentWriteLength = mPausedWriteLength;
4377 mBytesRemaining = mPausedBytesRemaining;
4378 mPausedBytesRemaining = 0;
4379 }
4380 if (mHwPaused) {
4381 doHwResume = true;
4382 mHwPaused = false;
4383 // threadLoop_mix() will handle the case that we need to
4384 // resume an interrupted write
4385 }
4386 // enable write to audio HAL
4387 sleepTime = 0;
4388
4389 // Do not handle new data in this iteration even if track->framesReady()
4390 mixerStatus = MIXER_TRACKS_ENABLED;
4391 }
4392 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004393 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004394 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004395 if (track->mFillingUpStatus == Track::FS_FILLED) {
4396 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004397 // make sure processVolume_l() will apply new volume even if 0
4398 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 }
4400
4401 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004402 sp<Track> previousTrack = mPreviousTrack.promote();
4403 if (previousTrack != 0) {
4404 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004405 // Flush any data still being written from last track
4406 mBytesRemaining = 0;
4407 if (mPausedBytesRemaining) {
4408 // Last track was paused so we also need to flush saved
4409 // mixbuffer state and invalidate track so that it will
4410 // re-submit that unwritten data when it is next resumed
4411 mPausedBytesRemaining = 0;
4412 // Invalidate is a bit drastic - would be more efficient
4413 // to have a flag to tell client that some of the
4414 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004415 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004416 }
4417 // flush data already sent to the DSP if changing audio session as audio
4418 // comes from a different source. Also invalidate previous track to force a
4419 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004420 if (previousTrack->sessionId() != track->sessionId()) {
4421 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004422 }
4423 }
4424 }
4425 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426 // reset retry count
4427 track->mRetryCount = kMaxTrackRetriesOffload;
4428 mActiveTrack = t;
4429 mixerStatus = MIXER_TRACKS_READY;
4430 }
4431 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004432 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004433 if (track->isStopping_1()) {
4434 // Hardware buffer can hold a large amount of audio so we must
4435 // wait for all current track's data to drain before we say
4436 // that the track is stopped.
4437 if (mBytesRemaining == 0) {
4438 // Only start draining when all data in mixbuffer
4439 // has been written
4440 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4441 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004442 // do not drain if no data was ever sent to HAL (mStandby == true)
4443 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004444 // do not modify drain sequence if we are already draining. This happens
4445 // when resuming from pause after drain.
4446 if ((mDrainSequence & 1) == 0) {
4447 sleepTime = 0;
4448 standbyTime = systemTime() + standbyDelay;
4449 mixerStatus = MIXER_DRAIN_TRACK;
4450 mDrainSequence += 2;
4451 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004452 if (mHwPaused) {
4453 // It is possible to move from PAUSED to STOPPING_1 without
4454 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004455 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 mHwPaused = false;
4457 }
4458 }
4459 }
4460 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004461 // Drain has completed or we are in standby, signal presentation complete
4462 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004463 track->mState = TrackBase::STOPPED;
4464 size_t audioHALFrames =
4465 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4466 size_t framesWritten =
4467 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4468 track->presentationComplete(framesWritten, audioHALFrames);
4469 track->reset();
4470 tracksToRemove->add(track);
4471 }
4472 } else {
4473 // No buffers for this track. Give it a few chances to
4474 // fill a buffer, then remove it from active list.
4475 if (--(track->mRetryCount) <= 0) {
4476 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4477 track->name());
4478 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004479 // indicate to client process that the track was disabled because of underrun;
4480 // it will then automatically call start() when data is available
4481 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482 } else if (last){
4483 mixerStatus = MIXER_TRACKS_ENABLED;
4484 }
4485 }
4486 }
4487 // compute volume for this track
4488 processVolume_l(track, last);
4489 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004490
Eric Laurentea0fade2013-10-04 16:23:48 -07004491 // make sure the pause/flush/resume sequence is executed in the right order.
4492 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4493 // before flush and then resume HW. This can happen in case of pause/flush/resume
4494 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004495 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004496 mOutput->stream->pause(mOutput->stream);
4497 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004498 if (mFlushPending) {
4499 flushHw_l();
4500 mFlushPending = false;
4501 }
Eric Laurentfd477972013-10-25 18:10:40 -07004502 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004503 mOutput->stream->resume(mOutput->stream);
4504 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004505
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 // remove all the tracks that need to be...
4507 removeTracks_l(*tracksToRemove);
4508
4509 return mixerStatus;
4510}
4511
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512// must be called with thread mutex locked
4513bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4514{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004515 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4516 mWriteAckSequence, mDrainSequence);
4517 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518 return true;
4519 }
4520 return false;
4521}
4522
4523// must be called with thread mutex locked
4524bool AudioFlinger::OffloadThread::shouldStandby_l()
4525{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004526 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527
4528 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4529 // after a timeout and we will enter standby then.
4530 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004531 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004532 }
4533
Glenn Kastene6f35b12013-08-19 09:58:50 -07004534 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004535}
4536
4537
4538bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4539{
4540 Mutex::Autolock _l(mLock);
4541 return waitingAsyncCallback_l();
4542}
4543
4544void AudioFlinger::OffloadThread::flushHw_l()
4545{
4546 mOutput->stream->flush(mOutput->stream);
4547 // Flush anything still waiting in the mixbuffer
4548 mCurrentWriteLength = 0;
4549 mBytesRemaining = 0;
4550 mPausedWriteLength = 0;
4551 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004552 mHwPaused = false;
4553
Eric Laurentbfb1b832013-01-07 09:53:42 -08004554 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004555 // discard any pending drain or write ack by incrementing sequence
4556 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4557 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004558 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004559 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4560 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 }
4562}
4563
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004564void AudioFlinger::OffloadThread::onAddNewTrack_l()
4565{
4566 sp<Track> previousTrack = mPreviousTrack.promote();
4567 sp<Track> latestTrack = mLatestActiveTrack.promote();
4568
4569 if (previousTrack != 0 && latestTrack != 0 &&
4570 (previousTrack->sessionId() != latestTrack->sessionId())) {
4571 mFlushPending = true;
4572 }
4573 PlaybackThread::onAddNewTrack_l();
4574}
4575
Eric Laurentbfb1b832013-01-07 09:53:42 -08004576// ----------------------------------------------------------------------------
4577
Eric Laurent81784c32012-11-19 14:55:58 -08004578AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4579 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4580 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4581 DUPLICATING),
4582 mWaitTimeMs(UINT_MAX)
4583{
4584 addOutputTrack(mainThread);
4585}
4586
4587AudioFlinger::DuplicatingThread::~DuplicatingThread()
4588{
4589 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4590 mOutputTracks[i]->destroy();
4591 }
4592}
4593
4594void AudioFlinger::DuplicatingThread::threadLoop_mix()
4595{
4596 // mix buffers...
4597 if (outputsReady(outputTracks)) {
4598 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4599 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004600 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004601 }
4602 sleepTime = 0;
4603 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004604 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004605 standbyTime = systemTime() + standbyDelay;
4606}
4607
4608void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4609{
4610 if (sleepTime == 0) {
4611 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4612 sleepTime = activeSleepTime;
4613 } else {
4614 sleepTime = idleSleepTime;
4615 }
4616 } else if (mBytesWritten != 0) {
4617 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4618 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004619 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004620 } else {
4621 // flush remaining overflow buffers in output tracks
4622 writeFrames = 0;
4623 }
4624 sleepTime = 0;
4625 }
4626}
4627
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004629{
4630 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004631 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4632 // for delivery downstream as needed. This in-place conversion is safe as
4633 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4634 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4635 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4636 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4637 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4638 }
4639 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004640 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004641 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004642 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004643}
4644
4645void AudioFlinger::DuplicatingThread::threadLoop_standby()
4646{
4647 // DuplicatingThread implements standby by stopping all tracks
4648 for (size_t i = 0; i < outputTracks.size(); i++) {
4649 outputTracks[i]->stop();
4650 }
4651}
4652
4653void AudioFlinger::DuplicatingThread::saveOutputTracks()
4654{
4655 outputTracks = mOutputTracks;
4656}
4657
4658void AudioFlinger::DuplicatingThread::clearOutputTracks()
4659{
4660 outputTracks.clear();
4661}
4662
4663void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4664{
4665 Mutex::Autolock _l(mLock);
4666 // FIXME explain this formula
4667 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004668 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4669 // due to current usage case and restrictions on the AudioBufferProvider.
4670 // Actual buffer conversion is done in threadLoop_write().
4671 //
4672 // TODO: This may change in the future, depending on multichannel
4673 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004674 OutputTrack *outputTrack = new OutputTrack(thread,
4675 this,
4676 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004677 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004678 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004679 frameCount,
4680 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004681 if (outputTrack->cblk() != NULL) {
4682 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4683 mOutputTracks.add(outputTrack);
4684 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4685 updateWaitTime_l();
4686 }
4687}
4688
4689void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4690{
4691 Mutex::Autolock _l(mLock);
4692 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4693 if (mOutputTracks[i]->thread() == thread) {
4694 mOutputTracks[i]->destroy();
4695 mOutputTracks.removeAt(i);
4696 updateWaitTime_l();
4697 return;
4698 }
4699 }
4700 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4701}
4702
4703// caller must hold mLock
4704void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4705{
4706 mWaitTimeMs = UINT_MAX;
4707 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4708 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4709 if (strong != 0) {
4710 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4711 if (waitTimeMs < mWaitTimeMs) {
4712 mWaitTimeMs = waitTimeMs;
4713 }
4714 }
4715 }
4716}
4717
4718
4719bool AudioFlinger::DuplicatingThread::outputsReady(
4720 const SortedVector< sp<OutputTrack> > &outputTracks)
4721{
4722 for (size_t i = 0; i < outputTracks.size(); i++) {
4723 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4724 if (thread == 0) {
4725 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4726 outputTracks[i].get());
4727 return false;
4728 }
4729 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4730 // see note at standby() declaration
4731 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4732 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4733 thread.get());
4734 return false;
4735 }
4736 }
4737 return true;
4738}
4739
4740uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4741{
4742 return (mWaitTimeMs * 1000) / 2;
4743}
4744
4745void AudioFlinger::DuplicatingThread::cacheParameters_l()
4746{
4747 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4748 updateWaitTime_l();
4749
4750 MixerThread::cacheParameters_l();
4751}
4752
4753// ----------------------------------------------------------------------------
4754// Record
4755// ----------------------------------------------------------------------------
4756
4757AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4758 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004759 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004760 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004761 audio_devices_t inDevice
4762#ifdef TEE_SINK
4763 , const sp<NBAIO_Sink>& teeSink
4764#endif
4765 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004766 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004767 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004768 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004769 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004770#ifdef TEE_SINK
4771 , mTeeSink(teeSink)
4772#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004773 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4774 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004775 // mFastCapture below
4776 , mFastCaptureFutex(0)
4777 // mInputSource
4778 // mPipeSink
4779 // mPipeSource
4780 , mPipeFramesP2(0)
4781 // mPipeMemory
4782 // mFastCaptureNBLogWriter
4783 , mFastTrackAvail(true)
Eric Laurent81784c32012-11-19 14:55:58 -08004784{
4785 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004786 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004787
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004788 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004789
4790 // create an NBAIO source for the HAL input stream, and negotiate
4791 mInputSource = new AudioStreamInSource(input->stream);
4792 size_t numCounterOffers = 0;
4793 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4794 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4795 ALOG_ASSERT(index == 0);
4796
4797 // initialize fast capture depending on configuration
4798 bool initFastCapture;
4799 switch (kUseFastCapture) {
4800 case FastCapture_Never:
4801 initFastCapture = false;
4802 break;
4803 case FastCapture_Always:
4804 initFastCapture = true;
4805 break;
4806 case FastCapture_Static:
4807 uint32_t primaryOutputSampleRate;
4808 {
4809 AutoMutex _l(audioFlinger->mHardwareLock);
4810 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4811 }
4812 initFastCapture =
4813 // either capture sample rate is same as (a reasonable) primary output sample rate
4814 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4815 (mSampleRate == primaryOutputSampleRate)) ||
4816 // or primary output sample rate is unknown, and capture sample rate is reasonable
4817 ((primaryOutputSampleRate == 0) &&
4818 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
4819 // and the buffer size is < 10 ms
4820 (mFrameCount * 1000) / mSampleRate < 10;
4821 break;
4822 // case FastCapture_Dynamic:
4823 }
4824
4825 if (initFastCapture) {
4826 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4827 NBAIO_Format format = mInputSource->format();
4828 size_t pipeFramesP2 = roundup(mFrameCount * 8);
4829 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4830 void *pipeBuffer;
4831 const sp<MemoryDealer> roHeap(readOnlyHeap());
4832 sp<IMemory> pipeMemory;
4833 if ((roHeap == 0) ||
4834 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4835 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4836 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4837 goto failed;
4838 }
4839 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4840 memset(pipeBuffer, 0, pipeSize);
4841 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4842 const NBAIO_Format offers[1] = {format};
4843 size_t numCounterOffers = 0;
4844 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4845 ALOG_ASSERT(index == 0);
4846 mPipeSink = pipe;
4847 PipeReader *pipeReader = new PipeReader(*pipe);
4848 numCounterOffers = 0;
4849 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4850 ALOG_ASSERT(index == 0);
4851 mPipeSource = pipeReader;
4852 mPipeFramesP2 = pipeFramesP2;
4853 mPipeMemory = pipeMemory;
4854
4855 // create fast capture
4856 mFastCapture = new FastCapture();
4857 FastCaptureStateQueue *sq = mFastCapture->sq();
4858#ifdef STATE_QUEUE_DUMP
4859 // FIXME
4860#endif
4861 FastCaptureState *state = sq->begin();
4862 state->mCblk = NULL;
4863 state->mInputSource = mInputSource.get();
4864 state->mInputSourceGen++;
4865 state->mPipeSink = pipe;
4866 state->mPipeSinkGen++;
4867 state->mFrameCount = mFrameCount;
4868 state->mCommand = FastCaptureState::COLD_IDLE;
4869 // already done in constructor initialization list
4870 //mFastCaptureFutex = 0;
4871 state->mColdFutexAddr = &mFastCaptureFutex;
4872 state->mColdGen++;
4873 state->mDumpState = &mFastCaptureDumpState;
4874#ifdef TEE_SINK
4875 // FIXME
4876#endif
4877 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4878 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4879 sq->end();
4880 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4881
4882 // start the fast capture
4883 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4884 pid_t tid = mFastCapture->getTid();
4885 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4886 if (err != 0) {
4887 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4888 kPriorityFastCapture, getpid_cached, tid, err);
4889 }
4890
4891#ifdef AUDIO_WATCHDOG
4892 // FIXME
4893#endif
4894
4895 }
4896failed: ;
4897
4898 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004899}
4900
4901
4902AudioFlinger::RecordThread::~RecordThread()
4903{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004904 if (mFastCapture != 0) {
4905 FastCaptureStateQueue *sq = mFastCapture->sq();
4906 FastCaptureState *state = sq->begin();
4907 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4908 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4909 if (old == -1) {
4910 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4911 }
4912 }
4913 state->mCommand = FastCaptureState::EXIT;
4914 sq->end();
4915 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4916 mFastCapture->join();
4917 mFastCapture.clear();
4918 }
4919 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004920 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004921 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004922}
4923
4924void AudioFlinger::RecordThread::onFirstRef()
4925{
4926 run(mName, PRIORITY_URGENT_AUDIO);
4927}
4928
Eric Laurent81784c32012-11-19 14:55:58 -08004929bool AudioFlinger::RecordThread::threadLoop()
4930{
Eric Laurent81784c32012-11-19 14:55:58 -08004931 nsecs_t lastWarning = 0;
4932
4933 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004934
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004935reacquire_wakelock:
4936 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004937 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004938 {
4939 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004940 size_t size = mActiveTracks.size();
4941 activeTracksGen = mActiveTracksGen;
4942 if (size > 0) {
4943 // FIXME an arbitrary choice
4944 activeTrack = mActiveTracks[0];
4945 acquireWakeLock_l(activeTrack->uid());
4946 if (size > 1) {
4947 SortedVector<int> tmp;
4948 for (size_t i = 0; i < size; i++) {
4949 tmp.add(mActiveTracks[i]->uid());
4950 }
4951 updateWakeLockUids_l(tmp);
4952 }
4953 } else {
4954 acquireWakeLock_l(-1);
4955 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004956 }
4957
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004958 // used to request a deferred sleep, to be executed later while mutex is unlocked
4959 uint32_t sleepUs = 0;
4960
4961 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004962 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004963 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004964
Glenn Kasten5edadd42013-08-14 16:30:49 -07004965 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004966 if (sleepUs > 0) {
4967 usleep(sleepUs);
4968 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004969 }
4970
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004971 // activeTracks accumulates a copy of a subset of mActiveTracks
4972 Vector< sp<RecordTrack> > activeTracks;
4973
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004974 // reference to the (first and only) fast track
4975 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07004976
Eric Laurent81784c32012-11-19 14:55:58 -08004977 { // scope for mLock
4978 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004979
Eric Laurent021cf962014-05-13 10:18:14 -07004980 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004981
Eric Laurent000a4192014-01-29 15:17:32 -08004982 // check exitPending here because checkForNewParameters_l() and
4983 // checkForNewParameters_l() can temporarily release mLock
4984 if (exitPending()) {
4985 break;
4986 }
4987
Glenn Kasten2b806402013-11-20 16:37:38 -08004988 // if no active track(s), then standby and release wakelock
4989 size_t size = mActiveTracks.size();
4990 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004991 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004992 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004993 releaseWakeLock_l();
4994 ALOGV("RecordThread: loop stopping");
4995 // go to sleep
4996 mWaitWorkCV.wait(mLock);
4997 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004998 goto reacquire_wakelock;
4999 }
5000
Glenn Kasten2b806402013-11-20 16:37:38 -08005001 if (mActiveTracksGen != activeTracksGen) {
5002 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005003 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005004 for (size_t i = 0; i < size; i++) {
5005 tmp.add(mActiveTracks[i]->uid());
5006 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005007 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005008 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005009
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005010 bool doBroadcast = false;
5011 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005012
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005013 activeTrack = mActiveTracks[i];
5014 if (activeTrack->isTerminated()) {
5015 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005016 mActiveTracks.remove(activeTrack);
5017 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005018 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005019 continue;
5020 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005021
5022 TrackBase::track_state activeTrackState = activeTrack->mState;
5023 switch (activeTrackState) {
5024
5025 case TrackBase::PAUSING:
5026 mActiveTracks.remove(activeTrack);
5027 mActiveTracksGen++;
5028 doBroadcast = true;
5029 size--;
5030 continue;
5031
5032 case TrackBase::STARTING_1:
5033 sleepUs = 10000;
5034 i++;
5035 continue;
5036
5037 case TrackBase::STARTING_2:
5038 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005039 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005040 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005041 break;
5042
5043 case TrackBase::ACTIVE:
5044 break;
5045
5046 case TrackBase::IDLE:
5047 i++;
5048 continue;
5049
5050 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005051 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005052 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005053
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005054 activeTracks.add(activeTrack);
5055 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005056
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005057 if (activeTrack->isFastTrack()) {
5058 ALOG_ASSERT(!mFastTrackAvail);
5059 ALOG_ASSERT(fastTrack == 0);
5060 fastTrack = activeTrack;
5061 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005062 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005063 if (doBroadcast) {
5064 mStartStopCond.broadcast();
5065 }
5066
5067 // sleep if there are no active tracks to process
5068 if (activeTracks.size() == 0) {
5069 if (sleepUs == 0) {
5070 sleepUs = kRecordThreadSleepUs;
5071 }
5072 continue;
5073 }
5074 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005075
Eric Laurent81784c32012-11-19 14:55:58 -08005076 lockEffectChains_l(effectChains);
5077 }
5078
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005079 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005080
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005081 size_t size = effectChains.size();
5082 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005083 // thread mutex is not locked, but effect chain is locked
5084 effectChains[i]->process_l();
5085 }
5086
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005087 // Start the fast capture if it's not already running
5088 if (mFastCapture != 0) {
5089 FastCaptureStateQueue *sq = mFastCapture->sq();
5090 FastCaptureState *state = sq->begin();
5091 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5092 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5093 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5094 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5095 if (old == -1) {
5096 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5097 }
5098 }
5099 state->mCommand = FastCaptureState::READ_WRITE;
5100#if 0 // FIXME
5101 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5102 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5103#endif
5104 state->mCblk = fastTrack != 0 ? fastTrack->cblk() : NULL;
5105 sq->end();
5106 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5107#if 0
5108 if (kUseFastCapture == FastCapture_Dynamic) {
5109 mNormalSource = mPipeSource;
5110 }
5111#endif
5112 } else {
5113 sq->end(false /*didModify*/);
5114 }
5115 }
5116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005117 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5118 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5119 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5120 // If destination is non-contiguous, first read past the nominal end of buffer, then
5121 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005123 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005124 ssize_t framesRead;
5125
5126 // If an NBAIO source is present, use it to read the normal capture's data
5127 if (mPipeSource != 0) {
5128 size_t framesToRead = mBufferSize / mFrameSize;
5129 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5130 framesToRead, AudioBufferProvider::kInvalidPTS);
5131 if (framesRead == 0) {
5132 // since pipe is non-blocking, simulate blocking input
5133 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5134 }
5135 // otherwise use the HAL / AudioStreamIn directly
5136 } else {
5137 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5138 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5139 if (bytesRead < 0) {
5140 framesRead = bytesRead;
5141 } else {
5142 framesRead = bytesRead / mFrameSize;
5143 }
5144 }
5145
5146 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5147 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005148 // Force input into standby so that it tries to recover at next read attempt
5149 inputStandBy();
5150 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005151 }
5152 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005153 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005154 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005155 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005157 if (mTeeSink != 0) {
5158 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5159 }
5160 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005161 {
5162 size_t part1 = mRsmpInFramesP2 - rear;
5163 if ((size_t) framesRead > part1) {
5164 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5165 (framesRead - part1) * mFrameSize);
5166 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005167 }
5168 rear = mRsmpInRear += framesRead;
5169
5170 size = activeTracks.size();
5171 // loop over each active track
5172 for (size_t i = 0; i < size; i++) {
5173 activeTrack = activeTracks[i];
5174
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005175 // skip fast tracks, as those are handled directly by FastCapture
5176 if (activeTrack->isFastTrack()) {
5177 continue;
5178 }
5179
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005180 enum {
5181 OVERRUN_UNKNOWN,
5182 OVERRUN_TRUE,
5183 OVERRUN_FALSE
5184 } overrun = OVERRUN_UNKNOWN;
5185
5186 // loop over getNextBuffer to handle circular sink
5187 for (;;) {
5188
5189 activeTrack->mSink.frameCount = ~0;
5190 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5191 size_t framesOut = activeTrack->mSink.frameCount;
5192 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5193
5194 int32_t front = activeTrack->mRsmpInFront;
5195 ssize_t filled = rear - front;
5196 size_t framesIn;
5197
5198 if (filled < 0) {
5199 // should not happen, but treat like a massive overrun and re-sync
5200 framesIn = 0;
5201 activeTrack->mRsmpInFront = rear;
5202 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005203 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005204 framesIn = (size_t) filled;
5205 } else {
5206 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005207 framesIn = mRsmpInFrames;
5208 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005209 overrun = OVERRUN_TRUE;
5210 }
5211
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005212 if (framesOut == 0 || framesIn == 0) {
5213 break;
5214 }
5215
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005216 if (activeTrack->mResampler == NULL) {
5217 // no resampling
5218 if (framesIn > framesOut) {
5219 framesIn = framesOut;
5220 } else {
5221 framesOut = framesIn;
5222 }
5223 int8_t *dst = activeTrack->mSink.i8;
5224 while (framesIn > 0) {
5225 front &= mRsmpInFramesP2 - 1;
5226 size_t part1 = mRsmpInFramesP2 - front;
5227 if (part1 > framesIn) {
5228 part1 = framesIn;
5229 }
5230 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005231 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005232 memcpy(dst, src, part1 * mFrameSize);
5233 } else if (mChannelCount == 1) {
5234 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
5235 part1);
5236 } else {
5237 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
5238 part1);
5239 }
5240 dst += part1 * activeTrack->mFrameSize;
5241 front += part1;
5242 framesIn -= part1;
5243 }
5244 activeTrack->mRsmpInFront += framesOut;
5245
5246 } else {
5247 // resampling
5248 // FIXME framesInNeeded should really be part of resampler API, and should
5249 // depend on the SRC ratio
5250 // to keep mRsmpInBuffer full so resampler always has sufficient input
5251 size_t framesInNeeded;
5252 // FIXME only re-calculate when it changes, and optimize for common ratios
5253 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
5254 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005255 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005256 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
5257 framesInNeeded, framesOut, inOverOut);
5258 // Although we theoretically have framesIn in circular buffer, some of those are
5259 // unreleased frames, and thus must be discounted for purpose of budgeting.
5260 size_t unreleased = activeTrack->mRsmpInUnrel;
5261 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005262 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005263 ALOGV("not enough to resample: have %u frames in but need %u in to "
5264 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005265 framesIn, framesInNeeded, framesOut, inOverOut);
5266 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005267 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5268 if (newFramesOut == 0) {
5269 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005270 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005271 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5272 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5273 framesInNeeded, newFramesOut, outOverIn);
5274 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5275 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5276 "given in/out ratio of %.4g",
5277 framesIn, framesInNeeded, newFramesOut, inOverOut);
5278 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005279 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005280 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005281 "given in/out ratio of %.4g",
5282 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005283 }
5284
5285 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5286 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005287 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005288 delete[] activeTrack->mRsmpOutBuffer;
5289 // resampler always outputs stereo
5290 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5291 activeTrack->mRsmpOutFrameCount = framesOut;
5292 }
5293
5294 // resampler accumulates, but we only have one source track
5295 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5296 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005297 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 activeTrack->mResamplerBufferProvider
5299 /*this*/ /* AudioBufferProvider* */);
5300 // ditherAndClamp() works as long as all buffers returned by
5301 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005302 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005303 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005304 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5305 framesOut);
5306 // the resampler always outputs stereo samples:
5307 // do post stereo to mono conversion
5308 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
5309 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
5310 } else {
5311 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5312 activeTrack->mRsmpOutBuffer, framesOut);
5313 }
5314 // now done with mRsmpOutBuffer
5315
5316 }
5317
5318 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5319 overrun = OVERRUN_FALSE;
5320 }
5321
5322 if (activeTrack->mFramesToDrop == 0) {
5323 if (framesOut > 0) {
5324 activeTrack->mSink.frameCount = framesOut;
5325 activeTrack->releaseBuffer(&activeTrack->mSink);
5326 }
5327 } else {
5328 // FIXME could do a partial drop of framesOut
5329 if (activeTrack->mFramesToDrop > 0) {
5330 activeTrack->mFramesToDrop -= framesOut;
5331 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005332 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005333 }
5334 } else {
5335 activeTrack->mFramesToDrop += framesOut;
5336 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5337 activeTrack->mSyncStartEvent->isCancelled()) {
5338 ALOGW("Synced record %s, session %d, trigger session %d",
5339 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5340 activeTrack->sessionId(),
5341 (activeTrack->mSyncStartEvent != 0) ?
5342 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005343 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005344 }
5345 }
5346 }
5347
5348 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005350 }
5351 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352
5353 switch (overrun) {
5354 case OVERRUN_TRUE:
5355 // client isn't retrieving buffers fast enough
5356 if (!activeTrack->setOverflow()) {
5357 nsecs_t now = systemTime();
5358 // FIXME should lastWarning per track?
5359 if ((now - lastWarning) > kWarningThrottleNs) {
5360 ALOGW("RecordThread: buffer overflow");
5361 lastWarning = now;
5362 }
5363 }
5364 break;
5365 case OVERRUN_FALSE:
5366 activeTrack->clearOverflow();
5367 break;
5368 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005369 break;
5370 }
5371
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005372 }
5373
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005374unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005375 // enable changes in effect chain
5376 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005377 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005378 }
5379
Glenn Kasten93e471f2013-08-19 08:40:07 -07005380 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005381
5382 {
5383 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005384 for (size_t i = 0; i < mTracks.size(); i++) {
5385 sp<RecordTrack> track = mTracks[i];
5386 track->invalidate();
5387 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005388 mActiveTracks.clear();
5389 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005390 mStartStopCond.broadcast();
5391 }
5392
5393 releaseWakeLock();
5394
5395 ALOGV("RecordThread %p exiting", this);
5396 return false;
5397}
5398
Glenn Kasten93e471f2013-08-19 08:40:07 -07005399void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005400{
5401 if (!mStandby) {
5402 inputStandBy();
5403 mStandby = true;
5404 }
5405}
5406
5407void AudioFlinger::RecordThread::inputStandBy()
5408{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005409 // Idle the fast capture if it's currently running
5410 if (mFastCapture != 0) {
5411 FastCaptureStateQueue *sq = mFastCapture->sq();
5412 FastCaptureState *state = sq->begin();
5413 if (!(state->mCommand & FastCaptureState::IDLE)) {
5414 state->mCommand = FastCaptureState::COLD_IDLE;
5415 state->mColdFutexAddr = &mFastCaptureFutex;
5416 state->mColdGen++;
5417 mFastCaptureFutex = 0;
5418 sq->end();
5419 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5420 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5421#if 0
5422 if (kUseFastCapture == FastCapture_Dynamic) {
5423 // FIXME
5424 }
5425#endif
5426#ifdef AUDIO_WATCHDOG
5427 // FIXME
5428#endif
5429 } else {
5430 sq->end(false /*didModify*/);
5431 }
5432 }
Eric Laurent81784c32012-11-19 14:55:58 -08005433 mInput->stream->common.standby(&mInput->stream->common);
5434}
5435
Glenn Kasten05997e22014-03-13 15:08:33 -07005436// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005437sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005438 const sp<AudioFlinger::Client>& client,
5439 uint32_t sampleRate,
5440 audio_format_t format,
5441 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005442 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005443 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005444 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005445 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005446 pid_t tid,
5447 status_t *status)
5448{
Glenn Kasten74935e42013-12-19 08:56:45 -08005449 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005450 sp<RecordTrack> track;
5451 status_t lStatus;
5452
Glenn Kasten90e58b12013-07-31 16:16:02 -07005453 // client expresses a preference for FAST, but we get the final say
5454 if (*flags & IAudioFlinger::TRACK_FAST) {
5455 if (
5456 // use case: callback handler and frame count is default or at least as large as HAL
5457 (
5458 (tid != -1) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005459 ((frameCount == 0) /*||
5460 // FIXME must be equal to pipe depth, so don't allow it to be specified by client
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005461 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005462 (frameCount >= mFrameCount)*/)
Glenn Kasten90e58b12013-07-31 16:16:02 -07005463 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005464 // PCM data
5465 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005466 // native format
5467 (format == mFormat) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005468 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005469 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5470 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005471 // native channel mask
5472 (channelMask == mChannelMask) &&
5473 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005474 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005475 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005476 hasFastCapture() &&
5477 // there are sufficient fast track slots available
5478 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005479 ) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005480 // if frameCount not specified, then it defaults to pipe frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005481 if (frameCount == 0) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005482 frameCount = mPipeFramesP2;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005483 }
5484 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5485 frameCount, mFrameCount);
5486 } else {
5487 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5488 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005489 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005490 frameCount, mFrameCount, format,
5491 audio_is_linear_pcm(format),
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005492 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005493 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005494 // 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 -07005495 // For compatibility with AudioRecord calculation, buffer depth is forced
5496 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5497 // This is probably too conservative, but legacy application code may depend on it.
5498 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005499 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005500 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5501 size_t mNormalFrameCount = 2048; // FIXME
5502 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5503 if (minBufCount < 2) {
5504 minBufCount = 2;
5505 }
5506 size_t minFrameCount = mNormalFrameCount * minBufCount;
5507 if (frameCount < minFrameCount) {
5508 frameCount = minFrameCount;
5509 }
5510 }
5511 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005512 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005513
Glenn Kasten15e57982013-09-24 11:52:37 -07005514 lStatus = initCheck();
5515 if (lStatus != NO_ERROR) {
5516 ALOGE("createRecordTrack_l() audio driver not initialized");
5517 goto Exit;
5518 }
Eric Laurent81784c32012-11-19 14:55:58 -08005519
5520 { // scope for mLock
5521 Mutex::Autolock _l(mLock);
5522
5523 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005524 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005525 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005526
Glenn Kasten03003332013-08-06 15:40:54 -07005527 lStatus = track->initCheck();
5528 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005529 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005530 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005531 goto Exit;
5532 }
5533 mTracks.add(track);
5534
5535 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5536 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5537 mAudioFlinger->btNrecIsOff();
5538 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5539 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005540
5541 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5542 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5543 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5544 // so ask activity manager to do this on our behalf
5545 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5546 }
Eric Laurent81784c32012-11-19 14:55:58 -08005547 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005548
Eric Laurent81784c32012-11-19 14:55:58 -08005549 lStatus = NO_ERROR;
5550
5551Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005552 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005553 return track;
5554}
5555
5556status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5557 AudioSystem::sync_event_t event,
5558 int triggerSession)
5559{
5560 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5561 sp<ThreadBase> strongMe = this;
5562 status_t status = NO_ERROR;
5563
5564 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005565 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005566 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005567 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005568 triggerSession,
5569 recordTrack->sessionId(),
5570 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005572 // Sync event can be cancelled by the trigger session if the track is not in a
5573 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005574 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005575 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005576 } else {
5577 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005578 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005579 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005580 }
5581 }
5582
5583 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005584 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005585 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5587 if (recordTrack->mState == TrackBase::PAUSING) {
5588 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005589 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005590 } else {
5591 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005592 }
5593 return status;
5594 }
5595
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005596 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5597 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5598 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005599 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005600 mActiveTracks.add(recordTrack);
5601 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005602 mLock.unlock();
5603 status_t status = AudioSystem::startInput(mId);
5604 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005605 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005606 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005607 mActiveTracks.remove(recordTrack);
5608 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005609 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005610 return status;
5611 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005612 // Catch up with current buffer indices if thread is already running.
5613 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5614 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5615 // see previously buffered data before it called start(), but with greater risk of overrun.
5616
5617 recordTrack->mRsmpInFront = mRsmpInRear;
5618 recordTrack->mRsmpInUnrel = 0;
5619 // FIXME why reset?
5620 if (recordTrack->mResampler != NULL) {
5621 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005622 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005623 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005625 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005626 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005627 ALOGV("Record failed to start");
5628 status = BAD_VALUE;
5629 goto startError;
5630 }
Eric Laurent81784c32012-11-19 14:55:58 -08005631 return status;
5632 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005633
Eric Laurent81784c32012-11-19 14:55:58 -08005634startError:
5635 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005636 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005638 return status;
5639}
5640
Eric Laurent81784c32012-11-19 14:55:58 -08005641void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5642{
5643 sp<SyncEvent> strongEvent = event.promote();
5644
5645 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005646 sp<RefBase> ptr = strongEvent->cookie().promote();
5647 if (ptr != 0) {
5648 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5649 recordTrack->handleSyncStartEvent(strongEvent);
5650 }
Eric Laurent81784c32012-11-19 14:55:58 -08005651 }
5652}
5653
Glenn Kastena8356f62013-07-25 14:37:52 -07005654bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005655 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005656 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005657 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005658 return false;
5659 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005660 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005661 recordTrack->mState = TrackBase::PAUSING;
5662 // do not wait for mStartStopCond if exiting
5663 if (exitPending()) {
5664 return true;
5665 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005666 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005667 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005668 // if we have been restarted, recordTrack is in mActiveTracks here
5669 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005670 ALOGV("Record stopped OK");
5671 return true;
5672 }
5673 return false;
5674}
5675
Glenn Kasten0f11b512014-01-31 16:18:54 -08005676bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005677{
5678 return false;
5679}
5680
Glenn Kasten0f11b512014-01-31 16:18:54 -08005681status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005682{
5683#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5684 if (!isValidSyncEvent(event)) {
5685 return BAD_VALUE;
5686 }
5687
5688 int eventSession = event->triggerSession();
5689 status_t ret = NAME_NOT_FOUND;
5690
5691 Mutex::Autolock _l(mLock);
5692
5693 for (size_t i = 0; i < mTracks.size(); i++) {
5694 sp<RecordTrack> track = mTracks[i];
5695 if (eventSession == track->sessionId()) {
5696 (void) track->setSyncEvent(event);
5697 ret = NO_ERROR;
5698 }
5699 }
5700 return ret;
5701#else
5702 return BAD_VALUE;
5703#endif
5704}
5705
5706// destroyTrack_l() must be called with ThreadBase::mLock held
5707void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5708{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005709 track->terminate();
5710 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005711 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005712 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005713 removeTrack_l(track);
5714 }
5715}
5716
5717void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5718{
5719 mTracks.remove(track);
5720 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005721 if (track->isFastTrack()) {
5722 ALOG_ASSERT(!mFastTrackAvail);
5723 mFastTrackAvail = true;
5724 }
Eric Laurent81784c32012-11-19 14:55:58 -08005725}
5726
5727void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5728{
5729 dumpInternals(fd, args);
5730 dumpTracks(fd, args);
5731 dumpEffectChains(fd, args);
5732}
5733
5734void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5735{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005736 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005737
Glenn Kasten2b806402013-11-20 16:37:38 -08005738 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005739 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005740 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005741 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005743 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005744
Eric Laurent81784c32012-11-19 14:55:58 -08005745 dumpBase(fd, args);
5746}
5747
Glenn Kasten0f11b512014-01-31 16:18:54 -08005748void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005749{
5750 const size_t SIZE = 256;
5751 char buffer[SIZE];
5752 String8 result;
5753
Marco Nelissenb2208842014-02-07 14:00:50 -08005754 size_t numtracks = mTracks.size();
5755 size_t numactive = mActiveTracks.size();
5756 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005757 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005758 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005759 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005760 RecordTrack::appendDumpHeader(result);
5761 for (size_t i = 0; i < numtracks ; ++i) {
5762 sp<RecordTrack> track = mTracks[i];
5763 if (track != 0) {
5764 bool active = mActiveTracks.indexOf(track) >= 0;
5765 if (active) {
5766 numactiveseen++;
5767 }
5768 track->dump(buffer, SIZE, active);
5769 result.append(buffer);
5770 }
Eric Laurent81784c32012-11-19 14:55:58 -08005771 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005772 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005773 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005774 }
5775
Marco Nelissenb2208842014-02-07 14:00:50 -08005776 if (numactiveseen != numactive) {
5777 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5778 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005779 result.append(buffer);
5780 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005781 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005782 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005783 if (mTracks.indexOf(track) < 0) {
5784 track->dump(buffer, SIZE, true);
5785 result.append(buffer);
5786 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005787 }
Eric Laurent81784c32012-11-19 14:55:58 -08005788
5789 }
5790 write(fd, result.string(), result.size());
5791}
5792
5793// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005794status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5795 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005796{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005797 RecordTrack *activeTrack = mRecordTrack;
5798 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5799 if (threadBase == 0) {
5800 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005801 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 return NOT_ENOUGH_DATA;
5803 }
5804 RecordThread *recordThread = (RecordThread *) threadBase.get();
5805 int32_t rear = recordThread->mRsmpInRear;
5806 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005807 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005808 // FIXME should not be P2 (don't want to increase latency)
5809 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005810 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005811 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005812 front &= recordThread->mRsmpInFramesP2 - 1;
5813 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005814 if (part1 > (size_t) filled) {
5815 part1 = filled;
5816 }
5817 size_t ask = buffer->frameCount;
5818 ALOG_ASSERT(ask > 0);
5819 if (part1 > ask) {
5820 part1 = ask;
5821 }
5822 if (part1 == 0) {
5823 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005824 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005825 buffer->raw = NULL;
5826 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005827 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005828 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005829 }
5830
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005831 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005832 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005833 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005834 return NO_ERROR;
5835}
5836
5837// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5839 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005840{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005841 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005842 size_t stepCount = buffer->frameCount;
5843 if (stepCount == 0) {
5844 return;
5845 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005846 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5847 activeTrack->mRsmpInUnrel -= stepCount;
5848 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005849 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005850 buffer->frameCount = 0;
5851}
5852
Eric Laurent10351942014-05-08 18:49:52 -07005853bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5854 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005855{
5856 bool reconfig = false;
5857
Eric Laurent10351942014-05-08 18:49:52 -07005858 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005859
Eric Laurent10351942014-05-08 18:49:52 -07005860 audio_format_t reqFormat = mFormat;
5861 uint32_t samplingRate = mSampleRate;
5862 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5863
5864 AudioParameter param = AudioParameter(keyValuePair);
5865 int value;
5866 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5867 // channel count change can be requested. Do we mandate the first client defines the
5868 // HAL sampling rate and channel count or do we allow changes on the fly?
5869 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5870 samplingRate = value;
5871 reconfig = true;
5872 }
5873 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5874 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5875 status = BAD_VALUE;
5876 } else {
5877 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005878 reconfig = true;
5879 }
Eric Laurent10351942014-05-08 18:49:52 -07005880 }
5881 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5882 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5883 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5884 status = BAD_VALUE;
5885 } else {
5886 channelMask = mask;
5887 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
Eric Laurent10351942014-05-08 18:49:52 -07005889 }
5890 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5891 // do not accept frame count changes if tracks are open as the track buffer
5892 // size depends on frame count and correct behavior would not be guaranteed
5893 // if frame count is changed after track creation
5894 if (mActiveTracks.size() > 0) {
5895 status = INVALID_OPERATION;
5896 } else {
5897 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005898 }
Eric Laurent10351942014-05-08 18:49:52 -07005899 }
5900 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5901 // forward device change to effects that have requested to be
5902 // aware of attached audio device.
5903 for (size_t i = 0; i < mEffectChains.size(); i++) {
5904 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005905 }
Eric Laurent81784c32012-11-19 14:55:58 -08005906
Eric Laurent10351942014-05-08 18:49:52 -07005907 // store input device and output device but do not forward output device to audio HAL.
5908 // Note that status is ignored by the caller for output device
5909 // (see AudioFlinger::setParameters()
5910 if (audio_is_output_devices(value)) {
5911 mOutDevice = value;
5912 status = BAD_VALUE;
5913 } else {
5914 mInDevice = value;
5915 // disable AEC and NS if the device is a BT SCO headset supporting those
5916 // pre processings
5917 if (mTracks.size() > 0) {
5918 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5919 mAudioFlinger->btNrecIsOff();
5920 for (size_t i = 0; i < mTracks.size(); i++) {
5921 sp<RecordTrack> track = mTracks[i];
5922 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5923 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005924 }
5925 }
5926 }
Eric Laurent10351942014-05-08 18:49:52 -07005927 }
5928 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5929 mAudioSource != (audio_source_t)value) {
5930 // forward device change to effects that have requested to be
5931 // aware of attached audio device.
5932 for (size_t i = 0; i < mEffectChains.size(); i++) {
5933 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
Eric Laurent10351942014-05-08 18:49:52 -07005935 mAudioSource = (audio_source_t)value;
5936 }
Glenn Kastene198c362013-08-13 09:13:36 -07005937
Eric Laurent10351942014-05-08 18:49:52 -07005938 if (status == NO_ERROR) {
5939 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5940 keyValuePair.string());
5941 if (status == INVALID_OPERATION) {
5942 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005943 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5944 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005945 }
5946 if (reconfig) {
5947 if (status == BAD_VALUE &&
5948 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5949 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5950 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5951 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005952 audio_channel_count_from_in_mask(
5953 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005954 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5955 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5956 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005957 }
Eric Laurent10351942014-05-08 18:49:52 -07005958 if (status == NO_ERROR) {
5959 readInputParameters_l();
5960 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005961 }
5962 }
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
Eric Laurent10351942014-05-08 18:49:52 -07005964
Eric Laurent81784c32012-11-19 14:55:58 -08005965 return reconfig;
5966}
5967
5968String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5969{
Eric Laurent81784c32012-11-19 14:55:58 -08005970 Mutex::Autolock _l(mLock);
5971 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005972 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005973 }
5974
Glenn Kastend8ea6992013-07-16 14:17:15 -07005975 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5976 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005977 free(s);
5978 return out_s8;
5979}
5980
Eric Laurent021cf962014-05-13 10:18:14 -07005981void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005982 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005983 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005984
5985 switch (event) {
5986 case AudioSystem::INPUT_OPENED:
5987 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005988 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005989 desc.samplingRate = mSampleRate;
5990 desc.format = mFormat;
5991 desc.frameCount = mFrameCount;
5992 desc.latency = 0;
5993 param2 = &desc;
5994 break;
5995
5996 case AudioSystem::INPUT_CLOSED:
5997 default:
5998 break;
5999 }
Eric Laurent021cf962014-05-13 10:18:14 -07006000 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006001}
6002
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006003void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006004{
Eric Laurent81784c32012-11-19 14:55:58 -08006005 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6006 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006007 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08006008 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006009 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006010 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006011 }
Eric Laurent81784c32012-11-19 14:55:58 -08006012 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08006013 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6014 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006015 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006016 // 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 -07006017 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006018 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006019 // A larger value should allow more old data to be read after a track calls start(),
6020 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006021 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006022 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07006024 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6025 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006026
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006027 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6028 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006029}
6030
Glenn Kasten5f972c02014-01-13 09:59:31 -08006031uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006032{
6033 Mutex::Autolock _l(mLock);
6034 if (initCheck() != NO_ERROR) {
6035 return 0;
6036 }
6037
6038 return mInput->stream->get_input_frames_lost(mInput->stream);
6039}
6040
6041uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6042{
6043 Mutex::Autolock _l(mLock);
6044 uint32_t result = 0;
6045 if (getEffectChain_l(sessionId) != 0) {
6046 result = EFFECT_SESSION;
6047 }
6048
6049 for (size_t i = 0; i < mTracks.size(); ++i) {
6050 if (sessionId == mTracks[i]->sessionId()) {
6051 result |= TRACK_SESSION;
6052 break;
6053 }
6054 }
6055
6056 return result;
6057}
6058
6059KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6060{
6061 KeyedVector<int, bool> ids;
6062 Mutex::Autolock _l(mLock);
6063 for (size_t j = 0; j < mTracks.size(); ++j) {
6064 sp<RecordThread::RecordTrack> track = mTracks[j];
6065 int sessionId = track->sessionId();
6066 if (ids.indexOfKey(sessionId) < 0) {
6067 ids.add(sessionId, true);
6068 }
6069 }
6070 return ids;
6071}
6072
6073AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6074{
6075 Mutex::Autolock _l(mLock);
6076 AudioStreamIn *input = mInput;
6077 mInput = NULL;
6078 return input;
6079}
6080
6081// this method must always be called either with ThreadBase mLock held or inside the thread loop
6082audio_stream_t* AudioFlinger::RecordThread::stream() const
6083{
6084 if (mInput == NULL) {
6085 return NULL;
6086 }
6087 return &mInput->stream->common;
6088}
6089
6090status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6091{
6092 // only one chain per input thread
6093 if (mEffectChains.size() != 0) {
6094 return INVALID_OPERATION;
6095 }
6096 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6097
6098 chain->setInBuffer(NULL);
6099 chain->setOutBuffer(NULL);
6100
6101 checkSuspendOnAddEffectChain_l(chain);
6102
6103 mEffectChains.add(chain);
6104
6105 return NO_ERROR;
6106}
6107
6108size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6109{
6110 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6111 ALOGW_IF(mEffectChains.size() != 1,
6112 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6113 chain.get(), mEffectChains.size(), this);
6114 if (mEffectChains.size() == 1) {
6115 mEffectChains.removeAt(0);
6116 }
6117 return 0;
6118}
6119
Eric Laurent1c333e22014-05-20 10:48:17 -07006120status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6121 audio_patch_handle_t *handle)
6122{
6123 status_t status = NO_ERROR;
6124 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6125 // store new device and send to effects
6126 mInDevice = patch->sources[0].ext.device.type;
6127 for (size_t i = 0; i < mEffectChains.size(); i++) {
6128 mEffectChains[i]->setDevice_l(mInDevice);
6129 }
6130
6131 // disable AEC and NS if the device is a BT SCO headset supporting those
6132 // pre processings
6133 if (mTracks.size() > 0) {
6134 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6135 mAudioFlinger->btNrecIsOff();
6136 for (size_t i = 0; i < mTracks.size(); i++) {
6137 sp<RecordTrack> track = mTracks[i];
6138 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6139 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6140 }
6141 }
6142
6143 // store new source and send to effects
6144 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6145 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6146 for (size_t i = 0; i < mEffectChains.size(); i++) {
6147 mEffectChains[i]->setAudioSource_l(mAudioSource);
6148 }
6149 }
6150
6151 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6152 status = hwDevice->create_audio_patch(hwDevice,
6153 patch->num_sources,
6154 patch->sources,
6155 patch->num_sinks,
6156 patch->sinks,
6157 handle);
6158 } else {
6159 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6160 }
6161 return status;
6162}
6163
6164status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6165{
6166 status_t status = NO_ERROR;
6167 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6168 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6169 status = hwDevice->release_audio_patch(hwDevice, handle);
6170 } else {
6171 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6172 }
6173 return status;
6174}
6175
6176
Eric Laurent81784c32012-11-19 14:55:58 -08006177}; // namespace android