blob: 651c6ea43fdd11800d146c54875ed70ffc1b043e [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
Eric Laurent83b88082014-06-20 18:31:16 -07001149void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1150{
1151 config->type = AUDIO_PORT_TYPE_MIX;
1152 config->ext.mix.handle = mId;
1153 config->sample_rate = mSampleRate;
1154 config->format = mFormat;
1155 config->channel_mask = mChannelMask;
1156 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1157 AUDIO_PORT_CONFIG_FORMAT;
1158}
1159
1160
Eric Laurent81784c32012-11-19 14:55:58 -08001161// ----------------------------------------------------------------------------
1162// Playback
1163// ----------------------------------------------------------------------------
1164
1165AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1166 AudioStreamOut* output,
1167 audio_io_handle_t id,
1168 audio_devices_t device,
1169 type_t type)
1170 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001171 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001172 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001173 mMixerBuffer(NULL),
1174 mMixerBufferSize(0),
1175 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1176 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001177 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001178 mEffectBuffer(NULL),
1179 mEffectBufferSize(0),
1180 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1181 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001182 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001183 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001184 // mStreamTypes[] initialized in constructor body
1185 mOutput(output),
1186 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1187 mMixerStatus(MIXER_IDLE),
1188 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1189 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001190 mBytesRemaining(0),
1191 mCurrentWriteLength(0),
1192 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001193 mWriteAckSequence(0),
1194 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001195 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001196 mScreenState(AudioFlinger::mScreenState),
1197 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001198 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1199 // mLatchD, mLatchQ,
1200 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001201{
1202 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001203 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001204
1205 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1206 // it would be safer to explicitly pass initial masterVolume/masterMute as
1207 // parameter.
1208 //
1209 // If the HAL we are using has support for master volume or master mute,
1210 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1211 // and the mute set to false).
1212 mMasterVolume = audioFlinger->masterVolume_l();
1213 mMasterMute = audioFlinger->masterMute_l();
1214 if (mOutput && mOutput->audioHwDev) {
1215 if (mOutput->audioHwDev->canSetMasterVolume()) {
1216 mMasterVolume = 1.0;
1217 }
1218
1219 if (mOutput->audioHwDev->canSetMasterMute()) {
1220 mMasterMute = false;
1221 }
1222 }
1223
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001224 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001225
1226 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1227 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001228 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001229 stream = (audio_stream_type_t) (stream + 1)) {
1230 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1231 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1232 }
1233 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1234 // because mAudioFlinger doesn't have one to copy from
1235}
1236
1237AudioFlinger::PlaybackThread::~PlaybackThread()
1238{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001239 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001240 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001241 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001242 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001243}
1244
1245void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1246{
1247 dumpInternals(fd, args);
1248 dumpTracks(fd, args);
1249 dumpEffectChains(fd, args);
1250}
1251
Glenn Kasten0f11b512014-01-31 16:18:54 -08001252void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001253{
1254 const size_t SIZE = 256;
1255 char buffer[SIZE];
1256 String8 result;
1257
Marco Nelissenb2208842014-02-07 14:00:50 -08001258 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001259 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1260 const stream_type_t *st = &mStreamTypes[i];
1261 if (i > 0) {
1262 result.appendFormat(", ");
1263 }
1264 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1265 if (st->mute) {
1266 result.append("M");
1267 }
1268 }
1269 result.append("\n");
1270 write(fd, result.string(), result.length());
1271 result.clear();
1272
Eric Laurent81784c32012-11-19 14:55:58 -08001273 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1274 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001275 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001276 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001277
1278 size_t numtracks = mTracks.size();
1279 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001280 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001281 size_t numactiveseen = 0;
1282 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001283 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001284 Track::appendDumpHeader(result);
1285 for (size_t i = 0; i < numtracks; ++i) {
1286 sp<Track> track = mTracks[i];
1287 if (track != 0) {
1288 bool active = mActiveTracks.indexOf(track) >= 0;
1289 if (active) {
1290 numactiveseen++;
1291 }
1292 track->dump(buffer, SIZE, active);
1293 result.append(buffer);
1294 }
1295 }
1296 } else {
1297 result.append("\n");
1298 }
1299 if (numactiveseen != numactive) {
1300 // some tracks in the active list were not in the tracks list
1301 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1302 " not in the track list\n");
1303 result.append(buffer);
1304 Track::appendDumpHeader(result);
1305 for (size_t i = 0; i < numactive; ++i) {
1306 sp<Track> track = mActiveTracks[i].promote();
1307 if (track != 0 && mTracks.indexOf(track) < 0) {
1308 track->dump(buffer, SIZE, true);
1309 result.append(buffer);
1310 }
1311 }
1312 }
1313
1314 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001315}
1316
1317void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1318{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001319 dprintf(fd, "\nOutput thread %p:\n", this);
1320 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1321 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1322 dprintf(fd, " Total writes: %d\n", mNumWrites);
1323 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1324 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1325 dprintf(fd, " Suspend count: %d\n", mSuspended);
1326 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1327 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1328 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1329 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001330
1331 dumpBase(fd, args);
1332}
1333
1334// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001335
1336void AudioFlinger::PlaybackThread::onFirstRef()
1337{
1338 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1339}
1340
1341// ThreadBase virtuals
1342void AudioFlinger::PlaybackThread::preExit()
1343{
1344 ALOGV(" preExit()");
1345 // FIXME this is using hard-coded strings but in the future, this functionality will be
1346 // converted to use audio HAL extensions required to support tunneling
1347 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1348}
1349
1350// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1351sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1352 const sp<AudioFlinger::Client>& client,
1353 audio_stream_type_t streamType,
1354 uint32_t sampleRate,
1355 audio_format_t format,
1356 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001357 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001358 const sp<IMemory>& sharedBuffer,
1359 int sessionId,
1360 IAudioFlinger::track_flags_t *flags,
1361 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001362 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001363 status_t *status)
1364{
Glenn Kasten74935e42013-12-19 08:56:45 -08001365 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001366 sp<Track> track;
1367 status_t lStatus;
1368
1369 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1370
1371 // client expresses a preference for FAST, but we get the final say
1372 if (*flags & IAudioFlinger::TRACK_FAST) {
1373 if (
1374 // not timed
1375 (!isTimed) &&
1376 // either of these use cases:
1377 (
1378 // use case 1: shared buffer with any frame count
1379 (
1380 (sharedBuffer != 0)
1381 ) ||
1382 // use case 2: callback handler and frame count is default or at least as large as HAL
1383 (
1384 (tid != -1) &&
1385 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001386 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001387 )
1388 ) &&
1389 // PCM data
1390 audio_is_linear_pcm(format) &&
1391 // mono or stereo
1392 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1393 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001394 // hardware sample rate
1395 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001396 // normal mixer has an associated fast mixer
1397 hasFastMixer() &&
1398 // there are sufficient fast track slots available
1399 (mFastTrackAvailMask != 0)
1400 // FIXME test that MixerThread for this fast track has a capable output HAL
1401 // FIXME add a permission test also?
1402 ) {
1403 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1404 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001405 // read the fast track multiplier property the first time it is needed
1406 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1407 if (ok != 0) {
1408 ALOGE("%s pthread_once failed: %d", __func__, ok);
1409 }
1410 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001411 }
1412 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1413 frameCount, mFrameCount);
1414 } else {
1415 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001416 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1417 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001418 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001419 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001420 audio_is_linear_pcm(format),
1421 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1422 *flags &= ~IAudioFlinger::TRACK_FAST;
1423 // For compatibility with AudioTrack calculation, buffer depth is forced
1424 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1425 // This is probably too conservative, but legacy application code may depend on it.
1426 // If you change this calculation, also review the start threshold which is related.
1427 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1428 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1429 if (minBufCount < 2) {
1430 minBufCount = 2;
1431 }
1432 size_t minFrameCount = mNormalFrameCount * minBufCount;
1433 if (frameCount < minFrameCount) {
1434 frameCount = minFrameCount;
1435 }
1436 }
1437 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001438 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001439
Glenn Kastenc3df8382014-03-13 15:05:25 -07001440 switch (mType) {
1441
1442 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001443 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001444 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001445 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1446 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001447 sampleRate, format, channelMask, mOutput, mFormat);
1448 lStatus = BAD_VALUE;
1449 goto Exit;
1450 }
1451 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001452 break;
1453
1454 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001455 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001456 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1457 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001458 sampleRate, format, channelMask, mOutput, mFormat);
1459 lStatus = BAD_VALUE;
1460 goto Exit;
1461 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001462 break;
1463
1464 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001465 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001466 ALOGE("createTrack_l() Bad parameter: format %#x \""
1467 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001468 format, mOutput, mFormat);
1469 lStatus = BAD_VALUE;
1470 goto Exit;
1471 }
Eric Laurent81784c32012-11-19 14:55:58 -08001472 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1473 if (sampleRate > mSampleRate*2) {
1474 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1475 lStatus = BAD_VALUE;
1476 goto Exit;
1477 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001478 break;
1479
Eric Laurent81784c32012-11-19 14:55:58 -08001480 }
1481
1482 lStatus = initCheck();
1483 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001484 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001485 goto Exit;
1486 }
1487
1488 { // scope for mLock
1489 Mutex::Autolock _l(mLock);
1490
1491 // all tracks in same audio session must share the same routing strategy otherwise
1492 // conflicts will happen when tracks are moved from one output to another by audio policy
1493 // manager
1494 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1495 for (size_t i = 0; i < mTracks.size(); ++i) {
1496 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001497 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001498 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1499 if (sessionId == t->sessionId() && strategy != actual) {
1500 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1501 strategy, actual);
1502 lStatus = BAD_VALUE;
1503 goto Exit;
1504 }
1505 }
1506 }
1507
1508 if (!isTimed) {
1509 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001510 channelMask, frameCount, NULL, sharedBuffer,
1511 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001512 } else {
1513 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001514 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001515 }
Glenn Kasten03003332013-08-06 15:40:54 -07001516
1517 // new Track always returns non-NULL,
1518 // but TimedTrack::create() is a factory that could fail by returning NULL
1519 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1520 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001521 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001522 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001523 goto Exit;
1524 }
1525 mTracks.add(track);
1526
1527 sp<EffectChain> chain = getEffectChain_l(sessionId);
1528 if (chain != 0) {
1529 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1530 track->setMainBuffer(chain->inBuffer());
1531 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1532 chain->incTrackCnt();
1533 }
1534
1535 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1536 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1537 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1538 // so ask activity manager to do this on our behalf
1539 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1540 }
1541 }
1542
1543 lStatus = NO_ERROR;
1544
1545Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001546 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001547 return track;
1548}
1549
1550uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1551{
1552 return latency;
1553}
1554
1555uint32_t AudioFlinger::PlaybackThread::latency() const
1556{
1557 Mutex::Autolock _l(mLock);
1558 return latency_l();
1559}
1560uint32_t AudioFlinger::PlaybackThread::latency_l() const
1561{
1562 if (initCheck() == NO_ERROR) {
1563 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1564 } else {
1565 return 0;
1566 }
1567}
1568
1569void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1570{
1571 Mutex::Autolock _l(mLock);
1572 // Don't apply master volume in SW if our HAL can do it for us.
1573 if (mOutput && mOutput->audioHwDev &&
1574 mOutput->audioHwDev->canSetMasterVolume()) {
1575 mMasterVolume = 1.0;
1576 } else {
1577 mMasterVolume = value;
1578 }
1579}
1580
1581void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1582{
1583 Mutex::Autolock _l(mLock);
1584 // Don't apply master mute in SW if our HAL can do it for us.
1585 if (mOutput && mOutput->audioHwDev &&
1586 mOutput->audioHwDev->canSetMasterMute()) {
1587 mMasterMute = false;
1588 } else {
1589 mMasterMute = muted;
1590 }
1591}
1592
1593void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1594{
1595 Mutex::Autolock _l(mLock);
1596 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001597 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001598}
1599
1600void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1601{
1602 Mutex::Autolock _l(mLock);
1603 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001604 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001605}
1606
1607float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1608{
1609 Mutex::Autolock _l(mLock);
1610 return mStreamTypes[stream].volume;
1611}
1612
1613// addTrack_l() must be called with ThreadBase::mLock held
1614status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1615{
1616 status_t status = ALREADY_EXISTS;
1617
1618 // set retry count for buffer fill
1619 track->mRetryCount = kMaxTrackStartupRetries;
1620 if (mActiveTracks.indexOf(track) < 0) {
1621 // the track is newly added, make sure it fills up all its
1622 // buffers before playing. This is to ensure the client will
1623 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001624 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001625 TrackBase::track_state state = track->mState;
1626 mLock.unlock();
1627 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1628 mLock.lock();
1629 // abort track was stopped/paused while we released the lock
1630 if (state != track->mState) {
1631 if (status == NO_ERROR) {
1632 mLock.unlock();
1633 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1634 mLock.lock();
1635 }
1636 return INVALID_OPERATION;
1637 }
1638 // abort if start is rejected by audio policy manager
1639 if (status != NO_ERROR) {
1640 return PERMISSION_DENIED;
1641 }
1642#ifdef ADD_BATTERY_DATA
1643 // to track the speaker usage
1644 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1645#endif
1646 }
1647
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001648 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001649 track->mResetDone = false;
1650 track->mPresentationCompleteFrames = 0;
1651 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001652 mWakeLockUids.add(track->uid());
1653 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001654 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001655 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1656 if (chain != 0) {
1657 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1658 track->sessionId());
1659 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001660 }
1661
1662 status = NO_ERROR;
1663 }
1664
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001665 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001666 return status;
1667}
1668
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001670{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001671 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001672 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001673 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1674 track->mState = TrackBase::STOPPED;
1675 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001676 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001677 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001680
1681 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001682}
1683
1684void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1685{
1686 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1687 mTracks.remove(track);
1688 deleteTrackName_l(track->name());
1689 // redundant as track is about to be destroyed, for dumpsys only
1690 track->mName = -1;
1691 if (track->isFastTrack()) {
1692 int index = track->mFastIndex;
1693 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1694 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1695 mFastTrackAvailMask |= 1 << index;
1696 // redundant as track is about to be destroyed, for dumpsys only
1697 track->mFastIndex = -1;
1698 }
1699 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1700 if (chain != 0) {
1701 chain->decTrackCnt();
1702 }
1703}
1704
Eric Laurentede6c3b2013-09-19 14:37:46 -07001705void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001706{
1707 // Thread could be blocked waiting for async
1708 // so signal it to handle state changes immediately
1709 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1710 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1711 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001712 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001713}
1714
Eric Laurent81784c32012-11-19 14:55:58 -08001715String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1716{
Eric Laurent81784c32012-11-19 14:55:58 -08001717 Mutex::Autolock _l(mLock);
1718 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001719 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001720 }
1721
Glenn Kastend8ea6992013-07-16 14:17:15 -07001722 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1723 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001724 free(s);
1725 return out_s8;
1726}
1727
Eric Laurent021cf962014-05-13 10:18:14 -07001728void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001729 AudioSystem::OutputDescriptor desc;
1730 void *param2 = NULL;
1731
Eric Laurent021cf962014-05-13 10:18:14 -07001732 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001733 param);
1734
1735 switch (event) {
1736 case AudioSystem::OUTPUT_OPENED:
1737 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001738 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001739 desc.samplingRate = mSampleRate;
1740 desc.format = mFormat;
1741 desc.frameCount = mNormalFrameCount; // FIXME see
1742 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001743 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001744 param2 = &desc;
1745 break;
1746
1747 case AudioSystem::STREAM_CONFIG_CHANGED:
1748 param2 = &param;
1749 case AudioSystem::OUTPUT_CLOSED:
1750 default:
1751 break;
1752 }
Eric Laurent021cf962014-05-13 10:18:14 -07001753 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001754}
1755
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756void AudioFlinger::PlaybackThread::writeCallback()
1757{
1758 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001759 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001760}
1761
1762void AudioFlinger::PlaybackThread::drainCallback()
1763{
1764 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001765 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766}
1767
Eric Laurent3b4529e2013-09-05 18:09:19 -07001768void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001769{
1770 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001771 // reject out of sequence requests
1772 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1773 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001774 mWaitWorkCV.signal();
1775 }
1776}
1777
Eric Laurent3b4529e2013-09-05 18:09:19 -07001778void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001779{
1780 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001781 // reject out of sequence requests
1782 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1783 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784 mWaitWorkCV.signal();
1785 }
1786}
1787
1788// static
1789int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001790 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791 void *cookie)
1792{
1793 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1794 ALOGV("asyncCallback() event %d", event);
1795 switch (event) {
1796 case STREAM_CBK_EVENT_WRITE_READY:
1797 me->writeCallback();
1798 break;
1799 case STREAM_CBK_EVENT_DRAIN_READY:
1800 me->drainCallback();
1801 break;
1802 default:
1803 ALOGW("asyncCallback() unknown event %d", event);
1804 break;
1805 }
1806 return 0;
1807}
1808
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001809void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001810{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001811 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001812 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1813 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001814 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001815 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001816 }
1817 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001818 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001819 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1820 }
Andy Hunge5412692014-05-16 11:25:07 -07001821 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001822 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1823 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001824 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001825 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001826 }
Andy Hung6146c082014-03-18 11:56:15 -07001827 if ((mType == MIXER || mType == DUPLICATING)
1828 && !isValidPcmSinkFormat(mFormat)) {
1829 LOG_FATAL("HAL format %#x not supported for mixed output",
1830 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001831 }
Eric Laurent665470b2014-07-03 16:37:08 -07001832 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001833 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1834 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001835 if (mFrameCount & 15) {
1836 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1837 mFrameCount);
1838 }
1839
Eric Laurentbfb1b832013-01-07 09:53:42 -08001840 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1841 (mOutput->stream->set_callback != NULL)) {
1842 if (mOutput->stream->set_callback(mOutput->stream,
1843 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1844 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001845 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001846 }
1847 }
1848
Andy Hung09a50072014-02-27 14:30:47 -08001849 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001850 double multiplier = 1.0;
1851 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1852 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001853 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1854 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001855 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1856 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1857 maxNormalFrameCount = maxNormalFrameCount & ~15;
1858 if (maxNormalFrameCount < minNormalFrameCount) {
1859 maxNormalFrameCount = minNormalFrameCount;
1860 }
1861 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1862 if (multiplier <= 1.0) {
1863 multiplier = 1.0;
1864 } else if (multiplier <= 2.0) {
1865 if (2 * mFrameCount <= maxNormalFrameCount) {
1866 multiplier = 2.0;
1867 } else {
1868 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1869 }
1870 } else {
1871 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001872 // 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 -08001873 // track, but we sometimes have to do this to satisfy the maximum frame count
1874 // constraint)
1875 // FIXME this rounding up should not be done if no HAL SRC
1876 uint32_t truncMult = (uint32_t) multiplier;
1877 if ((truncMult & 1)) {
1878 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1879 ++truncMult;
1880 }
1881 }
1882 multiplier = (double) truncMult;
1883 }
1884 }
1885 mNormalFrameCount = multiplier * mFrameCount;
1886 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001887 if (mType == MIXER || mType == DUPLICATING) {
1888 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1889 }
Andy Hung09a50072014-02-27 14:30:47 -08001890 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001891 mNormalFrameCount);
1892
Andy Hung010a1a12014-03-13 13:57:33 -07001893 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1894 // Originally this was int16_t[] array, need to remove legacy implications.
1895 free(mSinkBuffer);
1896 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001897 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1898 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1899 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001900 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001901
Andy Hung69aed5f2014-02-25 17:24:40 -08001902 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1903 // drives the output.
1904 free(mMixerBuffer);
1905 mMixerBuffer = NULL;
1906 if (mMixerBufferEnabled) {
1907 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1908 mMixerBufferSize = mNormalFrameCount * mChannelCount
1909 * audio_bytes_per_sample(mMixerBufferFormat);
1910 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1911 }
Andy Hung98ef9782014-03-04 14:46:50 -08001912 free(mEffectBuffer);
1913 mEffectBuffer = NULL;
1914 if (mEffectBufferEnabled) {
1915 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1916 mEffectBufferSize = mNormalFrameCount * mChannelCount
1917 * audio_bytes_per_sample(mEffectBufferFormat);
1918 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1919 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001920
Eric Laurent81784c32012-11-19 14:55:58 -08001921 // force reconfiguration of effect chains and engines to take new buffer size and audio
1922 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001923 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001924 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1925 // matter.
1926 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1927 Vector< sp<EffectChain> > effectChains = mEffectChains;
1928 for (size_t i = 0; i < effectChains.size(); i ++) {
1929 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1930 }
1931}
1932
1933
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001934status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001935{
1936 if (halFrames == NULL || dspFrames == NULL) {
1937 return BAD_VALUE;
1938 }
1939 Mutex::Autolock _l(mLock);
1940 if (initCheck() != NO_ERROR) {
1941 return INVALID_OPERATION;
1942 }
1943 size_t framesWritten = mBytesWritten / mFrameSize;
1944 *halFrames = framesWritten;
1945
1946 if (isSuspended()) {
1947 // return an estimation of rendered frames when the output is suspended
1948 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1949 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1950 return NO_ERROR;
1951 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001952 status_t status;
1953 uint32_t frames;
1954 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1955 *dspFrames = (size_t)frames;
1956 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001957 }
1958}
1959
1960uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1961{
1962 Mutex::Autolock _l(mLock);
1963 uint32_t result = 0;
1964 if (getEffectChain_l(sessionId) != 0) {
1965 result = EFFECT_SESSION;
1966 }
1967
1968 for (size_t i = 0; i < mTracks.size(); ++i) {
1969 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001970 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001971 result |= TRACK_SESSION;
1972 break;
1973 }
1974 }
1975
1976 return result;
1977}
1978
1979uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1980{
1981 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1982 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1983 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1984 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1985 }
1986 for (size_t i = 0; i < mTracks.size(); i++) {
1987 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001988 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001989 return AudioSystem::getStrategyForStream(track->streamType());
1990 }
1991 }
1992 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1993}
1994
1995
1996AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1997{
1998 Mutex::Autolock _l(mLock);
1999 return mOutput;
2000}
2001
2002AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2003{
2004 Mutex::Autolock _l(mLock);
2005 AudioStreamOut *output = mOutput;
2006 mOutput = NULL;
2007 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2008 // must push a NULL and wait for ack
2009 mOutputSink.clear();
2010 mPipeSink.clear();
2011 mNormalSink.clear();
2012 return output;
2013}
2014
2015// this method must always be called either with ThreadBase mLock held or inside the thread loop
2016audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2017{
2018 if (mOutput == NULL) {
2019 return NULL;
2020 }
2021 return &mOutput->stream->common;
2022}
2023
2024uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2025{
2026 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2027}
2028
2029status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2030{
2031 if (!isValidSyncEvent(event)) {
2032 return BAD_VALUE;
2033 }
2034
2035 Mutex::Autolock _l(mLock);
2036
2037 for (size_t i = 0; i < mTracks.size(); ++i) {
2038 sp<Track> track = mTracks[i];
2039 if (event->triggerSession() == track->sessionId()) {
2040 (void) track->setSyncEvent(event);
2041 return NO_ERROR;
2042 }
2043 }
2044
2045 return NAME_NOT_FOUND;
2046}
2047
2048bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2049{
2050 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2051}
2052
2053void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2054 const Vector< sp<Track> >& tracksToRemove)
2055{
2056 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002057 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002058 for (size_t i = 0 ; i < count ; i++) {
2059 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002060 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002061 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062#ifdef ADD_BATTERY_DATA
2063 // to track the speaker usage
2064 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2065#endif
2066 if (track->isTerminated()) {
2067 AudioSystem::releaseOutput(mId);
2068 }
Eric Laurent81784c32012-11-19 14:55:58 -08002069 }
2070 }
2071 }
Eric Laurent81784c32012-11-19 14:55:58 -08002072}
2073
2074void AudioFlinger::PlaybackThread::checkSilentMode_l()
2075{
2076 if (!mMasterMute) {
2077 char value[PROPERTY_VALUE_MAX];
2078 if (property_get("ro.audio.silent", value, "0") > 0) {
2079 char *endptr;
2080 unsigned long ul = strtoul(value, &endptr, 0);
2081 if (*endptr == '\0' && ul != 0) {
2082 ALOGD("Silence is golden");
2083 // The setprop command will not allow a property to be changed after
2084 // the first time it is set, so we don't have to worry about un-muting.
2085 setMasterMute_l(true);
2086 }
2087 }
2088 }
2089}
2090
2091// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002092ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002093{
2094 // FIXME rewrite to reduce number of system calls
2095 mLastWriteTime = systemTime();
2096 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002097 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002098 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002099
2100 // If an NBAIO sink is present, use it to write the normal mixer's submix
2101 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002102 const size_t count = mBytesRemaining / mFrameSize;
2103
Simon Wilson2d590962012-11-29 15:18:50 -08002104 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002105 // update the setpoint when AudioFlinger::mScreenState changes
2106 uint32_t screenState = AudioFlinger::mScreenState;
2107 if (screenState != mScreenState) {
2108 mScreenState = screenState;
2109 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2110 if (pipe != NULL) {
2111 pipe->setAvgFrames((mScreenState & 1) ?
2112 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2113 }
2114 }
Andy Hung010a1a12014-03-13 13:57:33 -07002115 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002116 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002117 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002118 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002119 } else {
2120 bytesWritten = framesWritten;
2121 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002122 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002123 if (status == NO_ERROR) {
2124 size_t totalFramesWritten = mNormalSink->framesWritten();
2125 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2126 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2127 mLatchDValid = true;
2128 }
2129 }
Eric Laurent81784c32012-11-19 14:55:58 -08002130 // otherwise use the HAL / AudioStreamOut directly
2131 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002132 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002133
Eric Laurentbfb1b832013-01-07 09:53:42 -08002134 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002135 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2136 mWriteAckSequence += 2;
2137 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002139 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002140 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002141 // FIXME We should have an implementation of timestamps for direct output threads.
2142 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002144 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 if (mUseAsyncWrite &&
2146 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2147 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002148 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002149 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002150 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 }
Eric Laurent81784c32012-11-19 14:55:58 -08002152 }
2153
Eric Laurent81784c32012-11-19 14:55:58 -08002154 mNumWrites++;
2155 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002156 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 return bytesWritten;
2158}
2159
2160void AudioFlinger::PlaybackThread::threadLoop_drain()
2161{
2162 if (mOutput->stream->drain) {
2163 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2164 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002165 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2166 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 }
2170 mOutput->stream->drain(mOutput->stream,
2171 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2172 : AUDIO_DRAIN_ALL);
2173 }
2174}
2175
2176void AudioFlinger::PlaybackThread::threadLoop_exit()
2177{
2178 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002179}
2180
2181/*
2182The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002183 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002184 - activeSleepTime from activeSleepTimeUs()
2185 - idleSleepTime from idleSleepTimeUs()
2186 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2187 - maxPeriod from frame count and sample rate (MIXER only)
2188
2189The parameters that affect these derived values are:
2190 - frame count
2191 - frame size
2192 - sample rate
2193 - device type: A2DP or not
2194 - device latency
2195 - format: PCM or not
2196 - active sleep time
2197 - idle sleep time
2198*/
2199
2200void AudioFlinger::PlaybackThread::cacheParameters_l()
2201{
Andy Hung25c2dac2014-02-27 14:56:00 -08002202 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002203 activeSleepTime = activeSleepTimeUs();
2204 idleSleepTime = idleSleepTimeUs();
2205}
2206
2207void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2208{
Glenn Kasten7c027242012-12-26 14:43:16 -08002209 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002210 this, streamType, mTracks.size());
2211 Mutex::Autolock _l(mLock);
2212
2213 size_t size = mTracks.size();
2214 for (size_t i = 0; i < size; i++) {
2215 sp<Track> t = mTracks[i];
2216 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002217 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002218 }
2219 }
2220}
2221
2222status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2223{
2224 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002225 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2226 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002227 bool ownsBuffer = false;
2228
2229 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2230 if (session > 0) {
2231 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002232 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002233 if (mType != DIRECT) {
2234 size_t numSamples = mNormalFrameCount * mChannelCount;
2235 buffer = new int16_t[numSamples];
2236 memset(buffer, 0, numSamples * sizeof(int16_t));
2237 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2238 ownsBuffer = true;
2239 }
2240
2241 // Attach all tracks with same session ID to this chain.
2242 for (size_t i = 0; i < mTracks.size(); ++i) {
2243 sp<Track> track = mTracks[i];
2244 if (session == track->sessionId()) {
2245 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2246 buffer);
2247 track->setMainBuffer(buffer);
2248 chain->incTrackCnt();
2249 }
2250 }
2251
2252 // indicate all active tracks in the chain
2253 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2254 sp<Track> track = mActiveTracks[i].promote();
2255 if (track == 0) {
2256 continue;
2257 }
2258 if (session == track->sessionId()) {
2259 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2260 chain->incActiveTrackCnt();
2261 }
2262 }
2263 }
2264
2265 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002266 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2267 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002268 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2269 // chains list in order to be processed last as it contains output stage effects
2270 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2271 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2272 // after track specific effects and before output stage
2273 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2274 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2275 // Effect chain for other sessions are inserted at beginning of effect
2276 // chains list to be processed before output mix effects. Relative order between other
2277 // sessions is not important
2278 size_t size = mEffectChains.size();
2279 size_t i = 0;
2280 for (i = 0; i < size; i++) {
2281 if (mEffectChains[i]->sessionId() < session) {
2282 break;
2283 }
2284 }
2285 mEffectChains.insertAt(chain, i);
2286 checkSuspendOnAddEffectChain_l(chain);
2287
2288 return NO_ERROR;
2289}
2290
2291size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2292{
2293 int session = chain->sessionId();
2294
2295 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2296
2297 for (size_t i = 0; i < mEffectChains.size(); i++) {
2298 if (chain == mEffectChains[i]) {
2299 mEffectChains.removeAt(i);
2300 // detach all active tracks from the chain
2301 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2302 sp<Track> track = mActiveTracks[i].promote();
2303 if (track == 0) {
2304 continue;
2305 }
2306 if (session == track->sessionId()) {
2307 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2308 chain.get(), session);
2309 chain->decActiveTrackCnt();
2310 }
2311 }
2312
2313 // detach all tracks with same session ID from this chain
2314 for (size_t i = 0; i < mTracks.size(); ++i) {
2315 sp<Track> track = mTracks[i];
2316 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002317 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002318 chain->decTrackCnt();
2319 }
2320 }
2321 break;
2322 }
2323 }
2324 return mEffectChains.size();
2325}
2326
2327status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2328 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2329{
2330 Mutex::Autolock _l(mLock);
2331 return attachAuxEffect_l(track, EffectId);
2332}
2333
2334status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2335 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2336{
2337 status_t status = NO_ERROR;
2338
2339 if (EffectId == 0) {
2340 track->setAuxBuffer(0, NULL);
2341 } else {
2342 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2343 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2344 if (effect != 0) {
2345 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2346 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2347 } else {
2348 status = INVALID_OPERATION;
2349 }
2350 } else {
2351 status = BAD_VALUE;
2352 }
2353 }
2354 return status;
2355}
2356
2357void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2358{
2359 for (size_t i = 0; i < mTracks.size(); ++i) {
2360 sp<Track> track = mTracks[i];
2361 if (track->auxEffectId() == effectId) {
2362 attachAuxEffect_l(track, 0);
2363 }
2364 }
2365}
2366
2367bool AudioFlinger::PlaybackThread::threadLoop()
2368{
2369 Vector< sp<Track> > tracksToRemove;
2370
2371 standbyTime = systemTime();
2372
2373 // MIXER
2374 nsecs_t lastWarning = 0;
2375
2376 // DUPLICATING
2377 // FIXME could this be made local to while loop?
2378 writeFrames = 0;
2379
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002380 int lastGeneration = 0;
2381
Eric Laurent81784c32012-11-19 14:55:58 -08002382 cacheParameters_l();
2383 sleepTime = idleSleepTime;
2384
2385 if (mType == MIXER) {
2386 sleepTimeShift = 0;
2387 }
2388
2389 CpuStats cpuStats;
2390 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2391
2392 acquireWakeLock();
2393
Glenn Kasten9e58b552013-01-18 15:09:48 -08002394 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2395 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2396 // and then that string will be logged at the next convenient opportunity.
2397 const char *logString = NULL;
2398
Eric Laurent664539d2013-09-23 18:24:31 -07002399 checkSilentMode_l();
2400
Eric Laurent81784c32012-11-19 14:55:58 -08002401 while (!exitPending())
2402 {
2403 cpuStats.sample(myName);
2404
2405 Vector< sp<EffectChain> > effectChains;
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 { // scope for mLock
2408
2409 Mutex::Autolock _l(mLock);
2410
Eric Laurent021cf962014-05-13 10:18:14 -07002411 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002412
Glenn Kasten9e58b552013-01-18 15:09:48 -08002413 if (logString != NULL) {
2414 mNBLogWriter->logTimestamp();
2415 mNBLogWriter->log(logString);
2416 logString = NULL;
2417 }
2418
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002419 if (mLatchDValid) {
2420 mLatchQ = mLatchD;
2421 mLatchDValid = false;
2422 mLatchQValid = true;
2423 }
2424
Eric Laurent81784c32012-11-19 14:55:58 -08002425 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426 if (mSignalPending) {
2427 // A signal was raised while we were unlocked
2428 mSignalPending = false;
2429 } else if (waitingAsyncCallback_l()) {
2430 if (exitPending()) {
2431 break;
2432 }
2433 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002434 mWakeLockUids.clear();
2435 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436 ALOGV("wait async completion");
2437 mWaitWorkCV.wait(mLock);
2438 ALOGV("async completion/wake");
2439 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002440 standbyTime = systemTime() + standbyDelay;
2441 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002442
2443 continue;
2444 }
2445 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446 isSuspended()) {
2447 // put audio hardware into standby after short delay
2448 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002449
2450 threadLoop_standby();
2451
2452 mStandby = true;
2453 }
2454
2455 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2456 // we're about to wait, flush the binder command buffer
2457 IPCThreadState::self()->flushCommands();
2458
2459 clearOutputTracks();
2460
2461 if (exitPending()) {
2462 break;
2463 }
2464
2465 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002466 mWakeLockUids.clear();
2467 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002468 // wait until we have something to do...
2469 ALOGV("%s going to sleep", myName.string());
2470 mWaitWorkCV.wait(mLock);
2471 ALOGV("%s waking up", myName.string());
2472 acquireWakeLock_l();
2473
2474 mMixerStatus = MIXER_IDLE;
2475 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2476 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002478 checkSilentMode_l();
2479
2480 standbyTime = systemTime() + standbyDelay;
2481 sleepTime = idleSleepTime;
2482 if (mType == MIXER) {
2483 sleepTimeShift = 0;
2484 }
2485
2486 continue;
2487 }
2488 }
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // mMixerStatusIgnoringFastTracks is also updated internally
2490 mMixerStatus = prepareTracks_l(&tracksToRemove);
2491
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002492 // compare with previously applied list
2493 if (lastGeneration != mActiveTracksGeneration) {
2494 // update wakelock
2495 updateWakeLockUids_l(mWakeLockUids);
2496 lastGeneration = mActiveTracksGeneration;
2497 }
2498
Eric Laurent81784c32012-11-19 14:55:58 -08002499 // prevent any changes in effect chain list and in each effect chain
2500 // during mixing and effect process as the audio buffers could be deleted
2501 // or modified if an effect is created or deleted
2502 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002503 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002504
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 if (mBytesRemaining == 0) {
2506 mCurrentWriteLength = 0;
2507 if (mMixerStatus == MIXER_TRACKS_READY) {
2508 // threadLoop_mix() sets mCurrentWriteLength
2509 threadLoop_mix();
2510 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2511 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2512 // threadLoop_sleepTime sets sleepTime to 0 if data
2513 // must be written to HAL
2514 threadLoop_sleepTime();
2515 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002516 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517 }
2518 }
Andy Hung98ef9782014-03-04 14:46:50 -08002519 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2520 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2521 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2522 // or mSinkBuffer (if there are no effects).
2523 //
2524 // This is done pre-effects computation; if effects change to
2525 // support higher precision, this needs to move.
2526 //
2527 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2528 // TODO use sleepTime == 0 as an additional condition.
2529 if (mMixerBufferValid) {
2530 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2531 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2532
2533 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2534 mNormalFrameCount * mChannelCount);
2535 }
2536
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 mBytesRemaining = mCurrentWriteLength;
2538 if (isSuspended()) {
2539 sleepTime = suspendSleepTimeUs();
2540 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002541 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542 mBytesRemaining = 0;
2543 }
Eric Laurent81784c32012-11-19 14:55:58 -08002544
Eric Laurentbfb1b832013-01-07 09:53:42 -08002545 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002546 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002547 for (size_t i = 0; i < effectChains.size(); i ++) {
2548 effectChains[i]->process_l();
2549 }
Eric Laurent81784c32012-11-19 14:55:58 -08002550 }
2551 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002552 // Process effect chains for offloaded thread even if no audio
2553 // was read from audio track: process only updates effect state
2554 // and thus does have to be synchronized with audio writes but may have
2555 // to be called while waiting for async write callback
2556 if (mType == OFFLOAD) {
2557 for (size_t i = 0; i < effectChains.size(); i ++) {
2558 effectChains[i]->process_l();
2559 }
2560 }
Eric Laurent81784c32012-11-19 14:55:58 -08002561
Andy Hung98ef9782014-03-04 14:46:50 -08002562 // Only if the Effects buffer is enabled and there is data in the
2563 // Effects buffer (buffer valid), we need to
2564 // copy into the sink buffer.
2565 // TODO use sleepTime == 0 as an additional condition.
2566 if (mEffectBufferValid) {
2567 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2568 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2569 mNormalFrameCount * mChannelCount);
2570 }
2571
Eric Laurent81784c32012-11-19 14:55:58 -08002572 // enable changes in effect chain
2573 unlockEffectChains(effectChains);
2574
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 if (!waitingAsyncCallback()) {
2576 // sleepTime == 0 means we must write to audio hardware
2577 if (sleepTime == 0) {
2578 if (mBytesRemaining) {
2579 ssize_t ret = threadLoop_write();
2580 if (ret < 0) {
2581 mBytesRemaining = 0;
2582 } else {
2583 mBytesWritten += ret;
2584 mBytesRemaining -= ret;
2585 }
2586 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2587 (mMixerStatus == MIXER_DRAIN_ALL)) {
2588 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002589 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002590 if (mType == MIXER) {
2591 // write blocked detection
2592 nsecs_t now = systemTime();
2593 nsecs_t delta = now - mLastWriteTime;
2594 if (!mStandby && delta > maxPeriod) {
2595 mNumDelayedWrites++;
2596 if ((now - lastWarning) > kWarningThrottleNs) {
2597 ATRACE_NAME("underrun");
2598 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2599 ns2ms(delta), mNumDelayedWrites, this);
2600 lastWarning = now;
2601 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002602 }
2603 }
Eric Laurent81784c32012-11-19 14:55:58 -08002604
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605 } else {
2606 usleep(sleepTime);
2607 }
Eric Laurent81784c32012-11-19 14:55:58 -08002608 }
2609
2610 // Finally let go of removed track(s), without the lock held
2611 // since we can't guarantee the destructors won't acquire that
2612 // same lock. This will also mutate and push a new fast mixer state.
2613 threadLoop_removeTracks(tracksToRemove);
2614 tracksToRemove.clear();
2615
2616 // FIXME I don't understand the need for this here;
2617 // it was in the original code but maybe the
2618 // assignment in saveOutputTracks() makes this unnecessary?
2619 clearOutputTracks();
2620
2621 // Effect chains will be actually deleted here if they were removed from
2622 // mEffectChains list during mixing or effects processing
2623 effectChains.clear();
2624
2625 // FIXME Note that the above .clear() is no longer necessary since effectChains
2626 // is now local to this block, but will keep it for now (at least until merge done).
2627 }
2628
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 threadLoop_exit();
2630
Eric Laurent81784c32012-11-19 14:55:58 -08002631 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002633 // put output stream into standby mode
2634 if (!mStandby) {
2635 mOutput->stream->common.standby(&mOutput->stream->common);
2636 }
2637 }
2638
2639 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002640 mWakeLockUids.clear();
2641 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002642
2643 ALOGV("Thread %p type %d exiting", this, mType);
2644 return false;
2645}
2646
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647// removeTracks_l() must be called with ThreadBase::mLock held
2648void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2649{
2650 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002651 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 for (size_t i=0 ; i<count ; i++) {
2653 const sp<Track>& track = tracksToRemove.itemAt(i);
2654 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002655 mWakeLockUids.remove(track->uid());
2656 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2658 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2659 if (chain != 0) {
2660 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2661 track->sessionId());
2662 chain->decActiveTrackCnt();
2663 }
2664 if (track->isTerminated()) {
2665 removeTrack_l(track);
2666 }
2667 }
2668 }
2669
2670}
Eric Laurent81784c32012-11-19 14:55:58 -08002671
Eric Laurentaccc1472013-09-20 09:36:34 -07002672status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2673{
2674 if (mNormalSink != 0) {
2675 return mNormalSink->getTimestamp(timestamp);
2676 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002677 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002678 uint64_t position64;
2679 int ret = mOutput->stream->get_presentation_position(
2680 mOutput->stream, &position64, &timestamp.mTime);
2681 if (ret == 0) {
2682 timestamp.mPosition = (uint32_t)position64;
2683 return NO_ERROR;
2684 }
2685 }
2686 return INVALID_OPERATION;
2687}
Eric Laurent1c333e22014-05-20 10:48:17 -07002688
2689status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2690 audio_patch_handle_t *handle)
2691{
2692 status_t status = NO_ERROR;
2693 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2694 // store new device and send to effects
2695 audio_devices_t type = AUDIO_DEVICE_NONE;
2696 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2697 type |= patch->sinks[i].ext.device.type;
2698 }
2699 mOutDevice = type;
2700 for (size_t i = 0; i < mEffectChains.size(); i++) {
2701 mEffectChains[i]->setDevice_l(mOutDevice);
2702 }
2703
2704 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2705 status = hwDevice->create_audio_patch(hwDevice,
2706 patch->num_sources,
2707 patch->sources,
2708 patch->num_sinks,
2709 patch->sinks,
2710 handle);
2711 } else {
2712 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2713 }
2714 return status;
2715}
2716
2717status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2718{
2719 status_t status = NO_ERROR;
2720 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2721 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2722 status = hwDevice->release_audio_patch(hwDevice, handle);
2723 } else {
2724 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2725 }
2726 return status;
2727}
2728
Eric Laurent83b88082014-06-20 18:31:16 -07002729void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2730{
2731 Mutex::Autolock _l(mLock);
2732 mTracks.add(track);
2733}
2734
2735void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2736{
2737 Mutex::Autolock _l(mLock);
2738 destroyTrack_l(track);
2739}
2740
2741void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2742{
2743 ThreadBase::getAudioPortConfig(config);
2744 config->role = AUDIO_PORT_ROLE_SOURCE;
2745 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2746 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2747}
2748
Eric Laurent81784c32012-11-19 14:55:58 -08002749// ----------------------------------------------------------------------------
2750
2751AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2752 audio_io_handle_t id, audio_devices_t device, type_t type)
2753 : PlaybackThread(audioFlinger, output, id, device, type),
2754 // mAudioMixer below
2755 // mFastMixer below
2756 mFastMixerFutex(0)
2757 // mOutputSink below
2758 // mPipeSink below
2759 // mNormalSink below
2760{
2761 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002762 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002763 "mFrameCount=%d, mNormalFrameCount=%d",
2764 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2765 mNormalFrameCount);
2766 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2767
2768 // FIXME - Current mixer implementation only supports stereo output
2769 if (mChannelCount != FCC_2) {
2770 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2771 }
2772
2773 // create an NBAIO sink for the HAL output stream, and negotiate
2774 mOutputSink = new AudioStreamOutSink(output->stream);
2775 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002776 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002777 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2778 ALOG_ASSERT(index == 0);
2779
2780 // initialize fast mixer depending on configuration
2781 bool initFastMixer;
2782 switch (kUseFastMixer) {
2783 case FastMixer_Never:
2784 initFastMixer = false;
2785 break;
2786 case FastMixer_Always:
2787 initFastMixer = true;
2788 break;
2789 case FastMixer_Static:
2790 case FastMixer_Dynamic:
2791 initFastMixer = mFrameCount < mNormalFrameCount;
2792 break;
2793 }
2794 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002795 audio_format_t fastMixerFormat;
2796 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2797 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2798 } else {
2799 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2800 }
2801 if (mFormat != fastMixerFormat) {
2802 // change our Sink format to accept our intermediate precision
2803 mFormat = fastMixerFormat;
2804 free(mSinkBuffer);
2805 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2806 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2807 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2808 }
Eric Laurent81784c32012-11-19 14:55:58 -08002809
2810 // create a MonoPipe to connect our submix to FastMixer
2811 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002812 // adjust format to match that of the Fast Mixer
2813 format.mFormat = fastMixerFormat;
2814 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2815
Eric Laurent81784c32012-11-19 14:55:58 -08002816 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2817 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2818 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2819 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2820 const NBAIO_Format offers[1] = {format};
2821 size_t numCounterOffers = 0;
2822 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2823 ALOG_ASSERT(index == 0);
2824 monoPipe->setAvgFrames((mScreenState & 1) ?
2825 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2826 mPipeSink = monoPipe;
2827
Glenn Kasten46909e72013-02-26 09:20:22 -08002828#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002829 if (mTeeSinkOutputEnabled) {
2830 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2831 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2832 numCounterOffers = 0;
2833 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2834 ALOG_ASSERT(index == 0);
2835 mTeeSink = teeSink;
2836 PipeReader *teeSource = new PipeReader(*teeSink);
2837 numCounterOffers = 0;
2838 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2839 ALOG_ASSERT(index == 0);
2840 mTeeSource = teeSource;
2841 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002842#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002843
2844 // create fast mixer and configure it initially with just one fast track for our submix
2845 mFastMixer = new FastMixer();
2846 FastMixerStateQueue *sq = mFastMixer->sq();
2847#ifdef STATE_QUEUE_DUMP
2848 sq->setObserverDump(&mStateQueueObserverDump);
2849 sq->setMutatorDump(&mStateQueueMutatorDump);
2850#endif
2851 FastMixerState *state = sq->begin();
2852 FastTrack *fastTrack = &state->mFastTracks[0];
2853 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2854 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2855 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002856 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2857 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002858 fastTrack->mGeneration++;
2859 state->mFastTracksGen++;
2860 state->mTrackMask = 1;
2861 // fast mixer will use the HAL output sink
2862 state->mOutputSink = mOutputSink.get();
2863 state->mOutputSinkGen++;
2864 state->mFrameCount = mFrameCount;
2865 state->mCommand = FastMixerState::COLD_IDLE;
2866 // already done in constructor initialization list
2867 //mFastMixerFutex = 0;
2868 state->mColdFutexAddr = &mFastMixerFutex;
2869 state->mColdGen++;
2870 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002871#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002872 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002873#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002874 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2875 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002876 sq->end();
2877 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2878
2879 // start the fast mixer
2880 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2881 pid_t tid = mFastMixer->getTid();
2882 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2883 if (err != 0) {
2884 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2885 kPriorityFastMixer, getpid_cached, tid, err);
2886 }
2887
2888#ifdef AUDIO_WATCHDOG
2889 // create and start the watchdog
2890 mAudioWatchdog = new AudioWatchdog();
2891 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2892 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2893 tid = mAudioWatchdog->getTid();
2894 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2895 if (err != 0) {
2896 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2897 kPriorityFastMixer, getpid_cached, tid, err);
2898 }
2899#endif
2900
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
2902
2903 switch (kUseFastMixer) {
2904 case FastMixer_Never:
2905 case FastMixer_Dynamic:
2906 mNormalSink = mOutputSink;
2907 break;
2908 case FastMixer_Always:
2909 mNormalSink = mPipeSink;
2910 break;
2911 case FastMixer_Static:
2912 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2913 break;
2914 }
2915}
2916
2917AudioFlinger::MixerThread::~MixerThread()
2918{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002919 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002920 FastMixerStateQueue *sq = mFastMixer->sq();
2921 FastMixerState *state = sq->begin();
2922 if (state->mCommand == FastMixerState::COLD_IDLE) {
2923 int32_t old = android_atomic_inc(&mFastMixerFutex);
2924 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002925 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002926 }
2927 }
2928 state->mCommand = FastMixerState::EXIT;
2929 sq->end();
2930 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2931 mFastMixer->join();
2932 // Though the fast mixer thread has exited, it's state queue is still valid.
2933 // We'll use that extract the final state which contains one remaining fast track
2934 // corresponding to our sub-mix.
2935 state = sq->begin();
2936 ALOG_ASSERT(state->mTrackMask == 1);
2937 FastTrack *fastTrack = &state->mFastTracks[0];
2938 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2939 delete fastTrack->mBufferProvider;
2940 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002941 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002942#ifdef AUDIO_WATCHDOG
2943 if (mAudioWatchdog != 0) {
2944 mAudioWatchdog->requestExit();
2945 mAudioWatchdog->requestExitAndWait();
2946 mAudioWatchdog.clear();
2947 }
2948#endif
2949 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002950 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002951 delete mAudioMixer;
2952}
2953
2954
2955uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2956{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002957 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002958 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2959 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2960 }
2961 return latency;
2962}
2963
2964
2965void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2966{
2967 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2968}
2969
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002971{
2972 // FIXME we should only do one push per cycle; confirm this is true
2973 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002974 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002975 FastMixerStateQueue *sq = mFastMixer->sq();
2976 FastMixerState *state = sq->begin();
2977 if (state->mCommand != FastMixerState::MIX_WRITE &&
2978 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2979 if (state->mCommand == FastMixerState::COLD_IDLE) {
2980 int32_t old = android_atomic_inc(&mFastMixerFutex);
2981 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002982 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002983 }
2984#ifdef AUDIO_WATCHDOG
2985 if (mAudioWatchdog != 0) {
2986 mAudioWatchdog->resume();
2987 }
2988#endif
2989 }
2990 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002991 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2992 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002993 sq->end();
2994 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2995 if (kUseFastMixer == FastMixer_Dynamic) {
2996 mNormalSink = mPipeSink;
2997 }
2998 } else {
2999 sq->end(false /*didModify*/);
3000 }
3001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003003}
3004
3005void AudioFlinger::MixerThread::threadLoop_standby()
3006{
3007 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003008 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003009 FastMixerStateQueue *sq = mFastMixer->sq();
3010 FastMixerState *state = sq->begin();
3011 if (!(state->mCommand & FastMixerState::IDLE)) {
3012 state->mCommand = FastMixerState::COLD_IDLE;
3013 state->mColdFutexAddr = &mFastMixerFutex;
3014 state->mColdGen++;
3015 mFastMixerFutex = 0;
3016 sq->end();
3017 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3018 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3019 if (kUseFastMixer == FastMixer_Dynamic) {
3020 mNormalSink = mOutputSink;
3021 }
3022#ifdef AUDIO_WATCHDOG
3023 if (mAudioWatchdog != 0) {
3024 mAudioWatchdog->pause();
3025 }
3026#endif
3027 } else {
3028 sq->end(false /*didModify*/);
3029 }
3030 }
3031 PlaybackThread::threadLoop_standby();
3032}
3033
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3035{
3036 return false;
3037}
3038
3039bool AudioFlinger::PlaybackThread::shouldStandby_l()
3040{
3041 return !mStandby;
3042}
3043
3044bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3045{
3046 Mutex::Autolock _l(mLock);
3047 return waitingAsyncCallback_l();
3048}
3049
Eric Laurent81784c32012-11-19 14:55:58 -08003050// shared by MIXER and DIRECT, overridden by DUPLICATING
3051void AudioFlinger::PlaybackThread::threadLoop_standby()
3052{
3053 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3054 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003056 // discard any pending drain or write ack by incrementing sequence
3057 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3058 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003060 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3061 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 }
Eric Laurent81784c32012-11-19 14:55:58 -08003063}
3064
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003065void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3066{
3067 ALOGV("signal playback thread");
3068 broadcast_l();
3069}
3070
Eric Laurent81784c32012-11-19 14:55:58 -08003071void AudioFlinger::MixerThread::threadLoop_mix()
3072{
3073 // obtain the presentation timestamp of the next output buffer
3074 int64_t pts;
3075 status_t status = INVALID_OPERATION;
3076
3077 if (mNormalSink != 0) {
3078 status = mNormalSink->getNextWriteTimestamp(&pts);
3079 } else {
3080 status = mOutputSink->getNextWriteTimestamp(&pts);
3081 }
3082
3083 if (status != NO_ERROR) {
3084 pts = AudioBufferProvider::kInvalidPTS;
3085 }
3086
3087 // mix buffers...
3088 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003089 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003090 // increase sleep time progressively when application underrun condition clears.
3091 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3092 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3093 // such that we would underrun the audio HAL.
3094 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3095 sleepTimeShift--;
3096 }
3097 sleepTime = 0;
3098 standbyTime = systemTime() + standbyDelay;
3099 //TODO: delay standby when effects have a tail
3100}
3101
3102void AudioFlinger::MixerThread::threadLoop_sleepTime()
3103{
3104 // If no tracks are ready, sleep once for the duration of an output
3105 // buffer size, then write 0s to the output
3106 if (sleepTime == 0) {
3107 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3108 sleepTime = activeSleepTime >> sleepTimeShift;
3109 if (sleepTime < kMinThreadSleepTimeUs) {
3110 sleepTime = kMinThreadSleepTimeUs;
3111 }
3112 // reduce sleep time in case of consecutive application underruns to avoid
3113 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3114 // duration we would end up writing less data than needed by the audio HAL if
3115 // the condition persists.
3116 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3117 sleepTimeShift++;
3118 }
3119 } else {
3120 sleepTime = idleSleepTime;
3121 }
3122 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003123 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3124 // before effects processing or output.
3125 if (mMixerBufferValid) {
3126 memset(mMixerBuffer, 0, mMixerBufferSize);
3127 } else {
3128 memset(mSinkBuffer, 0, mSinkBufferSize);
3129 }
Eric Laurent81784c32012-11-19 14:55:58 -08003130 sleepTime = 0;
3131 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3132 "anticipated start");
3133 }
3134 // TODO add standby time extension fct of effect tail
3135}
3136
3137// prepareTracks_l() must be called with ThreadBase::mLock held
3138AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3139 Vector< sp<Track> > *tracksToRemove)
3140{
3141
3142 mixer_state mixerStatus = MIXER_IDLE;
3143 // find out which tracks need to be processed
3144 size_t count = mActiveTracks.size();
3145 size_t mixedTracks = 0;
3146 size_t tracksWithEffect = 0;
3147 // counts only _active_ fast tracks
3148 size_t fastTracks = 0;
3149 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3150
3151 float masterVolume = mMasterVolume;
3152 bool masterMute = mMasterMute;
3153
3154 if (masterMute) {
3155 masterVolume = 0;
3156 }
3157 // Delegate master volume control to effect in output mix effect chain if needed
3158 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3159 if (chain != 0) {
3160 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3161 chain->setVolume_l(&v, &v);
3162 masterVolume = (float)((v + (1 << 23)) >> 24);
3163 chain.clear();
3164 }
3165
3166 // prepare a new state to push
3167 FastMixerStateQueue *sq = NULL;
3168 FastMixerState *state = NULL;
3169 bool didModify = false;
3170 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003171 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003172 sq = mFastMixer->sq();
3173 state = sq->begin();
3174 }
3175
Andy Hung69aed5f2014-02-25 17:24:40 -08003176 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003177 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003178
Eric Laurent81784c32012-11-19 14:55:58 -08003179 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003180 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003181 if (t == 0) {
3182 continue;
3183 }
3184
3185 // this const just means the local variable doesn't change
3186 Track* const track = t.get();
3187
3188 // process fast tracks
3189 if (track->isFastTrack()) {
3190
3191 // It's theoretically possible (though unlikely) for a fast track to be created
3192 // and then removed within the same normal mix cycle. This is not a problem, as
3193 // the track never becomes active so it's fast mixer slot is never touched.
3194 // The converse, of removing an (active) track and then creating a new track
3195 // at the identical fast mixer slot within the same normal mix cycle,
3196 // is impossible because the slot isn't marked available until the end of each cycle.
3197 int j = track->mFastIndex;
3198 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3199 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3200 FastTrack *fastTrack = &state->mFastTracks[j];
3201
3202 // Determine whether the track is currently in underrun condition,
3203 // and whether it had a recent underrun.
3204 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3205 FastTrackUnderruns underruns = ftDump->mUnderruns;
3206 uint32_t recentFull = (underruns.mBitFields.mFull -
3207 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3208 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3209 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3210 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3211 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3212 uint32_t recentUnderruns = recentPartial + recentEmpty;
3213 track->mObservedUnderruns = underruns;
3214 // don't count underruns that occur while stopping or pausing
3215 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003216 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3217 recentUnderruns > 0) {
3218 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3219 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003220 }
3221
3222 // This is similar to the state machine for normal tracks,
3223 // with a few modifications for fast tracks.
3224 bool isActive = true;
3225 switch (track->mState) {
3226 case TrackBase::STOPPING_1:
3227 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003228 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003229 track->mState = TrackBase::STOPPING_2;
3230 }
3231 break;
3232 case TrackBase::PAUSING:
3233 // ramp down is not yet implemented
3234 track->setPaused();
3235 break;
3236 case TrackBase::RESUMING:
3237 // ramp up is not yet implemented
3238 track->mState = TrackBase::ACTIVE;
3239 break;
3240 case TrackBase::ACTIVE:
3241 if (recentFull > 0 || recentPartial > 0) {
3242 // track has provided at least some frames recently: reset retry count
3243 track->mRetryCount = kMaxTrackRetries;
3244 }
3245 if (recentUnderruns == 0) {
3246 // no recent underruns: stay active
3247 break;
3248 }
3249 // there has recently been an underrun of some kind
3250 if (track->sharedBuffer() == 0) {
3251 // were any of the recent underruns "empty" (no frames available)?
3252 if (recentEmpty == 0) {
3253 // no, then ignore the partial underruns as they are allowed indefinitely
3254 break;
3255 }
3256 // there has recently been an "empty" underrun: decrement the retry counter
3257 if (--(track->mRetryCount) > 0) {
3258 break;
3259 }
3260 // indicate to client process that the track was disabled because of underrun;
3261 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003262 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003263 // remove from active list, but state remains ACTIVE [confusing but true]
3264 isActive = false;
3265 break;
3266 }
3267 // fall through
3268 case TrackBase::STOPPING_2:
3269 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003270 case TrackBase::STOPPED:
3271 case TrackBase::FLUSHED: // flush() while active
3272 // Check for presentation complete if track is inactive
3273 // We have consumed all the buffers of this track.
3274 // This would be incomplete if we auto-paused on underrun
3275 {
3276 size_t audioHALFrames =
3277 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3278 size_t framesWritten = mBytesWritten / mFrameSize;
3279 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3280 // track stays in active list until presentation is complete
3281 break;
3282 }
3283 }
3284 if (track->isStopping_2()) {
3285 track->mState = TrackBase::STOPPED;
3286 }
3287 if (track->isStopped()) {
3288 // Can't reset directly, as fast mixer is still polling this track
3289 // track->reset();
3290 // So instead mark this track as needing to be reset after push with ack
3291 resetMask |= 1 << i;
3292 }
3293 isActive = false;
3294 break;
3295 case TrackBase::IDLE:
3296 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003297 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
3299
3300 if (isActive) {
3301 // was it previously inactive?
3302 if (!(state->mTrackMask & (1 << j))) {
3303 ExtendedAudioBufferProvider *eabp = track;
3304 VolumeProvider *vp = track;
3305 fastTrack->mBufferProvider = eabp;
3306 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003307 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003308 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003309 fastTrack->mGeneration++;
3310 state->mTrackMask |= 1 << j;
3311 didModify = true;
3312 // no acknowledgement required for newly active tracks
3313 }
3314 // cache the combined master volume and stream type volume for fast mixer; this
3315 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003316 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003317 ++fastTracks;
3318 } else {
3319 // was it previously active?
3320 if (state->mTrackMask & (1 << j)) {
3321 fastTrack->mBufferProvider = NULL;
3322 fastTrack->mGeneration++;
3323 state->mTrackMask &= ~(1 << j);
3324 didModify = true;
3325 // If any fast tracks were removed, we must wait for acknowledgement
3326 // because we're about to decrement the last sp<> on those tracks.
3327 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3328 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003329 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003330 }
3331 tracksToRemove->add(track);
3332 // Avoids a misleading display in dumpsys
3333 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3334 }
3335 continue;
3336 }
3337
3338 { // local variable scope to avoid goto warning
3339
3340 audio_track_cblk_t* cblk = track->cblk();
3341
3342 // The first time a track is added we wait
3343 // for all its buffers to be filled before processing it
3344 int name = track->name();
3345 // make sure that we have enough frames to mix one full buffer.
3346 // enforce this condition only once to enable draining the buffer in case the client
3347 // app does not call stop() and relies on underrun to stop:
3348 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3349 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003350 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003351 uint32_t sr = track->sampleRate();
3352 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003353 desiredFrames = mNormalFrameCount;
3354 } else {
3355 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003356 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003357 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003358 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003359 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003360#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003361 // the minimum track buffer size is normally twice the number of frames necessary
3362 // to fill one buffer and the resampler should not leave more than one buffer worth
3363 // of unreleased frames after each pass, but just in case...
3364 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003365#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003366 }
Eric Laurent81784c32012-11-19 14:55:58 -08003367 uint32_t minFrames = 1;
3368 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3369 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003370 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003372
3373 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003374 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003375 !track->isPaused() && !track->isTerminated())
3376 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003377 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003378
3379 mixedTracks++;
3380
Andy Hung69aed5f2014-02-25 17:24:40 -08003381 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3382 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003383 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003384 if (track->mainBuffer() != mSinkBuffer &&
3385 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003386 if (mEffectBufferEnabled) {
3387 mEffectBufferValid = true; // Later can set directly.
3388 }
Eric Laurent81784c32012-11-19 14:55:58 -08003389 chain = getEffectChain_l(track->sessionId());
3390 // Delegate volume control to effect in track effect chain if needed
3391 if (chain != 0) {
3392 tracksWithEffect++;
3393 } else {
3394 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3395 "session %d",
3396 name, track->sessionId());
3397 }
3398 }
3399
3400
3401 int param = AudioMixer::VOLUME;
3402 if (track->mFillingUpStatus == Track::FS_FILLED) {
3403 // no ramp for the first volume setting
3404 track->mFillingUpStatus = Track::FS_ACTIVE;
3405 if (track->mState == TrackBase::RESUMING) {
3406 track->mState = TrackBase::ACTIVE;
3407 param = AudioMixer::RAMP_VOLUME;
3408 }
3409 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003410 // FIXME should not make a decision based on mServer
3411 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003412 // If the track is stopped before the first frame was mixed,
3413 // do not apply ramp
3414 param = AudioMixer::RAMP_VOLUME;
3415 }
3416
3417 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003418 uint32_t vl, vr; // in U8.24 integer format
3419 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003420 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003421 vl = vr = 0;
3422 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003423 if (track->isPausing()) {
3424 track->setPaused();
3425 }
3426 } else {
3427
3428 // read original volumes with volume control
3429 float typeVolume = mStreamTypes[track->streamType()].volume;
3430 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003431 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003432 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003433 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3434 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003435 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003436 if (vlf > GAIN_FLOAT_UNITY) {
3437 ALOGV("Track left volume out of range: %.3g", vlf);
3438 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003439 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003440 if (vrf > GAIN_FLOAT_UNITY) {
3441 ALOGV("Track right volume out of range: %.3g", vrf);
3442 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003443 }
3444 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003445 vlf *= v;
3446 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003447 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003448 // then derive vl and vr as U8.24 versions for the effect chain
3449 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3450 vl = (uint32_t) (scaleto8_24 * vlf);
3451 vr = (uint32_t) (scaleto8_24 * vrf);
3452 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003453 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003454 // send level comes from shared memory and so may be corrupt
3455 if (sendLevel > MAX_GAIN_INT) {
3456 ALOGV("Track send level out of range: %04X", sendLevel);
3457 sendLevel = MAX_GAIN_INT;
3458 }
Andy Hung6be49402014-05-30 10:42:03 -07003459 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3460 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003461 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462
Eric Laurent81784c32012-11-19 14:55:58 -08003463 // Delegate volume control to effect in track effect chain if needed
3464 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3465 // Do not ramp volume if volume is controlled by effect
3466 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003467 // Update remaining floating point volume levels
3468 vlf = (float)vl / (1 << 24);
3469 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003470 track->mHasVolumeController = true;
3471 } else {
3472 // force no volume ramp when volume controller was just disabled or removed
3473 // from effect chain to avoid volume spike
3474 if (track->mHasVolumeController) {
3475 param = AudioMixer::VOLUME;
3476 }
3477 track->mHasVolumeController = false;
3478 }
3479
Eric Laurent81784c32012-11-19 14:55:58 -08003480 // XXX: these things DON'T need to be done each time
3481 mAudioMixer->setBufferProvider(name, track);
3482 mAudioMixer->enable(name);
3483
Andy Hung6be49402014-05-30 10:42:03 -07003484 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3485 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3486 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003487 mAudioMixer->setParameter(
3488 name,
3489 AudioMixer::TRACK,
3490 AudioMixer::FORMAT, (void *)track->format());
3491 mAudioMixer->setParameter(
3492 name,
3493 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003494 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003495 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3496 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003497 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003498 if (reqSampleRate == 0) {
3499 reqSampleRate = mSampleRate;
3500 } else if (reqSampleRate > maxSampleRate) {
3501 reqSampleRate = maxSampleRate;
3502 }
Eric Laurent81784c32012-11-19 14:55:58 -08003503 mAudioMixer->setParameter(
3504 name,
3505 AudioMixer::RESAMPLE,
3506 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003507 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003508 /*
3509 * Select the appropriate output buffer for the track.
3510 *
Andy Hung98ef9782014-03-04 14:46:50 -08003511 * Tracks with effects go into their own effects chain buffer
3512 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003513 *
3514 * Other tracks can use mMixerBuffer for higher precision
3515 * channel accumulation. If this buffer is enabled
3516 * (mMixerBufferEnabled true), then selected tracks will accumulate
3517 * into it.
3518 *
3519 */
3520 if (mMixerBufferEnabled
3521 && (track->mainBuffer() == mSinkBuffer
3522 || track->mainBuffer() == mMixerBuffer)) {
3523 mAudioMixer->setParameter(
3524 name,
3525 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003526 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003527 mAudioMixer->setParameter(
3528 name,
3529 AudioMixer::TRACK,
3530 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3531 // TODO: override track->mainBuffer()?
3532 mMixerBufferValid = true;
3533 } else {
3534 mAudioMixer->setParameter(
3535 name,
3536 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003537 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003538 mAudioMixer->setParameter(
3539 name,
3540 AudioMixer::TRACK,
3541 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3542 }
Eric Laurent81784c32012-11-19 14:55:58 -08003543 mAudioMixer->setParameter(
3544 name,
3545 AudioMixer::TRACK,
3546 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3547
3548 // reset retry count
3549 track->mRetryCount = kMaxTrackRetries;
3550
3551 // If one track is ready, set the mixer ready if:
3552 // - the mixer was not ready during previous round OR
3553 // - no other track is not ready
3554 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3555 mixerStatus != MIXER_TRACKS_ENABLED) {
3556 mixerStatus = MIXER_TRACKS_READY;
3557 }
3558 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003559 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003560 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003561 }
Eric Laurent81784c32012-11-19 14:55:58 -08003562 // clear effect chain input buffer if an active track underruns to avoid sending
3563 // previous audio buffer again to effects
3564 chain = getEffectChain_l(track->sessionId());
3565 if (chain != 0) {
3566 chain->clearInputBuffer();
3567 }
3568
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003569 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003570 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3571 track->isStopped() || track->isPaused()) {
3572 // We have consumed all the buffers of this track.
3573 // Remove it from the list of active tracks.
3574 // TODO: use actual buffer filling status instead of latency when available from
3575 // audio HAL
3576 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3577 size_t framesWritten = mBytesWritten / mFrameSize;
3578 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3579 if (track->isStopped()) {
3580 track->reset();
3581 }
3582 tracksToRemove->add(track);
3583 }
3584 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // No buffers for this track. Give it a few chances to
3586 // fill a buffer, then remove it from active list.
3587 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003588 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003589 tracksToRemove->add(track);
3590 // indicate to client process that the track was disabled because of underrun;
3591 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003592 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003593 // If one track is not ready, mark the mixer also not ready if:
3594 // - the mixer was ready during previous round OR
3595 // - no other track is ready
3596 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3597 mixerStatus != MIXER_TRACKS_READY) {
3598 mixerStatus = MIXER_TRACKS_ENABLED;
3599 }
3600 }
3601 mAudioMixer->disable(name);
3602 }
3603
3604 } // local variable scope to avoid goto warning
3605track_is_ready: ;
3606
3607 }
3608
3609 // Push the new FastMixer state if necessary
3610 bool pauseAudioWatchdog = false;
3611 if (didModify) {
3612 state->mFastTracksGen++;
3613 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3614 if (kUseFastMixer == FastMixer_Dynamic &&
3615 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3616 state->mCommand = FastMixerState::COLD_IDLE;
3617 state->mColdFutexAddr = &mFastMixerFutex;
3618 state->mColdGen++;
3619 mFastMixerFutex = 0;
3620 if (kUseFastMixer == FastMixer_Dynamic) {
3621 mNormalSink = mOutputSink;
3622 }
3623 // If we go into cold idle, need to wait for acknowledgement
3624 // so that fast mixer stops doing I/O.
3625 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3626 pauseAudioWatchdog = true;
3627 }
Eric Laurent81784c32012-11-19 14:55:58 -08003628 }
3629 if (sq != NULL) {
3630 sq->end(didModify);
3631 sq->push(block);
3632 }
3633#ifdef AUDIO_WATCHDOG
3634 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3635 mAudioWatchdog->pause();
3636 }
3637#endif
3638
3639 // Now perform the deferred reset on fast tracks that have stopped
3640 while (resetMask != 0) {
3641 size_t i = __builtin_ctz(resetMask);
3642 ALOG_ASSERT(i < count);
3643 resetMask &= ~(1 << i);
3644 sp<Track> t = mActiveTracks[i].promote();
3645 if (t == 0) {
3646 continue;
3647 }
3648 Track* track = t.get();
3649 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3650 track->reset();
3651 }
3652
3653 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003654 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003655
Andy Hung69aed5f2014-02-25 17:24:40 -08003656 // sink or mix buffer must be cleared if all tracks are connected to an
3657 // effect chain as in this case the mixer will not write to the sink or mix buffer
3658 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003659 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3660 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003661 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003662 if (mMixerBufferValid) {
3663 memset(mMixerBuffer, 0, mMixerBufferSize);
3664 // TODO: In testing, mSinkBuffer below need not be cleared because
3665 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3666 // after mixing.
3667 //
3668 // To enforce this guarantee:
3669 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3670 // (mixedTracks == 0 && fastTracks > 0))
3671 // must imply MIXER_TRACKS_READY.
3672 // Later, we may clear buffers regardless, and skip much of this logic.
3673 }
Andy Hung98ef9782014-03-04 14:46:50 -08003674 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3675 if (mEffectBufferValid) {
3676 memset(mEffectBuffer, 0, mEffectBufferSize);
3677 }
3678 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003679 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003680 }
3681
3682 // if any fast tracks, then status is ready
3683 mMixerStatusIgnoringFastTracks = mixerStatus;
3684 if (fastTracks > 0) {
3685 mixerStatus = MIXER_TRACKS_READY;
3686 }
3687 return mixerStatus;
3688}
3689
3690// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003691int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3692 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003693{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003694 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003695}
3696
3697// deleteTrackName_l() must be called with ThreadBase::mLock held
3698void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3699{
3700 ALOGV("remove track (%d) and delete from mixer", name);
3701 mAudioMixer->deleteTrackName(name);
3702}
3703
Eric Laurent10351942014-05-08 18:49:52 -07003704// checkForNewParameter_l() must be called with ThreadBase::mLock held
3705bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3706 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003707{
Eric Laurent81784c32012-11-19 14:55:58 -08003708 bool reconfig = false;
3709
Eric Laurent10351942014-05-08 18:49:52 -07003710 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003711
Eric Laurent10351942014-05-08 18:49:52 -07003712 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3713 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003714 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003715 FastMixerStateQueue *sq = mFastMixer->sq();
3716 FastMixerState *state = sq->begin();
3717 if (!(state->mCommand & FastMixerState::IDLE)) {
3718 previousCommand = state->mCommand;
3719 state->mCommand = FastMixerState::HOT_IDLE;
3720 sq->end();
3721 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3722 } else {
3723 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003724 }
Eric Laurent10351942014-05-08 18:49:52 -07003725 }
Eric Laurent81784c32012-11-19 14:55:58 -08003726
Eric Laurent10351942014-05-08 18:49:52 -07003727 AudioParameter param = AudioParameter(keyValuePair);
3728 int value;
3729 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3730 reconfig = true;
3731 }
3732 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3733 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3734 status = BAD_VALUE;
3735 } else {
3736 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003737 reconfig = true;
3738 }
Eric Laurent10351942014-05-08 18:49:52 -07003739 }
3740 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3741 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3742 status = BAD_VALUE;
3743 } else {
3744 // no need to save value, since it's constant
3745 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003746 }
Eric Laurent10351942014-05-08 18:49:52 -07003747 }
3748 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3749 // do not accept frame count changes if tracks are open as the track buffer
3750 // size depends on frame count and correct behavior would not be guaranteed
3751 // if frame count is changed after track creation
3752 if (!mTracks.isEmpty()) {
3753 status = INVALID_OPERATION;
3754 } else {
3755 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003756 }
Eric Laurent10351942014-05-08 18:49:52 -07003757 }
3758 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003760 // when changing the audio output device, call addBatteryData to notify
3761 // the change
3762 if (mOutDevice != value) {
3763 uint32_t params = 0;
3764 // check whether speaker is on
3765 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3766 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003767 }
Eric Laurent10351942014-05-08 18:49:52 -07003768
3769 audio_devices_t deviceWithoutSpeaker
3770 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3771 // check if any other device (except speaker) is on
3772 if (value & deviceWithoutSpeaker ) {
3773 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3774 }
3775
3776 if (params != 0) {
3777 addBatteryData(params);
3778 }
3779 }
Eric Laurent81784c32012-11-19 14:55:58 -08003780#endif
3781
Eric Laurent10351942014-05-08 18:49:52 -07003782 // forward device change to effects that have requested to be
3783 // aware of attached audio device.
3784 if (value != AUDIO_DEVICE_NONE) {
3785 mOutDevice = value;
3786 for (size_t i = 0; i < mEffectChains.size(); i++) {
3787 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003788 }
3789 }
Eric Laurent10351942014-05-08 18:49:52 -07003790 }
Eric Laurent81784c32012-11-19 14:55:58 -08003791
Eric Laurent10351942014-05-08 18:49:52 -07003792 if (status == NO_ERROR) {
3793 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3794 keyValuePair.string());
3795 if (!mStandby && status == INVALID_OPERATION) {
3796 mOutput->stream->common.standby(&mOutput->stream->common);
3797 mStandby = true;
3798 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003799 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003800 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003801 }
Eric Laurent10351942014-05-08 18:49:52 -07003802 if (status == NO_ERROR && reconfig) {
3803 readOutputParameters_l();
3804 delete mAudioMixer;
3805 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3806 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003807 int name = getTrackName_l(mTracks[i]->mChannelMask,
3808 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003809 if (name < 0) {
3810 break;
3811 }
3812 mTracks[i]->mName = name;
3813 }
3814 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3815 }
Eric Laurent81784c32012-11-19 14:55:58 -08003816 }
3817
3818 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003819 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003820 FastMixerStateQueue *sq = mFastMixer->sq();
3821 FastMixerState *state = sq->begin();
3822 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3823 state->mCommand = previousCommand;
3824 sq->end();
3825 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3826 }
3827
3828 return reconfig;
3829}
3830
3831
3832void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3833{
3834 const size_t SIZE = 256;
3835 char buffer[SIZE];
3836 String8 result;
3837
3838 PlaybackThread::dumpInternals(fd, args);
3839
Elliott Hughes87cebad2014-05-22 10:14:43 -07003840 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003841
3842 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003843 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003844 copy.dump(fd);
3845
3846#ifdef STATE_QUEUE_DUMP
3847 // Similar for state queue
3848 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3849 observerCopy.dump(fd);
3850 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3851 mutatorCopy.dump(fd);
3852#endif
3853
Glenn Kasten46909e72013-02-26 09:20:22 -08003854#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // Write the tee output to a .wav file
3856 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003857#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003858
3859#ifdef AUDIO_WATCHDOG
3860 if (mAudioWatchdog != 0) {
3861 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3862 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3863 wdCopy.dump(fd);
3864 }
3865#endif
3866}
3867
3868uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3869{
3870 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3871}
3872
3873uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3874{
3875 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3876}
3877
3878void AudioFlinger::MixerThread::cacheParameters_l()
3879{
3880 PlaybackThread::cacheParameters_l();
3881
3882 // FIXME: Relaxed timing because of a certain device that can't meet latency
3883 // Should be reduced to 2x after the vendor fixes the driver issue
3884 // increase threshold again due to low power audio mode. The way this warning
3885 // threshold is calculated and its usefulness should be reconsidered anyway.
3886 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3887}
3888
3889// ----------------------------------------------------------------------------
3890
3891AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3892 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3893 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3894 // mLeftVolFloat, mRightVolFloat
3895{
3896}
3897
Eric Laurentbfb1b832013-01-07 09:53:42 -08003898AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3899 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3900 ThreadBase::type_t type)
3901 : PlaybackThread(audioFlinger, output, id, device, type)
3902 // mLeftVolFloat, mRightVolFloat
3903{
3904}
3905
Eric Laurent81784c32012-11-19 14:55:58 -08003906AudioFlinger::DirectOutputThread::~DirectOutputThread()
3907{
3908}
3909
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3911{
3912 audio_track_cblk_t* cblk = track->cblk();
3913 float left, right;
3914
3915 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3916 left = right = 0;
3917 } else {
3918 float typeVolume = mStreamTypes[track->streamType()].volume;
3919 float v = mMasterVolume * typeVolume;
3920 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003921 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3922 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3923 if (left > GAIN_FLOAT_UNITY) {
3924 left = GAIN_FLOAT_UNITY;
3925 }
3926 left *= v;
3927 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3928 if (right > GAIN_FLOAT_UNITY) {
3929 right = GAIN_FLOAT_UNITY;
3930 }
3931 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 }
3933
3934 if (lastTrack) {
3935 if (left != mLeftVolFloat || right != mRightVolFloat) {
3936 mLeftVolFloat = left;
3937 mRightVolFloat = right;
3938
3939 // Convert volumes from float to 8.24
3940 uint32_t vl = (uint32_t)(left * (1 << 24));
3941 uint32_t vr = (uint32_t)(right * (1 << 24));
3942
3943 // Delegate volume control to effect in track effect chain if needed
3944 // only one effect chain can be present on DirectOutputThread, so if
3945 // there is one, the track is connected to it
3946 if (!mEffectChains.isEmpty()) {
3947 mEffectChains[0]->setVolume_l(&vl, &vr);
3948 left = (float)vl / (1 << 24);
3949 right = (float)vr / (1 << 24);
3950 }
3951 if (mOutput->stream->set_volume) {
3952 mOutput->stream->set_volume(mOutput->stream, left, right);
3953 }
3954 }
3955 }
3956}
3957
3958
Eric Laurent81784c32012-11-19 14:55:58 -08003959AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3960 Vector< sp<Track> > *tracksToRemove
3961)
3962{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003963 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003964 mixer_state mixerStatus = MIXER_IDLE;
3965
3966 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003967 for (size_t i = 0; i < count; i++) {
3968 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003969 // The track died recently
3970 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003971 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003972 }
3973
3974 Track* const track = t.get();
3975 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003976 // Only consider last track started for volume and mixer state control.
3977 // In theory an older track could underrun and restart after the new one starts
3978 // but as we only care about the transition phase between two tracks on a
3979 // direct output, it is not a problem to ignore the underrun case.
3980 sp<Track> l = mLatestActiveTrack.promote();
3981 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003982
3983 // The first time a track is added we wait
3984 // for all its buffers to be filled before processing it
3985 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07003986 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003987 minFrames = mNormalFrameCount;
3988 } else {
3989 minFrames = 1;
3990 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003991
Eric Laurentab5cdba2014-06-09 17:22:27 -07003992 ALOGI("prepareTracks_l minFrames %d state %d frames ready %d, ",
3993 minFrames, track->mState, track->framesReady());
3994 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
3995 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08003996 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003997 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003998
3999 if (track->mFillingUpStatus == Track::FS_FILLED) {
4000 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004001 // make sure processVolume_l() will apply new volume even if 0
4002 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004003 if (track->mState == TrackBase::RESUMING) {
4004 track->mState = TrackBase::ACTIVE;
4005 }
4006 }
4007
4008 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004009 processVolume_l(track, last);
4010 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004011 // reset retry count
4012 track->mRetryCount = kMaxTrackRetriesDirect;
4013 mActiveTrack = t;
4014 mixerStatus = MIXER_TRACKS_READY;
4015 }
Eric Laurent81784c32012-11-19 14:55:58 -08004016 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004017 // clear effect chain input buffer if the last active track started underruns
4018 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004019 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004020 mEffectChains[0]->clearInputBuffer();
4021 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004022 if (track->isStopping_1()) {
4023 track->mState = TrackBase::STOPPING_2;
4024 }
4025 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4026 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004027 // We have consumed all the buffers of this track.
4028 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004029 size_t audioHALFrames;
4030 if (audio_is_linear_pcm(mFormat)) {
4031 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4032 } else {
4033 audioHALFrames = 0;
4034 }
4035
Eric Laurent81784c32012-11-19 14:55:58 -08004036 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004037 if (mStandby || !last ||
4038 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004039 if (track->isStopping_2()) {
4040 track->mState = TrackBase::STOPPED;
4041 }
Eric Laurent81784c32012-11-19 14:55:58 -08004042 if (track->isStopped()) {
4043 track->reset();
4044 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004045 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 }
4047 } else {
4048 // No buffers for this track. Give it a few chances to
4049 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004050 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004051 if (--(track->mRetryCount) <= 0) {
4052 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004053 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004054 // indicate to client process that the track was disabled because of underrun;
4055 // it will then automatically call start() when data is available
4056 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004058 mixerStatus = MIXER_TRACKS_ENABLED;
4059 }
4060 }
4061 }
4062 }
4063
Eric Laurent81784c32012-11-19 14:55:58 -08004064 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004066
4067 return mixerStatus;
4068}
4069
4070void AudioFlinger::DirectOutputThread::threadLoop_mix()
4071{
Eric Laurent81784c32012-11-19 14:55:58 -08004072 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004073 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004074 // output audio to hardware
4075 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004076 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004077 buffer.frameCount = frameCount;
4078 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004079 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004080 memset(curBuf, 0, frameCount * mFrameSize);
4081 break;
4082 }
4083 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4084 frameCount -= buffer.frameCount;
4085 curBuf += buffer.frameCount * mFrameSize;
4086 mActiveTrack->releaseBuffer(&buffer);
4087 }
Andy Hung2098f272014-02-27 14:00:06 -08004088 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004089 sleepTime = 0;
4090 standbyTime = systemTime() + standbyDelay;
4091 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004092}
4093
4094void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4095{
4096 if (sleepTime == 0) {
4097 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4098 sleepTime = activeSleepTime;
4099 } else {
4100 sleepTime = idleSleepTime;
4101 }
4102 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004103 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004104 sleepTime = 0;
4105 }
4106}
4107
4108// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004109int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004110 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004111{
4112 return 0;
4113}
4114
4115// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004116void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004117{
4118}
4119
Eric Laurent10351942014-05-08 18:49:52 -07004120// checkForNewParameter_l() must be called with ThreadBase::mLock held
4121bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4122 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004123{
4124 bool reconfig = false;
4125
Eric Laurent10351942014-05-08 18:49:52 -07004126 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004127
Eric Laurent10351942014-05-08 18:49:52 -07004128 AudioParameter param = AudioParameter(keyValuePair);
4129 int value;
4130 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4131 // forward device change to effects that have requested to be
4132 // aware of attached audio device.
4133 if (value != AUDIO_DEVICE_NONE) {
4134 mOutDevice = value;
4135 for (size_t i = 0; i < mEffectChains.size(); i++) {
4136 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004137 }
4138 }
Eric Laurent81784c32012-11-19 14:55:58 -08004139 }
Eric Laurent10351942014-05-08 18:49:52 -07004140 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4141 // do not accept frame count changes if tracks are open as the track buffer
4142 // size depends on frame count and correct behavior would not be garantied
4143 // if frame count is changed after track creation
4144 if (!mTracks.isEmpty()) {
4145 status = INVALID_OPERATION;
4146 } else {
4147 reconfig = true;
4148 }
4149 }
4150 if (status == NO_ERROR) {
4151 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4152 keyValuePair.string());
4153 if (!mStandby && status == INVALID_OPERATION) {
4154 mOutput->stream->common.standby(&mOutput->stream->common);
4155 mStandby = true;
4156 mBytesWritten = 0;
4157 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4158 keyValuePair.string());
4159 }
4160 if (status == NO_ERROR && reconfig) {
4161 readOutputParameters_l();
4162 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4163 }
4164 }
4165
Eric Laurent81784c32012-11-19 14:55:58 -08004166 return reconfig;
4167}
4168
4169uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4170{
4171 uint32_t time;
4172 if (audio_is_linear_pcm(mFormat)) {
4173 time = PlaybackThread::activeSleepTimeUs();
4174 } else {
4175 time = 10000;
4176 }
4177 return time;
4178}
4179
4180uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4181{
4182 uint32_t time;
4183 if (audio_is_linear_pcm(mFormat)) {
4184 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4185 } else {
4186 time = 10000;
4187 }
4188 return time;
4189}
4190
4191uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4192{
4193 uint32_t time;
4194 if (audio_is_linear_pcm(mFormat)) {
4195 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4196 } else {
4197 time = 10000;
4198 }
4199 return time;
4200}
4201
4202void AudioFlinger::DirectOutputThread::cacheParameters_l()
4203{
4204 PlaybackThread::cacheParameters_l();
4205
4206 // use shorter standby delay as on normal output to release
4207 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004208 if (audio_is_linear_pcm(mFormat)) {
4209 standbyDelay = microseconds(activeSleepTime*2);
4210 } else {
4211 standbyDelay = kOffloadStandbyDelayNs;
4212 }
Eric Laurent81784c32012-11-19 14:55:58 -08004213}
4214
4215// ----------------------------------------------------------------------------
4216
Eric Laurentbfb1b832013-01-07 09:53:42 -08004217AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004218 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004220 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004221 mWriteAckSequence(0),
4222 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223{
4224}
4225
4226AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4227{
4228}
4229
4230void AudioFlinger::AsyncCallbackThread::onFirstRef()
4231{
4232 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4233}
4234
4235bool AudioFlinger::AsyncCallbackThread::threadLoop()
4236{
4237 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004238 uint32_t writeAckSequence;
4239 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240
4241 {
4242 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004243 while (!((mWriteAckSequence & 1) ||
4244 (mDrainSequence & 1) ||
4245 exitPending())) {
4246 mWaitWorkCV.wait(mLock);
4247 }
4248
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 if (exitPending()) {
4250 break;
4251 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004252 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4253 mWriteAckSequence, mDrainSequence);
4254 writeAckSequence = mWriteAckSequence;
4255 mWriteAckSequence &= ~1;
4256 drainSequence = mDrainSequence;
4257 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 }
4259 {
Eric Laurent4de95592013-09-26 15:28:21 -07004260 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4261 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004262 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004263 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004265 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004266 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 }
4268 }
4269 }
4270 }
4271 return false;
4272}
4273
4274void AudioFlinger::AsyncCallbackThread::exit()
4275{
4276 ALOGV("AsyncCallbackThread::exit");
4277 Mutex::Autolock _l(mLock);
4278 requestExit();
4279 mWaitWorkCV.broadcast();
4280}
4281
Eric Laurent3b4529e2013-09-05 18:09:19 -07004282void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283{
4284 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004285 // bit 0 is cleared
4286 mWriteAckSequence = sequence << 1;
4287}
4288
4289void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4290{
4291 Mutex::Autolock _l(mLock);
4292 // ignore unexpected callbacks
4293 if (mWriteAckSequence & 2) {
4294 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 mWaitWorkCV.signal();
4296 }
4297}
4298
Eric Laurent3b4529e2013-09-05 18:09:19 -07004299void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300{
4301 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004302 // bit 0 is cleared
4303 mDrainSequence = sequence << 1;
4304}
4305
4306void AudioFlinger::AsyncCallbackThread::resetDraining()
4307{
4308 Mutex::Autolock _l(mLock);
4309 // ignore unexpected callbacks
4310 if (mDrainSequence & 2) {
4311 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312 mWaitWorkCV.signal();
4313 }
4314}
4315
4316
4317// ----------------------------------------------------------------------------
4318AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4319 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4320 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4321 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004322 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004323 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324{
Eric Laurentfd477972013-10-25 18:10:40 -07004325 //FIXME: mStandby should be set to true by ThreadBase constructor
4326 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327}
4328
Eric Laurentbfb1b832013-01-07 09:53:42 -08004329void AudioFlinger::OffloadThread::threadLoop_exit()
4330{
4331 if (mFlushPending || mHwPaused) {
4332 // If a flush is pending or track was paused, just discard buffered data
4333 flushHw_l();
4334 } else {
4335 mMixerStatus = MIXER_DRAIN_ALL;
4336 threadLoop_drain();
4337 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004338 if (mUseAsyncWrite) {
4339 ALOG_ASSERT(mCallbackThread != 0);
4340 mCallbackThread->exit();
4341 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 PlaybackThread::threadLoop_exit();
4343}
4344
4345AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4346 Vector< sp<Track> > *tracksToRemove
4347)
4348{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004349 size_t count = mActiveTracks.size();
4350
4351 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004352 bool doHwPause = false;
4353 bool doHwResume = false;
4354
Eric Laurentede6c3b2013-09-19 14:37:46 -07004355 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4356
Eric Laurentbfb1b832013-01-07 09:53:42 -08004357 // find out which tracks need to be processed
4358 for (size_t i = 0; i < count; i++) {
4359 sp<Track> t = mActiveTracks[i].promote();
4360 // The track died recently
4361 if (t == 0) {
4362 continue;
4363 }
4364 Track* const track = t.get();
4365 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004366 // Only consider last track started for volume and mixer state control.
4367 // In theory an older track could underrun and restart after the new one starts
4368 // but as we only care about the transition phase between two tracks on a
4369 // direct output, it is not a problem to ignore the underrun case.
4370 sp<Track> l = mLatestActiveTrack.promote();
4371 bool last = l.get() == track;
4372
Haynes Mathew George7844f672014-01-15 12:32:55 -08004373 if (track->isInvalid()) {
4374 ALOGW("An invalidated track shouldn't be in active list");
4375 tracksToRemove->add(track);
4376 continue;
4377 }
4378
4379 if (track->mState == TrackBase::IDLE) {
4380 ALOGW("An idle track shouldn't be in active list");
4381 continue;
4382 }
4383
Eric Laurentbfb1b832013-01-07 09:53:42 -08004384 if (track->isPausing()) {
4385 track->setPaused();
4386 if (last) {
4387 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004388 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 mHwPaused = true;
4390 }
4391 // If we were part way through writing the mixbuffer to
4392 // the HAL we must save this until we resume
4393 // BUG - this will be wrong if a different track is made active,
4394 // in that case we want to discard the pending data in the
4395 // mixbuffer and tell the client to present it again when the
4396 // track is resumed
4397 mPausedWriteLength = mCurrentWriteLength;
4398 mPausedBytesRemaining = mBytesRemaining;
4399 mBytesRemaining = 0; // stop writing
4400 }
4401 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004402 } else if (track->isFlushPending()) {
4403 track->flushAck();
4404 if (last) {
4405 mFlushPending = true;
4406 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004407 } else if (track->isResumePending()){
4408 track->resumeAck();
4409 if (last) {
4410 if (mPausedBytesRemaining) {
4411 // Need to continue write that was interrupted
4412 mCurrentWriteLength = mPausedWriteLength;
4413 mBytesRemaining = mPausedBytesRemaining;
4414 mPausedBytesRemaining = 0;
4415 }
4416 if (mHwPaused) {
4417 doHwResume = true;
4418 mHwPaused = false;
4419 // threadLoop_mix() will handle the case that we need to
4420 // resume an interrupted write
4421 }
4422 // enable write to audio HAL
4423 sleepTime = 0;
4424
4425 // Do not handle new data in this iteration even if track->framesReady()
4426 mixerStatus = MIXER_TRACKS_ENABLED;
4427 }
4428 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004429 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004430 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004431 if (track->mFillingUpStatus == Track::FS_FILLED) {
4432 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004433 // make sure processVolume_l() will apply new volume even if 0
4434 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004435 }
4436
4437 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004438 sp<Track> previousTrack = mPreviousTrack.promote();
4439 if (previousTrack != 0) {
4440 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004441 // Flush any data still being written from last track
4442 mBytesRemaining = 0;
4443 if (mPausedBytesRemaining) {
4444 // Last track was paused so we also need to flush saved
4445 // mixbuffer state and invalidate track so that it will
4446 // re-submit that unwritten data when it is next resumed
4447 mPausedBytesRemaining = 0;
4448 // Invalidate is a bit drastic - would be more efficient
4449 // to have a flag to tell client that some of the
4450 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004451 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004452 }
4453 // flush data already sent to the DSP if changing audio session as audio
4454 // comes from a different source. Also invalidate previous track to force a
4455 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004456 if (previousTrack->sessionId() != track->sessionId()) {
4457 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004458 }
4459 }
4460 }
4461 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004462 // reset retry count
4463 track->mRetryCount = kMaxTrackRetriesOffload;
4464 mActiveTrack = t;
4465 mixerStatus = MIXER_TRACKS_READY;
4466 }
4467 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004468 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004469 if (track->isStopping_1()) {
4470 // Hardware buffer can hold a large amount of audio so we must
4471 // wait for all current track's data to drain before we say
4472 // that the track is stopped.
4473 if (mBytesRemaining == 0) {
4474 // Only start draining when all data in mixbuffer
4475 // has been written
4476 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4477 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004478 // do not drain if no data was ever sent to HAL (mStandby == true)
4479 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004480 // do not modify drain sequence if we are already draining. This happens
4481 // when resuming from pause after drain.
4482 if ((mDrainSequence & 1) == 0) {
4483 sleepTime = 0;
4484 standbyTime = systemTime() + standbyDelay;
4485 mixerStatus = MIXER_DRAIN_TRACK;
4486 mDrainSequence += 2;
4487 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488 if (mHwPaused) {
4489 // It is possible to move from PAUSED to STOPPING_1 without
4490 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004491 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492 mHwPaused = false;
4493 }
4494 }
4495 }
4496 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004497 // Drain has completed or we are in standby, signal presentation complete
4498 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499 track->mState = TrackBase::STOPPED;
4500 size_t audioHALFrames =
4501 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4502 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004503 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004504 track->presentationComplete(framesWritten, audioHALFrames);
4505 track->reset();
4506 tracksToRemove->add(track);
4507 }
4508 } else {
4509 // No buffers for this track. Give it a few chances to
4510 // fill a buffer, then remove it from active list.
4511 if (--(track->mRetryCount) <= 0) {
4512 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4513 track->name());
4514 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004515 // indicate to client process that the track was disabled because of underrun;
4516 // it will then automatically call start() when data is available
4517 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518 } else if (last){
4519 mixerStatus = MIXER_TRACKS_ENABLED;
4520 }
4521 }
4522 }
4523 // compute volume for this track
4524 processVolume_l(track, last);
4525 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004526
Eric Laurentea0fade2013-10-04 16:23:48 -07004527 // make sure the pause/flush/resume sequence is executed in the right order.
4528 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4529 // before flush and then resume HW. This can happen in case of pause/flush/resume
4530 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004531 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004532 mOutput->stream->pause(mOutput->stream);
4533 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004534 if (mFlushPending) {
4535 flushHw_l();
4536 mFlushPending = false;
4537 }
Eric Laurentfd477972013-10-25 18:10:40 -07004538 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004539 mOutput->stream->resume(mOutput->stream);
4540 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004541
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 // remove all the tracks that need to be...
4543 removeTracks_l(*tracksToRemove);
4544
4545 return mixerStatus;
4546}
4547
Eric Laurentbfb1b832013-01-07 09:53:42 -08004548// must be called with thread mutex locked
4549bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4550{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004551 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4552 mWriteAckSequence, mDrainSequence);
4553 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004554 return true;
4555 }
4556 return false;
4557}
4558
4559// must be called with thread mutex locked
4560bool AudioFlinger::OffloadThread::shouldStandby_l()
4561{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004562 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004563
4564 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4565 // after a timeout and we will enter standby then.
4566 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004567 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004568 }
4569
Glenn Kastene6f35b12013-08-19 09:58:50 -07004570 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004571}
4572
4573
4574bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4575{
4576 Mutex::Autolock _l(mLock);
4577 return waitingAsyncCallback_l();
4578}
4579
4580void AudioFlinger::OffloadThread::flushHw_l()
4581{
4582 mOutput->stream->flush(mOutput->stream);
4583 // Flush anything still waiting in the mixbuffer
4584 mCurrentWriteLength = 0;
4585 mBytesRemaining = 0;
4586 mPausedWriteLength = 0;
4587 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004588 mHwPaused = false;
4589
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004591 // discard any pending drain or write ack by incrementing sequence
4592 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4593 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004594 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004595 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4596 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004597 }
4598}
4599
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004600void AudioFlinger::OffloadThread::onAddNewTrack_l()
4601{
4602 sp<Track> previousTrack = mPreviousTrack.promote();
4603 sp<Track> latestTrack = mLatestActiveTrack.promote();
4604
4605 if (previousTrack != 0 && latestTrack != 0 &&
4606 (previousTrack->sessionId() != latestTrack->sessionId())) {
4607 mFlushPending = true;
4608 }
4609 PlaybackThread::onAddNewTrack_l();
4610}
4611
Eric Laurentbfb1b832013-01-07 09:53:42 -08004612// ----------------------------------------------------------------------------
4613
Eric Laurent81784c32012-11-19 14:55:58 -08004614AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4615 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4616 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4617 DUPLICATING),
4618 mWaitTimeMs(UINT_MAX)
4619{
4620 addOutputTrack(mainThread);
4621}
4622
4623AudioFlinger::DuplicatingThread::~DuplicatingThread()
4624{
4625 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4626 mOutputTracks[i]->destroy();
4627 }
4628}
4629
4630void AudioFlinger::DuplicatingThread::threadLoop_mix()
4631{
4632 // mix buffers...
4633 if (outputsReady(outputTracks)) {
4634 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4635 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004636 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004637 }
4638 sleepTime = 0;
4639 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004640 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004641 standbyTime = systemTime() + standbyDelay;
4642}
4643
4644void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4645{
4646 if (sleepTime == 0) {
4647 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4648 sleepTime = activeSleepTime;
4649 } else {
4650 sleepTime = idleSleepTime;
4651 }
4652 } else if (mBytesWritten != 0) {
4653 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4654 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004655 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004656 } else {
4657 // flush remaining overflow buffers in output tracks
4658 writeFrames = 0;
4659 }
4660 sleepTime = 0;
4661 }
4662}
4663
Eric Laurentbfb1b832013-01-07 09:53:42 -08004664ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004665{
4666 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004667 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4668 // for delivery downstream as needed. This in-place conversion is safe as
4669 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4670 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4671 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4672 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4673 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4674 }
4675 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004676 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004677 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004678 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004679}
4680
4681void AudioFlinger::DuplicatingThread::threadLoop_standby()
4682{
4683 // DuplicatingThread implements standby by stopping all tracks
4684 for (size_t i = 0; i < outputTracks.size(); i++) {
4685 outputTracks[i]->stop();
4686 }
4687}
4688
4689void AudioFlinger::DuplicatingThread::saveOutputTracks()
4690{
4691 outputTracks = mOutputTracks;
4692}
4693
4694void AudioFlinger::DuplicatingThread::clearOutputTracks()
4695{
4696 outputTracks.clear();
4697}
4698
4699void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4700{
4701 Mutex::Autolock _l(mLock);
4702 // FIXME explain this formula
4703 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004704 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4705 // due to current usage case and restrictions on the AudioBufferProvider.
4706 // Actual buffer conversion is done in threadLoop_write().
4707 //
4708 // TODO: This may change in the future, depending on multichannel
4709 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004710 OutputTrack *outputTrack = new OutputTrack(thread,
4711 this,
4712 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004713 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004714 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004715 frameCount,
4716 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004717 if (outputTrack->cblk() != NULL) {
4718 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4719 mOutputTracks.add(outputTrack);
4720 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4721 updateWaitTime_l();
4722 }
4723}
4724
4725void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4726{
4727 Mutex::Autolock _l(mLock);
4728 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4729 if (mOutputTracks[i]->thread() == thread) {
4730 mOutputTracks[i]->destroy();
4731 mOutputTracks.removeAt(i);
4732 updateWaitTime_l();
4733 return;
4734 }
4735 }
4736 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4737}
4738
4739// caller must hold mLock
4740void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4741{
4742 mWaitTimeMs = UINT_MAX;
4743 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4744 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4745 if (strong != 0) {
4746 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4747 if (waitTimeMs < mWaitTimeMs) {
4748 mWaitTimeMs = waitTimeMs;
4749 }
4750 }
4751 }
4752}
4753
4754
4755bool AudioFlinger::DuplicatingThread::outputsReady(
4756 const SortedVector< sp<OutputTrack> > &outputTracks)
4757{
4758 for (size_t i = 0; i < outputTracks.size(); i++) {
4759 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4760 if (thread == 0) {
4761 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4762 outputTracks[i].get());
4763 return false;
4764 }
4765 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4766 // see note at standby() declaration
4767 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4768 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4769 thread.get());
4770 return false;
4771 }
4772 }
4773 return true;
4774}
4775
4776uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4777{
4778 return (mWaitTimeMs * 1000) / 2;
4779}
4780
4781void AudioFlinger::DuplicatingThread::cacheParameters_l()
4782{
4783 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4784 updateWaitTime_l();
4785
4786 MixerThread::cacheParameters_l();
4787}
4788
4789// ----------------------------------------------------------------------------
4790// Record
4791// ----------------------------------------------------------------------------
4792
4793AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4794 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004795 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004796 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004797 audio_devices_t inDevice
4798#ifdef TEE_SINK
4799 , const sp<NBAIO_Sink>& teeSink
4800#endif
4801 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004802 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004803 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004804 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004805 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004806#ifdef TEE_SINK
4807 , mTeeSink(teeSink)
4808#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004809 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4810 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004811 // mFastCapture below
4812 , mFastCaptureFutex(0)
4813 // mInputSource
4814 // mPipeSink
4815 // mPipeSource
4816 , mPipeFramesP2(0)
4817 // mPipeMemory
4818 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004819 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004820{
4821 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004822 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004823
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004824 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004825
4826 // create an NBAIO source for the HAL input stream, and negotiate
4827 mInputSource = new AudioStreamInSource(input->stream);
4828 size_t numCounterOffers = 0;
4829 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4830 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4831 ALOG_ASSERT(index == 0);
4832
4833 // initialize fast capture depending on configuration
4834 bool initFastCapture;
4835 switch (kUseFastCapture) {
4836 case FastCapture_Never:
4837 initFastCapture = false;
4838 break;
4839 case FastCapture_Always:
4840 initFastCapture = true;
4841 break;
4842 case FastCapture_Static:
4843 uint32_t primaryOutputSampleRate;
4844 {
4845 AutoMutex _l(audioFlinger->mHardwareLock);
4846 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4847 }
4848 initFastCapture =
4849 // either capture sample rate is same as (a reasonable) primary output sample rate
4850 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4851 (mSampleRate == primaryOutputSampleRate)) ||
4852 // or primary output sample rate is unknown, and capture sample rate is reasonable
4853 ((primaryOutputSampleRate == 0) &&
4854 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
4855 // and the buffer size is < 10 ms
4856 (mFrameCount * 1000) / mSampleRate < 10;
4857 break;
4858 // case FastCapture_Dynamic:
4859 }
4860
4861 if (initFastCapture) {
4862 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4863 NBAIO_Format format = mInputSource->format();
4864 size_t pipeFramesP2 = roundup(mFrameCount * 8);
4865 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4866 void *pipeBuffer;
4867 const sp<MemoryDealer> roHeap(readOnlyHeap());
4868 sp<IMemory> pipeMemory;
4869 if ((roHeap == 0) ||
4870 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4871 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4872 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4873 goto failed;
4874 }
4875 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4876 memset(pipeBuffer, 0, pipeSize);
4877 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4878 const NBAIO_Format offers[1] = {format};
4879 size_t numCounterOffers = 0;
4880 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4881 ALOG_ASSERT(index == 0);
4882 mPipeSink = pipe;
4883 PipeReader *pipeReader = new PipeReader(*pipe);
4884 numCounterOffers = 0;
4885 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4886 ALOG_ASSERT(index == 0);
4887 mPipeSource = pipeReader;
4888 mPipeFramesP2 = pipeFramesP2;
4889 mPipeMemory = pipeMemory;
4890
4891 // create fast capture
4892 mFastCapture = new FastCapture();
4893 FastCaptureStateQueue *sq = mFastCapture->sq();
4894#ifdef STATE_QUEUE_DUMP
4895 // FIXME
4896#endif
4897 FastCaptureState *state = sq->begin();
4898 state->mCblk = NULL;
4899 state->mInputSource = mInputSource.get();
4900 state->mInputSourceGen++;
4901 state->mPipeSink = pipe;
4902 state->mPipeSinkGen++;
4903 state->mFrameCount = mFrameCount;
4904 state->mCommand = FastCaptureState::COLD_IDLE;
4905 // already done in constructor initialization list
4906 //mFastCaptureFutex = 0;
4907 state->mColdFutexAddr = &mFastCaptureFutex;
4908 state->mColdGen++;
4909 state->mDumpState = &mFastCaptureDumpState;
4910#ifdef TEE_SINK
4911 // FIXME
4912#endif
4913 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4914 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4915 sq->end();
4916 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4917
4918 // start the fast capture
4919 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4920 pid_t tid = mFastCapture->getTid();
4921 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4922 if (err != 0) {
4923 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4924 kPriorityFastCapture, getpid_cached, tid, err);
4925 }
4926
4927#ifdef AUDIO_WATCHDOG
4928 // FIXME
4929#endif
4930
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004931 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004932 }
4933failed: ;
4934
4935 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004936}
4937
4938
4939AudioFlinger::RecordThread::~RecordThread()
4940{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004941 if (mFastCapture != 0) {
4942 FastCaptureStateQueue *sq = mFastCapture->sq();
4943 FastCaptureState *state = sq->begin();
4944 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4945 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4946 if (old == -1) {
4947 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4948 }
4949 }
4950 state->mCommand = FastCaptureState::EXIT;
4951 sq->end();
4952 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4953 mFastCapture->join();
4954 mFastCapture.clear();
4955 }
4956 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004957 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004958 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004959}
4960
4961void AudioFlinger::RecordThread::onFirstRef()
4962{
4963 run(mName, PRIORITY_URGENT_AUDIO);
4964}
4965
Eric Laurent81784c32012-11-19 14:55:58 -08004966bool AudioFlinger::RecordThread::threadLoop()
4967{
Eric Laurent81784c32012-11-19 14:55:58 -08004968 nsecs_t lastWarning = 0;
4969
4970 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004971
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004972reacquire_wakelock:
4973 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004974 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004975 {
4976 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004977 size_t size = mActiveTracks.size();
4978 activeTracksGen = mActiveTracksGen;
4979 if (size > 0) {
4980 // FIXME an arbitrary choice
4981 activeTrack = mActiveTracks[0];
4982 acquireWakeLock_l(activeTrack->uid());
4983 if (size > 1) {
4984 SortedVector<int> tmp;
4985 for (size_t i = 0; i < size; i++) {
4986 tmp.add(mActiveTracks[i]->uid());
4987 }
4988 updateWakeLockUids_l(tmp);
4989 }
4990 } else {
4991 acquireWakeLock_l(-1);
4992 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004993 }
4994
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004995 // used to request a deferred sleep, to be executed later while mutex is unlocked
4996 uint32_t sleepUs = 0;
4997
4998 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004999 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005000 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005001
Glenn Kasten5edadd42013-08-14 16:30:49 -07005002 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005003 if (sleepUs > 0) {
5004 usleep(sleepUs);
5005 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005006 }
5007
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005008 // activeTracks accumulates a copy of a subset of mActiveTracks
5009 Vector< sp<RecordTrack> > activeTracks;
5010
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005011 // reference to the (first and only) fast track
5012 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005013
Eric Laurent81784c32012-11-19 14:55:58 -08005014 { // scope for mLock
5015 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005016
Eric Laurent021cf962014-05-13 10:18:14 -07005017 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005018
Eric Laurent000a4192014-01-29 15:17:32 -08005019 // check exitPending here because checkForNewParameters_l() and
5020 // checkForNewParameters_l() can temporarily release mLock
5021 if (exitPending()) {
5022 break;
5023 }
5024
Glenn Kasten2b806402013-11-20 16:37:38 -08005025 // if no active track(s), then standby and release wakelock
5026 size_t size = mActiveTracks.size();
5027 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005028 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005029 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005030 releaseWakeLock_l();
5031 ALOGV("RecordThread: loop stopping");
5032 // go to sleep
5033 mWaitWorkCV.wait(mLock);
5034 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005035 goto reacquire_wakelock;
5036 }
5037
Glenn Kasten2b806402013-11-20 16:37:38 -08005038 if (mActiveTracksGen != activeTracksGen) {
5039 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005040 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005041 for (size_t i = 0; i < size; i++) {
5042 tmp.add(mActiveTracks[i]->uid());
5043 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005044 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005045 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005046
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005047 bool doBroadcast = false;
5048 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005049
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005050 activeTrack = mActiveTracks[i];
5051 if (activeTrack->isTerminated()) {
5052 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005053 mActiveTracks.remove(activeTrack);
5054 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005055 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005056 continue;
5057 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005058
5059 TrackBase::track_state activeTrackState = activeTrack->mState;
5060 switch (activeTrackState) {
5061
5062 case TrackBase::PAUSING:
5063 mActiveTracks.remove(activeTrack);
5064 mActiveTracksGen++;
5065 doBroadcast = true;
5066 size--;
5067 continue;
5068
5069 case TrackBase::STARTING_1:
5070 sleepUs = 10000;
5071 i++;
5072 continue;
5073
5074 case TrackBase::STARTING_2:
5075 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005076 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005077 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005078 break;
5079
5080 case TrackBase::ACTIVE:
5081 break;
5082
5083 case TrackBase::IDLE:
5084 i++;
5085 continue;
5086
5087 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005088 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005089 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005090
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005091 activeTracks.add(activeTrack);
5092 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005093
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005094 if (activeTrack->isFastTrack()) {
5095 ALOG_ASSERT(!mFastTrackAvail);
5096 ALOG_ASSERT(fastTrack == 0);
5097 fastTrack = activeTrack;
5098 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005099 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005100 if (doBroadcast) {
5101 mStartStopCond.broadcast();
5102 }
5103
5104 // sleep if there are no active tracks to process
5105 if (activeTracks.size() == 0) {
5106 if (sleepUs == 0) {
5107 sleepUs = kRecordThreadSleepUs;
5108 }
5109 continue;
5110 }
5111 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005112
Eric Laurent81784c32012-11-19 14:55:58 -08005113 lockEffectChains_l(effectChains);
5114 }
5115
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005116 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005117
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005118 size_t size = effectChains.size();
5119 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005120 // thread mutex is not locked, but effect chain is locked
5121 effectChains[i]->process_l();
5122 }
5123
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005124 // Start the fast capture if it's not already running
5125 if (mFastCapture != 0) {
5126 FastCaptureStateQueue *sq = mFastCapture->sq();
5127 FastCaptureState *state = sq->begin();
5128 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5129 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5130 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5131 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5132 if (old == -1) {
5133 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5134 }
5135 }
5136 state->mCommand = FastCaptureState::READ_WRITE;
5137#if 0 // FIXME
5138 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5139 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5140#endif
5141 state->mCblk = fastTrack != 0 ? fastTrack->cblk() : NULL;
5142 sq->end();
5143 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5144#if 0
5145 if (kUseFastCapture == FastCapture_Dynamic) {
5146 mNormalSource = mPipeSource;
5147 }
5148#endif
5149 } else {
5150 sq->end(false /*didModify*/);
5151 }
5152 }
5153
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005154 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5155 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5156 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5157 // If destination is non-contiguous, first read past the nominal end of buffer, then
5158 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005159
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005160 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005161 ssize_t framesRead;
5162
5163 // If an NBAIO source is present, use it to read the normal capture's data
5164 if (mPipeSource != 0) {
5165 size_t framesToRead = mBufferSize / mFrameSize;
5166 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5167 framesToRead, AudioBufferProvider::kInvalidPTS);
5168 if (framesRead == 0) {
5169 // since pipe is non-blocking, simulate blocking input
5170 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5171 }
5172 // otherwise use the HAL / AudioStreamIn directly
5173 } else {
5174 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5175 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5176 if (bytesRead < 0) {
5177 framesRead = bytesRead;
5178 } else {
5179 framesRead = bytesRead / mFrameSize;
5180 }
5181 }
5182
5183 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5184 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005185 // Force input into standby so that it tries to recover at next read attempt
5186 inputStandBy();
5187 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005188 }
5189 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005190 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005191 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005192 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005193
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005194 if (mTeeSink != 0) {
5195 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5196 }
5197 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005198 {
5199 size_t part1 = mRsmpInFramesP2 - rear;
5200 if ((size_t) framesRead > part1) {
5201 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5202 (framesRead - part1) * mFrameSize);
5203 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005204 }
5205 rear = mRsmpInRear += framesRead;
5206
5207 size = activeTracks.size();
5208 // loop over each active track
5209 for (size_t i = 0; i < size; i++) {
5210 activeTrack = activeTracks[i];
5211
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005212 // skip fast tracks, as those are handled directly by FastCapture
5213 if (activeTrack->isFastTrack()) {
5214 continue;
5215 }
5216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005217 enum {
5218 OVERRUN_UNKNOWN,
5219 OVERRUN_TRUE,
5220 OVERRUN_FALSE
5221 } overrun = OVERRUN_UNKNOWN;
5222
5223 // loop over getNextBuffer to handle circular sink
5224 for (;;) {
5225
5226 activeTrack->mSink.frameCount = ~0;
5227 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5228 size_t framesOut = activeTrack->mSink.frameCount;
5229 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5230
5231 int32_t front = activeTrack->mRsmpInFront;
5232 ssize_t filled = rear - front;
5233 size_t framesIn;
5234
5235 if (filled < 0) {
5236 // should not happen, but treat like a massive overrun and re-sync
5237 framesIn = 0;
5238 activeTrack->mRsmpInFront = rear;
5239 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005240 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 framesIn = (size_t) filled;
5242 } else {
5243 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005244 framesIn = mRsmpInFrames;
5245 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005246 overrun = OVERRUN_TRUE;
5247 }
5248
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005249 if (framesOut == 0 || framesIn == 0) {
5250 break;
5251 }
5252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005253 if (activeTrack->mResampler == NULL) {
5254 // no resampling
5255 if (framesIn > framesOut) {
5256 framesIn = framesOut;
5257 } else {
5258 framesOut = framesIn;
5259 }
5260 int8_t *dst = activeTrack->mSink.i8;
5261 while (framesIn > 0) {
5262 front &= mRsmpInFramesP2 - 1;
5263 size_t part1 = mRsmpInFramesP2 - front;
5264 if (part1 > framesIn) {
5265 part1 = framesIn;
5266 }
5267 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005268 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 memcpy(dst, src, part1 * mFrameSize);
5270 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005271 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005272 part1);
5273 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005274 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005275 part1);
5276 }
5277 dst += part1 * activeTrack->mFrameSize;
5278 front += part1;
5279 framesIn -= part1;
5280 }
5281 activeTrack->mRsmpInFront += framesOut;
5282
5283 } else {
5284 // resampling
5285 // FIXME framesInNeeded should really be part of resampler API, and should
5286 // depend on the SRC ratio
5287 // to keep mRsmpInBuffer full so resampler always has sufficient input
5288 size_t framesInNeeded;
5289 // FIXME only re-calculate when it changes, and optimize for common ratios
5290 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
5291 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005292 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005293 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
5294 framesInNeeded, framesOut, inOverOut);
5295 // Although we theoretically have framesIn in circular buffer, some of those are
5296 // unreleased frames, and thus must be discounted for purpose of budgeting.
5297 size_t unreleased = activeTrack->mRsmpInUnrel;
5298 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005299 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005300 ALOGV("not enough to resample: have %u frames in but need %u in to "
5301 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005302 framesIn, framesInNeeded, framesOut, inOverOut);
5303 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005304 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5305 if (newFramesOut == 0) {
5306 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005307 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005308 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5309 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5310 framesInNeeded, newFramesOut, outOverIn);
5311 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5312 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5313 "given in/out ratio of %.4g",
5314 framesIn, framesInNeeded, newFramesOut, inOverOut);
5315 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005316 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005317 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005318 "given in/out ratio of %.4g",
5319 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005320 }
5321
5322 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5323 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005324 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005325 delete[] activeTrack->mRsmpOutBuffer;
5326 // resampler always outputs stereo
5327 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5328 activeTrack->mRsmpOutFrameCount = framesOut;
5329 }
5330
5331 // resampler accumulates, but we only have one source track
5332 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5333 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005334 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005335 activeTrack->mResamplerBufferProvider
5336 /*this*/ /* AudioBufferProvider* */);
5337 // ditherAndClamp() works as long as all buffers returned by
5338 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005339 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005340 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005341 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5342 framesOut);
5343 // the resampler always outputs stereo samples:
5344 // do post stereo to mono conversion
5345 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005346 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005347 } else {
5348 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5349 activeTrack->mRsmpOutBuffer, framesOut);
5350 }
5351 // now done with mRsmpOutBuffer
5352
5353 }
5354
5355 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5356 overrun = OVERRUN_FALSE;
5357 }
5358
5359 if (activeTrack->mFramesToDrop == 0) {
5360 if (framesOut > 0) {
5361 activeTrack->mSink.frameCount = framesOut;
5362 activeTrack->releaseBuffer(&activeTrack->mSink);
5363 }
5364 } else {
5365 // FIXME could do a partial drop of framesOut
5366 if (activeTrack->mFramesToDrop > 0) {
5367 activeTrack->mFramesToDrop -= framesOut;
5368 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005369 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005370 }
5371 } else {
5372 activeTrack->mFramesToDrop += framesOut;
5373 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5374 activeTrack->mSyncStartEvent->isCancelled()) {
5375 ALOGW("Synced record %s, session %d, trigger session %d",
5376 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5377 activeTrack->sessionId(),
5378 (activeTrack->mSyncStartEvent != 0) ?
5379 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005380 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005381 }
5382 }
5383 }
5384
5385 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005386 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005387 }
5388 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005389
5390 switch (overrun) {
5391 case OVERRUN_TRUE:
5392 // client isn't retrieving buffers fast enough
5393 if (!activeTrack->setOverflow()) {
5394 nsecs_t now = systemTime();
5395 // FIXME should lastWarning per track?
5396 if ((now - lastWarning) > kWarningThrottleNs) {
5397 ALOGW("RecordThread: buffer overflow");
5398 lastWarning = now;
5399 }
5400 }
5401 break;
5402 case OVERRUN_FALSE:
5403 activeTrack->clearOverflow();
5404 break;
5405 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005406 break;
5407 }
5408
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005409 }
5410
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005411unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005412 // enable changes in effect chain
5413 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005414 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005415 }
5416
Glenn Kasten93e471f2013-08-19 08:40:07 -07005417 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005418
5419 {
5420 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005421 for (size_t i = 0; i < mTracks.size(); i++) {
5422 sp<RecordTrack> track = mTracks[i];
5423 track->invalidate();
5424 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005425 mActiveTracks.clear();
5426 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005427 mStartStopCond.broadcast();
5428 }
5429
5430 releaseWakeLock();
5431
5432 ALOGV("RecordThread %p exiting", this);
5433 return false;
5434}
5435
Glenn Kasten93e471f2013-08-19 08:40:07 -07005436void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005437{
5438 if (!mStandby) {
5439 inputStandBy();
5440 mStandby = true;
5441 }
5442}
5443
5444void AudioFlinger::RecordThread::inputStandBy()
5445{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005446 // Idle the fast capture if it's currently running
5447 if (mFastCapture != 0) {
5448 FastCaptureStateQueue *sq = mFastCapture->sq();
5449 FastCaptureState *state = sq->begin();
5450 if (!(state->mCommand & FastCaptureState::IDLE)) {
5451 state->mCommand = FastCaptureState::COLD_IDLE;
5452 state->mColdFutexAddr = &mFastCaptureFutex;
5453 state->mColdGen++;
5454 mFastCaptureFutex = 0;
5455 sq->end();
5456 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5457 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5458#if 0
5459 if (kUseFastCapture == FastCapture_Dynamic) {
5460 // FIXME
5461 }
5462#endif
5463#ifdef AUDIO_WATCHDOG
5464 // FIXME
5465#endif
5466 } else {
5467 sq->end(false /*didModify*/);
5468 }
5469 }
Eric Laurent81784c32012-11-19 14:55:58 -08005470 mInput->stream->common.standby(&mInput->stream->common);
5471}
5472
Glenn Kasten05997e22014-03-13 15:08:33 -07005473// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005474sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005475 const sp<AudioFlinger::Client>& client,
5476 uint32_t sampleRate,
5477 audio_format_t format,
5478 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005479 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005480 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005481 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005482 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005483 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005484 pid_t tid,
5485 status_t *status)
5486{
Glenn Kasten74935e42013-12-19 08:56:45 -08005487 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005488 sp<RecordTrack> track;
5489 status_t lStatus;
5490
Glenn Kasten90e58b12013-07-31 16:16:02 -07005491 // client expresses a preference for FAST, but we get the final say
5492 if (*flags & IAudioFlinger::TRACK_FAST) {
5493 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005494 // use case: callback handler
5495 (tid != -1) &&
5496 // frame count is not specified, or is exactly the pipe depth
5497 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005498 // PCM data
5499 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005500 // native format
5501 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005502 // native channel mask
5503 (channelMask == mChannelMask) &&
5504 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005505 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005506 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005507 hasFastCapture() &&
5508 // there are sufficient fast track slots available
5509 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005510 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005511 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005512 frameCount, mFrameCount);
5513 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005514 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5515 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005516 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005517 frameCount, mFrameCount, mPipeFramesP2,
5518 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5519 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005520 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005521 }
5522 }
5523
5524 // compute track buffer size in frames, and suggest the notification frame count
5525 if (*flags & IAudioFlinger::TRACK_FAST) {
5526 // fast track: frame count is exactly the pipe depth
5527 frameCount = mPipeFramesP2;
5528 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5529 *notificationFrames = mFrameCount;
5530 } else {
5531 // not fast track: frame count is at least 2 HAL buffers and at least 20 ms
5532 size_t minFrameCount = ((int64_t) mFrameCount * 2 * sampleRate + mSampleRate - 1) /
5533 mSampleRate;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005534 if (frameCount < minFrameCount) {
5535 frameCount = minFrameCount;
5536 }
Glenn Kasten74105912014-07-03 12:28:53 -07005537 minFrameCount = (sampleRate * 20 / 1000 + 1) & ~1;
5538 if (frameCount < minFrameCount) {
5539 frameCount = minFrameCount;
5540 }
5541 // notification is forced to be at least double-buffering
5542 size_t maxNotification = frameCount / 2;
5543 if (*notificationFrames == 0 || *notificationFrames > maxNotification) {
5544 *notificationFrames = maxNotification;
5545 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005546 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005547 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005548
Glenn Kasten15e57982013-09-24 11:52:37 -07005549 lStatus = initCheck();
5550 if (lStatus != NO_ERROR) {
5551 ALOGE("createRecordTrack_l() audio driver not initialized");
5552 goto Exit;
5553 }
Eric Laurent81784c32012-11-19 14:55:58 -08005554
5555 { // scope for mLock
5556 Mutex::Autolock _l(mLock);
5557
5558 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005559 format, channelMask, frameCount, NULL, sessionId, uid,
5560 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005561
Glenn Kasten03003332013-08-06 15:40:54 -07005562 lStatus = track->initCheck();
5563 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005564 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005565 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005566 goto Exit;
5567 }
5568 mTracks.add(track);
5569
5570 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5571 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5572 mAudioFlinger->btNrecIsOff();
5573 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5574 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005575
5576 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5577 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5578 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5579 // so ask activity manager to do this on our behalf
5580 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5581 }
Eric Laurent81784c32012-11-19 14:55:58 -08005582 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005583
Eric Laurent81784c32012-11-19 14:55:58 -08005584 lStatus = NO_ERROR;
5585
5586Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005587 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 return track;
5589}
5590
5591status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5592 AudioSystem::sync_event_t event,
5593 int triggerSession)
5594{
5595 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5596 sp<ThreadBase> strongMe = this;
5597 status_t status = NO_ERROR;
5598
5599 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005600 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005601 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005602 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005603 triggerSession,
5604 recordTrack->sessionId(),
5605 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005606 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005607 // Sync event can be cancelled by the trigger session if the track is not in a
5608 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005609 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005610 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005611 } else {
5612 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005613 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005614 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005615 }
5616 }
5617
5618 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005619 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005620 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005621 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5622 if (recordTrack->mState == TrackBase::PAUSING) {
5623 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005624 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005625 } else {
5626 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005627 }
5628 return status;
5629 }
5630
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005631 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5632 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5633 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005635 mActiveTracks.add(recordTrack);
5636 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005637 status_t status = NO_ERROR;
5638 if (recordTrack->isExternalTrack()) {
5639 mLock.unlock();
5640 status = AudioSystem::startInput(mId);
5641 mLock.lock();
5642 // FIXME should verify that recordTrack is still in mActiveTracks
5643 if (status != NO_ERROR) {
5644 mActiveTracks.remove(recordTrack);
5645 mActiveTracksGen++;
5646 recordTrack->clearSyncStartEvent();
5647 ALOGV("RecordThread::start error %d", status);
5648 return status;
5649 }
Eric Laurent81784c32012-11-19 14:55:58 -08005650 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005651 // Catch up with current buffer indices if thread is already running.
5652 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5653 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5654 // see previously buffered data before it called start(), but with greater risk of overrun.
5655
5656 recordTrack->mRsmpInFront = mRsmpInRear;
5657 recordTrack->mRsmpInUnrel = 0;
5658 // FIXME why reset?
5659 if (recordTrack->mResampler != NULL) {
5660 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005662 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005663 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005664 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005665 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005666 ALOGV("Record failed to start");
5667 status = BAD_VALUE;
5668 goto startError;
5669 }
Eric Laurent81784c32012-11-19 14:55:58 -08005670 return status;
5671 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005672
Eric Laurent81784c32012-11-19 14:55:58 -08005673startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005674 if (recordTrack->isExternalTrack()) {
5675 AudioSystem::stopInput(mId);
5676 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005677 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005679 return status;
5680}
5681
Eric Laurent81784c32012-11-19 14:55:58 -08005682void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5683{
5684 sp<SyncEvent> strongEvent = event.promote();
5685
5686 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005687 sp<RefBase> ptr = strongEvent->cookie().promote();
5688 if (ptr != 0) {
5689 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5690 recordTrack->handleSyncStartEvent(strongEvent);
5691 }
Eric Laurent81784c32012-11-19 14:55:58 -08005692 }
5693}
5694
Glenn Kastena8356f62013-07-25 14:37:52 -07005695bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005696 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005697 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005698 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005699 return false;
5700 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005701 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005702 recordTrack->mState = TrackBase::PAUSING;
5703 // do not wait for mStartStopCond if exiting
5704 if (exitPending()) {
5705 return true;
5706 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005707 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005708 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005709 // if we have been restarted, recordTrack is in mActiveTracks here
5710 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005711 ALOGV("Record stopped OK");
5712 return true;
5713 }
5714 return false;
5715}
5716
Glenn Kasten0f11b512014-01-31 16:18:54 -08005717bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005718{
5719 return false;
5720}
5721
Glenn Kasten0f11b512014-01-31 16:18:54 -08005722status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005723{
5724#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5725 if (!isValidSyncEvent(event)) {
5726 return BAD_VALUE;
5727 }
5728
5729 int eventSession = event->triggerSession();
5730 status_t ret = NAME_NOT_FOUND;
5731
5732 Mutex::Autolock _l(mLock);
5733
5734 for (size_t i = 0; i < mTracks.size(); i++) {
5735 sp<RecordTrack> track = mTracks[i];
5736 if (eventSession == track->sessionId()) {
5737 (void) track->setSyncEvent(event);
5738 ret = NO_ERROR;
5739 }
5740 }
5741 return ret;
5742#else
5743 return BAD_VALUE;
5744#endif
5745}
5746
5747// destroyTrack_l() must be called with ThreadBase::mLock held
5748void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5749{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005750 track->terminate();
5751 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005752 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005753 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005754 removeTrack_l(track);
5755 }
5756}
5757
5758void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5759{
5760 mTracks.remove(track);
5761 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762 if (track->isFastTrack()) {
5763 ALOG_ASSERT(!mFastTrackAvail);
5764 mFastTrackAvail = true;
5765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766}
5767
5768void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5769{
5770 dumpInternals(fd, args);
5771 dumpTracks(fd, args);
5772 dumpEffectChains(fd, args);
5773}
5774
5775void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5776{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005777 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005778
Glenn Kasten2b806402013-11-20 16:37:38 -08005779 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005780 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005781 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005782 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005783 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005784 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005785 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005786
Eric Laurent81784c32012-11-19 14:55:58 -08005787 dumpBase(fd, args);
5788}
5789
Glenn Kasten0f11b512014-01-31 16:18:54 -08005790void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005791{
5792 const size_t SIZE = 256;
5793 char buffer[SIZE];
5794 String8 result;
5795
Marco Nelissenb2208842014-02-07 14:00:50 -08005796 size_t numtracks = mTracks.size();
5797 size_t numactive = mActiveTracks.size();
5798 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005799 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005800 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005801 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005802 RecordTrack::appendDumpHeader(result);
5803 for (size_t i = 0; i < numtracks ; ++i) {
5804 sp<RecordTrack> track = mTracks[i];
5805 if (track != 0) {
5806 bool active = mActiveTracks.indexOf(track) >= 0;
5807 if (active) {
5808 numactiveseen++;
5809 }
5810 track->dump(buffer, SIZE, active);
5811 result.append(buffer);
5812 }
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005814 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005815 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005816 }
5817
Marco Nelissenb2208842014-02-07 14:00:50 -08005818 if (numactiveseen != numactive) {
5819 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5820 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005821 result.append(buffer);
5822 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005823 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005824 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005825 if (mTracks.indexOf(track) < 0) {
5826 track->dump(buffer, SIZE, true);
5827 result.append(buffer);
5828 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005829 }
Eric Laurent81784c32012-11-19 14:55:58 -08005830
5831 }
5832 write(fd, result.string(), result.size());
5833}
5834
5835// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005836status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5837 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005838{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005839 RecordTrack *activeTrack = mRecordTrack;
5840 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5841 if (threadBase == 0) {
5842 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005843 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005844 return NOT_ENOUGH_DATA;
5845 }
5846 RecordThread *recordThread = (RecordThread *) threadBase.get();
5847 int32_t rear = recordThread->mRsmpInRear;
5848 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005849 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005850 // FIXME should not be P2 (don't want to increase latency)
5851 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005852 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005853 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005854 front &= recordThread->mRsmpInFramesP2 - 1;
5855 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005856 if (part1 > (size_t) filled) {
5857 part1 = filled;
5858 }
5859 size_t ask = buffer->frameCount;
5860 ALOG_ASSERT(ask > 0);
5861 if (part1 > ask) {
5862 part1 = ask;
5863 }
5864 if (part1 == 0) {
5865 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005866 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005867 buffer->raw = NULL;
5868 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005869 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005870 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005871 }
5872
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005873 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005874 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005875 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005876 return NO_ERROR;
5877}
5878
5879// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5881 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005882{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005883 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005884 size_t stepCount = buffer->frameCount;
5885 if (stepCount == 0) {
5886 return;
5887 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005888 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5889 activeTrack->mRsmpInUnrel -= stepCount;
5890 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005891 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005892 buffer->frameCount = 0;
5893}
5894
Eric Laurent10351942014-05-08 18:49:52 -07005895bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5896 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005897{
5898 bool reconfig = false;
5899
Eric Laurent10351942014-05-08 18:49:52 -07005900 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005901
Eric Laurent10351942014-05-08 18:49:52 -07005902 audio_format_t reqFormat = mFormat;
5903 uint32_t samplingRate = mSampleRate;
5904 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5905
5906 AudioParameter param = AudioParameter(keyValuePair);
5907 int value;
5908 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5909 // channel count change can be requested. Do we mandate the first client defines the
5910 // HAL sampling rate and channel count or do we allow changes on the fly?
5911 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5912 samplingRate = value;
5913 reconfig = true;
5914 }
5915 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5916 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5917 status = BAD_VALUE;
5918 } else {
5919 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005920 reconfig = true;
5921 }
Eric Laurent10351942014-05-08 18:49:52 -07005922 }
5923 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5924 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5925 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5926 status = BAD_VALUE;
5927 } else {
5928 channelMask = mask;
5929 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005930 }
Eric Laurent10351942014-05-08 18:49:52 -07005931 }
5932 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5933 // do not accept frame count changes if tracks are open as the track buffer
5934 // size depends on frame count and correct behavior would not be guaranteed
5935 // if frame count is changed after track creation
5936 if (mActiveTracks.size() > 0) {
5937 status = INVALID_OPERATION;
5938 } else {
5939 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 }
Eric Laurent10351942014-05-08 18:49:52 -07005941 }
5942 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5943 // forward device change to effects that have requested to be
5944 // aware of attached audio device.
5945 for (size_t i = 0; i < mEffectChains.size(); i++) {
5946 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005947 }
Eric Laurent81784c32012-11-19 14:55:58 -08005948
Eric Laurent10351942014-05-08 18:49:52 -07005949 // store input device and output device but do not forward output device to audio HAL.
5950 // Note that status is ignored by the caller for output device
5951 // (see AudioFlinger::setParameters()
5952 if (audio_is_output_devices(value)) {
5953 mOutDevice = value;
5954 status = BAD_VALUE;
5955 } else {
5956 mInDevice = value;
5957 // disable AEC and NS if the device is a BT SCO headset supporting those
5958 // pre processings
5959 if (mTracks.size() > 0) {
5960 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5961 mAudioFlinger->btNrecIsOff();
5962 for (size_t i = 0; i < mTracks.size(); i++) {
5963 sp<RecordTrack> track = mTracks[i];
5964 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5965 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005966 }
5967 }
5968 }
Eric Laurent10351942014-05-08 18:49:52 -07005969 }
5970 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5971 mAudioSource != (audio_source_t)value) {
5972 // forward device change to effects that have requested to be
5973 // aware of attached audio device.
5974 for (size_t i = 0; i < mEffectChains.size(); i++) {
5975 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005976 }
Eric Laurent10351942014-05-08 18:49:52 -07005977 mAudioSource = (audio_source_t)value;
5978 }
Glenn Kastene198c362013-08-13 09:13:36 -07005979
Eric Laurent10351942014-05-08 18:49:52 -07005980 if (status == NO_ERROR) {
5981 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5982 keyValuePair.string());
5983 if (status == INVALID_OPERATION) {
5984 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005985 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5986 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005987 }
5988 if (reconfig) {
5989 if (status == BAD_VALUE &&
5990 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5991 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5992 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5993 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005994 audio_channel_count_from_in_mask(
5995 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005996 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5997 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5998 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005999 }
Eric Laurent10351942014-05-08 18:49:52 -07006000 if (status == NO_ERROR) {
6001 readInputParameters_l();
6002 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006003 }
6004 }
Eric Laurent81784c32012-11-19 14:55:58 -08006005 }
Eric Laurent10351942014-05-08 18:49:52 -07006006
Eric Laurent81784c32012-11-19 14:55:58 -08006007 return reconfig;
6008}
6009
6010String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6011{
Eric Laurent81784c32012-11-19 14:55:58 -08006012 Mutex::Autolock _l(mLock);
6013 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006014 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006015 }
6016
Glenn Kastend8ea6992013-07-16 14:17:15 -07006017 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6018 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006019 free(s);
6020 return out_s8;
6021}
6022
Eric Laurent021cf962014-05-13 10:18:14 -07006023void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006024 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006025 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006026
6027 switch (event) {
6028 case AudioSystem::INPUT_OPENED:
6029 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006030 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006031 desc.samplingRate = mSampleRate;
6032 desc.format = mFormat;
6033 desc.frameCount = mFrameCount;
6034 desc.latency = 0;
6035 param2 = &desc;
6036 break;
6037
6038 case AudioSystem::INPUT_CLOSED:
6039 default:
6040 break;
6041 }
Eric Laurent021cf962014-05-13 10:18:14 -07006042 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006043}
6044
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006045void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006046{
Eric Laurent81784c32012-11-19 14:55:58 -08006047 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6048 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006049 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006050 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6051 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006052 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006053 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006054 }
Eric Laurent665470b2014-07-03 16:37:08 -07006055 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006056 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6057 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006058 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006059 // 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 -07006060 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006061 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 // A larger value should allow more old data to be read after a track calls start(),
6063 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006064 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006065 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07006067 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6068 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006069
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006070 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6071 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006072}
6073
Glenn Kasten5f972c02014-01-13 09:59:31 -08006074uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006075{
6076 Mutex::Autolock _l(mLock);
6077 if (initCheck() != NO_ERROR) {
6078 return 0;
6079 }
6080
6081 return mInput->stream->get_input_frames_lost(mInput->stream);
6082}
6083
6084uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6085{
6086 Mutex::Autolock _l(mLock);
6087 uint32_t result = 0;
6088 if (getEffectChain_l(sessionId) != 0) {
6089 result = EFFECT_SESSION;
6090 }
6091
6092 for (size_t i = 0; i < mTracks.size(); ++i) {
6093 if (sessionId == mTracks[i]->sessionId()) {
6094 result |= TRACK_SESSION;
6095 break;
6096 }
6097 }
6098
6099 return result;
6100}
6101
6102KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6103{
6104 KeyedVector<int, bool> ids;
6105 Mutex::Autolock _l(mLock);
6106 for (size_t j = 0; j < mTracks.size(); ++j) {
6107 sp<RecordThread::RecordTrack> track = mTracks[j];
6108 int sessionId = track->sessionId();
6109 if (ids.indexOfKey(sessionId) < 0) {
6110 ids.add(sessionId, true);
6111 }
6112 }
6113 return ids;
6114}
6115
6116AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6117{
6118 Mutex::Autolock _l(mLock);
6119 AudioStreamIn *input = mInput;
6120 mInput = NULL;
6121 return input;
6122}
6123
6124// this method must always be called either with ThreadBase mLock held or inside the thread loop
6125audio_stream_t* AudioFlinger::RecordThread::stream() const
6126{
6127 if (mInput == NULL) {
6128 return NULL;
6129 }
6130 return &mInput->stream->common;
6131}
6132
6133status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6134{
6135 // only one chain per input thread
6136 if (mEffectChains.size() != 0) {
6137 return INVALID_OPERATION;
6138 }
6139 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6140
6141 chain->setInBuffer(NULL);
6142 chain->setOutBuffer(NULL);
6143
6144 checkSuspendOnAddEffectChain_l(chain);
6145
6146 mEffectChains.add(chain);
6147
6148 return NO_ERROR;
6149}
6150
6151size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6152{
6153 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6154 ALOGW_IF(mEffectChains.size() != 1,
6155 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6156 chain.get(), mEffectChains.size(), this);
6157 if (mEffectChains.size() == 1) {
6158 mEffectChains.removeAt(0);
6159 }
6160 return 0;
6161}
6162
Eric Laurent1c333e22014-05-20 10:48:17 -07006163status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6164 audio_patch_handle_t *handle)
6165{
6166 status_t status = NO_ERROR;
6167 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6168 // store new device and send to effects
6169 mInDevice = patch->sources[0].ext.device.type;
6170 for (size_t i = 0; i < mEffectChains.size(); i++) {
6171 mEffectChains[i]->setDevice_l(mInDevice);
6172 }
6173
6174 // disable AEC and NS if the device is a BT SCO headset supporting those
6175 // pre processings
6176 if (mTracks.size() > 0) {
6177 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6178 mAudioFlinger->btNrecIsOff();
6179 for (size_t i = 0; i < mTracks.size(); i++) {
6180 sp<RecordTrack> track = mTracks[i];
6181 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6182 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6183 }
6184 }
6185
6186 // store new source and send to effects
6187 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6188 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6189 for (size_t i = 0; i < mEffectChains.size(); i++) {
6190 mEffectChains[i]->setAudioSource_l(mAudioSource);
6191 }
6192 }
6193
6194 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6195 status = hwDevice->create_audio_patch(hwDevice,
6196 patch->num_sources,
6197 patch->sources,
6198 patch->num_sinks,
6199 patch->sinks,
6200 handle);
6201 } else {
6202 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6203 }
6204 return status;
6205}
6206
6207status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6208{
6209 status_t status = NO_ERROR;
6210 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6211 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6212 status = hwDevice->release_audio_patch(hwDevice, handle);
6213 } else {
6214 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6215 }
6216 return status;
6217}
6218
Eric Laurent83b88082014-06-20 18:31:16 -07006219void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6220{
6221 Mutex::Autolock _l(mLock);
6222 mTracks.add(record);
6223}
6224
6225void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6226{
6227 Mutex::Autolock _l(mLock);
6228 destroyTrack_l(record);
6229}
6230
6231void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6232{
6233 ThreadBase::getAudioPortConfig(config);
6234 config->role = AUDIO_PORT_ROLE_SINK;
6235 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6236 config->ext.mix.usecase.source = mAudioSource;
6237}
Eric Laurent1c333e22014-05-20 10:48:17 -07006238
Eric Laurent81784c32012-11-19 14:55:58 -08006239}; // namespace android