blob: 0f01b02c002888d26efb0eabf74653b99e24c52a [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());
Andy Hung463be252014-07-10 16:56:07 -0700589 dprintf(fd, " Format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700590 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 Hung6146c082014-03-18 11:56:15 -07001160 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001161 mMixerBuffer(NULL),
1162 mMixerBufferSize(0),
1163 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1164 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001165 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001166 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 "
Andy Hung6146c082014-03-18 11:56:15 -07001404 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1405 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001406 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001407 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001408 audio_is_linear_pcm(format),
1409 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1410 *flags &= ~IAudioFlinger::TRACK_FAST;
1411 // For compatibility with AudioTrack calculation, buffer depth is forced
1412 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1413 // This is probably too conservative, but legacy application code may depend on it.
1414 // If you change this calculation, also review the start threshold which is related.
1415 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1416 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1417 if (minBufCount < 2) {
1418 minBufCount = 2;
1419 }
1420 size_t minFrameCount = mNormalFrameCount * minBufCount;
1421 if (frameCount < minFrameCount) {
1422 frameCount = minFrameCount;
1423 }
1424 }
1425 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001426 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001427
Glenn Kastenc3df8382014-03-13 15:05:25 -07001428 switch (mType) {
1429
1430 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001431 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001432 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001433 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1434 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001435 sampleRate, format, channelMask, mOutput, mFormat);
1436 lStatus = BAD_VALUE;
1437 goto Exit;
1438 }
1439 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001440 break;
1441
1442 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001443 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001444 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1445 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001446 sampleRate, format, channelMask, mOutput, mFormat);
1447 lStatus = BAD_VALUE;
1448 goto Exit;
1449 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001450 break;
1451
1452 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001453 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001454 ALOGE("createTrack_l() Bad parameter: format %#x \""
1455 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001456 format, mOutput, mFormat);
1457 lStatus = BAD_VALUE;
1458 goto Exit;
1459 }
Eric Laurent81784c32012-11-19 14:55:58 -08001460 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1461 if (sampleRate > mSampleRate*2) {
1462 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1463 lStatus = BAD_VALUE;
1464 goto Exit;
1465 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001466 break;
1467
Eric Laurent81784c32012-11-19 14:55:58 -08001468 }
1469
1470 lStatus = initCheck();
1471 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001472 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001473 goto Exit;
1474 }
1475
1476 { // scope for mLock
1477 Mutex::Autolock _l(mLock);
1478
1479 // all tracks in same audio session must share the same routing strategy otherwise
1480 // conflicts will happen when tracks are moved from one output to another by audio policy
1481 // manager
1482 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1483 for (size_t i = 0; i < mTracks.size(); ++i) {
1484 sp<Track> t = mTracks[i];
1485 if (t != 0 && !t->isOutputTrack()) {
1486 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1487 if (sessionId == t->sessionId() && strategy != actual) {
1488 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1489 strategy, actual);
1490 lStatus = BAD_VALUE;
1491 goto Exit;
1492 }
1493 }
1494 }
1495
1496 if (!isTimed) {
1497 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001498 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001499 } else {
1500 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001501 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001502 }
Glenn Kasten03003332013-08-06 15:40:54 -07001503
1504 // new Track always returns non-NULL,
1505 // but TimedTrack::create() is a factory that could fail by returning NULL
1506 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1507 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001508 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001509 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001510 goto Exit;
1511 }
1512 mTracks.add(track);
1513
1514 sp<EffectChain> chain = getEffectChain_l(sessionId);
1515 if (chain != 0) {
1516 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1517 track->setMainBuffer(chain->inBuffer());
1518 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1519 chain->incTrackCnt();
1520 }
1521
1522 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1523 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1524 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1525 // so ask activity manager to do this on our behalf
1526 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1527 }
1528 }
1529
1530 lStatus = NO_ERROR;
1531
1532Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001533 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001534 return track;
1535}
1536
1537uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1538{
1539 return latency;
1540}
1541
1542uint32_t AudioFlinger::PlaybackThread::latency() const
1543{
1544 Mutex::Autolock _l(mLock);
1545 return latency_l();
1546}
1547uint32_t AudioFlinger::PlaybackThread::latency_l() const
1548{
1549 if (initCheck() == NO_ERROR) {
1550 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1551 } else {
1552 return 0;
1553 }
1554}
1555
1556void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1557{
1558 Mutex::Autolock _l(mLock);
1559 // Don't apply master volume in SW if our HAL can do it for us.
1560 if (mOutput && mOutput->audioHwDev &&
1561 mOutput->audioHwDev->canSetMasterVolume()) {
1562 mMasterVolume = 1.0;
1563 } else {
1564 mMasterVolume = value;
1565 }
1566}
1567
1568void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1569{
1570 Mutex::Autolock _l(mLock);
1571 // Don't apply master mute in SW if our HAL can do it for us.
1572 if (mOutput && mOutput->audioHwDev &&
1573 mOutput->audioHwDev->canSetMasterMute()) {
1574 mMasterMute = false;
1575 } else {
1576 mMasterMute = muted;
1577 }
1578}
1579
1580void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1581{
1582 Mutex::Autolock _l(mLock);
1583 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001584 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001585}
1586
1587void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1588{
1589 Mutex::Autolock _l(mLock);
1590 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001591 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001592}
1593
1594float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1595{
1596 Mutex::Autolock _l(mLock);
1597 return mStreamTypes[stream].volume;
1598}
1599
1600// addTrack_l() must be called with ThreadBase::mLock held
1601status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1602{
1603 status_t status = ALREADY_EXISTS;
1604
1605 // set retry count for buffer fill
1606 track->mRetryCount = kMaxTrackStartupRetries;
1607 if (mActiveTracks.indexOf(track) < 0) {
1608 // the track is newly added, make sure it fills up all its
1609 // buffers before playing. This is to ensure the client will
1610 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001611 if (!track->isOutputTrack()) {
1612 TrackBase::track_state state = track->mState;
1613 mLock.unlock();
1614 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1615 mLock.lock();
1616 // abort track was stopped/paused while we released the lock
1617 if (state != track->mState) {
1618 if (status == NO_ERROR) {
1619 mLock.unlock();
1620 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1621 mLock.lock();
1622 }
1623 return INVALID_OPERATION;
1624 }
1625 // abort if start is rejected by audio policy manager
1626 if (status != NO_ERROR) {
1627 return PERMISSION_DENIED;
1628 }
1629#ifdef ADD_BATTERY_DATA
1630 // to track the speaker usage
1631 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1632#endif
1633 }
1634
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001635 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001636 track->mResetDone = false;
1637 track->mPresentationCompleteFrames = 0;
1638 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001639 mWakeLockUids.add(track->uid());
1640 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001641 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001642 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1643 if (chain != 0) {
1644 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1645 track->sessionId());
1646 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001647 }
1648
1649 status = NO_ERROR;
1650 }
1651
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001652 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001653 return status;
1654}
1655
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001657{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001659 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001660 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1661 track->mState = TrackBase::STOPPED;
1662 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001663 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001664 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001665 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667
1668 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001669}
1670
1671void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1672{
1673 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1674 mTracks.remove(track);
1675 deleteTrackName_l(track->name());
1676 // redundant as track is about to be destroyed, for dumpsys only
1677 track->mName = -1;
1678 if (track->isFastTrack()) {
1679 int index = track->mFastIndex;
1680 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1681 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1682 mFastTrackAvailMask |= 1 << index;
1683 // redundant as track is about to be destroyed, for dumpsys only
1684 track->mFastIndex = -1;
1685 }
1686 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1687 if (chain != 0) {
1688 chain->decTrackCnt();
1689 }
1690}
1691
Eric Laurentede6c3b2013-09-19 14:37:46 -07001692void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001693{
1694 // Thread could be blocked waiting for async
1695 // so signal it to handle state changes immediately
1696 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1697 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1698 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001699 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700}
1701
Eric Laurent81784c32012-11-19 14:55:58 -08001702String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1703{
Eric Laurent81784c32012-11-19 14:55:58 -08001704 Mutex::Autolock _l(mLock);
1705 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001706 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001707 }
1708
Glenn Kastend8ea6992013-07-16 14:17:15 -07001709 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1710 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001711 free(s);
1712 return out_s8;
1713}
1714
Eric Laurent021cf962014-05-13 10:18:14 -07001715void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001716 AudioSystem::OutputDescriptor desc;
1717 void *param2 = NULL;
1718
Eric Laurent021cf962014-05-13 10:18:14 -07001719 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001720 param);
1721
1722 switch (event) {
1723 case AudioSystem::OUTPUT_OPENED:
1724 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001725 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001726 desc.samplingRate = mSampleRate;
1727 desc.format = mFormat;
1728 desc.frameCount = mNormalFrameCount; // FIXME see
1729 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001730 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001731 param2 = &desc;
1732 break;
1733
1734 case AudioSystem::STREAM_CONFIG_CHANGED:
1735 param2 = &param;
1736 case AudioSystem::OUTPUT_CLOSED:
1737 default:
1738 break;
1739 }
Eric Laurent021cf962014-05-13 10:18:14 -07001740 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001741}
1742
Eric Laurentbfb1b832013-01-07 09:53:42 -08001743void AudioFlinger::PlaybackThread::writeCallback()
1744{
1745 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001746 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747}
1748
1749void AudioFlinger::PlaybackThread::drainCallback()
1750{
1751 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001752 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001753}
1754
Eric Laurent3b4529e2013-09-05 18:09:19 -07001755void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756{
1757 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001758 // reject out of sequence requests
1759 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1760 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001761 mWaitWorkCV.signal();
1762 }
1763}
1764
Eric Laurent3b4529e2013-09-05 18:09:19 -07001765void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766{
1767 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001768 // reject out of sequence requests
1769 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1770 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001771 mWaitWorkCV.signal();
1772 }
1773}
1774
1775// static
1776int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001777 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001778 void *cookie)
1779{
1780 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1781 ALOGV("asyncCallback() event %d", event);
1782 switch (event) {
1783 case STREAM_CBK_EVENT_WRITE_READY:
1784 me->writeCallback();
1785 break;
1786 case STREAM_CBK_EVENT_DRAIN_READY:
1787 me->drainCallback();
1788 break;
1789 default:
1790 ALOGW("asyncCallback() unknown event %d", event);
1791 break;
1792 }
1793 return 0;
1794}
1795
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001796void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001797{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001798 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001799 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1800 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001801 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001802 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001803 }
1804 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001805 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001806 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1807 }
Andy Hunge5412692014-05-16 11:25:07 -07001808 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001809 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1810 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001811 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001812 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001813 }
Andy Hung6146c082014-03-18 11:56:15 -07001814 if ((mType == MIXER || mType == DUPLICATING)
1815 && !isValidPcmSinkFormat(mFormat)) {
1816 LOG_FATAL("HAL format %#x not supported for mixed output",
1817 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001818 }
Eric Laurent665470b2014-07-03 16:37:08 -07001819 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001820 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1821 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001822 if (mFrameCount & 15) {
1823 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1824 mFrameCount);
1825 }
1826
Eric Laurentbfb1b832013-01-07 09:53:42 -08001827 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1828 (mOutput->stream->set_callback != NULL)) {
1829 if (mOutput->stream->set_callback(mOutput->stream,
1830 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1831 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001832 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833 }
1834 }
1835
Andy Hung09a50072014-02-27 14:30:47 -08001836 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001837 double multiplier = 1.0;
1838 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1839 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001840 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1841 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001842 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1843 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1844 maxNormalFrameCount = maxNormalFrameCount & ~15;
1845 if (maxNormalFrameCount < minNormalFrameCount) {
1846 maxNormalFrameCount = minNormalFrameCount;
1847 }
1848 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1849 if (multiplier <= 1.0) {
1850 multiplier = 1.0;
1851 } else if (multiplier <= 2.0) {
1852 if (2 * mFrameCount <= maxNormalFrameCount) {
1853 multiplier = 2.0;
1854 } else {
1855 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1856 }
1857 } else {
1858 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001859 // 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 -08001860 // track, but we sometimes have to do this to satisfy the maximum frame count
1861 // constraint)
1862 // FIXME this rounding up should not be done if no HAL SRC
1863 uint32_t truncMult = (uint32_t) multiplier;
1864 if ((truncMult & 1)) {
1865 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1866 ++truncMult;
1867 }
1868 }
1869 multiplier = (double) truncMult;
1870 }
1871 }
1872 mNormalFrameCount = multiplier * mFrameCount;
1873 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001874 if (mType == MIXER || mType == DUPLICATING) {
1875 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1876 }
Andy Hung09a50072014-02-27 14:30:47 -08001877 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001878 mNormalFrameCount);
1879
Andy Hung010a1a12014-03-13 13:57:33 -07001880 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1881 // Originally this was int16_t[] array, need to remove legacy implications.
1882 free(mSinkBuffer);
1883 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001884 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1885 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1886 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001887 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001888
Andy Hung69aed5f2014-02-25 17:24:40 -08001889 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1890 // drives the output.
1891 free(mMixerBuffer);
1892 mMixerBuffer = NULL;
1893 if (mMixerBufferEnabled) {
1894 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1895 mMixerBufferSize = mNormalFrameCount * mChannelCount
1896 * audio_bytes_per_sample(mMixerBufferFormat);
1897 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1898 }
Andy Hung98ef9782014-03-04 14:46:50 -08001899 free(mEffectBuffer);
1900 mEffectBuffer = NULL;
1901 if (mEffectBufferEnabled) {
1902 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1903 mEffectBufferSize = mNormalFrameCount * mChannelCount
1904 * audio_bytes_per_sample(mEffectBufferFormat);
1905 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1906 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001907
Eric Laurent81784c32012-11-19 14:55:58 -08001908 // force reconfiguration of effect chains and engines to take new buffer size and audio
1909 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001910 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001911 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1912 // matter.
1913 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1914 Vector< sp<EffectChain> > effectChains = mEffectChains;
1915 for (size_t i = 0; i < effectChains.size(); i ++) {
1916 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1917 }
1918}
1919
1920
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001921status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001922{
1923 if (halFrames == NULL || dspFrames == NULL) {
1924 return BAD_VALUE;
1925 }
1926 Mutex::Autolock _l(mLock);
1927 if (initCheck() != NO_ERROR) {
1928 return INVALID_OPERATION;
1929 }
1930 size_t framesWritten = mBytesWritten / mFrameSize;
1931 *halFrames = framesWritten;
1932
1933 if (isSuspended()) {
1934 // return an estimation of rendered frames when the output is suspended
1935 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1936 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1937 return NO_ERROR;
1938 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001939 status_t status;
1940 uint32_t frames;
1941 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1942 *dspFrames = (size_t)frames;
1943 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001944 }
1945}
1946
1947uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1948{
1949 Mutex::Autolock _l(mLock);
1950 uint32_t result = 0;
1951 if (getEffectChain_l(sessionId) != 0) {
1952 result = EFFECT_SESSION;
1953 }
1954
1955 for (size_t i = 0; i < mTracks.size(); ++i) {
1956 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001957 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001958 result |= TRACK_SESSION;
1959 break;
1960 }
1961 }
1962
1963 return result;
1964}
1965
1966uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1967{
1968 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1969 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1970 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1971 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1972 }
1973 for (size_t i = 0; i < mTracks.size(); i++) {
1974 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001975 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001976 return AudioSystem::getStrategyForStream(track->streamType());
1977 }
1978 }
1979 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1980}
1981
1982
1983AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1984{
1985 Mutex::Autolock _l(mLock);
1986 return mOutput;
1987}
1988
1989AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1990{
1991 Mutex::Autolock _l(mLock);
1992 AudioStreamOut *output = mOutput;
1993 mOutput = NULL;
1994 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1995 // must push a NULL and wait for ack
1996 mOutputSink.clear();
1997 mPipeSink.clear();
1998 mNormalSink.clear();
1999 return output;
2000}
2001
2002// this method must always be called either with ThreadBase mLock held or inside the thread loop
2003audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2004{
2005 if (mOutput == NULL) {
2006 return NULL;
2007 }
2008 return &mOutput->stream->common;
2009}
2010
2011uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2012{
2013 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2014}
2015
2016status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2017{
2018 if (!isValidSyncEvent(event)) {
2019 return BAD_VALUE;
2020 }
2021
2022 Mutex::Autolock _l(mLock);
2023
2024 for (size_t i = 0; i < mTracks.size(); ++i) {
2025 sp<Track> track = mTracks[i];
2026 if (event->triggerSession() == track->sessionId()) {
2027 (void) track->setSyncEvent(event);
2028 return NO_ERROR;
2029 }
2030 }
2031
2032 return NAME_NOT_FOUND;
2033}
2034
2035bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2036{
2037 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2038}
2039
2040void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2041 const Vector< sp<Track> >& tracksToRemove)
2042{
2043 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002044 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002045 for (size_t i = 0 ; i < count ; i++) {
2046 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002047 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002048 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002049#ifdef ADD_BATTERY_DATA
2050 // to track the speaker usage
2051 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2052#endif
2053 if (track->isTerminated()) {
2054 AudioSystem::releaseOutput(mId);
2055 }
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
2057 }
2058 }
Eric Laurent81784c32012-11-19 14:55:58 -08002059}
2060
2061void AudioFlinger::PlaybackThread::checkSilentMode_l()
2062{
2063 if (!mMasterMute) {
2064 char value[PROPERTY_VALUE_MAX];
2065 if (property_get("ro.audio.silent", value, "0") > 0) {
2066 char *endptr;
2067 unsigned long ul = strtoul(value, &endptr, 0);
2068 if (*endptr == '\0' && ul != 0) {
2069 ALOGD("Silence is golden");
2070 // The setprop command will not allow a property to be changed after
2071 // the first time it is set, so we don't have to worry about un-muting.
2072 setMasterMute_l(true);
2073 }
2074 }
2075 }
2076}
2077
2078// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002079ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002080{
2081 // FIXME rewrite to reduce number of system calls
2082 mLastWriteTime = systemTime();
2083 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002084 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002085 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002086
2087 // If an NBAIO sink is present, use it to write the normal mixer's submix
2088 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002089 const size_t count = mBytesRemaining / mFrameSize;
2090
Simon Wilson2d590962012-11-29 15:18:50 -08002091 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002092 // update the setpoint when AudioFlinger::mScreenState changes
2093 uint32_t screenState = AudioFlinger::mScreenState;
2094 if (screenState != mScreenState) {
2095 mScreenState = screenState;
2096 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2097 if (pipe != NULL) {
2098 pipe->setAvgFrames((mScreenState & 1) ?
2099 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2100 }
2101 }
Andy Hung010a1a12014-03-13 13:57:33 -07002102 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002103 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002104 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002105 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002106 } else {
2107 bytesWritten = framesWritten;
2108 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002109 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002110 if (status == NO_ERROR) {
2111 size_t totalFramesWritten = mNormalSink->framesWritten();
2112 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2113 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2114 mLatchDValid = true;
2115 }
2116 }
Eric Laurent81784c32012-11-19 14:55:58 -08002117 // otherwise use the HAL / AudioStreamOut directly
2118 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002120
Eric Laurentbfb1b832013-01-07 09:53:42 -08002121 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002122 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2123 mWriteAckSequence += 2;
2124 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002125 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002126 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002128 // FIXME We should have an implementation of timestamps for direct output threads.
2129 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002130 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002131 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002132 if (mUseAsyncWrite &&
2133 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2134 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002135 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002136 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002137 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138 }
Eric Laurent81784c32012-11-19 14:55:58 -08002139 }
2140
Eric Laurent81784c32012-11-19 14:55:58 -08002141 mNumWrites++;
2142 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002143 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 return bytesWritten;
2145}
2146
2147void AudioFlinger::PlaybackThread::threadLoop_drain()
2148{
2149 if (mOutput->stream->drain) {
2150 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2151 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002152 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2153 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002154 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002155 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156 }
2157 mOutput->stream->drain(mOutput->stream,
2158 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2159 : AUDIO_DRAIN_ALL);
2160 }
2161}
2162
2163void AudioFlinger::PlaybackThread::threadLoop_exit()
2164{
2165 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002166}
2167
2168/*
2169The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002170 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002171 - activeSleepTime from activeSleepTimeUs()
2172 - idleSleepTime from idleSleepTimeUs()
2173 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2174 - maxPeriod from frame count and sample rate (MIXER only)
2175
2176The parameters that affect these derived values are:
2177 - frame count
2178 - frame size
2179 - sample rate
2180 - device type: A2DP or not
2181 - device latency
2182 - format: PCM or not
2183 - active sleep time
2184 - idle sleep time
2185*/
2186
2187void AudioFlinger::PlaybackThread::cacheParameters_l()
2188{
Andy Hung25c2dac2014-02-27 14:56:00 -08002189 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002190 activeSleepTime = activeSleepTimeUs();
2191 idleSleepTime = idleSleepTimeUs();
2192}
2193
2194void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2195{
Glenn Kasten7c027242012-12-26 14:43:16 -08002196 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002197 this, streamType, mTracks.size());
2198 Mutex::Autolock _l(mLock);
2199
2200 size_t size = mTracks.size();
2201 for (size_t i = 0; i < size; i++) {
2202 sp<Track> t = mTracks[i];
2203 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002204 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002205 }
2206 }
2207}
2208
2209status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2210{
2211 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002212 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2213 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002214 bool ownsBuffer = false;
2215
2216 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2217 if (session > 0) {
2218 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002219 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002220 if (mType != DIRECT) {
2221 size_t numSamples = mNormalFrameCount * mChannelCount;
2222 buffer = new int16_t[numSamples];
2223 memset(buffer, 0, numSamples * sizeof(int16_t));
2224 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2225 ownsBuffer = true;
2226 }
2227
2228 // Attach all tracks with same session ID to this chain.
2229 for (size_t i = 0; i < mTracks.size(); ++i) {
2230 sp<Track> track = mTracks[i];
2231 if (session == track->sessionId()) {
2232 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2233 buffer);
2234 track->setMainBuffer(buffer);
2235 chain->incTrackCnt();
2236 }
2237 }
2238
2239 // indicate all active tracks in the chain
2240 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2241 sp<Track> track = mActiveTracks[i].promote();
2242 if (track == 0) {
2243 continue;
2244 }
2245 if (session == track->sessionId()) {
2246 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2247 chain->incActiveTrackCnt();
2248 }
2249 }
2250 }
2251
2252 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002253 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2254 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002255 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2256 // chains list in order to be processed last as it contains output stage effects
2257 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2258 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2259 // after track specific effects and before output stage
2260 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2261 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2262 // Effect chain for other sessions are inserted at beginning of effect
2263 // chains list to be processed before output mix effects. Relative order between other
2264 // sessions is not important
2265 size_t size = mEffectChains.size();
2266 size_t i = 0;
2267 for (i = 0; i < size; i++) {
2268 if (mEffectChains[i]->sessionId() < session) {
2269 break;
2270 }
2271 }
2272 mEffectChains.insertAt(chain, i);
2273 checkSuspendOnAddEffectChain_l(chain);
2274
2275 return NO_ERROR;
2276}
2277
2278size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2279{
2280 int session = chain->sessionId();
2281
2282 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2283
2284 for (size_t i = 0; i < mEffectChains.size(); i++) {
2285 if (chain == mEffectChains[i]) {
2286 mEffectChains.removeAt(i);
2287 // detach all active tracks from the chain
2288 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2289 sp<Track> track = mActiveTracks[i].promote();
2290 if (track == 0) {
2291 continue;
2292 }
2293 if (session == track->sessionId()) {
2294 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2295 chain.get(), session);
2296 chain->decActiveTrackCnt();
2297 }
2298 }
2299
2300 // detach all tracks with same session ID from this chain
2301 for (size_t i = 0; i < mTracks.size(); ++i) {
2302 sp<Track> track = mTracks[i];
2303 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002304 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002305 chain->decTrackCnt();
2306 }
2307 }
2308 break;
2309 }
2310 }
2311 return mEffectChains.size();
2312}
2313
2314status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2315 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2316{
2317 Mutex::Autolock _l(mLock);
2318 return attachAuxEffect_l(track, EffectId);
2319}
2320
2321status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2322 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2323{
2324 status_t status = NO_ERROR;
2325
2326 if (EffectId == 0) {
2327 track->setAuxBuffer(0, NULL);
2328 } else {
2329 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2330 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2331 if (effect != 0) {
2332 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2333 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2334 } else {
2335 status = INVALID_OPERATION;
2336 }
2337 } else {
2338 status = BAD_VALUE;
2339 }
2340 }
2341 return status;
2342}
2343
2344void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2345{
2346 for (size_t i = 0; i < mTracks.size(); ++i) {
2347 sp<Track> track = mTracks[i];
2348 if (track->auxEffectId() == effectId) {
2349 attachAuxEffect_l(track, 0);
2350 }
2351 }
2352}
2353
2354bool AudioFlinger::PlaybackThread::threadLoop()
2355{
2356 Vector< sp<Track> > tracksToRemove;
2357
2358 standbyTime = systemTime();
2359
2360 // MIXER
2361 nsecs_t lastWarning = 0;
2362
2363 // DUPLICATING
2364 // FIXME could this be made local to while loop?
2365 writeFrames = 0;
2366
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002367 int lastGeneration = 0;
2368
Eric Laurent81784c32012-11-19 14:55:58 -08002369 cacheParameters_l();
2370 sleepTime = idleSleepTime;
2371
2372 if (mType == MIXER) {
2373 sleepTimeShift = 0;
2374 }
2375
2376 CpuStats cpuStats;
2377 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2378
2379 acquireWakeLock();
2380
Glenn Kasten9e58b552013-01-18 15:09:48 -08002381 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2382 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2383 // and then that string will be logged at the next convenient opportunity.
2384 const char *logString = NULL;
2385
Eric Laurent664539d2013-09-23 18:24:31 -07002386 checkSilentMode_l();
2387
Eric Laurent81784c32012-11-19 14:55:58 -08002388 while (!exitPending())
2389 {
2390 cpuStats.sample(myName);
2391
2392 Vector< sp<EffectChain> > effectChains;
2393
Eric Laurent81784c32012-11-19 14:55:58 -08002394 { // scope for mLock
2395
2396 Mutex::Autolock _l(mLock);
2397
Eric Laurent021cf962014-05-13 10:18:14 -07002398 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002399
Glenn Kasten9e58b552013-01-18 15:09:48 -08002400 if (logString != NULL) {
2401 mNBLogWriter->logTimestamp();
2402 mNBLogWriter->log(logString);
2403 logString = NULL;
2404 }
2405
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002406 if (mLatchDValid) {
2407 mLatchQ = mLatchD;
2408 mLatchDValid = false;
2409 mLatchQValid = true;
2410 }
2411
Eric Laurent81784c32012-11-19 14:55:58 -08002412 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 if (mSignalPending) {
2414 // A signal was raised while we were unlocked
2415 mSignalPending = false;
2416 } else if (waitingAsyncCallback_l()) {
2417 if (exitPending()) {
2418 break;
2419 }
2420 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002421 mWakeLockUids.clear();
2422 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002423 ALOGV("wait async completion");
2424 mWaitWorkCV.wait(mLock);
2425 ALOGV("async completion/wake");
2426 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002427 standbyTime = systemTime() + standbyDelay;
2428 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002429
2430 continue;
2431 }
2432 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002433 isSuspended()) {
2434 // put audio hardware into standby after short delay
2435 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002436
2437 threadLoop_standby();
2438
2439 mStandby = true;
2440 }
2441
2442 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2443 // we're about to wait, flush the binder command buffer
2444 IPCThreadState::self()->flushCommands();
2445
2446 clearOutputTracks();
2447
2448 if (exitPending()) {
2449 break;
2450 }
2451
2452 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002453 mWakeLockUids.clear();
2454 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // wait until we have something to do...
2456 ALOGV("%s going to sleep", myName.string());
2457 mWaitWorkCV.wait(mLock);
2458 ALOGV("%s waking up", myName.string());
2459 acquireWakeLock_l();
2460
2461 mMixerStatus = MIXER_IDLE;
2462 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2463 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002465 checkSilentMode_l();
2466
2467 standbyTime = systemTime() + standbyDelay;
2468 sleepTime = idleSleepTime;
2469 if (mType == MIXER) {
2470 sleepTimeShift = 0;
2471 }
2472
2473 continue;
2474 }
2475 }
Eric Laurent81784c32012-11-19 14:55:58 -08002476 // mMixerStatusIgnoringFastTracks is also updated internally
2477 mMixerStatus = prepareTracks_l(&tracksToRemove);
2478
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002479 // compare with previously applied list
2480 if (lastGeneration != mActiveTracksGeneration) {
2481 // update wakelock
2482 updateWakeLockUids_l(mWakeLockUids);
2483 lastGeneration = mActiveTracksGeneration;
2484 }
2485
Eric Laurent81784c32012-11-19 14:55:58 -08002486 // prevent any changes in effect chain list and in each effect chain
2487 // during mixing and effect process as the audio buffers could be deleted
2488 // or modified if an effect is created or deleted
2489 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002490 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002491
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 if (mBytesRemaining == 0) {
2493 mCurrentWriteLength = 0;
2494 if (mMixerStatus == MIXER_TRACKS_READY) {
2495 // threadLoop_mix() sets mCurrentWriteLength
2496 threadLoop_mix();
2497 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2498 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2499 // threadLoop_sleepTime sets sleepTime to 0 if data
2500 // must be written to HAL
2501 threadLoop_sleepTime();
2502 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002503 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504 }
2505 }
Andy Hung98ef9782014-03-04 14:46:50 -08002506 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2507 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2508 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2509 // or mSinkBuffer (if there are no effects).
2510 //
2511 // This is done pre-effects computation; if effects change to
2512 // support higher precision, this needs to move.
2513 //
2514 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2515 // TODO use sleepTime == 0 as an additional condition.
2516 if (mMixerBufferValid) {
2517 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2518 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2519
2520 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2521 mNormalFrameCount * mChannelCount);
2522 }
2523
Eric Laurentbfb1b832013-01-07 09:53:42 -08002524 mBytesRemaining = mCurrentWriteLength;
2525 if (isSuspended()) {
2526 sleepTime = suspendSleepTimeUs();
2527 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002528 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002529 mBytesRemaining = 0;
2530 }
Eric Laurent81784c32012-11-19 14:55:58 -08002531
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002533 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002534 for (size_t i = 0; i < effectChains.size(); i ++) {
2535 effectChains[i]->process_l();
2536 }
Eric Laurent81784c32012-11-19 14:55:58 -08002537 }
2538 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002539 // Process effect chains for offloaded thread even if no audio
2540 // was read from audio track: process only updates effect state
2541 // and thus does have to be synchronized with audio writes but may have
2542 // to be called while waiting for async write callback
2543 if (mType == OFFLOAD) {
2544 for (size_t i = 0; i < effectChains.size(); i ++) {
2545 effectChains[i]->process_l();
2546 }
2547 }
Eric Laurent81784c32012-11-19 14:55:58 -08002548
Andy Hung98ef9782014-03-04 14:46:50 -08002549 // Only if the Effects buffer is enabled and there is data in the
2550 // Effects buffer (buffer valid), we need to
2551 // copy into the sink buffer.
2552 // TODO use sleepTime == 0 as an additional condition.
2553 if (mEffectBufferValid) {
2554 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2555 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2556 mNormalFrameCount * mChannelCount);
2557 }
2558
Eric Laurent81784c32012-11-19 14:55:58 -08002559 // enable changes in effect chain
2560 unlockEffectChains(effectChains);
2561
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 if (!waitingAsyncCallback()) {
2563 // sleepTime == 0 means we must write to audio hardware
2564 if (sleepTime == 0) {
2565 if (mBytesRemaining) {
2566 ssize_t ret = threadLoop_write();
2567 if (ret < 0) {
2568 mBytesRemaining = 0;
2569 } else {
2570 mBytesWritten += ret;
2571 mBytesRemaining -= ret;
2572 }
2573 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2574 (mMixerStatus == MIXER_DRAIN_ALL)) {
2575 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002577 if (mType == MIXER) {
2578 // write blocked detection
2579 nsecs_t now = systemTime();
2580 nsecs_t delta = now - mLastWriteTime;
2581 if (!mStandby && delta > maxPeriod) {
2582 mNumDelayedWrites++;
2583 if ((now - lastWarning) > kWarningThrottleNs) {
2584 ATRACE_NAME("underrun");
2585 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2586 ns2ms(delta), mNumDelayedWrites, this);
2587 lastWarning = now;
2588 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589 }
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 } else {
2593 usleep(sleepTime);
2594 }
Eric Laurent81784c32012-11-19 14:55:58 -08002595 }
2596
2597 // Finally let go of removed track(s), without the lock held
2598 // since we can't guarantee the destructors won't acquire that
2599 // same lock. This will also mutate and push a new fast mixer state.
2600 threadLoop_removeTracks(tracksToRemove);
2601 tracksToRemove.clear();
2602
2603 // FIXME I don't understand the need for this here;
2604 // it was in the original code but maybe the
2605 // assignment in saveOutputTracks() makes this unnecessary?
2606 clearOutputTracks();
2607
2608 // Effect chains will be actually deleted here if they were removed from
2609 // mEffectChains list during mixing or effects processing
2610 effectChains.clear();
2611
2612 // FIXME Note that the above .clear() is no longer necessary since effectChains
2613 // is now local to this block, but will keep it for now (at least until merge done).
2614 }
2615
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 threadLoop_exit();
2617
Eric Laurent81784c32012-11-19 14:55:58 -08002618 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002619 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // put output stream into standby mode
2621 if (!mStandby) {
2622 mOutput->stream->common.standby(&mOutput->stream->common);
2623 }
2624 }
2625
2626 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002627 mWakeLockUids.clear();
2628 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002629
2630 ALOGV("Thread %p type %d exiting", this, mType);
2631 return false;
2632}
2633
Eric Laurentbfb1b832013-01-07 09:53:42 -08002634// removeTracks_l() must be called with ThreadBase::mLock held
2635void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2636{
2637 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002638 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 for (size_t i=0 ; i<count ; i++) {
2640 const sp<Track>& track = tracksToRemove.itemAt(i);
2641 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002642 mWakeLockUids.remove(track->uid());
2643 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2645 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2646 if (chain != 0) {
2647 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2648 track->sessionId());
2649 chain->decActiveTrackCnt();
2650 }
2651 if (track->isTerminated()) {
2652 removeTrack_l(track);
2653 }
2654 }
2655 }
2656
2657}
Eric Laurent81784c32012-11-19 14:55:58 -08002658
Eric Laurentaccc1472013-09-20 09:36:34 -07002659status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2660{
2661 if (mNormalSink != 0) {
2662 return mNormalSink->getTimestamp(timestamp);
2663 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002664 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002665 uint64_t position64;
2666 int ret = mOutput->stream->get_presentation_position(
2667 mOutput->stream, &position64, &timestamp.mTime);
2668 if (ret == 0) {
2669 timestamp.mPosition = (uint32_t)position64;
2670 return NO_ERROR;
2671 }
2672 }
2673 return INVALID_OPERATION;
2674}
Eric Laurent1c333e22014-05-20 10:48:17 -07002675
2676status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2677 audio_patch_handle_t *handle)
2678{
2679 status_t status = NO_ERROR;
2680 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2681 // store new device and send to effects
2682 audio_devices_t type = AUDIO_DEVICE_NONE;
2683 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2684 type |= patch->sinks[i].ext.device.type;
2685 }
2686 mOutDevice = type;
2687 for (size_t i = 0; i < mEffectChains.size(); i++) {
2688 mEffectChains[i]->setDevice_l(mOutDevice);
2689 }
2690
2691 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2692 status = hwDevice->create_audio_patch(hwDevice,
2693 patch->num_sources,
2694 patch->sources,
2695 patch->num_sinks,
2696 patch->sinks,
2697 handle);
2698 } else {
2699 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2700 }
2701 return status;
2702}
2703
2704status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2705{
2706 status_t status = NO_ERROR;
2707 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2708 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2709 status = hwDevice->release_audio_patch(hwDevice, handle);
2710 } else {
2711 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2712 }
2713 return status;
2714}
2715
Eric Laurent81784c32012-11-19 14:55:58 -08002716// ----------------------------------------------------------------------------
2717
2718AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2719 audio_io_handle_t id, audio_devices_t device, type_t type)
2720 : PlaybackThread(audioFlinger, output, id, device, type),
2721 // mAudioMixer below
2722 // mFastMixer below
2723 mFastMixerFutex(0)
2724 // mOutputSink below
2725 // mPipeSink below
2726 // mNormalSink below
2727{
2728 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002729 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002730 "mFrameCount=%d, mNormalFrameCount=%d",
2731 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2732 mNormalFrameCount);
2733 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2734
2735 // FIXME - Current mixer implementation only supports stereo output
2736 if (mChannelCount != FCC_2) {
2737 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2738 }
2739
2740 // create an NBAIO sink for the HAL output stream, and negotiate
2741 mOutputSink = new AudioStreamOutSink(output->stream);
2742 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002743 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002744 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2745 ALOG_ASSERT(index == 0);
2746
2747 // initialize fast mixer depending on configuration
2748 bool initFastMixer;
2749 switch (kUseFastMixer) {
2750 case FastMixer_Never:
2751 initFastMixer = false;
2752 break;
2753 case FastMixer_Always:
2754 initFastMixer = true;
2755 break;
2756 case FastMixer_Static:
2757 case FastMixer_Dynamic:
2758 initFastMixer = mFrameCount < mNormalFrameCount;
2759 break;
2760 }
2761 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002762 audio_format_t fastMixerFormat;
2763 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2764 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2765 } else {
2766 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2767 }
2768 if (mFormat != fastMixerFormat) {
2769 // change our Sink format to accept our intermediate precision
2770 mFormat = fastMixerFormat;
2771 free(mSinkBuffer);
2772 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2773 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2774 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2775 }
Eric Laurent81784c32012-11-19 14:55:58 -08002776
2777 // create a MonoPipe to connect our submix to FastMixer
2778 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002779 // adjust format to match that of the Fast Mixer
2780 format.mFormat = fastMixerFormat;
2781 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2782
Eric Laurent81784c32012-11-19 14:55:58 -08002783 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2784 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2785 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2786 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2787 const NBAIO_Format offers[1] = {format};
2788 size_t numCounterOffers = 0;
2789 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2790 ALOG_ASSERT(index == 0);
2791 monoPipe->setAvgFrames((mScreenState & 1) ?
2792 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2793 mPipeSink = monoPipe;
2794
Glenn Kasten46909e72013-02-26 09:20:22 -08002795#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002796 if (mTeeSinkOutputEnabled) {
2797 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2798 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2799 numCounterOffers = 0;
2800 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2801 ALOG_ASSERT(index == 0);
2802 mTeeSink = teeSink;
2803 PipeReader *teeSource = new PipeReader(*teeSink);
2804 numCounterOffers = 0;
2805 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2806 ALOG_ASSERT(index == 0);
2807 mTeeSource = teeSource;
2808 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002809#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002810
2811 // create fast mixer and configure it initially with just one fast track for our submix
2812 mFastMixer = new FastMixer();
2813 FastMixerStateQueue *sq = mFastMixer->sq();
2814#ifdef STATE_QUEUE_DUMP
2815 sq->setObserverDump(&mStateQueueObserverDump);
2816 sq->setMutatorDump(&mStateQueueMutatorDump);
2817#endif
2818 FastMixerState *state = sq->begin();
2819 FastTrack *fastTrack = &state->mFastTracks[0];
2820 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2821 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2822 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002823 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2824 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002825 fastTrack->mGeneration++;
2826 state->mFastTracksGen++;
2827 state->mTrackMask = 1;
2828 // fast mixer will use the HAL output sink
2829 state->mOutputSink = mOutputSink.get();
2830 state->mOutputSinkGen++;
2831 state->mFrameCount = mFrameCount;
2832 state->mCommand = FastMixerState::COLD_IDLE;
2833 // already done in constructor initialization list
2834 //mFastMixerFutex = 0;
2835 state->mColdFutexAddr = &mFastMixerFutex;
2836 state->mColdGen++;
2837 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002838#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002839 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002840#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002841 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2842 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002843 sq->end();
2844 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2845
2846 // start the fast mixer
2847 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2848 pid_t tid = mFastMixer->getTid();
2849 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2850 if (err != 0) {
2851 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2852 kPriorityFastMixer, getpid_cached, tid, err);
2853 }
2854
2855#ifdef AUDIO_WATCHDOG
2856 // create and start the watchdog
2857 mAudioWatchdog = new AudioWatchdog();
2858 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2859 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2860 tid = mAudioWatchdog->getTid();
2861 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2862 if (err != 0) {
2863 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2864 kPriorityFastMixer, getpid_cached, tid, err);
2865 }
2866#endif
2867
Eric Laurent81784c32012-11-19 14:55:58 -08002868 }
2869
2870 switch (kUseFastMixer) {
2871 case FastMixer_Never:
2872 case FastMixer_Dynamic:
2873 mNormalSink = mOutputSink;
2874 break;
2875 case FastMixer_Always:
2876 mNormalSink = mPipeSink;
2877 break;
2878 case FastMixer_Static:
2879 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2880 break;
2881 }
2882}
2883
2884AudioFlinger::MixerThread::~MixerThread()
2885{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002886 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002887 FastMixerStateQueue *sq = mFastMixer->sq();
2888 FastMixerState *state = sq->begin();
2889 if (state->mCommand == FastMixerState::COLD_IDLE) {
2890 int32_t old = android_atomic_inc(&mFastMixerFutex);
2891 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002892 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002893 }
2894 }
2895 state->mCommand = FastMixerState::EXIT;
2896 sq->end();
2897 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2898 mFastMixer->join();
2899 // Though the fast mixer thread has exited, it's state queue is still valid.
2900 // We'll use that extract the final state which contains one remaining fast track
2901 // corresponding to our sub-mix.
2902 state = sq->begin();
2903 ALOG_ASSERT(state->mTrackMask == 1);
2904 FastTrack *fastTrack = &state->mFastTracks[0];
2905 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2906 delete fastTrack->mBufferProvider;
2907 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002908 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002909#ifdef AUDIO_WATCHDOG
2910 if (mAudioWatchdog != 0) {
2911 mAudioWatchdog->requestExit();
2912 mAudioWatchdog->requestExitAndWait();
2913 mAudioWatchdog.clear();
2914 }
2915#endif
2916 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002917 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002918 delete mAudioMixer;
2919}
2920
2921
2922uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2923{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002924 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002925 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2926 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2927 }
2928 return latency;
2929}
2930
2931
2932void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2933{
2934 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2935}
2936
Eric Laurentbfb1b832013-01-07 09:53:42 -08002937ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002938{
2939 // FIXME we should only do one push per cycle; confirm this is true
2940 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002941 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002942 FastMixerStateQueue *sq = mFastMixer->sq();
2943 FastMixerState *state = sq->begin();
2944 if (state->mCommand != FastMixerState::MIX_WRITE &&
2945 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2946 if (state->mCommand == FastMixerState::COLD_IDLE) {
2947 int32_t old = android_atomic_inc(&mFastMixerFutex);
2948 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002949 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002950 }
2951#ifdef AUDIO_WATCHDOG
2952 if (mAudioWatchdog != 0) {
2953 mAudioWatchdog->resume();
2954 }
2955#endif
2956 }
2957 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002958 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2959 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002960 sq->end();
2961 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2962 if (kUseFastMixer == FastMixer_Dynamic) {
2963 mNormalSink = mPipeSink;
2964 }
2965 } else {
2966 sq->end(false /*didModify*/);
2967 }
2968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002969 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002970}
2971
2972void AudioFlinger::MixerThread::threadLoop_standby()
2973{
2974 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002975 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002976 FastMixerStateQueue *sq = mFastMixer->sq();
2977 FastMixerState *state = sq->begin();
2978 if (!(state->mCommand & FastMixerState::IDLE)) {
2979 state->mCommand = FastMixerState::COLD_IDLE;
2980 state->mColdFutexAddr = &mFastMixerFutex;
2981 state->mColdGen++;
2982 mFastMixerFutex = 0;
2983 sq->end();
2984 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2985 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2986 if (kUseFastMixer == FastMixer_Dynamic) {
2987 mNormalSink = mOutputSink;
2988 }
2989#ifdef AUDIO_WATCHDOG
2990 if (mAudioWatchdog != 0) {
2991 mAudioWatchdog->pause();
2992 }
2993#endif
2994 } else {
2995 sq->end(false /*didModify*/);
2996 }
2997 }
2998 PlaybackThread::threadLoop_standby();
2999}
3000
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3002{
3003 return false;
3004}
3005
3006bool AudioFlinger::PlaybackThread::shouldStandby_l()
3007{
3008 return !mStandby;
3009}
3010
3011bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3012{
3013 Mutex::Autolock _l(mLock);
3014 return waitingAsyncCallback_l();
3015}
3016
Eric Laurent81784c32012-11-19 14:55:58 -08003017// shared by MIXER and DIRECT, overridden by DUPLICATING
3018void AudioFlinger::PlaybackThread::threadLoop_standby()
3019{
3020 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3021 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003022 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003023 // discard any pending drain or write ack by incrementing sequence
3024 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3025 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003027 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3028 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003029 }
Eric Laurent81784c32012-11-19 14:55:58 -08003030}
3031
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003032void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3033{
3034 ALOGV("signal playback thread");
3035 broadcast_l();
3036}
3037
Eric Laurent81784c32012-11-19 14:55:58 -08003038void AudioFlinger::MixerThread::threadLoop_mix()
3039{
3040 // obtain the presentation timestamp of the next output buffer
3041 int64_t pts;
3042 status_t status = INVALID_OPERATION;
3043
3044 if (mNormalSink != 0) {
3045 status = mNormalSink->getNextWriteTimestamp(&pts);
3046 } else {
3047 status = mOutputSink->getNextWriteTimestamp(&pts);
3048 }
3049
3050 if (status != NO_ERROR) {
3051 pts = AudioBufferProvider::kInvalidPTS;
3052 }
3053
3054 // mix buffers...
3055 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003056 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003057 // increase sleep time progressively when application underrun condition clears.
3058 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3059 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3060 // such that we would underrun the audio HAL.
3061 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3062 sleepTimeShift--;
3063 }
3064 sleepTime = 0;
3065 standbyTime = systemTime() + standbyDelay;
3066 //TODO: delay standby when effects have a tail
3067}
3068
3069void AudioFlinger::MixerThread::threadLoop_sleepTime()
3070{
3071 // If no tracks are ready, sleep once for the duration of an output
3072 // buffer size, then write 0s to the output
3073 if (sleepTime == 0) {
3074 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3075 sleepTime = activeSleepTime >> sleepTimeShift;
3076 if (sleepTime < kMinThreadSleepTimeUs) {
3077 sleepTime = kMinThreadSleepTimeUs;
3078 }
3079 // reduce sleep time in case of consecutive application underruns to avoid
3080 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3081 // duration we would end up writing less data than needed by the audio HAL if
3082 // the condition persists.
3083 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3084 sleepTimeShift++;
3085 }
3086 } else {
3087 sleepTime = idleSleepTime;
3088 }
3089 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003090 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3091 // before effects processing or output.
3092 if (mMixerBufferValid) {
3093 memset(mMixerBuffer, 0, mMixerBufferSize);
3094 } else {
3095 memset(mSinkBuffer, 0, mSinkBufferSize);
3096 }
Eric Laurent81784c32012-11-19 14:55:58 -08003097 sleepTime = 0;
3098 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3099 "anticipated start");
3100 }
3101 // TODO add standby time extension fct of effect tail
3102}
3103
3104// prepareTracks_l() must be called with ThreadBase::mLock held
3105AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3106 Vector< sp<Track> > *tracksToRemove)
3107{
3108
3109 mixer_state mixerStatus = MIXER_IDLE;
3110 // find out which tracks need to be processed
3111 size_t count = mActiveTracks.size();
3112 size_t mixedTracks = 0;
3113 size_t tracksWithEffect = 0;
3114 // counts only _active_ fast tracks
3115 size_t fastTracks = 0;
3116 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3117
3118 float masterVolume = mMasterVolume;
3119 bool masterMute = mMasterMute;
3120
3121 if (masterMute) {
3122 masterVolume = 0;
3123 }
3124 // Delegate master volume control to effect in output mix effect chain if needed
3125 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3126 if (chain != 0) {
3127 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3128 chain->setVolume_l(&v, &v);
3129 masterVolume = (float)((v + (1 << 23)) >> 24);
3130 chain.clear();
3131 }
3132
3133 // prepare a new state to push
3134 FastMixerStateQueue *sq = NULL;
3135 FastMixerState *state = NULL;
3136 bool didModify = false;
3137 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003138 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003139 sq = mFastMixer->sq();
3140 state = sq->begin();
3141 }
3142
Andy Hung69aed5f2014-02-25 17:24:40 -08003143 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003144 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003145
Eric Laurent81784c32012-11-19 14:55:58 -08003146 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003147 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003148 if (t == 0) {
3149 continue;
3150 }
3151
3152 // this const just means the local variable doesn't change
3153 Track* const track = t.get();
3154
3155 // process fast tracks
3156 if (track->isFastTrack()) {
3157
3158 // It's theoretically possible (though unlikely) for a fast track to be created
3159 // and then removed within the same normal mix cycle. This is not a problem, as
3160 // the track never becomes active so it's fast mixer slot is never touched.
3161 // The converse, of removing an (active) track and then creating a new track
3162 // at the identical fast mixer slot within the same normal mix cycle,
3163 // is impossible because the slot isn't marked available until the end of each cycle.
3164 int j = track->mFastIndex;
3165 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3166 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3167 FastTrack *fastTrack = &state->mFastTracks[j];
3168
3169 // Determine whether the track is currently in underrun condition,
3170 // and whether it had a recent underrun.
3171 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3172 FastTrackUnderruns underruns = ftDump->mUnderruns;
3173 uint32_t recentFull = (underruns.mBitFields.mFull -
3174 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3175 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3176 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3177 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3178 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3179 uint32_t recentUnderruns = recentPartial + recentEmpty;
3180 track->mObservedUnderruns = underruns;
3181 // don't count underruns that occur while stopping or pausing
3182 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003183 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3184 recentUnderruns > 0) {
3185 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3186 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003187 }
3188
3189 // This is similar to the state machine for normal tracks,
3190 // with a few modifications for fast tracks.
3191 bool isActive = true;
3192 switch (track->mState) {
3193 case TrackBase::STOPPING_1:
3194 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003196 track->mState = TrackBase::STOPPING_2;
3197 }
3198 break;
3199 case TrackBase::PAUSING:
3200 // ramp down is not yet implemented
3201 track->setPaused();
3202 break;
3203 case TrackBase::RESUMING:
3204 // ramp up is not yet implemented
3205 track->mState = TrackBase::ACTIVE;
3206 break;
3207 case TrackBase::ACTIVE:
3208 if (recentFull > 0 || recentPartial > 0) {
3209 // track has provided at least some frames recently: reset retry count
3210 track->mRetryCount = kMaxTrackRetries;
3211 }
3212 if (recentUnderruns == 0) {
3213 // no recent underruns: stay active
3214 break;
3215 }
3216 // there has recently been an underrun of some kind
3217 if (track->sharedBuffer() == 0) {
3218 // were any of the recent underruns "empty" (no frames available)?
3219 if (recentEmpty == 0) {
3220 // no, then ignore the partial underruns as they are allowed indefinitely
3221 break;
3222 }
3223 // there has recently been an "empty" underrun: decrement the retry counter
3224 if (--(track->mRetryCount) > 0) {
3225 break;
3226 }
3227 // indicate to client process that the track was disabled because of underrun;
3228 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003229 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003230 // remove from active list, but state remains ACTIVE [confusing but true]
3231 isActive = false;
3232 break;
3233 }
3234 // fall through
3235 case TrackBase::STOPPING_2:
3236 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003237 case TrackBase::STOPPED:
3238 case TrackBase::FLUSHED: // flush() while active
3239 // Check for presentation complete if track is inactive
3240 // We have consumed all the buffers of this track.
3241 // This would be incomplete if we auto-paused on underrun
3242 {
3243 size_t audioHALFrames =
3244 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3245 size_t framesWritten = mBytesWritten / mFrameSize;
3246 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3247 // track stays in active list until presentation is complete
3248 break;
3249 }
3250 }
3251 if (track->isStopping_2()) {
3252 track->mState = TrackBase::STOPPED;
3253 }
3254 if (track->isStopped()) {
3255 // Can't reset directly, as fast mixer is still polling this track
3256 // track->reset();
3257 // So instead mark this track as needing to be reset after push with ack
3258 resetMask |= 1 << i;
3259 }
3260 isActive = false;
3261 break;
3262 case TrackBase::IDLE:
3263 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003264 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003265 }
3266
3267 if (isActive) {
3268 // was it previously inactive?
3269 if (!(state->mTrackMask & (1 << j))) {
3270 ExtendedAudioBufferProvider *eabp = track;
3271 VolumeProvider *vp = track;
3272 fastTrack->mBufferProvider = eabp;
3273 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003274 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003275 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003276 fastTrack->mGeneration++;
3277 state->mTrackMask |= 1 << j;
3278 didModify = true;
3279 // no acknowledgement required for newly active tracks
3280 }
3281 // cache the combined master volume and stream type volume for fast mixer; this
3282 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003283 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003284 ++fastTracks;
3285 } else {
3286 // was it previously active?
3287 if (state->mTrackMask & (1 << j)) {
3288 fastTrack->mBufferProvider = NULL;
3289 fastTrack->mGeneration++;
3290 state->mTrackMask &= ~(1 << j);
3291 didModify = true;
3292 // If any fast tracks were removed, we must wait for acknowledgement
3293 // because we're about to decrement the last sp<> on those tracks.
3294 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3295 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003296 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003297 }
3298 tracksToRemove->add(track);
3299 // Avoids a misleading display in dumpsys
3300 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3301 }
3302 continue;
3303 }
3304
3305 { // local variable scope to avoid goto warning
3306
3307 audio_track_cblk_t* cblk = track->cblk();
3308
3309 // The first time a track is added we wait
3310 // for all its buffers to be filled before processing it
3311 int name = track->name();
3312 // make sure that we have enough frames to mix one full buffer.
3313 // enforce this condition only once to enable draining the buffer in case the client
3314 // app does not call stop() and relies on underrun to stop:
3315 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3316 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003317 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003318 uint32_t sr = track->sampleRate();
3319 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003320 desiredFrames = mNormalFrameCount;
3321 } else {
3322 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003323 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003324 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003325 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003326 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003327#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003328 // the minimum track buffer size is normally twice the number of frames necessary
3329 // to fill one buffer and the resampler should not leave more than one buffer worth
3330 // of unreleased frames after each pass, but just in case...
3331 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003332#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003333 }
Eric Laurent81784c32012-11-19 14:55:58 -08003334 uint32_t minFrames = 1;
3335 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3336 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003337 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003338 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003339
3340 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003341 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003342 !track->isPaused() && !track->isTerminated())
3343 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003344 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003345
3346 mixedTracks++;
3347
Andy Hung69aed5f2014-02-25 17:24:40 -08003348 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3349 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003350 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003351 if (track->mainBuffer() != mSinkBuffer &&
3352 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003353 if (mEffectBufferEnabled) {
3354 mEffectBufferValid = true; // Later can set directly.
3355 }
Eric Laurent81784c32012-11-19 14:55:58 -08003356 chain = getEffectChain_l(track->sessionId());
3357 // Delegate volume control to effect in track effect chain if needed
3358 if (chain != 0) {
3359 tracksWithEffect++;
3360 } else {
3361 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3362 "session %d",
3363 name, track->sessionId());
3364 }
3365 }
3366
3367
3368 int param = AudioMixer::VOLUME;
3369 if (track->mFillingUpStatus == Track::FS_FILLED) {
3370 // no ramp for the first volume setting
3371 track->mFillingUpStatus = Track::FS_ACTIVE;
3372 if (track->mState == TrackBase::RESUMING) {
3373 track->mState = TrackBase::ACTIVE;
3374 param = AudioMixer::RAMP_VOLUME;
3375 }
3376 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003377 // FIXME should not make a decision based on mServer
3378 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003379 // If the track is stopped before the first frame was mixed,
3380 // do not apply ramp
3381 param = AudioMixer::RAMP_VOLUME;
3382 }
3383
3384 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003385 uint32_t vl, vr; // in U8.24 integer format
3386 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003387 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003388 vl = vr = 0;
3389 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003390 if (track->isPausing()) {
3391 track->setPaused();
3392 }
3393 } else {
3394
3395 // read original volumes with volume control
3396 float typeVolume = mStreamTypes[track->streamType()].volume;
3397 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003398 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003399 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003400 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3401 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003402 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003403 if (vlf > GAIN_FLOAT_UNITY) {
3404 ALOGV("Track left volume out of range: %.3g", vlf);
3405 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003406 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003407 if (vrf > GAIN_FLOAT_UNITY) {
3408 ALOGV("Track right volume out of range: %.3g", vrf);
3409 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003410 }
3411 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003412 vlf *= v;
3413 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003414 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003415 // then derive vl and vr as U8.24 versions for the effect chain
3416 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3417 vl = (uint32_t) (scaleto8_24 * vlf);
3418 vr = (uint32_t) (scaleto8_24 * vrf);
3419 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003420 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003421 // send level comes from shared memory and so may be corrupt
3422 if (sendLevel > MAX_GAIN_INT) {
3423 ALOGV("Track send level out of range: %04X", sendLevel);
3424 sendLevel = MAX_GAIN_INT;
3425 }
Andy Hung6be49402014-05-30 10:42:03 -07003426 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3427 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003428 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429
Eric Laurent81784c32012-11-19 14:55:58 -08003430 // Delegate volume control to effect in track effect chain if needed
3431 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3432 // Do not ramp volume if volume is controlled by effect
3433 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003434 // Update remaining floating point volume levels
3435 vlf = (float)vl / (1 << 24);
3436 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003437 track->mHasVolumeController = true;
3438 } else {
3439 // force no volume ramp when volume controller was just disabled or removed
3440 // from effect chain to avoid volume spike
3441 if (track->mHasVolumeController) {
3442 param = AudioMixer::VOLUME;
3443 }
3444 track->mHasVolumeController = false;
3445 }
3446
Eric Laurent81784c32012-11-19 14:55:58 -08003447 // XXX: these things DON'T need to be done each time
3448 mAudioMixer->setBufferProvider(name, track);
3449 mAudioMixer->enable(name);
3450
Andy Hung6be49402014-05-30 10:42:03 -07003451 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3452 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3453 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003454 mAudioMixer->setParameter(
3455 name,
3456 AudioMixer::TRACK,
3457 AudioMixer::FORMAT, (void *)track->format());
3458 mAudioMixer->setParameter(
3459 name,
3460 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003461 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003462 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3463 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003464 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003465 if (reqSampleRate == 0) {
3466 reqSampleRate = mSampleRate;
3467 } else if (reqSampleRate > maxSampleRate) {
3468 reqSampleRate = maxSampleRate;
3469 }
Eric Laurent81784c32012-11-19 14:55:58 -08003470 mAudioMixer->setParameter(
3471 name,
3472 AudioMixer::RESAMPLE,
3473 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003474 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003475 /*
3476 * Select the appropriate output buffer for the track.
3477 *
Andy Hung98ef9782014-03-04 14:46:50 -08003478 * Tracks with effects go into their own effects chain buffer
3479 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003480 *
3481 * Other tracks can use mMixerBuffer for higher precision
3482 * channel accumulation. If this buffer is enabled
3483 * (mMixerBufferEnabled true), then selected tracks will accumulate
3484 * into it.
3485 *
3486 */
3487 if (mMixerBufferEnabled
3488 && (track->mainBuffer() == mSinkBuffer
3489 || track->mainBuffer() == mMixerBuffer)) {
3490 mAudioMixer->setParameter(
3491 name,
3492 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003493 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003494 mAudioMixer->setParameter(
3495 name,
3496 AudioMixer::TRACK,
3497 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3498 // TODO: override track->mainBuffer()?
3499 mMixerBufferValid = true;
3500 } else {
3501 mAudioMixer->setParameter(
3502 name,
3503 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003504 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003505 mAudioMixer->setParameter(
3506 name,
3507 AudioMixer::TRACK,
3508 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3509 }
Eric Laurent81784c32012-11-19 14:55:58 -08003510 mAudioMixer->setParameter(
3511 name,
3512 AudioMixer::TRACK,
3513 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3514
3515 // reset retry count
3516 track->mRetryCount = kMaxTrackRetries;
3517
3518 // If one track is ready, set the mixer ready if:
3519 // - the mixer was not ready during previous round OR
3520 // - no other track is not ready
3521 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3522 mixerStatus != MIXER_TRACKS_ENABLED) {
3523 mixerStatus = MIXER_TRACKS_READY;
3524 }
3525 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003526 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003527 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003528 }
Eric Laurent81784c32012-11-19 14:55:58 -08003529 // clear effect chain input buffer if an active track underruns to avoid sending
3530 // previous audio buffer again to effects
3531 chain = getEffectChain_l(track->sessionId());
3532 if (chain != 0) {
3533 chain->clearInputBuffer();
3534 }
3535
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003536 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3538 track->isStopped() || track->isPaused()) {
3539 // We have consumed all the buffers of this track.
3540 // Remove it from the list of active tracks.
3541 // TODO: use actual buffer filling status instead of latency when available from
3542 // audio HAL
3543 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3544 size_t framesWritten = mBytesWritten / mFrameSize;
3545 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3546 if (track->isStopped()) {
3547 track->reset();
3548 }
3549 tracksToRemove->add(track);
3550 }
3551 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003552 // No buffers for this track. Give it a few chances to
3553 // fill a buffer, then remove it from active list.
3554 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003555 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003556 tracksToRemove->add(track);
3557 // indicate to client process that the track was disabled because of underrun;
3558 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003559 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003560 // If one track is not ready, mark the mixer also not ready if:
3561 // - the mixer was ready during previous round OR
3562 // - no other track is ready
3563 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3564 mixerStatus != MIXER_TRACKS_READY) {
3565 mixerStatus = MIXER_TRACKS_ENABLED;
3566 }
3567 }
3568 mAudioMixer->disable(name);
3569 }
3570
3571 } // local variable scope to avoid goto warning
3572track_is_ready: ;
3573
3574 }
3575
3576 // Push the new FastMixer state if necessary
3577 bool pauseAudioWatchdog = false;
3578 if (didModify) {
3579 state->mFastTracksGen++;
3580 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3581 if (kUseFastMixer == FastMixer_Dynamic &&
3582 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3583 state->mCommand = FastMixerState::COLD_IDLE;
3584 state->mColdFutexAddr = &mFastMixerFutex;
3585 state->mColdGen++;
3586 mFastMixerFutex = 0;
3587 if (kUseFastMixer == FastMixer_Dynamic) {
3588 mNormalSink = mOutputSink;
3589 }
3590 // If we go into cold idle, need to wait for acknowledgement
3591 // so that fast mixer stops doing I/O.
3592 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3593 pauseAudioWatchdog = true;
3594 }
Eric Laurent81784c32012-11-19 14:55:58 -08003595 }
3596 if (sq != NULL) {
3597 sq->end(didModify);
3598 sq->push(block);
3599 }
3600#ifdef AUDIO_WATCHDOG
3601 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3602 mAudioWatchdog->pause();
3603 }
3604#endif
3605
3606 // Now perform the deferred reset on fast tracks that have stopped
3607 while (resetMask != 0) {
3608 size_t i = __builtin_ctz(resetMask);
3609 ALOG_ASSERT(i < count);
3610 resetMask &= ~(1 << i);
3611 sp<Track> t = mActiveTracks[i].promote();
3612 if (t == 0) {
3613 continue;
3614 }
3615 Track* track = t.get();
3616 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3617 track->reset();
3618 }
3619
3620 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003622
Andy Hung69aed5f2014-02-25 17:24:40 -08003623 // sink or mix buffer must be cleared if all tracks are connected to an
3624 // effect chain as in this case the mixer will not write to the sink or mix buffer
3625 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3627 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003628 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003629 if (mMixerBufferValid) {
3630 memset(mMixerBuffer, 0, mMixerBufferSize);
3631 // TODO: In testing, mSinkBuffer below need not be cleared because
3632 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3633 // after mixing.
3634 //
3635 // To enforce this guarantee:
3636 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3637 // (mixedTracks == 0 && fastTracks > 0))
3638 // must imply MIXER_TRACKS_READY.
3639 // Later, we may clear buffers regardless, and skip much of this logic.
3640 }
Andy Hung98ef9782014-03-04 14:46:50 -08003641 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3642 if (mEffectBufferValid) {
3643 memset(mEffectBuffer, 0, mEffectBufferSize);
3644 }
3645 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003646 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003647 }
3648
3649 // if any fast tracks, then status is ready
3650 mMixerStatusIgnoringFastTracks = mixerStatus;
3651 if (fastTracks > 0) {
3652 mixerStatus = MIXER_TRACKS_READY;
3653 }
3654 return mixerStatus;
3655}
3656
3657// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003658int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3659 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003660{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003661 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003662}
3663
3664// deleteTrackName_l() must be called with ThreadBase::mLock held
3665void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3666{
3667 ALOGV("remove track (%d) and delete from mixer", name);
3668 mAudioMixer->deleteTrackName(name);
3669}
3670
Eric Laurent10351942014-05-08 18:49:52 -07003671// checkForNewParameter_l() must be called with ThreadBase::mLock held
3672bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3673 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003674{
Eric Laurent81784c32012-11-19 14:55:58 -08003675 bool reconfig = false;
3676
Eric Laurent10351942014-05-08 18:49:52 -07003677 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003678
Eric Laurent10351942014-05-08 18:49:52 -07003679 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3680 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003681 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003682 FastMixerStateQueue *sq = mFastMixer->sq();
3683 FastMixerState *state = sq->begin();
3684 if (!(state->mCommand & FastMixerState::IDLE)) {
3685 previousCommand = state->mCommand;
3686 state->mCommand = FastMixerState::HOT_IDLE;
3687 sq->end();
3688 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3689 } else {
3690 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003691 }
Eric Laurent10351942014-05-08 18:49:52 -07003692 }
Eric Laurent81784c32012-11-19 14:55:58 -08003693
Eric Laurent10351942014-05-08 18:49:52 -07003694 AudioParameter param = AudioParameter(keyValuePair);
3695 int value;
3696 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3697 reconfig = true;
3698 }
3699 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3700 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3701 status = BAD_VALUE;
3702 } else {
3703 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003704 reconfig = true;
3705 }
Eric Laurent10351942014-05-08 18:49:52 -07003706 }
3707 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3708 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3709 status = BAD_VALUE;
3710 } else {
3711 // no need to save value, since it's constant
3712 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003713 }
Eric Laurent10351942014-05-08 18:49:52 -07003714 }
3715 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3716 // do not accept frame count changes if tracks are open as the track buffer
3717 // size depends on frame count and correct behavior would not be guaranteed
3718 // if frame count is changed after track creation
3719 if (!mTracks.isEmpty()) {
3720 status = INVALID_OPERATION;
3721 } else {
3722 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003723 }
Eric Laurent10351942014-05-08 18:49:52 -07003724 }
3725 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003726#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003727 // when changing the audio output device, call addBatteryData to notify
3728 // the change
3729 if (mOutDevice != value) {
3730 uint32_t params = 0;
3731 // check whether speaker is on
3732 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3733 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003734 }
Eric Laurent10351942014-05-08 18:49:52 -07003735
3736 audio_devices_t deviceWithoutSpeaker
3737 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3738 // check if any other device (except speaker) is on
3739 if (value & deviceWithoutSpeaker ) {
3740 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3741 }
3742
3743 if (params != 0) {
3744 addBatteryData(params);
3745 }
3746 }
Eric Laurent81784c32012-11-19 14:55:58 -08003747#endif
3748
Eric Laurent10351942014-05-08 18:49:52 -07003749 // forward device change to effects that have requested to be
3750 // aware of attached audio device.
3751 if (value != AUDIO_DEVICE_NONE) {
3752 mOutDevice = value;
3753 for (size_t i = 0; i < mEffectChains.size(); i++) {
3754 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003755 }
3756 }
Eric Laurent10351942014-05-08 18:49:52 -07003757 }
Eric Laurent81784c32012-11-19 14:55:58 -08003758
Eric Laurent10351942014-05-08 18:49:52 -07003759 if (status == NO_ERROR) {
3760 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3761 keyValuePair.string());
3762 if (!mStandby && status == INVALID_OPERATION) {
3763 mOutput->stream->common.standby(&mOutput->stream->common);
3764 mStandby = true;
3765 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003766 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003767 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003768 }
Eric Laurent10351942014-05-08 18:49:52 -07003769 if (status == NO_ERROR && reconfig) {
3770 readOutputParameters_l();
3771 delete mAudioMixer;
3772 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3773 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003774 int name = getTrackName_l(mTracks[i]->mChannelMask,
3775 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003776 if (name < 0) {
3777 break;
3778 }
3779 mTracks[i]->mName = name;
3780 }
3781 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3782 }
Eric Laurent81784c32012-11-19 14:55:58 -08003783 }
3784
3785 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003786 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003787 FastMixerStateQueue *sq = mFastMixer->sq();
3788 FastMixerState *state = sq->begin();
3789 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3790 state->mCommand = previousCommand;
3791 sq->end();
3792 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3793 }
3794
3795 return reconfig;
3796}
3797
3798
3799void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3800{
3801 const size_t SIZE = 256;
3802 char buffer[SIZE];
3803 String8 result;
3804
3805 PlaybackThread::dumpInternals(fd, args);
3806
Elliott Hughes87cebad2014-05-22 10:14:43 -07003807 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003808
3809 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003810 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003811 copy.dump(fd);
3812
3813#ifdef STATE_QUEUE_DUMP
3814 // Similar for state queue
3815 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3816 observerCopy.dump(fd);
3817 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3818 mutatorCopy.dump(fd);
3819#endif
3820
Glenn Kasten46909e72013-02-26 09:20:22 -08003821#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003822 // Write the tee output to a .wav file
3823 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003824#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003825
3826#ifdef AUDIO_WATCHDOG
3827 if (mAudioWatchdog != 0) {
3828 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3829 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3830 wdCopy.dump(fd);
3831 }
3832#endif
3833}
3834
3835uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3836{
3837 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3838}
3839
3840uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3841{
3842 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3843}
3844
3845void AudioFlinger::MixerThread::cacheParameters_l()
3846{
3847 PlaybackThread::cacheParameters_l();
3848
3849 // FIXME: Relaxed timing because of a certain device that can't meet latency
3850 // Should be reduced to 2x after the vendor fixes the driver issue
3851 // increase threshold again due to low power audio mode. The way this warning
3852 // threshold is calculated and its usefulness should be reconsidered anyway.
3853 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3854}
3855
3856// ----------------------------------------------------------------------------
3857
3858AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3859 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3860 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3861 // mLeftVolFloat, mRightVolFloat
3862{
3863}
3864
Eric Laurentbfb1b832013-01-07 09:53:42 -08003865AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3866 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3867 ThreadBase::type_t type)
3868 : PlaybackThread(audioFlinger, output, id, device, type)
3869 // mLeftVolFloat, mRightVolFloat
3870{
3871}
3872
Eric Laurent81784c32012-11-19 14:55:58 -08003873AudioFlinger::DirectOutputThread::~DirectOutputThread()
3874{
3875}
3876
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3878{
3879 audio_track_cblk_t* cblk = track->cblk();
3880 float left, right;
3881
3882 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3883 left = right = 0;
3884 } else {
3885 float typeVolume = mStreamTypes[track->streamType()].volume;
3886 float v = mMasterVolume * typeVolume;
3887 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003888 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3889 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3890 if (left > GAIN_FLOAT_UNITY) {
3891 left = GAIN_FLOAT_UNITY;
3892 }
3893 left *= v;
3894 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3895 if (right > GAIN_FLOAT_UNITY) {
3896 right = GAIN_FLOAT_UNITY;
3897 }
3898 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 }
3900
3901 if (lastTrack) {
3902 if (left != mLeftVolFloat || right != mRightVolFloat) {
3903 mLeftVolFloat = left;
3904 mRightVolFloat = right;
3905
3906 // Convert volumes from float to 8.24
3907 uint32_t vl = (uint32_t)(left * (1 << 24));
3908 uint32_t vr = (uint32_t)(right * (1 << 24));
3909
3910 // Delegate volume control to effect in track effect chain if needed
3911 // only one effect chain can be present on DirectOutputThread, so if
3912 // there is one, the track is connected to it
3913 if (!mEffectChains.isEmpty()) {
3914 mEffectChains[0]->setVolume_l(&vl, &vr);
3915 left = (float)vl / (1 << 24);
3916 right = (float)vr / (1 << 24);
3917 }
3918 if (mOutput->stream->set_volume) {
3919 mOutput->stream->set_volume(mOutput->stream, left, right);
3920 }
3921 }
3922 }
3923}
3924
3925
Eric Laurent81784c32012-11-19 14:55:58 -08003926AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3927 Vector< sp<Track> > *tracksToRemove
3928)
3929{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003930 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003931 mixer_state mixerStatus = MIXER_IDLE;
3932
3933 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003934 for (size_t i = 0; i < count; i++) {
3935 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003936 // The track died recently
3937 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003938 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
3940
3941 Track* const track = t.get();
3942 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003943 // Only consider last track started for volume and mixer state control.
3944 // In theory an older track could underrun and restart after the new one starts
3945 // but as we only care about the transition phase between two tracks on a
3946 // direct output, it is not a problem to ignore the underrun case.
3947 sp<Track> l = mLatestActiveTrack.promote();
3948 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003949
3950 // The first time a track is added we wait
3951 // for all its buffers to be filled before processing it
3952 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07003953 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003954 minFrames = mNormalFrameCount;
3955 } else {
3956 minFrames = 1;
3957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958
Eric Laurentab5cdba2014-06-09 17:22:27 -07003959 ALOGI("prepareTracks_l minFrames %d state %d frames ready %d, ",
3960 minFrames, track->mState, track->framesReady());
3961 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
3962 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08003963 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003964 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003965
3966 if (track->mFillingUpStatus == Track::FS_FILLED) {
3967 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003968 // make sure processVolume_l() will apply new volume even if 0
3969 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 if (track->mState == TrackBase::RESUMING) {
3971 track->mState = TrackBase::ACTIVE;
3972 }
3973 }
3974
3975 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003976 processVolume_l(track, last);
3977 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003978 // reset retry count
3979 track->mRetryCount = kMaxTrackRetriesDirect;
3980 mActiveTrack = t;
3981 mixerStatus = MIXER_TRACKS_READY;
3982 }
Eric Laurent81784c32012-11-19 14:55:58 -08003983 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003984 // clear effect chain input buffer if the last active track started underruns
3985 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003986 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003987 mEffectChains[0]->clearInputBuffer();
3988 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07003989 if (track->isStopping_1()) {
3990 track->mState = TrackBase::STOPPING_2;
3991 }
3992 if ((track->sharedBuffer() != 0) || track->isStopped() ||
3993 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003994 // We have consumed all the buffers of this track.
3995 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07003996 size_t audioHALFrames;
3997 if (audio_is_linear_pcm(mFormat)) {
3998 audioHALFrames = (latency_l() * mSampleRate) / 1000;
3999 } else {
4000 audioHALFrames = 0;
4001 }
4002
Eric Laurent81784c32012-11-19 14:55:58 -08004003 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004004 if (mStandby || !last ||
4005 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004006 if (track->isStopping_2()) {
4007 track->mState = TrackBase::STOPPED;
4008 }
Eric Laurent81784c32012-11-19 14:55:58 -08004009 if (track->isStopped()) {
4010 track->reset();
4011 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004012 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004013 }
4014 } else {
4015 // No buffers for this track. Give it a few chances to
4016 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004017 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004018 if (--(track->mRetryCount) <= 0) {
4019 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004020 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004021 // indicate to client process that the track was disabled because of underrun;
4022 // it will then automatically call start() when data is available
4023 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004025 mixerStatus = MIXER_TRACKS_ENABLED;
4026 }
4027 }
4028 }
4029 }
4030
Eric Laurent81784c32012-11-19 14:55:58 -08004031 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004032 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004033
4034 return mixerStatus;
4035}
4036
4037void AudioFlinger::DirectOutputThread::threadLoop_mix()
4038{
Eric Laurent81784c32012-11-19 14:55:58 -08004039 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004040 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004041 // output audio to hardware
4042 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004043 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004044 buffer.frameCount = frameCount;
4045 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004046 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004047 memset(curBuf, 0, frameCount * mFrameSize);
4048 break;
4049 }
4050 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4051 frameCount -= buffer.frameCount;
4052 curBuf += buffer.frameCount * mFrameSize;
4053 mActiveTrack->releaseBuffer(&buffer);
4054 }
Andy Hung2098f272014-02-27 14:00:06 -08004055 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004056 sleepTime = 0;
4057 standbyTime = systemTime() + standbyDelay;
4058 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004059}
4060
4061void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4062{
4063 if (sleepTime == 0) {
4064 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4065 sleepTime = activeSleepTime;
4066 } else {
4067 sleepTime = idleSleepTime;
4068 }
4069 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004070 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004071 sleepTime = 0;
4072 }
4073}
4074
4075// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004076int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004077 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004078{
4079 return 0;
4080}
4081
4082// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004083void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004084{
4085}
4086
Eric Laurent10351942014-05-08 18:49:52 -07004087// checkForNewParameter_l() must be called with ThreadBase::mLock held
4088bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4089 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004090{
4091 bool reconfig = false;
4092
Eric Laurent10351942014-05-08 18:49:52 -07004093 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004094
Eric Laurent10351942014-05-08 18:49:52 -07004095 AudioParameter param = AudioParameter(keyValuePair);
4096 int value;
4097 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4098 // forward device change to effects that have requested to be
4099 // aware of attached audio device.
4100 if (value != AUDIO_DEVICE_NONE) {
4101 mOutDevice = value;
4102 for (size_t i = 0; i < mEffectChains.size(); i++) {
4103 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004104 }
4105 }
Eric Laurent81784c32012-11-19 14:55:58 -08004106 }
Eric Laurent10351942014-05-08 18:49:52 -07004107 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4108 // do not accept frame count changes if tracks are open as the track buffer
4109 // size depends on frame count and correct behavior would not be garantied
4110 // if frame count is changed after track creation
4111 if (!mTracks.isEmpty()) {
4112 status = INVALID_OPERATION;
4113 } else {
4114 reconfig = true;
4115 }
4116 }
4117 if (status == NO_ERROR) {
4118 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4119 keyValuePair.string());
4120 if (!mStandby && status == INVALID_OPERATION) {
4121 mOutput->stream->common.standby(&mOutput->stream->common);
4122 mStandby = true;
4123 mBytesWritten = 0;
4124 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4125 keyValuePair.string());
4126 }
4127 if (status == NO_ERROR && reconfig) {
4128 readOutputParameters_l();
4129 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4130 }
4131 }
4132
Eric Laurent81784c32012-11-19 14:55:58 -08004133 return reconfig;
4134}
4135
4136uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4137{
4138 uint32_t time;
4139 if (audio_is_linear_pcm(mFormat)) {
4140 time = PlaybackThread::activeSleepTimeUs();
4141 } else {
4142 time = 10000;
4143 }
4144 return time;
4145}
4146
4147uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4148{
4149 uint32_t time;
4150 if (audio_is_linear_pcm(mFormat)) {
4151 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4152 } else {
4153 time = 10000;
4154 }
4155 return time;
4156}
4157
4158uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4159{
4160 uint32_t time;
4161 if (audio_is_linear_pcm(mFormat)) {
4162 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4163 } else {
4164 time = 10000;
4165 }
4166 return time;
4167}
4168
4169void AudioFlinger::DirectOutputThread::cacheParameters_l()
4170{
4171 PlaybackThread::cacheParameters_l();
4172
4173 // use shorter standby delay as on normal output to release
4174 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004175 if (audio_is_linear_pcm(mFormat)) {
4176 standbyDelay = microseconds(activeSleepTime*2);
4177 } else {
4178 standbyDelay = kOffloadStandbyDelayNs;
4179 }
Eric Laurent81784c32012-11-19 14:55:58 -08004180}
4181
4182// ----------------------------------------------------------------------------
4183
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004185 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004186 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004187 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004188 mWriteAckSequence(0),
4189 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190{
4191}
4192
4193AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4194{
4195}
4196
4197void AudioFlinger::AsyncCallbackThread::onFirstRef()
4198{
4199 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4200}
4201
4202bool AudioFlinger::AsyncCallbackThread::threadLoop()
4203{
4204 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004205 uint32_t writeAckSequence;
4206 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004207
4208 {
4209 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004210 while (!((mWriteAckSequence & 1) ||
4211 (mDrainSequence & 1) ||
4212 exitPending())) {
4213 mWaitWorkCV.wait(mLock);
4214 }
4215
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 if (exitPending()) {
4217 break;
4218 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004219 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4220 mWriteAckSequence, mDrainSequence);
4221 writeAckSequence = mWriteAckSequence;
4222 mWriteAckSequence &= ~1;
4223 drainSequence = mDrainSequence;
4224 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004225 }
4226 {
Eric Laurent4de95592013-09-26 15:28:21 -07004227 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4228 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004229 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004230 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004231 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004232 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004233 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004234 }
4235 }
4236 }
4237 }
4238 return false;
4239}
4240
4241void AudioFlinger::AsyncCallbackThread::exit()
4242{
4243 ALOGV("AsyncCallbackThread::exit");
4244 Mutex::Autolock _l(mLock);
4245 requestExit();
4246 mWaitWorkCV.broadcast();
4247}
4248
Eric Laurent3b4529e2013-09-05 18:09:19 -07004249void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250{
4251 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004252 // bit 0 is cleared
4253 mWriteAckSequence = sequence << 1;
4254}
4255
4256void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4257{
4258 Mutex::Autolock _l(mLock);
4259 // ignore unexpected callbacks
4260 if (mWriteAckSequence & 2) {
4261 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004262 mWaitWorkCV.signal();
4263 }
4264}
4265
Eric Laurent3b4529e2013-09-05 18:09:19 -07004266void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267{
4268 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004269 // bit 0 is cleared
4270 mDrainSequence = sequence << 1;
4271}
4272
4273void AudioFlinger::AsyncCallbackThread::resetDraining()
4274{
4275 Mutex::Autolock _l(mLock);
4276 // ignore unexpected callbacks
4277 if (mDrainSequence & 2) {
4278 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004279 mWaitWorkCV.signal();
4280 }
4281}
4282
4283
4284// ----------------------------------------------------------------------------
4285AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4286 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4287 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4288 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004289 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004290 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291{
Eric Laurentfd477972013-10-25 18:10:40 -07004292 //FIXME: mStandby should be set to true by ThreadBase constructor
4293 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294}
4295
Eric Laurentbfb1b832013-01-07 09:53:42 -08004296void AudioFlinger::OffloadThread::threadLoop_exit()
4297{
4298 if (mFlushPending || mHwPaused) {
4299 // If a flush is pending or track was paused, just discard buffered data
4300 flushHw_l();
4301 } else {
4302 mMixerStatus = MIXER_DRAIN_ALL;
4303 threadLoop_drain();
4304 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004305 if (mUseAsyncWrite) {
4306 ALOG_ASSERT(mCallbackThread != 0);
4307 mCallbackThread->exit();
4308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309 PlaybackThread::threadLoop_exit();
4310}
4311
4312AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4313 Vector< sp<Track> > *tracksToRemove
4314)
4315{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004316 size_t count = mActiveTracks.size();
4317
4318 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004319 bool doHwPause = false;
4320 bool doHwResume = false;
4321
Eric Laurentede6c3b2013-09-19 14:37:46 -07004322 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4323
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324 // find out which tracks need to be processed
4325 for (size_t i = 0; i < count; i++) {
4326 sp<Track> t = mActiveTracks[i].promote();
4327 // The track died recently
4328 if (t == 0) {
4329 continue;
4330 }
4331 Track* const track = t.get();
4332 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004333 // Only consider last track started for volume and mixer state control.
4334 // In theory an older track could underrun and restart after the new one starts
4335 // but as we only care about the transition phase between two tracks on a
4336 // direct output, it is not a problem to ignore the underrun case.
4337 sp<Track> l = mLatestActiveTrack.promote();
4338 bool last = l.get() == track;
4339
Haynes Mathew George7844f672014-01-15 12:32:55 -08004340 if (track->isInvalid()) {
4341 ALOGW("An invalidated track shouldn't be in active list");
4342 tracksToRemove->add(track);
4343 continue;
4344 }
4345
4346 if (track->mState == TrackBase::IDLE) {
4347 ALOGW("An idle track shouldn't be in active list");
4348 continue;
4349 }
4350
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 if (track->isPausing()) {
4352 track->setPaused();
4353 if (last) {
4354 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004355 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 mHwPaused = true;
4357 }
4358 // If we were part way through writing the mixbuffer to
4359 // the HAL we must save this until we resume
4360 // BUG - this will be wrong if a different track is made active,
4361 // in that case we want to discard the pending data in the
4362 // mixbuffer and tell the client to present it again when the
4363 // track is resumed
4364 mPausedWriteLength = mCurrentWriteLength;
4365 mPausedBytesRemaining = mBytesRemaining;
4366 mBytesRemaining = 0; // stop writing
4367 }
4368 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004369 } else if (track->isFlushPending()) {
4370 track->flushAck();
4371 if (last) {
4372 mFlushPending = true;
4373 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004374 } else if (track->isResumePending()){
4375 track->resumeAck();
4376 if (last) {
4377 if (mPausedBytesRemaining) {
4378 // Need to continue write that was interrupted
4379 mCurrentWriteLength = mPausedWriteLength;
4380 mBytesRemaining = mPausedBytesRemaining;
4381 mPausedBytesRemaining = 0;
4382 }
4383 if (mHwPaused) {
4384 doHwResume = true;
4385 mHwPaused = false;
4386 // threadLoop_mix() will handle the case that we need to
4387 // resume an interrupted write
4388 }
4389 // enable write to audio HAL
4390 sleepTime = 0;
4391
4392 // Do not handle new data in this iteration even if track->framesReady()
4393 mixerStatus = MIXER_TRACKS_ENABLED;
4394 }
4395 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004396 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004397 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398 if (track->mFillingUpStatus == Track::FS_FILLED) {
4399 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004400 // make sure processVolume_l() will apply new volume even if 0
4401 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402 }
4403
4404 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004405 sp<Track> previousTrack = mPreviousTrack.promote();
4406 if (previousTrack != 0) {
4407 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004408 // Flush any data still being written from last track
4409 mBytesRemaining = 0;
4410 if (mPausedBytesRemaining) {
4411 // Last track was paused so we also need to flush saved
4412 // mixbuffer state and invalidate track so that it will
4413 // re-submit that unwritten data when it is next resumed
4414 mPausedBytesRemaining = 0;
4415 // Invalidate is a bit drastic - would be more efficient
4416 // to have a flag to tell client that some of the
4417 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004418 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004419 }
4420 // flush data already sent to the DSP if changing audio session as audio
4421 // comes from a different source. Also invalidate previous track to force a
4422 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004423 if (previousTrack->sessionId() != track->sessionId()) {
4424 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004425 }
4426 }
4427 }
4428 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004429 // reset retry count
4430 track->mRetryCount = kMaxTrackRetriesOffload;
4431 mActiveTrack = t;
4432 mixerStatus = MIXER_TRACKS_READY;
4433 }
4434 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004435 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 if (track->isStopping_1()) {
4437 // Hardware buffer can hold a large amount of audio so we must
4438 // wait for all current track's data to drain before we say
4439 // that the track is stopped.
4440 if (mBytesRemaining == 0) {
4441 // Only start draining when all data in mixbuffer
4442 // has been written
4443 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4444 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004445 // do not drain if no data was ever sent to HAL (mStandby == true)
4446 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004447 // do not modify drain sequence if we are already draining. This happens
4448 // when resuming from pause after drain.
4449 if ((mDrainSequence & 1) == 0) {
4450 sleepTime = 0;
4451 standbyTime = systemTime() + standbyDelay;
4452 mixerStatus = MIXER_DRAIN_TRACK;
4453 mDrainSequence += 2;
4454 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455 if (mHwPaused) {
4456 // It is possible to move from PAUSED to STOPPING_1 without
4457 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004458 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004459 mHwPaused = false;
4460 }
4461 }
4462 }
4463 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004464 // Drain has completed or we are in standby, signal presentation complete
4465 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004466 track->mState = TrackBase::STOPPED;
4467 size_t audioHALFrames =
4468 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4469 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004470 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 track->presentationComplete(framesWritten, audioHALFrames);
4472 track->reset();
4473 tracksToRemove->add(track);
4474 }
4475 } else {
4476 // No buffers for this track. Give it a few chances to
4477 // fill a buffer, then remove it from active list.
4478 if (--(track->mRetryCount) <= 0) {
4479 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4480 track->name());
4481 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004482 // indicate to client process that the track was disabled because of underrun;
4483 // it will then automatically call start() when data is available
4484 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485 } else if (last){
4486 mixerStatus = MIXER_TRACKS_ENABLED;
4487 }
4488 }
4489 }
4490 // compute volume for this track
4491 processVolume_l(track, last);
4492 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004493
Eric Laurentea0fade2013-10-04 16:23:48 -07004494 // make sure the pause/flush/resume sequence is executed in the right order.
4495 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4496 // before flush and then resume HW. This can happen in case of pause/flush/resume
4497 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004498 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004499 mOutput->stream->pause(mOutput->stream);
4500 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004501 if (mFlushPending) {
4502 flushHw_l();
4503 mFlushPending = false;
4504 }
Eric Laurentfd477972013-10-25 18:10:40 -07004505 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004506 mOutput->stream->resume(mOutput->stream);
4507 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004508
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 // remove all the tracks that need to be...
4510 removeTracks_l(*tracksToRemove);
4511
4512 return mixerStatus;
4513}
4514
Eric Laurentbfb1b832013-01-07 09:53:42 -08004515// must be called with thread mutex locked
4516bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4517{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004518 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4519 mWriteAckSequence, mDrainSequence);
4520 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004521 return true;
4522 }
4523 return false;
4524}
4525
4526// must be called with thread mutex locked
4527bool AudioFlinger::OffloadThread::shouldStandby_l()
4528{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004529 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530
4531 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4532 // after a timeout and we will enter standby then.
4533 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004534 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004535 }
4536
Glenn Kastene6f35b12013-08-19 09:58:50 -07004537 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538}
4539
4540
4541bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4542{
4543 Mutex::Autolock _l(mLock);
4544 return waitingAsyncCallback_l();
4545}
4546
4547void AudioFlinger::OffloadThread::flushHw_l()
4548{
4549 mOutput->stream->flush(mOutput->stream);
4550 // Flush anything still waiting in the mixbuffer
4551 mCurrentWriteLength = 0;
4552 mBytesRemaining = 0;
4553 mPausedWriteLength = 0;
4554 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004555 mHwPaused = false;
4556
Eric Laurentbfb1b832013-01-07 09:53:42 -08004557 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004558 // discard any pending drain or write ack by incrementing sequence
4559 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4560 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004562 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4563 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 }
4565}
4566
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004567void AudioFlinger::OffloadThread::onAddNewTrack_l()
4568{
4569 sp<Track> previousTrack = mPreviousTrack.promote();
4570 sp<Track> latestTrack = mLatestActiveTrack.promote();
4571
4572 if (previousTrack != 0 && latestTrack != 0 &&
4573 (previousTrack->sessionId() != latestTrack->sessionId())) {
4574 mFlushPending = true;
4575 }
4576 PlaybackThread::onAddNewTrack_l();
4577}
4578
Eric Laurentbfb1b832013-01-07 09:53:42 -08004579// ----------------------------------------------------------------------------
4580
Eric Laurent81784c32012-11-19 14:55:58 -08004581AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4582 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4583 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4584 DUPLICATING),
4585 mWaitTimeMs(UINT_MAX)
4586{
4587 addOutputTrack(mainThread);
4588}
4589
4590AudioFlinger::DuplicatingThread::~DuplicatingThread()
4591{
4592 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4593 mOutputTracks[i]->destroy();
4594 }
4595}
4596
4597void AudioFlinger::DuplicatingThread::threadLoop_mix()
4598{
4599 // mix buffers...
4600 if (outputsReady(outputTracks)) {
4601 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4602 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004603 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004604 }
4605 sleepTime = 0;
4606 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004607 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004608 standbyTime = systemTime() + standbyDelay;
4609}
4610
4611void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4612{
4613 if (sleepTime == 0) {
4614 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4615 sleepTime = activeSleepTime;
4616 } else {
4617 sleepTime = idleSleepTime;
4618 }
4619 } else if (mBytesWritten != 0) {
4620 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4621 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004622 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004623 } else {
4624 // flush remaining overflow buffers in output tracks
4625 writeFrames = 0;
4626 }
4627 sleepTime = 0;
4628 }
4629}
4630
Eric Laurentbfb1b832013-01-07 09:53:42 -08004631ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004632{
4633 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004634 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4635 // for delivery downstream as needed. This in-place conversion is safe as
4636 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4637 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4638 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4639 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4640 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4641 }
4642 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004643 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004644 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004645 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004646}
4647
4648void AudioFlinger::DuplicatingThread::threadLoop_standby()
4649{
4650 // DuplicatingThread implements standby by stopping all tracks
4651 for (size_t i = 0; i < outputTracks.size(); i++) {
4652 outputTracks[i]->stop();
4653 }
4654}
4655
4656void AudioFlinger::DuplicatingThread::saveOutputTracks()
4657{
4658 outputTracks = mOutputTracks;
4659}
4660
4661void AudioFlinger::DuplicatingThread::clearOutputTracks()
4662{
4663 outputTracks.clear();
4664}
4665
4666void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4667{
4668 Mutex::Autolock _l(mLock);
4669 // FIXME explain this formula
4670 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004671 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4672 // due to current usage case and restrictions on the AudioBufferProvider.
4673 // Actual buffer conversion is done in threadLoop_write().
4674 //
4675 // TODO: This may change in the future, depending on multichannel
4676 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004677 OutputTrack *outputTrack = new OutputTrack(thread,
4678 this,
4679 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004680 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004681 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004682 frameCount,
4683 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004684 if (outputTrack->cblk() != NULL) {
4685 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4686 mOutputTracks.add(outputTrack);
4687 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4688 updateWaitTime_l();
4689 }
4690}
4691
4692void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4693{
4694 Mutex::Autolock _l(mLock);
4695 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4696 if (mOutputTracks[i]->thread() == thread) {
4697 mOutputTracks[i]->destroy();
4698 mOutputTracks.removeAt(i);
4699 updateWaitTime_l();
4700 return;
4701 }
4702 }
4703 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4704}
4705
4706// caller must hold mLock
4707void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4708{
4709 mWaitTimeMs = UINT_MAX;
4710 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4711 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4712 if (strong != 0) {
4713 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4714 if (waitTimeMs < mWaitTimeMs) {
4715 mWaitTimeMs = waitTimeMs;
4716 }
4717 }
4718 }
4719}
4720
4721
4722bool AudioFlinger::DuplicatingThread::outputsReady(
4723 const SortedVector< sp<OutputTrack> > &outputTracks)
4724{
4725 for (size_t i = 0; i < outputTracks.size(); i++) {
4726 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4727 if (thread == 0) {
4728 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4729 outputTracks[i].get());
4730 return false;
4731 }
4732 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4733 // see note at standby() declaration
4734 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4735 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4736 thread.get());
4737 return false;
4738 }
4739 }
4740 return true;
4741}
4742
4743uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4744{
4745 return (mWaitTimeMs * 1000) / 2;
4746}
4747
4748void AudioFlinger::DuplicatingThread::cacheParameters_l()
4749{
4750 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4751 updateWaitTime_l();
4752
4753 MixerThread::cacheParameters_l();
4754}
4755
4756// ----------------------------------------------------------------------------
4757// Record
4758// ----------------------------------------------------------------------------
4759
4760AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4761 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004762 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004763 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004764 audio_devices_t inDevice
4765#ifdef TEE_SINK
4766 , const sp<NBAIO_Sink>& teeSink
4767#endif
4768 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004769 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004770 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004771 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004772 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004773#ifdef TEE_SINK
4774 , mTeeSink(teeSink)
4775#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004776 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4777 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004778 // mFastCapture below
4779 , mFastCaptureFutex(0)
4780 // mInputSource
4781 // mPipeSink
4782 // mPipeSource
4783 , mPipeFramesP2(0)
4784 // mPipeMemory
4785 // mFastCaptureNBLogWriter
4786 , mFastTrackAvail(true)
Eric Laurent81784c32012-11-19 14:55:58 -08004787{
4788 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004789 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004790
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004791 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004792
4793 // create an NBAIO source for the HAL input stream, and negotiate
4794 mInputSource = new AudioStreamInSource(input->stream);
4795 size_t numCounterOffers = 0;
4796 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4797 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4798 ALOG_ASSERT(index == 0);
4799
4800 // initialize fast capture depending on configuration
4801 bool initFastCapture;
4802 switch (kUseFastCapture) {
4803 case FastCapture_Never:
4804 initFastCapture = false;
4805 break;
4806 case FastCapture_Always:
4807 initFastCapture = true;
4808 break;
4809 case FastCapture_Static:
4810 uint32_t primaryOutputSampleRate;
4811 {
4812 AutoMutex _l(audioFlinger->mHardwareLock);
4813 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4814 }
4815 initFastCapture =
4816 // either capture sample rate is same as (a reasonable) primary output sample rate
4817 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4818 (mSampleRate == primaryOutputSampleRate)) ||
4819 // or primary output sample rate is unknown, and capture sample rate is reasonable
4820 ((primaryOutputSampleRate == 0) &&
4821 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
4822 // and the buffer size is < 10 ms
4823 (mFrameCount * 1000) / mSampleRate < 10;
4824 break;
4825 // case FastCapture_Dynamic:
4826 }
4827
4828 if (initFastCapture) {
4829 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4830 NBAIO_Format format = mInputSource->format();
4831 size_t pipeFramesP2 = roundup(mFrameCount * 8);
4832 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4833 void *pipeBuffer;
4834 const sp<MemoryDealer> roHeap(readOnlyHeap());
4835 sp<IMemory> pipeMemory;
4836 if ((roHeap == 0) ||
4837 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4838 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4839 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4840 goto failed;
4841 }
4842 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4843 memset(pipeBuffer, 0, pipeSize);
4844 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4845 const NBAIO_Format offers[1] = {format};
4846 size_t numCounterOffers = 0;
4847 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4848 ALOG_ASSERT(index == 0);
4849 mPipeSink = pipe;
4850 PipeReader *pipeReader = new PipeReader(*pipe);
4851 numCounterOffers = 0;
4852 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4853 ALOG_ASSERT(index == 0);
4854 mPipeSource = pipeReader;
4855 mPipeFramesP2 = pipeFramesP2;
4856 mPipeMemory = pipeMemory;
4857
4858 // create fast capture
4859 mFastCapture = new FastCapture();
4860 FastCaptureStateQueue *sq = mFastCapture->sq();
4861#ifdef STATE_QUEUE_DUMP
4862 // FIXME
4863#endif
4864 FastCaptureState *state = sq->begin();
4865 state->mCblk = NULL;
4866 state->mInputSource = mInputSource.get();
4867 state->mInputSourceGen++;
4868 state->mPipeSink = pipe;
4869 state->mPipeSinkGen++;
4870 state->mFrameCount = mFrameCount;
4871 state->mCommand = FastCaptureState::COLD_IDLE;
4872 // already done in constructor initialization list
4873 //mFastCaptureFutex = 0;
4874 state->mColdFutexAddr = &mFastCaptureFutex;
4875 state->mColdGen++;
4876 state->mDumpState = &mFastCaptureDumpState;
4877#ifdef TEE_SINK
4878 // FIXME
4879#endif
4880 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4881 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4882 sq->end();
4883 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4884
4885 // start the fast capture
4886 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4887 pid_t tid = mFastCapture->getTid();
4888 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4889 if (err != 0) {
4890 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4891 kPriorityFastCapture, getpid_cached, tid, err);
4892 }
4893
4894#ifdef AUDIO_WATCHDOG
4895 // FIXME
4896#endif
4897
4898 }
4899failed: ;
4900
4901 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004902}
4903
4904
4905AudioFlinger::RecordThread::~RecordThread()
4906{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004907 if (mFastCapture != 0) {
4908 FastCaptureStateQueue *sq = mFastCapture->sq();
4909 FastCaptureState *state = sq->begin();
4910 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4911 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4912 if (old == -1) {
4913 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4914 }
4915 }
4916 state->mCommand = FastCaptureState::EXIT;
4917 sq->end();
4918 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4919 mFastCapture->join();
4920 mFastCapture.clear();
4921 }
4922 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004923 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004924 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004925}
4926
4927void AudioFlinger::RecordThread::onFirstRef()
4928{
4929 run(mName, PRIORITY_URGENT_AUDIO);
4930}
4931
Eric Laurent81784c32012-11-19 14:55:58 -08004932bool AudioFlinger::RecordThread::threadLoop()
4933{
Eric Laurent81784c32012-11-19 14:55:58 -08004934 nsecs_t lastWarning = 0;
4935
4936 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004937
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004938reacquire_wakelock:
4939 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004940 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004941 {
4942 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004943 size_t size = mActiveTracks.size();
4944 activeTracksGen = mActiveTracksGen;
4945 if (size > 0) {
4946 // FIXME an arbitrary choice
4947 activeTrack = mActiveTracks[0];
4948 acquireWakeLock_l(activeTrack->uid());
4949 if (size > 1) {
4950 SortedVector<int> tmp;
4951 for (size_t i = 0; i < size; i++) {
4952 tmp.add(mActiveTracks[i]->uid());
4953 }
4954 updateWakeLockUids_l(tmp);
4955 }
4956 } else {
4957 acquireWakeLock_l(-1);
4958 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004959 }
4960
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004961 // used to request a deferred sleep, to be executed later while mutex is unlocked
4962 uint32_t sleepUs = 0;
4963
4964 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004965 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004966 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004967
Glenn Kasten5edadd42013-08-14 16:30:49 -07004968 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004969 if (sleepUs > 0) {
4970 usleep(sleepUs);
4971 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004972 }
4973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004974 // activeTracks accumulates a copy of a subset of mActiveTracks
4975 Vector< sp<RecordTrack> > activeTracks;
4976
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004977 // reference to the (first and only) fast track
4978 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07004979
Eric Laurent81784c32012-11-19 14:55:58 -08004980 { // scope for mLock
4981 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004982
Eric Laurent021cf962014-05-13 10:18:14 -07004983 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004984
Eric Laurent000a4192014-01-29 15:17:32 -08004985 // check exitPending here because checkForNewParameters_l() and
4986 // checkForNewParameters_l() can temporarily release mLock
4987 if (exitPending()) {
4988 break;
4989 }
4990
Glenn Kasten2b806402013-11-20 16:37:38 -08004991 // if no active track(s), then standby and release wakelock
4992 size_t size = mActiveTracks.size();
4993 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004994 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004995 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004996 releaseWakeLock_l();
4997 ALOGV("RecordThread: loop stopping");
4998 // go to sleep
4999 mWaitWorkCV.wait(mLock);
5000 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005001 goto reacquire_wakelock;
5002 }
5003
Glenn Kasten2b806402013-11-20 16:37:38 -08005004 if (mActiveTracksGen != activeTracksGen) {
5005 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005006 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005007 for (size_t i = 0; i < size; i++) {
5008 tmp.add(mActiveTracks[i]->uid());
5009 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005010 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005011 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005012
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005013 bool doBroadcast = false;
5014 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005015
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005016 activeTrack = mActiveTracks[i];
5017 if (activeTrack->isTerminated()) {
5018 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005019 mActiveTracks.remove(activeTrack);
5020 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005021 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005022 continue;
5023 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005024
5025 TrackBase::track_state activeTrackState = activeTrack->mState;
5026 switch (activeTrackState) {
5027
5028 case TrackBase::PAUSING:
5029 mActiveTracks.remove(activeTrack);
5030 mActiveTracksGen++;
5031 doBroadcast = true;
5032 size--;
5033 continue;
5034
5035 case TrackBase::STARTING_1:
5036 sleepUs = 10000;
5037 i++;
5038 continue;
5039
5040 case TrackBase::STARTING_2:
5041 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005042 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005043 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005044 break;
5045
5046 case TrackBase::ACTIVE:
5047 break;
5048
5049 case TrackBase::IDLE:
5050 i++;
5051 continue;
5052
5053 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005054 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005055 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005056
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005057 activeTracks.add(activeTrack);
5058 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005059
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005060 if (activeTrack->isFastTrack()) {
5061 ALOG_ASSERT(!mFastTrackAvail);
5062 ALOG_ASSERT(fastTrack == 0);
5063 fastTrack = activeTrack;
5064 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005065 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005066 if (doBroadcast) {
5067 mStartStopCond.broadcast();
5068 }
5069
5070 // sleep if there are no active tracks to process
5071 if (activeTracks.size() == 0) {
5072 if (sleepUs == 0) {
5073 sleepUs = kRecordThreadSleepUs;
5074 }
5075 continue;
5076 }
5077 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005078
Eric Laurent81784c32012-11-19 14:55:58 -08005079 lockEffectChains_l(effectChains);
5080 }
5081
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005082 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005083
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005084 size_t size = effectChains.size();
5085 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005086 // thread mutex is not locked, but effect chain is locked
5087 effectChains[i]->process_l();
5088 }
5089
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005090 // Start the fast capture if it's not already running
5091 if (mFastCapture != 0) {
5092 FastCaptureStateQueue *sq = mFastCapture->sq();
5093 FastCaptureState *state = sq->begin();
5094 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5095 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5096 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5097 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5098 if (old == -1) {
5099 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5100 }
5101 }
5102 state->mCommand = FastCaptureState::READ_WRITE;
5103#if 0 // FIXME
5104 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5105 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5106#endif
5107 state->mCblk = fastTrack != 0 ? fastTrack->cblk() : NULL;
5108 sq->end();
5109 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5110#if 0
5111 if (kUseFastCapture == FastCapture_Dynamic) {
5112 mNormalSource = mPipeSource;
5113 }
5114#endif
5115 } else {
5116 sq->end(false /*didModify*/);
5117 }
5118 }
5119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005120 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5121 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5122 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5123 // If destination is non-contiguous, first read past the nominal end of buffer, then
5124 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005126 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005127 ssize_t framesRead;
5128
5129 // If an NBAIO source is present, use it to read the normal capture's data
5130 if (mPipeSource != 0) {
5131 size_t framesToRead = mBufferSize / mFrameSize;
5132 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5133 framesToRead, AudioBufferProvider::kInvalidPTS);
5134 if (framesRead == 0) {
5135 // since pipe is non-blocking, simulate blocking input
5136 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5137 }
5138 // otherwise use the HAL / AudioStreamIn directly
5139 } else {
5140 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5141 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5142 if (bytesRead < 0) {
5143 framesRead = bytesRead;
5144 } else {
5145 framesRead = bytesRead / mFrameSize;
5146 }
5147 }
5148
5149 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5150 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005151 // Force input into standby so that it tries to recover at next read attempt
5152 inputStandBy();
5153 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005154 }
5155 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005156 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005157 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005158 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005159
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005160 if (mTeeSink != 0) {
5161 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5162 }
5163 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005164 {
5165 size_t part1 = mRsmpInFramesP2 - rear;
5166 if ((size_t) framesRead > part1) {
5167 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5168 (framesRead - part1) * mFrameSize);
5169 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005170 }
5171 rear = mRsmpInRear += framesRead;
5172
5173 size = activeTracks.size();
5174 // loop over each active track
5175 for (size_t i = 0; i < size; i++) {
5176 activeTrack = activeTracks[i];
5177
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005178 // skip fast tracks, as those are handled directly by FastCapture
5179 if (activeTrack->isFastTrack()) {
5180 continue;
5181 }
5182
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005183 enum {
5184 OVERRUN_UNKNOWN,
5185 OVERRUN_TRUE,
5186 OVERRUN_FALSE
5187 } overrun = OVERRUN_UNKNOWN;
5188
5189 // loop over getNextBuffer to handle circular sink
5190 for (;;) {
5191
5192 activeTrack->mSink.frameCount = ~0;
5193 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5194 size_t framesOut = activeTrack->mSink.frameCount;
5195 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5196
5197 int32_t front = activeTrack->mRsmpInFront;
5198 ssize_t filled = rear - front;
5199 size_t framesIn;
5200
5201 if (filled < 0) {
5202 // should not happen, but treat like a massive overrun and re-sync
5203 framesIn = 0;
5204 activeTrack->mRsmpInFront = rear;
5205 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005206 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005207 framesIn = (size_t) filled;
5208 } else {
5209 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005210 framesIn = mRsmpInFrames;
5211 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005212 overrun = OVERRUN_TRUE;
5213 }
5214
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005215 if (framesOut == 0 || framesIn == 0) {
5216 break;
5217 }
5218
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005219 if (activeTrack->mResampler == NULL) {
5220 // no resampling
5221 if (framesIn > framesOut) {
5222 framesIn = framesOut;
5223 } else {
5224 framesOut = framesIn;
5225 }
5226 int8_t *dst = activeTrack->mSink.i8;
5227 while (framesIn > 0) {
5228 front &= mRsmpInFramesP2 - 1;
5229 size_t part1 = mRsmpInFramesP2 - front;
5230 if (part1 > framesIn) {
5231 part1 = framesIn;
5232 }
5233 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005234 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005235 memcpy(dst, src, part1 * mFrameSize);
5236 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005237 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005238 part1);
5239 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005240 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 part1);
5242 }
5243 dst += part1 * activeTrack->mFrameSize;
5244 front += part1;
5245 framesIn -= part1;
5246 }
5247 activeTrack->mRsmpInFront += framesOut;
5248
5249 } else {
5250 // resampling
5251 // FIXME framesInNeeded should really be part of resampler API, and should
5252 // depend on the SRC ratio
5253 // to keep mRsmpInBuffer full so resampler always has sufficient input
5254 size_t framesInNeeded;
5255 // FIXME only re-calculate when it changes, and optimize for common ratios
5256 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
5257 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005258 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005259 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
5260 framesInNeeded, framesOut, inOverOut);
5261 // Although we theoretically have framesIn in circular buffer, some of those are
5262 // unreleased frames, and thus must be discounted for purpose of budgeting.
5263 size_t unreleased = activeTrack->mRsmpInUnrel;
5264 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005265 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005266 ALOGV("not enough to resample: have %u frames in but need %u in to "
5267 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005268 framesIn, framesInNeeded, framesOut, inOverOut);
5269 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005270 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5271 if (newFramesOut == 0) {
5272 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005273 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005274 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5275 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5276 framesInNeeded, newFramesOut, outOverIn);
5277 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5278 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5279 "given in/out ratio of %.4g",
5280 framesIn, framesInNeeded, newFramesOut, inOverOut);
5281 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005282 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005283 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005284 "given in/out ratio of %.4g",
5285 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005286 }
5287
5288 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5289 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005290 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005291 delete[] activeTrack->mRsmpOutBuffer;
5292 // resampler always outputs stereo
5293 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5294 activeTrack->mRsmpOutFrameCount = framesOut;
5295 }
5296
5297 // resampler accumulates, but we only have one source track
5298 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5299 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005300 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005301 activeTrack->mResamplerBufferProvider
5302 /*this*/ /* AudioBufferProvider* */);
5303 // ditherAndClamp() works as long as all buffers returned by
5304 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005305 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005306 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005307 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5308 framesOut);
5309 // the resampler always outputs stereo samples:
5310 // do post stereo to mono conversion
5311 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005312 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005313 } else {
5314 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5315 activeTrack->mRsmpOutBuffer, framesOut);
5316 }
5317 // now done with mRsmpOutBuffer
5318
5319 }
5320
5321 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5322 overrun = OVERRUN_FALSE;
5323 }
5324
5325 if (activeTrack->mFramesToDrop == 0) {
5326 if (framesOut > 0) {
5327 activeTrack->mSink.frameCount = framesOut;
5328 activeTrack->releaseBuffer(&activeTrack->mSink);
5329 }
5330 } else {
5331 // FIXME could do a partial drop of framesOut
5332 if (activeTrack->mFramesToDrop > 0) {
5333 activeTrack->mFramesToDrop -= framesOut;
5334 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005335 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005336 }
5337 } else {
5338 activeTrack->mFramesToDrop += framesOut;
5339 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5340 activeTrack->mSyncStartEvent->isCancelled()) {
5341 ALOGW("Synced record %s, session %d, trigger session %d",
5342 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5343 activeTrack->sessionId(),
5344 (activeTrack->mSyncStartEvent != 0) ?
5345 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005346 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005347 }
5348 }
5349 }
5350
5351 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005353 }
5354 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005355
5356 switch (overrun) {
5357 case OVERRUN_TRUE:
5358 // client isn't retrieving buffers fast enough
5359 if (!activeTrack->setOverflow()) {
5360 nsecs_t now = systemTime();
5361 // FIXME should lastWarning per track?
5362 if ((now - lastWarning) > kWarningThrottleNs) {
5363 ALOGW("RecordThread: buffer overflow");
5364 lastWarning = now;
5365 }
5366 }
5367 break;
5368 case OVERRUN_FALSE:
5369 activeTrack->clearOverflow();
5370 break;
5371 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005372 break;
5373 }
5374
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005375 }
5376
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005377unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005378 // enable changes in effect chain
5379 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005380 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
5382
Glenn Kasten93e471f2013-08-19 08:40:07 -07005383 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005384
5385 {
5386 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005387 for (size_t i = 0; i < mTracks.size(); i++) {
5388 sp<RecordTrack> track = mTracks[i];
5389 track->invalidate();
5390 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005391 mActiveTracks.clear();
5392 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005393 mStartStopCond.broadcast();
5394 }
5395
5396 releaseWakeLock();
5397
5398 ALOGV("RecordThread %p exiting", this);
5399 return false;
5400}
5401
Glenn Kasten93e471f2013-08-19 08:40:07 -07005402void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005403{
5404 if (!mStandby) {
5405 inputStandBy();
5406 mStandby = true;
5407 }
5408}
5409
5410void AudioFlinger::RecordThread::inputStandBy()
5411{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005412 // Idle the fast capture if it's currently running
5413 if (mFastCapture != 0) {
5414 FastCaptureStateQueue *sq = mFastCapture->sq();
5415 FastCaptureState *state = sq->begin();
5416 if (!(state->mCommand & FastCaptureState::IDLE)) {
5417 state->mCommand = FastCaptureState::COLD_IDLE;
5418 state->mColdFutexAddr = &mFastCaptureFutex;
5419 state->mColdGen++;
5420 mFastCaptureFutex = 0;
5421 sq->end();
5422 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5423 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5424#if 0
5425 if (kUseFastCapture == FastCapture_Dynamic) {
5426 // FIXME
5427 }
5428#endif
5429#ifdef AUDIO_WATCHDOG
5430 // FIXME
5431#endif
5432 } else {
5433 sq->end(false /*didModify*/);
5434 }
5435 }
Eric Laurent81784c32012-11-19 14:55:58 -08005436 mInput->stream->common.standby(&mInput->stream->common);
5437}
5438
Glenn Kasten05997e22014-03-13 15:08:33 -07005439// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005440sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005441 const sp<AudioFlinger::Client>& client,
5442 uint32_t sampleRate,
5443 audio_format_t format,
5444 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005445 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005446 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005447 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005448 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005449 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005450 pid_t tid,
5451 status_t *status)
5452{
Glenn Kasten74935e42013-12-19 08:56:45 -08005453 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005454 sp<RecordTrack> track;
5455 status_t lStatus;
5456
Glenn Kasten90e58b12013-07-31 16:16:02 -07005457 // client expresses a preference for FAST, but we get the final say
5458 if (*flags & IAudioFlinger::TRACK_FAST) {
5459 if (
5460 // use case: callback handler and frame count is default or at least as large as HAL
5461 (
5462 (tid != -1) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005463 ((frameCount == 0) /*||
5464 // FIXME must be equal to pipe depth, so don't allow it to be specified by client
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005465 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005466 (frameCount >= mFrameCount)*/)
Glenn Kasten90e58b12013-07-31 16:16:02 -07005467 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005468 // PCM data
5469 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005470 // native format
5471 (format == mFormat) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005472 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005473 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5474 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005475 // native channel mask
5476 (channelMask == mChannelMask) &&
5477 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005478 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005479 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005480 hasFastCapture() &&
5481 // there are sufficient fast track slots available
5482 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005483 ) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005484 // if frameCount not specified, then it defaults to pipe frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005485 if (frameCount == 0) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005486 frameCount = mPipeFramesP2;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005487 }
5488 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5489 frameCount, mFrameCount);
5490 } else {
5491 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5492 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005493 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005494 frameCount, mFrameCount, format,
5495 audio_is_linear_pcm(format),
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005496 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005497 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005498 // 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 -07005499 // For compatibility with AudioRecord calculation, buffer depth is forced
5500 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5501 // This is probably too conservative, but legacy application code may depend on it.
5502 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005503 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005504 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5505 size_t mNormalFrameCount = 2048; // FIXME
5506 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5507 if (minBufCount < 2) {
5508 minBufCount = 2;
5509 }
5510 size_t minFrameCount = mNormalFrameCount * minBufCount;
5511 if (frameCount < minFrameCount) {
5512 frameCount = minFrameCount;
5513 }
5514 }
5515 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005516 *pFrameCount = frameCount;
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005517 *notificationFrames = 0; // FIXME implement
Glenn Kasten90e58b12013-07-31 16:16:02 -07005518
Glenn Kasten15e57982013-09-24 11:52:37 -07005519 lStatus = initCheck();
5520 if (lStatus != NO_ERROR) {
5521 ALOGE("createRecordTrack_l() audio driver not initialized");
5522 goto Exit;
5523 }
Eric Laurent81784c32012-11-19 14:55:58 -08005524
5525 { // scope for mLock
5526 Mutex::Autolock _l(mLock);
5527
5528 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005529 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005530 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005531
Glenn Kasten03003332013-08-06 15:40:54 -07005532 lStatus = track->initCheck();
5533 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005534 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005535 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005536 goto Exit;
5537 }
5538 mTracks.add(track);
5539
5540 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5541 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5542 mAudioFlinger->btNrecIsOff();
5543 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5544 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005545
5546 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5547 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5548 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5549 // so ask activity manager to do this on our behalf
5550 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5551 }
Eric Laurent81784c32012-11-19 14:55:58 -08005552 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005553
Eric Laurent81784c32012-11-19 14:55:58 -08005554 lStatus = NO_ERROR;
5555
5556Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005557 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005558 return track;
5559}
5560
5561status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5562 AudioSystem::sync_event_t event,
5563 int triggerSession)
5564{
5565 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5566 sp<ThreadBase> strongMe = this;
5567 status_t status = NO_ERROR;
5568
5569 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005570 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005571 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005572 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005573 triggerSession,
5574 recordTrack->sessionId(),
5575 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005576 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005577 // Sync event can be cancelled by the trigger session if the track is not in a
5578 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005579 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005580 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005581 } else {
5582 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005583 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005584 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
5586 }
5587
5588 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005589 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005590 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5592 if (recordTrack->mState == TrackBase::PAUSING) {
5593 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005594 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005595 } else {
5596 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005597 }
5598 return status;
5599 }
5600
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005601 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5602 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5603 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005604 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005605 mActiveTracks.add(recordTrack);
5606 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005607 mLock.unlock();
5608 status_t status = AudioSystem::startInput(mId);
5609 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005611 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005612 mActiveTracks.remove(recordTrack);
5613 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005614 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005615 return status;
5616 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005617 // Catch up with current buffer indices if thread is already running.
5618 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5619 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5620 // see previously buffered data before it called start(), but with greater risk of overrun.
5621
5622 recordTrack->mRsmpInFront = mRsmpInRear;
5623 recordTrack->mRsmpInUnrel = 0;
5624 // FIXME why reset?
5625 if (recordTrack->mResampler != NULL) {
5626 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005627 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005628 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005629 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005630 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005631 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005632 ALOGV("Record failed to start");
5633 status = BAD_VALUE;
5634 goto startError;
5635 }
Eric Laurent81784c32012-11-19 14:55:58 -08005636 return status;
5637 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005638
Eric Laurent81784c32012-11-19 14:55:58 -08005639startError:
5640 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005641 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005642 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005643 return status;
5644}
5645
Eric Laurent81784c32012-11-19 14:55:58 -08005646void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5647{
5648 sp<SyncEvent> strongEvent = event.promote();
5649
5650 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005651 sp<RefBase> ptr = strongEvent->cookie().promote();
5652 if (ptr != 0) {
5653 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5654 recordTrack->handleSyncStartEvent(strongEvent);
5655 }
Eric Laurent81784c32012-11-19 14:55:58 -08005656 }
5657}
5658
Glenn Kastena8356f62013-07-25 14:37:52 -07005659bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005660 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005661 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005662 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005663 return false;
5664 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005665 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005666 recordTrack->mState = TrackBase::PAUSING;
5667 // do not wait for mStartStopCond if exiting
5668 if (exitPending()) {
5669 return true;
5670 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005671 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005672 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005673 // if we have been restarted, recordTrack is in mActiveTracks here
5674 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005675 ALOGV("Record stopped OK");
5676 return true;
5677 }
5678 return false;
5679}
5680
Glenn Kasten0f11b512014-01-31 16:18:54 -08005681bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005682{
5683 return false;
5684}
5685
Glenn Kasten0f11b512014-01-31 16:18:54 -08005686status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005687{
5688#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5689 if (!isValidSyncEvent(event)) {
5690 return BAD_VALUE;
5691 }
5692
5693 int eventSession = event->triggerSession();
5694 status_t ret = NAME_NOT_FOUND;
5695
5696 Mutex::Autolock _l(mLock);
5697
5698 for (size_t i = 0; i < mTracks.size(); i++) {
5699 sp<RecordTrack> track = mTracks[i];
5700 if (eventSession == track->sessionId()) {
5701 (void) track->setSyncEvent(event);
5702 ret = NO_ERROR;
5703 }
5704 }
5705 return ret;
5706#else
5707 return BAD_VALUE;
5708#endif
5709}
5710
5711// destroyTrack_l() must be called with ThreadBase::mLock held
5712void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5713{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714 track->terminate();
5715 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005716 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005717 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005718 removeTrack_l(track);
5719 }
5720}
5721
5722void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5723{
5724 mTracks.remove(track);
5725 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005726 if (track->isFastTrack()) {
5727 ALOG_ASSERT(!mFastTrackAvail);
5728 mFastTrackAvail = true;
5729 }
Eric Laurent81784c32012-11-19 14:55:58 -08005730}
5731
5732void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5733{
5734 dumpInternals(fd, args);
5735 dumpTracks(fd, args);
5736 dumpEffectChains(fd, args);
5737}
5738
5739void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5740{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005741 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005742
Glenn Kasten2b806402013-11-20 16:37:38 -08005743 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005744 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005745 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005746 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005747 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005748 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005749
Eric Laurent81784c32012-11-19 14:55:58 -08005750 dumpBase(fd, args);
5751}
5752
Glenn Kasten0f11b512014-01-31 16:18:54 -08005753void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005754{
5755 const size_t SIZE = 256;
5756 char buffer[SIZE];
5757 String8 result;
5758
Marco Nelissenb2208842014-02-07 14:00:50 -08005759 size_t numtracks = mTracks.size();
5760 size_t numactive = mActiveTracks.size();
5761 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005762 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005763 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005764 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005765 RecordTrack::appendDumpHeader(result);
5766 for (size_t i = 0; i < numtracks ; ++i) {
5767 sp<RecordTrack> track = mTracks[i];
5768 if (track != 0) {
5769 bool active = mActiveTracks.indexOf(track) >= 0;
5770 if (active) {
5771 numactiveseen++;
5772 }
5773 track->dump(buffer, SIZE, active);
5774 result.append(buffer);
5775 }
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005777 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005778 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005779 }
5780
Marco Nelissenb2208842014-02-07 14:00:50 -08005781 if (numactiveseen != numactive) {
5782 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5783 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005784 result.append(buffer);
5785 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005786 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005787 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005788 if (mTracks.indexOf(track) < 0) {
5789 track->dump(buffer, SIZE, true);
5790 result.append(buffer);
5791 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005792 }
Eric Laurent81784c32012-11-19 14:55:58 -08005793
5794 }
5795 write(fd, result.string(), result.size());
5796}
5797
5798// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005799status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5800 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005801{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 RecordTrack *activeTrack = mRecordTrack;
5803 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5804 if (threadBase == 0) {
5805 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005806 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 return NOT_ENOUGH_DATA;
5808 }
5809 RecordThread *recordThread = (RecordThread *) threadBase.get();
5810 int32_t rear = recordThread->mRsmpInRear;
5811 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005812 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005813 // FIXME should not be P2 (don't want to increase latency)
5814 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005815 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005816 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005817 front &= recordThread->mRsmpInFramesP2 - 1;
5818 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005819 if (part1 > (size_t) filled) {
5820 part1 = filled;
5821 }
5822 size_t ask = buffer->frameCount;
5823 ALOG_ASSERT(ask > 0);
5824 if (part1 > ask) {
5825 part1 = ask;
5826 }
5827 if (part1 == 0) {
5828 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005829 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005830 buffer->raw = NULL;
5831 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005832 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005833 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005834 }
5835
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005836 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005837 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005839 return NO_ERROR;
5840}
5841
5842// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005843void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5844 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005845{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005846 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005847 size_t stepCount = buffer->frameCount;
5848 if (stepCount == 0) {
5849 return;
5850 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005851 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5852 activeTrack->mRsmpInUnrel -= stepCount;
5853 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005854 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005855 buffer->frameCount = 0;
5856}
5857
Eric Laurent10351942014-05-08 18:49:52 -07005858bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5859 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005860{
5861 bool reconfig = false;
5862
Eric Laurent10351942014-05-08 18:49:52 -07005863 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005864
Eric Laurent10351942014-05-08 18:49:52 -07005865 audio_format_t reqFormat = mFormat;
5866 uint32_t samplingRate = mSampleRate;
5867 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5868
5869 AudioParameter param = AudioParameter(keyValuePair);
5870 int value;
5871 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5872 // channel count change can be requested. Do we mandate the first client defines the
5873 // HAL sampling rate and channel count or do we allow changes on the fly?
5874 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5875 samplingRate = value;
5876 reconfig = true;
5877 }
5878 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5879 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5880 status = BAD_VALUE;
5881 } else {
5882 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005883 reconfig = true;
5884 }
Eric Laurent10351942014-05-08 18:49:52 -07005885 }
5886 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5887 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5888 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5889 status = BAD_VALUE;
5890 } else {
5891 channelMask = mask;
5892 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005893 }
Eric Laurent10351942014-05-08 18:49:52 -07005894 }
5895 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5896 // do not accept frame count changes if tracks are open as the track buffer
5897 // size depends on frame count and correct behavior would not be guaranteed
5898 // if frame count is changed after track creation
5899 if (mActiveTracks.size() > 0) {
5900 status = INVALID_OPERATION;
5901 } else {
5902 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005903 }
Eric Laurent10351942014-05-08 18:49:52 -07005904 }
5905 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5906 // forward device change to effects that have requested to be
5907 // aware of attached audio device.
5908 for (size_t i = 0; i < mEffectChains.size(); i++) {
5909 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005910 }
Eric Laurent81784c32012-11-19 14:55:58 -08005911
Eric Laurent10351942014-05-08 18:49:52 -07005912 // store input device and output device but do not forward output device to audio HAL.
5913 // Note that status is ignored by the caller for output device
5914 // (see AudioFlinger::setParameters()
5915 if (audio_is_output_devices(value)) {
5916 mOutDevice = value;
5917 status = BAD_VALUE;
5918 } else {
5919 mInDevice = value;
5920 // disable AEC and NS if the device is a BT SCO headset supporting those
5921 // pre processings
5922 if (mTracks.size() > 0) {
5923 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5924 mAudioFlinger->btNrecIsOff();
5925 for (size_t i = 0; i < mTracks.size(); i++) {
5926 sp<RecordTrack> track = mTracks[i];
5927 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5928 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
5930 }
5931 }
Eric Laurent10351942014-05-08 18:49:52 -07005932 }
5933 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5934 mAudioSource != (audio_source_t)value) {
5935 // forward device change to effects that have requested to be
5936 // aware of attached audio device.
5937 for (size_t i = 0; i < mEffectChains.size(); i++) {
5938 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005939 }
Eric Laurent10351942014-05-08 18:49:52 -07005940 mAudioSource = (audio_source_t)value;
5941 }
Glenn Kastene198c362013-08-13 09:13:36 -07005942
Eric Laurent10351942014-05-08 18:49:52 -07005943 if (status == NO_ERROR) {
5944 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5945 keyValuePair.string());
5946 if (status == INVALID_OPERATION) {
5947 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005948 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5949 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005950 }
5951 if (reconfig) {
5952 if (status == BAD_VALUE &&
5953 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5954 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5955 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5956 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005957 audio_channel_count_from_in_mask(
5958 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005959 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5960 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5961 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005962 }
Eric Laurent10351942014-05-08 18:49:52 -07005963 if (status == NO_ERROR) {
5964 readInputParameters_l();
5965 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005966 }
5967 }
Eric Laurent81784c32012-11-19 14:55:58 -08005968 }
Eric Laurent10351942014-05-08 18:49:52 -07005969
Eric Laurent81784c32012-11-19 14:55:58 -08005970 return reconfig;
5971}
5972
5973String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5974{
Eric Laurent81784c32012-11-19 14:55:58 -08005975 Mutex::Autolock _l(mLock);
5976 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005977 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005978 }
5979
Glenn Kastend8ea6992013-07-16 14:17:15 -07005980 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5981 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005982 free(s);
5983 return out_s8;
5984}
5985
Eric Laurent021cf962014-05-13 10:18:14 -07005986void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005987 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005988 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005989
5990 switch (event) {
5991 case AudioSystem::INPUT_OPENED:
5992 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005993 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005994 desc.samplingRate = mSampleRate;
5995 desc.format = mFormat;
5996 desc.frameCount = mFrameCount;
5997 desc.latency = 0;
5998 param2 = &desc;
5999 break;
6000
6001 case AudioSystem::INPUT_CLOSED:
6002 default:
6003 break;
6004 }
Eric Laurent021cf962014-05-13 10:18:14 -07006005 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006006}
6007
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006008void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006009{
Eric Laurent81784c32012-11-19 14:55:58 -08006010 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6011 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006012 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006013 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6014 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006015 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006016 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006017 }
Eric Laurent665470b2014-07-03 16:37:08 -07006018 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006019 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6020 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006021 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006022 // 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 -07006023 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006024 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 // A larger value should allow more old data to be read after a track calls start(),
6026 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006027 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006028 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07006030 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6031 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006032
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006033 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6034 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006035}
6036
Glenn Kasten5f972c02014-01-13 09:59:31 -08006037uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006038{
6039 Mutex::Autolock _l(mLock);
6040 if (initCheck() != NO_ERROR) {
6041 return 0;
6042 }
6043
6044 return mInput->stream->get_input_frames_lost(mInput->stream);
6045}
6046
6047uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6048{
6049 Mutex::Autolock _l(mLock);
6050 uint32_t result = 0;
6051 if (getEffectChain_l(sessionId) != 0) {
6052 result = EFFECT_SESSION;
6053 }
6054
6055 for (size_t i = 0; i < mTracks.size(); ++i) {
6056 if (sessionId == mTracks[i]->sessionId()) {
6057 result |= TRACK_SESSION;
6058 break;
6059 }
6060 }
6061
6062 return result;
6063}
6064
6065KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6066{
6067 KeyedVector<int, bool> ids;
6068 Mutex::Autolock _l(mLock);
6069 for (size_t j = 0; j < mTracks.size(); ++j) {
6070 sp<RecordThread::RecordTrack> track = mTracks[j];
6071 int sessionId = track->sessionId();
6072 if (ids.indexOfKey(sessionId) < 0) {
6073 ids.add(sessionId, true);
6074 }
6075 }
6076 return ids;
6077}
6078
6079AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6080{
6081 Mutex::Autolock _l(mLock);
6082 AudioStreamIn *input = mInput;
6083 mInput = NULL;
6084 return input;
6085}
6086
6087// this method must always be called either with ThreadBase mLock held or inside the thread loop
6088audio_stream_t* AudioFlinger::RecordThread::stream() const
6089{
6090 if (mInput == NULL) {
6091 return NULL;
6092 }
6093 return &mInput->stream->common;
6094}
6095
6096status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6097{
6098 // only one chain per input thread
6099 if (mEffectChains.size() != 0) {
6100 return INVALID_OPERATION;
6101 }
6102 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6103
6104 chain->setInBuffer(NULL);
6105 chain->setOutBuffer(NULL);
6106
6107 checkSuspendOnAddEffectChain_l(chain);
6108
6109 mEffectChains.add(chain);
6110
6111 return NO_ERROR;
6112}
6113
6114size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6115{
6116 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6117 ALOGW_IF(mEffectChains.size() != 1,
6118 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6119 chain.get(), mEffectChains.size(), this);
6120 if (mEffectChains.size() == 1) {
6121 mEffectChains.removeAt(0);
6122 }
6123 return 0;
6124}
6125
Eric Laurent1c333e22014-05-20 10:48:17 -07006126status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6127 audio_patch_handle_t *handle)
6128{
6129 status_t status = NO_ERROR;
6130 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6131 // store new device and send to effects
6132 mInDevice = patch->sources[0].ext.device.type;
6133 for (size_t i = 0; i < mEffectChains.size(); i++) {
6134 mEffectChains[i]->setDevice_l(mInDevice);
6135 }
6136
6137 // disable AEC and NS if the device is a BT SCO headset supporting those
6138 // pre processings
6139 if (mTracks.size() > 0) {
6140 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6141 mAudioFlinger->btNrecIsOff();
6142 for (size_t i = 0; i < mTracks.size(); i++) {
6143 sp<RecordTrack> track = mTracks[i];
6144 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6145 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6146 }
6147 }
6148
6149 // store new source and send to effects
6150 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6151 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6152 for (size_t i = 0; i < mEffectChains.size(); i++) {
6153 mEffectChains[i]->setAudioSource_l(mAudioSource);
6154 }
6155 }
6156
6157 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6158 status = hwDevice->create_audio_patch(hwDevice,
6159 patch->num_sources,
6160 patch->sources,
6161 patch->num_sinks,
6162 patch->sinks,
6163 handle);
6164 } else {
6165 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6166 }
6167 return status;
6168}
6169
6170status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6171{
6172 status_t status = NO_ERROR;
6173 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6174 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6175 status = hwDevice->release_audio_patch(hwDevice, handle);
6176 } else {
6177 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6178 }
6179 return status;
6180}
6181
6182
Eric Laurent81784c32012-11-19 14:55:58 -08006183}; // namespace android