blob: 193f8e4bdacef3135b6e67e0bd907491d72d8500 [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>
Andy Hungcd044842014-08-07 11:04:34 -070029#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070042#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043#include <media/nbaio/AudioStreamOutSink.h>
44#include <media/nbaio/MonoPipe.h>
45#include <media/nbaio/MonoPipeReader.h>
46#include <media/nbaio/Pipe.h>
47#include <media/nbaio/PipeReader.h>
48#include <media/nbaio/SourceAudioBufferProvider.h>
49
50#include <powermanager/PowerManager.h>
51
52#include <common_time/cc_helper.h>
53#include <common_time/local_clock.h>
54
55#include "AudioFlinger.h"
56#include "AudioMixer.h"
57#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "ServiceUtilities.h"
60#include "SchedulingPolicyService.h"
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef ADD_BATTERY_DATA
63#include <media/IMediaPlayerService.h>
64#include <media/IMediaDeathNotifier.h>
65#endif
66
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
71
72// ----------------------------------------------------------------------------
73
74// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
86
Glenn Kasten49d00ad2014-07-21 11:22:03 -070087#define max(a, b) ((a) > (b) ? (a) : (b))
88
Eric Laurent81784c32012-11-19 14:55:58 -080089namespace android {
90
91// retry counts for buffer fill timeout
92// 50 * ~20msecs = 1 second
93static const int8_t kMaxTrackRetries = 50;
94static const int8_t kMaxTrackStartupRetries = 50;
95// allow less retry attempts on direct output thread.
96// direct outputs can be a scarce resource in audio hardware and should
97// be released as quickly as possible.
98static const int8_t kMaxTrackRetriesDirect = 2;
99
100// don't warn about blocked writes or record buffer overflows more often than this
101static const nsecs_t kWarningThrottleNs = seconds(5);
102
103// RecordThread loop sleep time upon application overrun or audio HAL read error
104static const int kRecordThreadSleepUs = 5000;
105
Eric Laurent10351942014-05-08 18:49:52 -0700106// maximum time to wait in sendConfigEvent_l() for a status to be received
107static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109// minimum sleep time for the mixer thread loop when tracks are active but in underrun
110static const uint32_t kMinThreadSleepTimeUs = 5000;
111// maximum divider applied to the active sleep time in the mixer thread loop
112static const uint32_t kMaxThreadSleepTimeShift = 2;
113
Andy Hung09a50072014-02-27 14:30:47 -0800114// minimum normal sink buffer size, expressed in milliseconds rather than frames
115static const uint32_t kMinNormalSinkBufferSizeMs = 20;
116// maximum normal sink buffer size
117static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800118
Eric Laurent972a1732013-09-04 09:42:59 -0700119// Offloaded output thread standby delay: allows track transition without going to standby
120static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122// Whether to use fast mixer
123static const enum {
124 FastMixer_Never, // never initialize or use: for debugging only
125 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
126 // normal mixer multiplier is 1
127 FastMixer_Static, // initialize if needed, then use all the time if initialized,
128 // multiplier is calculated based on min & max normal mixer buffer size
129 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 // FIXME for FastMixer_Dynamic:
132 // Supporting this option will require fixing HALs that can't handle large writes.
133 // For example, one HAL implementation returns an error from a large write,
134 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
135 // We could either fix the HAL implementations, or provide a wrapper that breaks
136 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
137} kUseFastMixer = FastMixer_Static;
138
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139// Whether to use fast capture
140static const enum {
141 FastCapture_Never, // never initialize or use: for debugging only
142 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
143 FastCapture_Static, // initialize if needed, then use all the time if initialized
144} kUseFastCapture = FastCapture_Static;
145
Eric Laurent81784c32012-11-19 14:55:58 -0800146// Priorities for requestPriority
147static const int kPriorityAudioApp = 2;
148static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700149static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
152// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800153// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
154// So for now we just assume that client is double-buffered for fast tracks.
155// FIXME It would be better for client to tell AudioFlinger the value of N,
156// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800157// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700158
159// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800160static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
Glenn Kasten03490092014-05-27 12:30:54 -0700162// The minimum and maximum allowed values
163static const int kFastTrackMultiplierMin = 1;
164static const int kFastTrackMultiplierMax = 2;
165
166// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
167static int sFastTrackMultiplier = kFastTrackMultiplier;
168
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700169// See Thread::readOnlyHeap().
170// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
171// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
172// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700173static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700174
Eric Laurent81784c32012-11-19 14:55:58 -0800175// ----------------------------------------------------------------------------
176
Glenn Kasten03490092014-05-27 12:30:54 -0700177static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
178
179static void sFastTrackMultiplierInit()
180{
181 char value[PROPERTY_VALUE_MAX];
182 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
183 char *endptr;
184 unsigned long ul = strtoul(value, &endptr, 0);
185 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
186 sFastTrackMultiplier = (int) ul;
187 }
188 }
189}
190
191// ----------------------------------------------------------------------------
192
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef ADD_BATTERY_DATA
194// To collect the amplifier usage
195static void addBatteryData(uint32_t params) {
196 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
197 if (service == NULL) {
198 // it already logged
199 return;
200 }
201
202 service->addBatteryData(params);
203}
204#endif
205
206
207// ----------------------------------------------------------------------------
208// CPU Stats
209// ----------------------------------------------------------------------------
210
211class CpuStats {
212public:
213 CpuStats();
214 void sample(const String8 &title);
215#ifdef DEBUG_CPU_USAGE
216private:
217 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
218 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
219
220 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
221
222 int mCpuNum; // thread's current CPU number
223 int mCpukHz; // frequency of thread's current CPU in kHz
224#endif
225};
226
227CpuStats::CpuStats()
228#ifdef DEBUG_CPU_USAGE
229 : mCpuNum(-1), mCpukHz(-1)
230#endif
231{
232}
233
Glenn Kasten0f11b512014-01-31 16:18:54 -0800234void CpuStats::sample(const String8 &title
235#ifndef DEBUG_CPU_USAGE
236 __unused
237#endif
238 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800239#ifdef DEBUG_CPU_USAGE
240 // get current thread's delta CPU time in wall clock ns
241 double wcNs;
242 bool valid = mCpuUsage.sampleAndEnable(wcNs);
243
244 // record sample for wall clock statistics
245 if (valid) {
246 mWcStats.sample(wcNs);
247 }
248
249 // get the current CPU number
250 int cpuNum = sched_getcpu();
251
252 // get the current CPU frequency in kHz
253 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
254
255 // check if either CPU number or frequency changed
256 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
257 mCpuNum = cpuNum;
258 mCpukHz = cpukHz;
259 // ignore sample for purposes of cycles
260 valid = false;
261 }
262
263 // if no change in CPU number or frequency, then record sample for cycle statistics
264 if (valid && mCpukHz > 0) {
265 double cycles = wcNs * cpukHz * 0.000001;
266 mHzStats.sample(cycles);
267 }
268
269 unsigned n = mWcStats.n();
270 // mCpuUsage.elapsed() is expensive, so don't call it every loop
271 if ((n & 127) == 1) {
272 long long elapsed = mCpuUsage.elapsed();
273 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
274 double perLoop = elapsed / (double) n;
275 double perLoop100 = perLoop * 0.01;
276 double perLoop1k = perLoop * 0.001;
277 double mean = mWcStats.mean();
278 double stddev = mWcStats.stddev();
279 double minimum = mWcStats.minimum();
280 double maximum = mWcStats.maximum();
281 double meanCycles = mHzStats.mean();
282 double stddevCycles = mHzStats.stddev();
283 double minCycles = mHzStats.minimum();
284 double maxCycles = mHzStats.maximum();
285 mCpuUsage.resetElapsed();
286 mWcStats.reset();
287 mHzStats.reset();
288 ALOGD("CPU usage for %s over past %.1f secs\n"
289 " (%u mixer loops at %.1f mean ms per loop):\n"
290 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
291 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
292 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
293 title.string(),
294 elapsed * .000000001, n, perLoop * .000001,
295 mean * .001,
296 stddev * .001,
297 minimum * .001,
298 maximum * .001,
299 mean / perLoop100,
300 stddev / perLoop100,
301 minimum / perLoop100,
302 maximum / perLoop100,
303 meanCycles / perLoop1k,
304 stddevCycles / perLoop1k,
305 minCycles / perLoop1k,
306 maxCycles / perLoop1k);
307
308 }
309 }
310#endif
311};
312
313// ----------------------------------------------------------------------------
314// ThreadBase
315// ----------------------------------------------------------------------------
316
317AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
318 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
319 : Thread(false /*canCallJava*/),
320 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700321 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700322 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800323 // are set by PlaybackThread::readOutputParameters_l() or
324 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700325 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800326 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
327 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
328 // mName will be set by concrete (non-virtual) subclass
329 mDeathRecipient(new PMDeathRecipient(this))
330{
331}
332
333AudioFlinger::ThreadBase::~ThreadBase()
334{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700335 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700336 mConfigEvents.clear();
337
Eric Laurent81784c32012-11-19 14:55:58 -0800338 // do not lock the mutex in destructor
339 releaseWakeLock_l();
340 if (mPowerManager != 0) {
341 sp<IBinder> binder = mPowerManager->asBinder();
342 binder->unlinkToDeath(mDeathRecipient);
343 }
344}
345
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700346status_t AudioFlinger::ThreadBase::readyToRun()
347{
348 status_t status = initCheck();
349 if (status == NO_ERROR) {
350 ALOGI("AudioFlinger's thread %p ready to run", this);
351 } else {
352 ALOGE("No working audio driver found.");
353 }
354 return status;
355}
356
Eric Laurent81784c32012-11-19 14:55:58 -0800357void AudioFlinger::ThreadBase::exit()
358{
359 ALOGV("ThreadBase::exit");
360 // do any cleanup required for exit to succeed
361 preExit();
362 {
363 // This lock prevents the following race in thread (uniprocessor for illustration):
364 // if (!exitPending()) {
365 // // context switch from here to exit()
366 // // exit() calls requestExit(), what exitPending() observes
367 // // exit() calls signal(), which is dropped since no waiters
368 // // context switch back from exit() to here
369 // mWaitWorkCV.wait(...);
370 // // now thread is hung
371 // }
372 AutoMutex lock(mLock);
373 requestExit();
374 mWaitWorkCV.broadcast();
375 }
376 // When Thread::requestExitAndWait is made virtual and this method is renamed to
377 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
378 requestExitAndWait();
379}
380
381status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
382{
383 status_t status;
384
385 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
386 Mutex::Autolock _l(mLock);
387
Eric Laurent10351942014-05-08 18:49:52 -0700388 return sendSetParameterConfigEvent_l(keyValuePairs);
389}
390
391// sendConfigEvent_l() must be called with ThreadBase::mLock held
392// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
393status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
394{
395 status_t status = NO_ERROR;
396
397 mConfigEvents.add(event);
398 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800399 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700400 mLock.unlock();
401 {
402 Mutex::Autolock _l(event->mLock);
403 while (event->mWaitStatus) {
404 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
405 event->mStatus = TIMED_OUT;
406 event->mWaitStatus = false;
407 }
408 }
409 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800410 }
Eric Laurent10351942014-05-08 18:49:52 -0700411 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800412 return status;
413}
414
415void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
416{
417 Mutex::Autolock _l(mLock);
418 sendIoConfigEvent_l(event, param);
419}
420
421// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
422void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
423{
Eric Laurent10351942014-05-08 18:49:52 -0700424 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
425 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
428// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
429void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
430{
Eric Laurent10351942014-05-08 18:49:52 -0700431 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
432 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800433}
434
Eric Laurent10351942014-05-08 18:49:52 -0700435// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
436status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800437{
Eric Laurent10351942014-05-08 18:49:52 -0700438 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
439 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700440}
441
Eric Laurent1c333e22014-05-20 10:48:17 -0700442status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
443 const struct audio_patch *patch,
444 audio_patch_handle_t *handle)
445{
446 Mutex::Autolock _l(mLock);
447 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
448 status_t status = sendConfigEvent_l(configEvent);
449 if (status == NO_ERROR) {
450 CreateAudioPatchConfigEventData *data =
451 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
452 *handle = data->mHandle;
453 }
454 return status;
455}
456
457status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
458 const audio_patch_handle_t handle)
459{
460 Mutex::Autolock _l(mLock);
461 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
462 return sendConfigEvent_l(configEvent);
463}
464
465
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700466// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700467void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700468{
Eric Laurent10351942014-05-08 18:49:52 -0700469 bool configChanged = false;
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700472 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
473 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800474 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700475 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700476 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700477 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
478 // FIXME Need to understand why this has to be done asynchronously
479 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700480 true /*asynchronous*/);
481 if (err != 0) {
482 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700483 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700484 }
485 } break;
486 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700487 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700488 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700489 } break;
490 case CFG_EVENT_SET_PARAMETER: {
491 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
492 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
493 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700494 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700495 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700496 case CFG_EVENT_CREATE_AUDIO_PATCH: {
497 CreateAudioPatchConfigEventData *data =
498 (CreateAudioPatchConfigEventData *)event->mData.get();
499 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
500 } break;
501 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
502 ReleaseAudioPatchConfigEventData *data =
503 (ReleaseAudioPatchConfigEventData *)event->mData.get();
504 event->mStatus = releaseAudioPatch_l(data->mHandle);
505 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700506 default:
Eric Laurent10351942014-05-08 18:49:52 -0700507 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700508 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Eric Laurent10351942014-05-08 18:49:52 -0700510 {
511 Mutex::Autolock _l(event->mLock);
512 if (event->mWaitStatus) {
513 event->mWaitStatus = false;
514 event->mCond.signal();
515 }
516 }
517 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
518 }
519
520 if (configChanged) {
521 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523}
524
Marco Nelissenb2208842014-02-07 14:00:50 -0800525String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
526 String8 s;
527 if (output) {
528 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
529 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
530 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
531 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
532 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
533 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
534 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
535 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
536 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
537 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
538 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
539 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
540 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
541 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
542 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
543 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
544 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
545 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
546 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
547 } else {
548 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
549 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
550 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
551 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
552 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
553 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
554 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
555 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
556 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
557 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
558 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
559 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
560 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
561 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
562 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
563 }
564 int len = s.length();
565 if (s.length() > 2) {
566 char *str = s.lockBuffer(len);
567 s.unlockBuffer(len - 2);
568 }
569 return s;
570}
571
Glenn Kasten0f11b512014-01-31 16:18:54 -0800572void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800573{
574 const size_t SIZE = 256;
575 char buffer[SIZE];
576 String8 result;
577
578 bool locked = AudioFlinger::dumpTryLock(mLock);
579 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700580 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800581 }
582
Elliott Hughes87cebad2014-05-22 10:14:43 -0700583 dprintf(fd, " I/O handle: %d\n", mId);
584 dprintf(fd, " TID: %d\n", getTid());
585 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
586 dprintf(fd, " Sample rate: %u\n", mSampleRate);
587 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
588 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
589 dprintf(fd, " Channel Count: %u\n", mChannelCount);
590 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800591 channelMaskToString(mChannelMask, mType != RECORD).string());
Andy Hung463be252014-07-10 16:56:07 -0700592 dprintf(fd, " Format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700593 dprintf(fd, " Frame size: %zu\n", mFrameSize);
594 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800595 size_t numConfig = mConfigEvents.size();
596 if (numConfig) {
597 for (size_t i = 0; i < numConfig; i++) {
598 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700599 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800600 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700601 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800602 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700603 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800604 }
Eric Laurent81784c32012-11-19 14:55:58 -0800605
606 if (locked) {
607 mLock.unlock();
608 }
609}
610
611void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
612{
613 const size_t SIZE = 256;
614 char buffer[SIZE];
615 String8 result;
616
Marco Nelissenb2208842014-02-07 14:00:50 -0800617 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000618 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 write(fd, buffer, strlen(buffer));
620
Marco Nelissenb2208842014-02-07 14:00:50 -0800621 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800622 sp<EffectChain> chain = mEffectChains[i];
623 if (chain != 0) {
624 chain->dump(fd, args);
625 }
626 }
627}
628
Marco Nelissene14a5d62013-10-03 08:51:24 -0700629void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
631 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700632 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100635String16 AudioFlinger::ThreadBase::getWakeLockTag()
636{
637 switch (mType) {
638 case MIXER:
639 return String16("AudioMix");
640 case DIRECT:
641 return String16("AudioDirectOut");
642 case DUPLICATING:
643 return String16("AudioDup");
644 case RECORD:
645 return String16("AudioIn");
646 case OFFLOAD:
647 return String16("AudioOffload");
648 default:
649 ALOG_ASSERT(false);
650 return String16("AudioUnknown");
651 }
652}
653
Marco Nelissene14a5d62013-10-03 08:51:24 -0700654void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800656 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800657 if (mPowerManager != 0) {
658 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700659 status_t status;
660 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700661 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700662 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100663 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700664 String16("media"),
665 uid);
666 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700667 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700668 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100669 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700670 String16("media"));
671 }
Eric Laurent81784c32012-11-19 14:55:58 -0800672 if (status == NO_ERROR) {
673 mWakeLockToken = binder;
674 }
675 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
676 }
677}
678
679void AudioFlinger::ThreadBase::releaseWakeLock()
680{
681 Mutex::Autolock _l(mLock);
682 releaseWakeLock_l();
683}
684
685void AudioFlinger::ThreadBase::releaseWakeLock_l()
686{
687 if (mWakeLockToken != 0) {
688 ALOGV("releaseWakeLock_l() %s", mName);
689 if (mPowerManager != 0) {
690 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
691 }
692 mWakeLockToken.clear();
693 }
694}
695
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800696void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
697 Mutex::Autolock _l(mLock);
698 updateWakeLockUids_l(uids);
699}
700
701void AudioFlinger::ThreadBase::getPowerManager_l() {
702
703 if (mPowerManager == 0) {
704 // use checkService() to avoid blocking if power service is not up yet
705 sp<IBinder> binder =
706 defaultServiceManager()->checkService(String16("power"));
707 if (binder == 0) {
708 ALOGW("Thread %s cannot connect to the power manager service", mName);
709 } else {
710 mPowerManager = interface_cast<IPowerManager>(binder);
711 binder->linkToDeath(mDeathRecipient);
712 }
713 }
714}
715
716void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
717
718 getPowerManager_l();
719 if (mWakeLockToken == NULL) {
720 ALOGE("no wake lock to update!");
721 return;
722 }
723 if (mPowerManager != 0) {
724 sp<IBinder> binder = new BBinder();
725 status_t status;
726 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
727 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
728 }
729}
730
Eric Laurent81784c32012-11-19 14:55:58 -0800731void AudioFlinger::ThreadBase::clearPowerManager()
732{
733 Mutex::Autolock _l(mLock);
734 releaseWakeLock_l();
735 mPowerManager.clear();
736}
737
Glenn Kasten0f11b512014-01-31 16:18:54 -0800738void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800739{
740 sp<ThreadBase> thread = mThread.promote();
741 if (thread != 0) {
742 thread->clearPowerManager();
743 }
744 ALOGW("power manager service died !!!");
745}
746
747void AudioFlinger::ThreadBase::setEffectSuspended(
748 const effect_uuid_t *type, bool suspend, int sessionId)
749{
750 Mutex::Autolock _l(mLock);
751 setEffectSuspended_l(type, suspend, sessionId);
752}
753
754void AudioFlinger::ThreadBase::setEffectSuspended_l(
755 const effect_uuid_t *type, bool suspend, int sessionId)
756{
757 sp<EffectChain> chain = getEffectChain_l(sessionId);
758 if (chain != 0) {
759 if (type != NULL) {
760 chain->setEffectSuspended_l(type, suspend);
761 } else {
762 chain->setEffectSuspendedAll_l(suspend);
763 }
764 }
765
766 updateSuspendedSessions_l(type, suspend, sessionId);
767}
768
769void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
770{
771 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
772 if (index < 0) {
773 return;
774 }
775
776 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
777 mSuspendedSessions.valueAt(index);
778
779 for (size_t i = 0; i < sessionEffects.size(); i++) {
780 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
781 for (int j = 0; j < desc->mRefCount; j++) {
782 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
783 chain->setEffectSuspendedAll_l(true);
784 } else {
785 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
786 desc->mType.timeLow);
787 chain->setEffectSuspended_l(&desc->mType, true);
788 }
789 }
790 }
791}
792
793void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
794 bool suspend,
795 int sessionId)
796{
797 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
798
799 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
800
801 if (suspend) {
802 if (index >= 0) {
803 sessionEffects = mSuspendedSessions.valueAt(index);
804 } else {
805 mSuspendedSessions.add(sessionId, sessionEffects);
806 }
807 } else {
808 if (index < 0) {
809 return;
810 }
811 sessionEffects = mSuspendedSessions.valueAt(index);
812 }
813
814
815 int key = EffectChain::kKeyForSuspendAll;
816 if (type != NULL) {
817 key = type->timeLow;
818 }
819 index = sessionEffects.indexOfKey(key);
820
821 sp<SuspendedSessionDesc> desc;
822 if (suspend) {
823 if (index >= 0) {
824 desc = sessionEffects.valueAt(index);
825 } else {
826 desc = new SuspendedSessionDesc();
827 if (type != NULL) {
828 desc->mType = *type;
829 }
830 sessionEffects.add(key, desc);
831 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
832 }
833 desc->mRefCount++;
834 } else {
835 if (index < 0) {
836 return;
837 }
838 desc = sessionEffects.valueAt(index);
839 if (--desc->mRefCount == 0) {
840 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
841 sessionEffects.removeItemsAt(index);
842 if (sessionEffects.isEmpty()) {
843 ALOGV("updateSuspendedSessions_l() restore removing session %d",
844 sessionId);
845 mSuspendedSessions.removeItem(sessionId);
846 }
847 }
848 }
849 if (!sessionEffects.isEmpty()) {
850 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
851 }
852}
853
854void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
855 bool enabled,
856 int sessionId)
857{
858 Mutex::Autolock _l(mLock);
859 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
860}
861
862void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
863 bool enabled,
864 int sessionId)
865{
866 if (mType != RECORD) {
867 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
868 // another session. This gives the priority to well behaved effect control panels
869 // and applications not using global effects.
870 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
871 // global effects
872 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
873 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
874 }
875 }
876
877 sp<EffectChain> chain = getEffectChain_l(sessionId);
878 if (chain != 0) {
879 chain->checkSuspendOnEffectEnabled(effect, enabled);
880 }
881}
882
883// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
884sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
885 const sp<AudioFlinger::Client>& client,
886 const sp<IEffectClient>& effectClient,
887 int32_t priority,
888 int sessionId,
889 effect_descriptor_t *desc,
890 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700891 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800892{
893 sp<EffectModule> effect;
894 sp<EffectHandle> handle;
895 status_t lStatus;
896 sp<EffectChain> chain;
897 bool chainCreated = false;
898 bool effectCreated = false;
899 bool effectRegistered = false;
900
901 lStatus = initCheck();
902 if (lStatus != NO_ERROR) {
903 ALOGW("createEffect_l() Audio driver not initialized.");
904 goto Exit;
905 }
906
Andy Hung98ef9782014-03-04 14:46:50 -0800907 // Reject any effect on Direct output threads for now, since the format of
908 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
909 if (mType == DIRECT) {
910 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
911 desc->name, mName);
912 lStatus = BAD_VALUE;
913 goto Exit;
914 }
915
Andy Hung389cfdb2014-08-07 17:49:53 -0700916 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700917 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700918 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
919 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
920 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700921 lStatus = BAD_VALUE;
922 goto Exit;
923 }
924
Eric Laurent5baf2af2013-09-12 17:37:00 -0700925 // Allow global effects only on offloaded and mixer threads
926 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
927 switch (mType) {
928 case MIXER:
929 case OFFLOAD:
930 break;
931 case DIRECT:
932 case DUPLICATING:
933 case RECORD:
934 default:
935 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
936 lStatus = BAD_VALUE;
937 goto Exit;
938 }
Eric Laurent81784c32012-11-19 14:55:58 -0800939 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700940
Eric Laurent81784c32012-11-19 14:55:58 -0800941 // Only Pre processor effects are allowed on input threads and only on input threads
942 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
943 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
944 desc->name, desc->flags, mType);
945 lStatus = BAD_VALUE;
946 goto Exit;
947 }
948
949 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
950
951 { // scope for mLock
952 Mutex::Autolock _l(mLock);
953
954 // check for existing effect chain with the requested audio session
955 chain = getEffectChain_l(sessionId);
956 if (chain == 0) {
957 // create a new chain for this session
958 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
959 chain = new EffectChain(this, sessionId);
960 addEffectChain_l(chain);
961 chain->setStrategy(getStrategyForSession_l(sessionId));
962 chainCreated = true;
963 } else {
964 effect = chain->getEffectFromDesc_l(desc);
965 }
966
967 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
968
969 if (effect == 0) {
970 int id = mAudioFlinger->nextUniqueId();
971 // Check CPU and memory usage
972 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
973 if (lStatus != NO_ERROR) {
974 goto Exit;
975 }
976 effectRegistered = true;
977 // create a new effect module if none present in the chain
978 effect = new EffectModule(this, chain, desc, id, sessionId);
979 lStatus = effect->status();
980 if (lStatus != NO_ERROR) {
981 goto Exit;
982 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700983 effect->setOffloaded(mType == OFFLOAD, mId);
984
Eric Laurent81784c32012-11-19 14:55:58 -0800985 lStatus = chain->addEffect_l(effect);
986 if (lStatus != NO_ERROR) {
987 goto Exit;
988 }
989 effectCreated = true;
990
991 effect->setDevice(mOutDevice);
992 effect->setDevice(mInDevice);
993 effect->setMode(mAudioFlinger->getMode());
994 effect->setAudioSource(mAudioSource);
995 }
996 // create effect handle and connect it to effect module
997 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800998 lStatus = handle->initCheck();
999 if (lStatus == OK) {
1000 lStatus = effect->addHandle(handle.get());
1001 }
Eric Laurent81784c32012-11-19 14:55:58 -08001002 if (enabled != NULL) {
1003 *enabled = (int)effect->isEnabled();
1004 }
1005 }
1006
1007Exit:
1008 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1009 Mutex::Autolock _l(mLock);
1010 if (effectCreated) {
1011 chain->removeEffect_l(effect);
1012 }
1013 if (effectRegistered) {
1014 AudioSystem::unregisterEffect(effect->id());
1015 }
1016 if (chainCreated) {
1017 removeEffectChain_l(chain);
1018 }
1019 handle.clear();
1020 }
1021
Glenn Kasten9156ef32013-08-06 15:39:08 -07001022 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001023 return handle;
1024}
1025
1026sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1027{
1028 Mutex::Autolock _l(mLock);
1029 return getEffect_l(sessionId, effectId);
1030}
1031
1032sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1033{
1034 sp<EffectChain> chain = getEffectChain_l(sessionId);
1035 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1036}
1037
1038// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1039// PlaybackThread::mLock held
1040status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1041{
1042 // check for existing effect chain with the requested audio session
1043 int sessionId = effect->sessionId();
1044 sp<EffectChain> chain = getEffectChain_l(sessionId);
1045 bool chainCreated = false;
1046
Eric Laurent5baf2af2013-09-12 17:37:00 -07001047 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1048 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1049 this, effect->desc().name, effect->desc().flags);
1050
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (chain == 0) {
1052 // create a new chain for this session
1053 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1054 chain = new EffectChain(this, sessionId);
1055 addEffectChain_l(chain);
1056 chain->setStrategy(getStrategyForSession_l(sessionId));
1057 chainCreated = true;
1058 }
1059 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1060
1061 if (chain->getEffectFromId_l(effect->id()) != 0) {
1062 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1063 this, effect->desc().name, chain.get());
1064 return BAD_VALUE;
1065 }
1066
Eric Laurent5baf2af2013-09-12 17:37:00 -07001067 effect->setOffloaded(mType == OFFLOAD, mId);
1068
Eric Laurent81784c32012-11-19 14:55:58 -08001069 status_t status = chain->addEffect_l(effect);
1070 if (status != NO_ERROR) {
1071 if (chainCreated) {
1072 removeEffectChain_l(chain);
1073 }
1074 return status;
1075 }
1076
1077 effect->setDevice(mOutDevice);
1078 effect->setDevice(mInDevice);
1079 effect->setMode(mAudioFlinger->getMode());
1080 effect->setAudioSource(mAudioSource);
1081 return NO_ERROR;
1082}
1083
1084void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1085
1086 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1087 effect_descriptor_t desc = effect->desc();
1088 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1089 detachAuxEffect_l(effect->id());
1090 }
1091
1092 sp<EffectChain> chain = effect->chain().promote();
1093 if (chain != 0) {
1094 // remove effect chain if removing last effect
1095 if (chain->removeEffect_l(effect) == 0) {
1096 removeEffectChain_l(chain);
1097 }
1098 } else {
1099 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1100 }
1101}
1102
1103void AudioFlinger::ThreadBase::lockEffectChains_l(
1104 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1105{
1106 effectChains = mEffectChains;
1107 for (size_t i = 0; i < mEffectChains.size(); i++) {
1108 mEffectChains[i]->lock();
1109 }
1110}
1111
1112void AudioFlinger::ThreadBase::unlockEffectChains(
1113 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1114{
1115 for (size_t i = 0; i < effectChains.size(); i++) {
1116 effectChains[i]->unlock();
1117 }
1118}
1119
1120sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1121{
1122 Mutex::Autolock _l(mLock);
1123 return getEffectChain_l(sessionId);
1124}
1125
1126sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1127{
1128 size_t size = mEffectChains.size();
1129 for (size_t i = 0; i < size; i++) {
1130 if (mEffectChains[i]->sessionId() == sessionId) {
1131 return mEffectChains[i];
1132 }
1133 }
1134 return 0;
1135}
1136
1137void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1138{
1139 Mutex::Autolock _l(mLock);
1140 size_t size = mEffectChains.size();
1141 for (size_t i = 0; i < size; i++) {
1142 mEffectChains[i]->setMode_l(mode);
1143 }
1144}
1145
1146void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1147 EffectHandle *handle,
1148 bool unpinIfLast) {
1149
1150 Mutex::Autolock _l(mLock);
1151 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1152 // delete the effect module if removing last handle on it
1153 if (effect->removeHandle(handle) == 0) {
1154 if (!effect->isPinned() || unpinIfLast) {
1155 removeEffect_l(effect);
1156 AudioSystem::unregisterEffect(effect->id());
1157 }
1158 }
1159}
1160
Eric Laurent83b88082014-06-20 18:31:16 -07001161void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1162{
1163 config->type = AUDIO_PORT_TYPE_MIX;
1164 config->ext.mix.handle = mId;
1165 config->sample_rate = mSampleRate;
1166 config->format = mFormat;
1167 config->channel_mask = mChannelMask;
1168 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1169 AUDIO_PORT_CONFIG_FORMAT;
1170}
1171
1172
Eric Laurent81784c32012-11-19 14:55:58 -08001173// ----------------------------------------------------------------------------
1174// Playback
1175// ----------------------------------------------------------------------------
1176
1177AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1178 AudioStreamOut* output,
1179 audio_io_handle_t id,
1180 audio_devices_t device,
1181 type_t type)
1182 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001183 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001184 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001185 mMixerBuffer(NULL),
1186 mMixerBufferSize(0),
1187 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1188 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001189 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001190 mEffectBuffer(NULL),
1191 mEffectBufferSize(0),
1192 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1193 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001194 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001195 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001196 // mStreamTypes[] initialized in constructor body
1197 mOutput(output),
1198 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1199 mMixerStatus(MIXER_IDLE),
1200 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1201 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001202 mBytesRemaining(0),
1203 mCurrentWriteLength(0),
1204 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001205 mWriteAckSequence(0),
1206 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001207 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001208 mScreenState(AudioFlinger::mScreenState),
1209 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001210 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1211 // mLatchD, mLatchQ,
1212 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001213{
1214 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001215 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001216
1217 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1218 // it would be safer to explicitly pass initial masterVolume/masterMute as
1219 // parameter.
1220 //
1221 // If the HAL we are using has support for master volume or master mute,
1222 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1223 // and the mute set to false).
1224 mMasterVolume = audioFlinger->masterVolume_l();
1225 mMasterMute = audioFlinger->masterMute_l();
1226 if (mOutput && mOutput->audioHwDev) {
1227 if (mOutput->audioHwDev->canSetMasterVolume()) {
1228 mMasterVolume = 1.0;
1229 }
1230
1231 if (mOutput->audioHwDev->canSetMasterMute()) {
1232 mMasterMute = false;
1233 }
1234 }
1235
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001236 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001237
1238 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1239 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001240 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001241 stream = (audio_stream_type_t) (stream + 1)) {
1242 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1243 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1244 }
1245 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1246 // because mAudioFlinger doesn't have one to copy from
1247}
1248
1249AudioFlinger::PlaybackThread::~PlaybackThread()
1250{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001251 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001252 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001253 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001254 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001255}
1256
1257void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1258{
1259 dumpInternals(fd, args);
1260 dumpTracks(fd, args);
1261 dumpEffectChains(fd, args);
1262}
1263
Glenn Kasten0f11b512014-01-31 16:18:54 -08001264void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001265{
1266 const size_t SIZE = 256;
1267 char buffer[SIZE];
1268 String8 result;
1269
Marco Nelissenb2208842014-02-07 14:00:50 -08001270 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001271 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1272 const stream_type_t *st = &mStreamTypes[i];
1273 if (i > 0) {
1274 result.appendFormat(", ");
1275 }
1276 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1277 if (st->mute) {
1278 result.append("M");
1279 }
1280 }
1281 result.append("\n");
1282 write(fd, result.string(), result.length());
1283 result.clear();
1284
Eric Laurent81784c32012-11-19 14:55:58 -08001285 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1286 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001287 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001288 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001289
1290 size_t numtracks = mTracks.size();
1291 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001292 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001293 size_t numactiveseen = 0;
1294 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001295 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001296 Track::appendDumpHeader(result);
1297 for (size_t i = 0; i < numtracks; ++i) {
1298 sp<Track> track = mTracks[i];
1299 if (track != 0) {
1300 bool active = mActiveTracks.indexOf(track) >= 0;
1301 if (active) {
1302 numactiveseen++;
1303 }
1304 track->dump(buffer, SIZE, active);
1305 result.append(buffer);
1306 }
1307 }
1308 } else {
1309 result.append("\n");
1310 }
1311 if (numactiveseen != numactive) {
1312 // some tracks in the active list were not in the tracks list
1313 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1314 " not in the track list\n");
1315 result.append(buffer);
1316 Track::appendDumpHeader(result);
1317 for (size_t i = 0; i < numactive; ++i) {
1318 sp<Track> track = mActiveTracks[i].promote();
1319 if (track != 0 && mTracks.indexOf(track) < 0) {
1320 track->dump(buffer, SIZE, true);
1321 result.append(buffer);
1322 }
1323 }
1324 }
1325
1326 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001327}
1328
1329void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1330{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001331 dprintf(fd, "\nOutput thread %p:\n", this);
1332 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1333 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1334 dprintf(fd, " Total writes: %d\n", mNumWrites);
1335 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1336 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1337 dprintf(fd, " Suspend count: %d\n", mSuspended);
1338 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1339 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1340 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1341 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001342
1343 dumpBase(fd, args);
1344}
1345
1346// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001347
1348void AudioFlinger::PlaybackThread::onFirstRef()
1349{
1350 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1351}
1352
1353// ThreadBase virtuals
1354void AudioFlinger::PlaybackThread::preExit()
1355{
1356 ALOGV(" preExit()");
1357 // FIXME this is using hard-coded strings but in the future, this functionality will be
1358 // converted to use audio HAL extensions required to support tunneling
1359 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1360}
1361
1362// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1363sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1364 const sp<AudioFlinger::Client>& client,
1365 audio_stream_type_t streamType,
1366 uint32_t sampleRate,
1367 audio_format_t format,
1368 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001369 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001370 const sp<IMemory>& sharedBuffer,
1371 int sessionId,
1372 IAudioFlinger::track_flags_t *flags,
1373 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001374 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001375 status_t *status)
1376{
Glenn Kasten74935e42013-12-19 08:56:45 -08001377 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001378 sp<Track> track;
1379 status_t lStatus;
1380
1381 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1382
1383 // client expresses a preference for FAST, but we get the final say
1384 if (*flags & IAudioFlinger::TRACK_FAST) {
1385 if (
1386 // not timed
1387 (!isTimed) &&
1388 // either of these use cases:
1389 (
1390 // use case 1: shared buffer with any frame count
1391 (
1392 (sharedBuffer != 0)
1393 ) ||
1394 // use case 2: callback handler and frame count is default or at least as large as HAL
1395 (
1396 (tid != -1) &&
1397 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001398 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001399 )
1400 ) &&
1401 // PCM data
1402 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001403 // identical channel mask to sink, or mono in and stereo sink
1404 (channelMask == mChannelMask ||
1405 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1406 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001407 // hardware sample rate
1408 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001409 // normal mixer has an associated fast mixer
1410 hasFastMixer() &&
1411 // there are sufficient fast track slots available
1412 (mFastTrackAvailMask != 0)
1413 // FIXME test that MixerThread for this fast track has a capable output HAL
1414 // FIXME add a permission test also?
1415 ) {
1416 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1417 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001418 // read the fast track multiplier property the first time it is needed
1419 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1420 if (ok != 0) {
1421 ALOGE("%s pthread_once failed: %d", __func__, ok);
1422 }
1423 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001424 }
1425 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1426 frameCount, mFrameCount);
1427 } else {
1428 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001429 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1430 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001431 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001432 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001433 audio_is_linear_pcm(format),
1434 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1435 *flags &= ~IAudioFlinger::TRACK_FAST;
1436 // For compatibility with AudioTrack calculation, buffer depth is forced
1437 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1438 // This is probably too conservative, but legacy application code may depend on it.
1439 // If you change this calculation, also review the start threshold which is related.
1440 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1441 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1442 if (minBufCount < 2) {
1443 minBufCount = 2;
1444 }
1445 size_t minFrameCount = mNormalFrameCount * minBufCount;
1446 if (frameCount < minFrameCount) {
1447 frameCount = minFrameCount;
1448 }
1449 }
1450 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001451 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001452
Glenn Kastenc3df8382014-03-13 15:05:25 -07001453 switch (mType) {
1454
1455 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001456 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001457 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001458 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1459 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001460 sampleRate, format, channelMask, mOutput, mFormat);
1461 lStatus = BAD_VALUE;
1462 goto Exit;
1463 }
1464 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001465 break;
1466
1467 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001468 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001469 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1470 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001471 sampleRate, format, channelMask, mOutput, mFormat);
1472 lStatus = BAD_VALUE;
1473 goto Exit;
1474 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001475 break;
1476
1477 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001478 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001479 ALOGE("createTrack_l() Bad parameter: format %#x \""
1480 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001481 format, mOutput, mFormat);
1482 lStatus = BAD_VALUE;
1483 goto Exit;
1484 }
Andy Hungcd044842014-08-07 11:04:34 -07001485 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001486 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1487 lStatus = BAD_VALUE;
1488 goto Exit;
1489 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001490 break;
1491
Eric Laurent81784c32012-11-19 14:55:58 -08001492 }
1493
1494 lStatus = initCheck();
1495 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001496 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001497 goto Exit;
1498 }
1499
1500 { // scope for mLock
1501 Mutex::Autolock _l(mLock);
1502
1503 // all tracks in same audio session must share the same routing strategy otherwise
1504 // conflicts will happen when tracks are moved from one output to another by audio policy
1505 // manager
1506 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1507 for (size_t i = 0; i < mTracks.size(); ++i) {
1508 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001509 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001510 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1511 if (sessionId == t->sessionId() && strategy != actual) {
1512 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1513 strategy, actual);
1514 lStatus = BAD_VALUE;
1515 goto Exit;
1516 }
1517 }
1518 }
1519
1520 if (!isTimed) {
1521 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001522 channelMask, frameCount, NULL, sharedBuffer,
1523 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001524 } else {
1525 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001526 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001527 }
Glenn Kasten03003332013-08-06 15:40:54 -07001528
1529 // new Track always returns non-NULL,
1530 // but TimedTrack::create() is a factory that could fail by returning NULL
1531 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1532 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001533 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001534 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001535 goto Exit;
1536 }
1537 mTracks.add(track);
1538
1539 sp<EffectChain> chain = getEffectChain_l(sessionId);
1540 if (chain != 0) {
1541 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1542 track->setMainBuffer(chain->inBuffer());
1543 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1544 chain->incTrackCnt();
1545 }
1546
1547 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1548 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1549 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1550 // so ask activity manager to do this on our behalf
1551 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1552 }
1553 }
1554
1555 lStatus = NO_ERROR;
1556
1557Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001558 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001559 return track;
1560}
1561
1562uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1563{
1564 return latency;
1565}
1566
1567uint32_t AudioFlinger::PlaybackThread::latency() const
1568{
1569 Mutex::Autolock _l(mLock);
1570 return latency_l();
1571}
1572uint32_t AudioFlinger::PlaybackThread::latency_l() const
1573{
1574 if (initCheck() == NO_ERROR) {
1575 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1576 } else {
1577 return 0;
1578 }
1579}
1580
1581void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1582{
1583 Mutex::Autolock _l(mLock);
1584 // Don't apply master volume in SW if our HAL can do it for us.
1585 if (mOutput && mOutput->audioHwDev &&
1586 mOutput->audioHwDev->canSetMasterVolume()) {
1587 mMasterVolume = 1.0;
1588 } else {
1589 mMasterVolume = value;
1590 }
1591}
1592
1593void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1594{
1595 Mutex::Autolock _l(mLock);
1596 // Don't apply master mute in SW if our HAL can do it for us.
1597 if (mOutput && mOutput->audioHwDev &&
1598 mOutput->audioHwDev->canSetMasterMute()) {
1599 mMasterMute = false;
1600 } else {
1601 mMasterMute = muted;
1602 }
1603}
1604
1605void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1606{
1607 Mutex::Autolock _l(mLock);
1608 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001609 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001610}
1611
1612void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1613{
1614 Mutex::Autolock _l(mLock);
1615 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001616 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001617}
1618
1619float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1620{
1621 Mutex::Autolock _l(mLock);
1622 return mStreamTypes[stream].volume;
1623}
1624
1625// addTrack_l() must be called with ThreadBase::mLock held
1626status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1627{
1628 status_t status = ALREADY_EXISTS;
1629
1630 // set retry count for buffer fill
1631 track->mRetryCount = kMaxTrackStartupRetries;
1632 if (mActiveTracks.indexOf(track) < 0) {
1633 // the track is newly added, make sure it fills up all its
1634 // buffers before playing. This is to ensure the client will
1635 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001636 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001637 TrackBase::track_state state = track->mState;
1638 mLock.unlock();
1639 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1640 mLock.lock();
1641 // abort track was stopped/paused while we released the lock
1642 if (state != track->mState) {
1643 if (status == NO_ERROR) {
1644 mLock.unlock();
1645 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1646 mLock.lock();
1647 }
1648 return INVALID_OPERATION;
1649 }
1650 // abort if start is rejected by audio policy manager
1651 if (status != NO_ERROR) {
1652 return PERMISSION_DENIED;
1653 }
1654#ifdef ADD_BATTERY_DATA
1655 // to track the speaker usage
1656 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1657#endif
1658 }
1659
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001660 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001661 track->mResetDone = false;
1662 track->mPresentationCompleteFrames = 0;
1663 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001664 mWakeLockUids.add(track->uid());
1665 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001666 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001667 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1668 if (chain != 0) {
1669 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1670 track->sessionId());
1671 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001672 }
1673
1674 status = NO_ERROR;
1675 }
1676
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001677 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001678 return status;
1679}
1680
Eric Laurentbfb1b832013-01-07 09:53:42 -08001681bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001682{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001683 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001684 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001685 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1686 track->mState = TrackBase::STOPPED;
1687 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001688 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001689 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001690 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001691 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692
1693 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001694}
1695
1696void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1697{
1698 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1699 mTracks.remove(track);
1700 deleteTrackName_l(track->name());
1701 // redundant as track is about to be destroyed, for dumpsys only
1702 track->mName = -1;
1703 if (track->isFastTrack()) {
1704 int index = track->mFastIndex;
1705 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1706 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1707 mFastTrackAvailMask |= 1 << index;
1708 // redundant as track is about to be destroyed, for dumpsys only
1709 track->mFastIndex = -1;
1710 }
1711 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1712 if (chain != 0) {
1713 chain->decTrackCnt();
1714 }
1715}
1716
Eric Laurentede6c3b2013-09-19 14:37:46 -07001717void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001718{
1719 // Thread could be blocked waiting for async
1720 // so signal it to handle state changes immediately
1721 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1722 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1723 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001724 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001725}
1726
Eric Laurent81784c32012-11-19 14:55:58 -08001727String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1728{
Eric Laurent81784c32012-11-19 14:55:58 -08001729 Mutex::Autolock _l(mLock);
1730 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001731 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001732 }
1733
Glenn Kastend8ea6992013-07-16 14:17:15 -07001734 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1735 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001736 free(s);
1737 return out_s8;
1738}
1739
Eric Laurent021cf962014-05-13 10:18:14 -07001740void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001741 AudioSystem::OutputDescriptor desc;
1742 void *param2 = NULL;
1743
Eric Laurent021cf962014-05-13 10:18:14 -07001744 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001745 param);
1746
1747 switch (event) {
1748 case AudioSystem::OUTPUT_OPENED:
1749 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001750 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001751 desc.samplingRate = mSampleRate;
1752 desc.format = mFormat;
1753 desc.frameCount = mNormalFrameCount; // FIXME see
1754 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001755 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001756 param2 = &desc;
1757 break;
1758
1759 case AudioSystem::STREAM_CONFIG_CHANGED:
1760 param2 = &param;
1761 case AudioSystem::OUTPUT_CLOSED:
1762 default:
1763 break;
1764 }
Eric Laurent021cf962014-05-13 10:18:14 -07001765 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001766}
1767
Eric Laurentbfb1b832013-01-07 09:53:42 -08001768void AudioFlinger::PlaybackThread::writeCallback()
1769{
1770 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001771 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001772}
1773
1774void AudioFlinger::PlaybackThread::drainCallback()
1775{
1776 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001777 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001778}
1779
Eric Laurent3b4529e2013-09-05 18:09:19 -07001780void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001781{
1782 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001783 // reject out of sequence requests
1784 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1785 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001786 mWaitWorkCV.signal();
1787 }
1788}
1789
Eric Laurent3b4529e2013-09-05 18:09:19 -07001790void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791{
1792 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001793 // reject out of sequence requests
1794 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1795 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001796 mWaitWorkCV.signal();
1797 }
1798}
1799
1800// static
1801int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001802 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001803 void *cookie)
1804{
1805 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1806 ALOGV("asyncCallback() event %d", event);
1807 switch (event) {
1808 case STREAM_CBK_EVENT_WRITE_READY:
1809 me->writeCallback();
1810 break;
1811 case STREAM_CBK_EVENT_DRAIN_READY:
1812 me->drainCallback();
1813 break;
1814 default:
1815 ALOGW("asyncCallback() unknown event %d", event);
1816 break;
1817 }
1818 return 0;
1819}
1820
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001821void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001822{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001823 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001824 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1825 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001826 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001827 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001828 }
Andy Hung9a592762014-07-21 21:56:01 -07001829 if ((mType == MIXER || mType == DUPLICATING)
1830 && !isValidPcmSinkChannelMask(mChannelMask)) {
1831 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1832 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001833 }
Andy Hunge5412692014-05-16 11:25:07 -07001834 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001835 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1836 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001837 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001838 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001839 }
Andy Hung6146c082014-03-18 11:56:15 -07001840 if ((mType == MIXER || mType == DUPLICATING)
1841 && !isValidPcmSinkFormat(mFormat)) {
1842 LOG_FATAL("HAL format %#x not supported for mixed output",
1843 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001844 }
Eric Laurent665470b2014-07-03 16:37:08 -07001845 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001846 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1847 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001848 if (mFrameCount & 15) {
1849 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1850 mFrameCount);
1851 }
1852
Eric Laurentbfb1b832013-01-07 09:53:42 -08001853 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1854 (mOutput->stream->set_callback != NULL)) {
1855 if (mOutput->stream->set_callback(mOutput->stream,
1856 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1857 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001858 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859 }
1860 }
1861
Andy Hung09a50072014-02-27 14:30:47 -08001862 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001863 double multiplier = 1.0;
1864 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1865 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001866 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1867 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001868 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1869 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1870 maxNormalFrameCount = maxNormalFrameCount & ~15;
1871 if (maxNormalFrameCount < minNormalFrameCount) {
1872 maxNormalFrameCount = minNormalFrameCount;
1873 }
1874 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1875 if (multiplier <= 1.0) {
1876 multiplier = 1.0;
1877 } else if (multiplier <= 2.0) {
1878 if (2 * mFrameCount <= maxNormalFrameCount) {
1879 multiplier = 2.0;
1880 } else {
1881 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1882 }
1883 } else {
1884 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001885 // 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 -08001886 // track, but we sometimes have to do this to satisfy the maximum frame count
1887 // constraint)
1888 // FIXME this rounding up should not be done if no HAL SRC
1889 uint32_t truncMult = (uint32_t) multiplier;
1890 if ((truncMult & 1)) {
1891 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1892 ++truncMult;
1893 }
1894 }
1895 multiplier = (double) truncMult;
1896 }
1897 }
1898 mNormalFrameCount = multiplier * mFrameCount;
1899 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001900 if (mType == MIXER || mType == DUPLICATING) {
1901 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1902 }
Andy Hung09a50072014-02-27 14:30:47 -08001903 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001904 mNormalFrameCount);
1905
Andy Hung010a1a12014-03-13 13:57:33 -07001906 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1907 // Originally this was int16_t[] array, need to remove legacy implications.
1908 free(mSinkBuffer);
1909 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001910 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1911 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1912 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001913 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001914
Andy Hung69aed5f2014-02-25 17:24:40 -08001915 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1916 // drives the output.
1917 free(mMixerBuffer);
1918 mMixerBuffer = NULL;
1919 if (mMixerBufferEnabled) {
1920 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1921 mMixerBufferSize = mNormalFrameCount * mChannelCount
1922 * audio_bytes_per_sample(mMixerBufferFormat);
1923 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1924 }
Andy Hung98ef9782014-03-04 14:46:50 -08001925 free(mEffectBuffer);
1926 mEffectBuffer = NULL;
1927 if (mEffectBufferEnabled) {
1928 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1929 mEffectBufferSize = mNormalFrameCount * mChannelCount
1930 * audio_bytes_per_sample(mEffectBufferFormat);
1931 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1932 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001933
Eric Laurent81784c32012-11-19 14:55:58 -08001934 // force reconfiguration of effect chains and engines to take new buffer size and audio
1935 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001936 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001937 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1938 // matter.
1939 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1940 Vector< sp<EffectChain> > effectChains = mEffectChains;
1941 for (size_t i = 0; i < effectChains.size(); i ++) {
1942 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1943 }
1944}
1945
1946
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001947status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001948{
1949 if (halFrames == NULL || dspFrames == NULL) {
1950 return BAD_VALUE;
1951 }
1952 Mutex::Autolock _l(mLock);
1953 if (initCheck() != NO_ERROR) {
1954 return INVALID_OPERATION;
1955 }
1956 size_t framesWritten = mBytesWritten / mFrameSize;
1957 *halFrames = framesWritten;
1958
1959 if (isSuspended()) {
1960 // return an estimation of rendered frames when the output is suspended
1961 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1962 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1963 return NO_ERROR;
1964 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001965 status_t status;
1966 uint32_t frames;
1967 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1968 *dspFrames = (size_t)frames;
1969 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001970 }
1971}
1972
1973uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1974{
1975 Mutex::Autolock _l(mLock);
1976 uint32_t result = 0;
1977 if (getEffectChain_l(sessionId) != 0) {
1978 result = EFFECT_SESSION;
1979 }
1980
1981 for (size_t i = 0; i < mTracks.size(); ++i) {
1982 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001983 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001984 result |= TRACK_SESSION;
1985 break;
1986 }
1987 }
1988
1989 return result;
1990}
1991
1992uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1993{
1994 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1995 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1996 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1997 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1998 }
1999 for (size_t i = 0; i < mTracks.size(); i++) {
2000 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002001 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002002 return AudioSystem::getStrategyForStream(track->streamType());
2003 }
2004 }
2005 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2006}
2007
2008
2009AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2010{
2011 Mutex::Autolock _l(mLock);
2012 return mOutput;
2013}
2014
2015AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2016{
2017 Mutex::Autolock _l(mLock);
2018 AudioStreamOut *output = mOutput;
2019 mOutput = NULL;
2020 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2021 // must push a NULL and wait for ack
2022 mOutputSink.clear();
2023 mPipeSink.clear();
2024 mNormalSink.clear();
2025 return output;
2026}
2027
2028// this method must always be called either with ThreadBase mLock held or inside the thread loop
2029audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2030{
2031 if (mOutput == NULL) {
2032 return NULL;
2033 }
2034 return &mOutput->stream->common;
2035}
2036
2037uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2038{
2039 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2040}
2041
2042status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2043{
2044 if (!isValidSyncEvent(event)) {
2045 return BAD_VALUE;
2046 }
2047
2048 Mutex::Autolock _l(mLock);
2049
2050 for (size_t i = 0; i < mTracks.size(); ++i) {
2051 sp<Track> track = mTracks[i];
2052 if (event->triggerSession() == track->sessionId()) {
2053 (void) track->setSyncEvent(event);
2054 return NO_ERROR;
2055 }
2056 }
2057
2058 return NAME_NOT_FOUND;
2059}
2060
2061bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2062{
2063 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2064}
2065
2066void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2067 const Vector< sp<Track> >& tracksToRemove)
2068{
2069 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002070 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002071 for (size_t i = 0 ; i < count ; i++) {
2072 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002073 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002074 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002075#ifdef ADD_BATTERY_DATA
2076 // to track the speaker usage
2077 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2078#endif
2079 if (track->isTerminated()) {
2080 AudioSystem::releaseOutput(mId);
2081 }
Eric Laurent81784c32012-11-19 14:55:58 -08002082 }
2083 }
2084 }
Eric Laurent81784c32012-11-19 14:55:58 -08002085}
2086
2087void AudioFlinger::PlaybackThread::checkSilentMode_l()
2088{
2089 if (!mMasterMute) {
2090 char value[PROPERTY_VALUE_MAX];
2091 if (property_get("ro.audio.silent", value, "0") > 0) {
2092 char *endptr;
2093 unsigned long ul = strtoul(value, &endptr, 0);
2094 if (*endptr == '\0' && ul != 0) {
2095 ALOGD("Silence is golden");
2096 // The setprop command will not allow a property to be changed after
2097 // the first time it is set, so we don't have to worry about un-muting.
2098 setMasterMute_l(true);
2099 }
2100 }
2101 }
2102}
2103
2104// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002106{
2107 // FIXME rewrite to reduce number of system calls
2108 mLastWriteTime = systemTime();
2109 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002111 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002112
2113 // If an NBAIO sink is present, use it to write the normal mixer's submix
2114 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002115 const size_t count = mBytesRemaining / mFrameSize;
2116
Simon Wilson2d590962012-11-29 15:18:50 -08002117 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002118 // update the setpoint when AudioFlinger::mScreenState changes
2119 uint32_t screenState = AudioFlinger::mScreenState;
2120 if (screenState != mScreenState) {
2121 mScreenState = screenState;
2122 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2123 if (pipe != NULL) {
2124 pipe->setAvgFrames((mScreenState & 1) ?
2125 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2126 }
2127 }
Andy Hung010a1a12014-03-13 13:57:33 -07002128 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002129 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002130 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002131 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002132 } else {
2133 bytesWritten = framesWritten;
2134 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002135 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002136 if (status == NO_ERROR) {
2137 size_t totalFramesWritten = mNormalSink->framesWritten();
2138 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2139 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2140 mLatchDValid = true;
2141 }
2142 }
Eric Laurent81784c32012-11-19 14:55:58 -08002143 // otherwise use the HAL / AudioStreamOut directly
2144 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002146
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002148 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2149 mWriteAckSequence += 2;
2150 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002152 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002154 // FIXME We should have an implementation of timestamps for direct output threads.
2155 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002157 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158 if (mUseAsyncWrite &&
2159 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2160 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002161 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002163 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 }
Eric Laurent81784c32012-11-19 14:55:58 -08002165 }
2166
Eric Laurent81784c32012-11-19 14:55:58 -08002167 mNumWrites++;
2168 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002169 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 return bytesWritten;
2171}
2172
2173void AudioFlinger::PlaybackThread::threadLoop_drain()
2174{
2175 if (mOutput->stream->drain) {
2176 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2177 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002178 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2179 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002181 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 }
2183 mOutput->stream->drain(mOutput->stream,
2184 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2185 : AUDIO_DRAIN_ALL);
2186 }
2187}
2188
2189void AudioFlinger::PlaybackThread::threadLoop_exit()
2190{
2191 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002192}
2193
2194/*
2195The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002196 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002197 - activeSleepTime from activeSleepTimeUs()
2198 - idleSleepTime from idleSleepTimeUs()
2199 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2200 - maxPeriod from frame count and sample rate (MIXER only)
2201
2202The parameters that affect these derived values are:
2203 - frame count
2204 - frame size
2205 - sample rate
2206 - device type: A2DP or not
2207 - device latency
2208 - format: PCM or not
2209 - active sleep time
2210 - idle sleep time
2211*/
2212
2213void AudioFlinger::PlaybackThread::cacheParameters_l()
2214{
Andy Hung25c2dac2014-02-27 14:56:00 -08002215 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002216 activeSleepTime = activeSleepTimeUs();
2217 idleSleepTime = idleSleepTimeUs();
2218}
2219
2220void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2221{
Glenn Kasten7c027242012-12-26 14:43:16 -08002222 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002223 this, streamType, mTracks.size());
2224 Mutex::Autolock _l(mLock);
2225
2226 size_t size = mTracks.size();
2227 for (size_t i = 0; i < size; i++) {
2228 sp<Track> t = mTracks[i];
2229 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002230 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002231 }
2232 }
2233}
2234
2235status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2236{
2237 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002238 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2239 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002240 bool ownsBuffer = false;
2241
2242 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2243 if (session > 0) {
2244 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002245 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002246 if (mType != DIRECT) {
2247 size_t numSamples = mNormalFrameCount * mChannelCount;
2248 buffer = new int16_t[numSamples];
2249 memset(buffer, 0, numSamples * sizeof(int16_t));
2250 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2251 ownsBuffer = true;
2252 }
2253
2254 // Attach all tracks with same session ID to this chain.
2255 for (size_t i = 0; i < mTracks.size(); ++i) {
2256 sp<Track> track = mTracks[i];
2257 if (session == track->sessionId()) {
2258 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2259 buffer);
2260 track->setMainBuffer(buffer);
2261 chain->incTrackCnt();
2262 }
2263 }
2264
2265 // indicate all active tracks in the chain
2266 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2267 sp<Track> track = mActiveTracks[i].promote();
2268 if (track == 0) {
2269 continue;
2270 }
2271 if (session == track->sessionId()) {
2272 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2273 chain->incActiveTrackCnt();
2274 }
2275 }
2276 }
2277
2278 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002279 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2280 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002281 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2282 // chains list in order to be processed last as it contains output stage effects
2283 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2284 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2285 // after track specific effects and before output stage
2286 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2287 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2288 // Effect chain for other sessions are inserted at beginning of effect
2289 // chains list to be processed before output mix effects. Relative order between other
2290 // sessions is not important
2291 size_t size = mEffectChains.size();
2292 size_t i = 0;
2293 for (i = 0; i < size; i++) {
2294 if (mEffectChains[i]->sessionId() < session) {
2295 break;
2296 }
2297 }
2298 mEffectChains.insertAt(chain, i);
2299 checkSuspendOnAddEffectChain_l(chain);
2300
2301 return NO_ERROR;
2302}
2303
2304size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2305{
2306 int session = chain->sessionId();
2307
2308 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2309
2310 for (size_t i = 0; i < mEffectChains.size(); i++) {
2311 if (chain == mEffectChains[i]) {
2312 mEffectChains.removeAt(i);
2313 // detach all active tracks from the chain
2314 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2315 sp<Track> track = mActiveTracks[i].promote();
2316 if (track == 0) {
2317 continue;
2318 }
2319 if (session == track->sessionId()) {
2320 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2321 chain.get(), session);
2322 chain->decActiveTrackCnt();
2323 }
2324 }
2325
2326 // detach all tracks with same session ID from this chain
2327 for (size_t i = 0; i < mTracks.size(); ++i) {
2328 sp<Track> track = mTracks[i];
2329 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002330 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002331 chain->decTrackCnt();
2332 }
2333 }
2334 break;
2335 }
2336 }
2337 return mEffectChains.size();
2338}
2339
2340status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2341 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2342{
2343 Mutex::Autolock _l(mLock);
2344 return attachAuxEffect_l(track, EffectId);
2345}
2346
2347status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2348 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2349{
2350 status_t status = NO_ERROR;
2351
2352 if (EffectId == 0) {
2353 track->setAuxBuffer(0, NULL);
2354 } else {
2355 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2356 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2357 if (effect != 0) {
2358 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2359 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2360 } else {
2361 status = INVALID_OPERATION;
2362 }
2363 } else {
2364 status = BAD_VALUE;
2365 }
2366 }
2367 return status;
2368}
2369
2370void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2371{
2372 for (size_t i = 0; i < mTracks.size(); ++i) {
2373 sp<Track> track = mTracks[i];
2374 if (track->auxEffectId() == effectId) {
2375 attachAuxEffect_l(track, 0);
2376 }
2377 }
2378}
2379
2380bool AudioFlinger::PlaybackThread::threadLoop()
2381{
2382 Vector< sp<Track> > tracksToRemove;
2383
2384 standbyTime = systemTime();
2385
2386 // MIXER
2387 nsecs_t lastWarning = 0;
2388
2389 // DUPLICATING
2390 // FIXME could this be made local to while loop?
2391 writeFrames = 0;
2392
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002393 int lastGeneration = 0;
2394
Eric Laurent81784c32012-11-19 14:55:58 -08002395 cacheParameters_l();
2396 sleepTime = idleSleepTime;
2397
2398 if (mType == MIXER) {
2399 sleepTimeShift = 0;
2400 }
2401
2402 CpuStats cpuStats;
2403 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2404
2405 acquireWakeLock();
2406
Glenn Kasten9e58b552013-01-18 15:09:48 -08002407 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2408 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2409 // and then that string will be logged at the next convenient opportunity.
2410 const char *logString = NULL;
2411
Eric Laurent664539d2013-09-23 18:24:31 -07002412 checkSilentMode_l();
2413
Eric Laurent81784c32012-11-19 14:55:58 -08002414 while (!exitPending())
2415 {
2416 cpuStats.sample(myName);
2417
2418 Vector< sp<EffectChain> > effectChains;
2419
Eric Laurent81784c32012-11-19 14:55:58 -08002420 { // scope for mLock
2421
2422 Mutex::Autolock _l(mLock);
2423
Eric Laurent021cf962014-05-13 10:18:14 -07002424 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002425
Glenn Kasten9e58b552013-01-18 15:09:48 -08002426 if (logString != NULL) {
2427 mNBLogWriter->logTimestamp();
2428 mNBLogWriter->log(logString);
2429 logString = NULL;
2430 }
2431
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002432 if (mLatchDValid) {
2433 mLatchQ = mLatchD;
2434 mLatchDValid = false;
2435 mLatchQValid = true;
2436 }
2437
Eric Laurent81784c32012-11-19 14:55:58 -08002438 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002439 if (mSignalPending) {
2440 // A signal was raised while we were unlocked
2441 mSignalPending = false;
2442 } else if (waitingAsyncCallback_l()) {
2443 if (exitPending()) {
2444 break;
2445 }
2446 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002447 mWakeLockUids.clear();
2448 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 ALOGV("wait async completion");
2450 mWaitWorkCV.wait(mLock);
2451 ALOGV("async completion/wake");
2452 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002453 standbyTime = systemTime() + standbyDelay;
2454 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002455
2456 continue;
2457 }
2458 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 isSuspended()) {
2460 // put audio hardware into standby after short delay
2461 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002462
2463 threadLoop_standby();
2464
2465 mStandby = true;
2466 }
2467
2468 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2469 // we're about to wait, flush the binder command buffer
2470 IPCThreadState::self()->flushCommands();
2471
2472 clearOutputTracks();
2473
2474 if (exitPending()) {
2475 break;
2476 }
2477
2478 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002479 mWakeLockUids.clear();
2480 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002481 // wait until we have something to do...
2482 ALOGV("%s going to sleep", myName.string());
2483 mWaitWorkCV.wait(mLock);
2484 ALOGV("%s waking up", myName.string());
2485 acquireWakeLock_l();
2486
2487 mMixerStatus = MIXER_IDLE;
2488 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2489 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002491 checkSilentMode_l();
2492
2493 standbyTime = systemTime() + standbyDelay;
2494 sleepTime = idleSleepTime;
2495 if (mType == MIXER) {
2496 sleepTimeShift = 0;
2497 }
2498
2499 continue;
2500 }
2501 }
Eric Laurent81784c32012-11-19 14:55:58 -08002502 // mMixerStatusIgnoringFastTracks is also updated internally
2503 mMixerStatus = prepareTracks_l(&tracksToRemove);
2504
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002505 // compare with previously applied list
2506 if (lastGeneration != mActiveTracksGeneration) {
2507 // update wakelock
2508 updateWakeLockUids_l(mWakeLockUids);
2509 lastGeneration = mActiveTracksGeneration;
2510 }
2511
Eric Laurent81784c32012-11-19 14:55:58 -08002512 // prevent any changes in effect chain list and in each effect chain
2513 // during mixing and effect process as the audio buffers could be deleted
2514 // or modified if an effect is created or deleted
2515 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002516 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002517
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 if (mBytesRemaining == 0) {
2519 mCurrentWriteLength = 0;
2520 if (mMixerStatus == MIXER_TRACKS_READY) {
2521 // threadLoop_mix() sets mCurrentWriteLength
2522 threadLoop_mix();
2523 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2524 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2525 // threadLoop_sleepTime sets sleepTime to 0 if data
2526 // must be written to HAL
2527 threadLoop_sleepTime();
2528 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002529 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530 }
2531 }
Andy Hung98ef9782014-03-04 14:46:50 -08002532 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2533 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2534 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2535 // or mSinkBuffer (if there are no effects).
2536 //
2537 // This is done pre-effects computation; if effects change to
2538 // support higher precision, this needs to move.
2539 //
2540 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2541 // TODO use sleepTime == 0 as an additional condition.
2542 if (mMixerBufferValid) {
2543 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2544 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2545
2546 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2547 mNormalFrameCount * mChannelCount);
2548 }
2549
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550 mBytesRemaining = mCurrentWriteLength;
2551 if (isSuspended()) {
2552 sleepTime = suspendSleepTimeUs();
2553 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002554 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002555 mBytesRemaining = 0;
2556 }
Eric Laurent81784c32012-11-19 14:55:58 -08002557
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002559 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 for (size_t i = 0; i < effectChains.size(); i ++) {
2561 effectChains[i]->process_l();
2562 }
Eric Laurent81784c32012-11-19 14:55:58 -08002563 }
2564 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002565 // Process effect chains for offloaded thread even if no audio
2566 // was read from audio track: process only updates effect state
2567 // and thus does have to be synchronized with audio writes but may have
2568 // to be called while waiting for async write callback
2569 if (mType == OFFLOAD) {
2570 for (size_t i = 0; i < effectChains.size(); i ++) {
2571 effectChains[i]->process_l();
2572 }
2573 }
Eric Laurent81784c32012-11-19 14:55:58 -08002574
Andy Hung98ef9782014-03-04 14:46:50 -08002575 // Only if the Effects buffer is enabled and there is data in the
2576 // Effects buffer (buffer valid), we need to
2577 // copy into the sink buffer.
2578 // TODO use sleepTime == 0 as an additional condition.
2579 if (mEffectBufferValid) {
2580 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2581 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2582 mNormalFrameCount * mChannelCount);
2583 }
2584
Eric Laurent81784c32012-11-19 14:55:58 -08002585 // enable changes in effect chain
2586 unlockEffectChains(effectChains);
2587
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 if (!waitingAsyncCallback()) {
2589 // sleepTime == 0 means we must write to audio hardware
2590 if (sleepTime == 0) {
2591 if (mBytesRemaining) {
2592 ssize_t ret = threadLoop_write();
2593 if (ret < 0) {
2594 mBytesRemaining = 0;
2595 } else {
2596 mBytesWritten += ret;
2597 mBytesRemaining -= ret;
2598 }
2599 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2600 (mMixerStatus == MIXER_DRAIN_ALL)) {
2601 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002602 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002603 if (mType == MIXER) {
2604 // write blocked detection
2605 nsecs_t now = systemTime();
2606 nsecs_t delta = now - mLastWriteTime;
2607 if (!mStandby && delta > maxPeriod) {
2608 mNumDelayedWrites++;
2609 if ((now - lastWarning) > kWarningThrottleNs) {
2610 ATRACE_NAME("underrun");
2611 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2612 ns2ms(delta), mNumDelayedWrites, this);
2613 lastWarning = now;
2614 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615 }
2616 }
Eric Laurent81784c32012-11-19 14:55:58 -08002617
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 } else {
2619 usleep(sleepTime);
2620 }
Eric Laurent81784c32012-11-19 14:55:58 -08002621 }
2622
2623 // Finally let go of removed track(s), without the lock held
2624 // since we can't guarantee the destructors won't acquire that
2625 // same lock. This will also mutate and push a new fast mixer state.
2626 threadLoop_removeTracks(tracksToRemove);
2627 tracksToRemove.clear();
2628
2629 // FIXME I don't understand the need for this here;
2630 // it was in the original code but maybe the
2631 // assignment in saveOutputTracks() makes this unnecessary?
2632 clearOutputTracks();
2633
2634 // Effect chains will be actually deleted here if they were removed from
2635 // mEffectChains list during mixing or effects processing
2636 effectChains.clear();
2637
2638 // FIXME Note that the above .clear() is no longer necessary since effectChains
2639 // is now local to this block, but will keep it for now (at least until merge done).
2640 }
2641
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 threadLoop_exit();
2643
Eric Laurentcf817a22014-08-04 20:36:31 -07002644 if (!mStandby) {
2645 threadLoop_standby();
2646 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002647 }
2648
2649 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002650 mWakeLockUids.clear();
2651 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002652
2653 ALOGV("Thread %p type %d exiting", this, mType);
2654 return false;
2655}
2656
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657// removeTracks_l() must be called with ThreadBase::mLock held
2658void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2659{
2660 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002661 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 for (size_t i=0 ; i<count ; i++) {
2663 const sp<Track>& track = tracksToRemove.itemAt(i);
2664 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002665 mWakeLockUids.remove(track->uid());
2666 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2668 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2669 if (chain != 0) {
2670 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2671 track->sessionId());
2672 chain->decActiveTrackCnt();
2673 }
2674 if (track->isTerminated()) {
2675 removeTrack_l(track);
2676 }
2677 }
2678 }
2679
2680}
Eric Laurent81784c32012-11-19 14:55:58 -08002681
Eric Laurentaccc1472013-09-20 09:36:34 -07002682status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2683{
2684 if (mNormalSink != 0) {
2685 return mNormalSink->getTimestamp(timestamp);
2686 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002687 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002688 uint64_t position64;
2689 int ret = mOutput->stream->get_presentation_position(
2690 mOutput->stream, &position64, &timestamp.mTime);
2691 if (ret == 0) {
2692 timestamp.mPosition = (uint32_t)position64;
2693 return NO_ERROR;
2694 }
2695 }
2696 return INVALID_OPERATION;
2697}
Eric Laurent1c333e22014-05-20 10:48:17 -07002698
2699status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2700 audio_patch_handle_t *handle)
2701{
2702 status_t status = NO_ERROR;
2703 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2704 // store new device and send to effects
2705 audio_devices_t type = AUDIO_DEVICE_NONE;
2706 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2707 type |= patch->sinks[i].ext.device.type;
2708 }
2709 mOutDevice = type;
2710 for (size_t i = 0; i < mEffectChains.size(); i++) {
2711 mEffectChains[i]->setDevice_l(mOutDevice);
2712 }
2713
2714 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2715 status = hwDevice->create_audio_patch(hwDevice,
2716 patch->num_sources,
2717 patch->sources,
2718 patch->num_sinks,
2719 patch->sinks,
2720 handle);
2721 } else {
2722 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2723 }
2724 return status;
2725}
2726
2727status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2728{
2729 status_t status = NO_ERROR;
2730 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2731 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2732 status = hwDevice->release_audio_patch(hwDevice, handle);
2733 } else {
2734 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2735 }
2736 return status;
2737}
2738
Eric Laurent83b88082014-06-20 18:31:16 -07002739void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2740{
2741 Mutex::Autolock _l(mLock);
2742 mTracks.add(track);
2743}
2744
2745void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2746{
2747 Mutex::Autolock _l(mLock);
2748 destroyTrack_l(track);
2749}
2750
2751void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2752{
2753 ThreadBase::getAudioPortConfig(config);
2754 config->role = AUDIO_PORT_ROLE_SOURCE;
2755 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2756 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2757}
2758
Eric Laurent81784c32012-11-19 14:55:58 -08002759// ----------------------------------------------------------------------------
2760
2761AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2762 audio_io_handle_t id, audio_devices_t device, type_t type)
2763 : PlaybackThread(audioFlinger, output, id, device, type),
2764 // mAudioMixer below
2765 // mFastMixer below
2766 mFastMixerFutex(0)
2767 // mOutputSink below
2768 // mPipeSink below
2769 // mNormalSink below
2770{
2771 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002772 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002773 "mFrameCount=%d, mNormalFrameCount=%d",
2774 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2775 mNormalFrameCount);
2776 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2777
Eric Laurent81784c32012-11-19 14:55:58 -08002778 // create an NBAIO sink for the HAL output stream, and negotiate
2779 mOutputSink = new AudioStreamOutSink(output->stream);
2780 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002781 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002782 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2783 ALOG_ASSERT(index == 0);
2784
2785 // initialize fast mixer depending on configuration
2786 bool initFastMixer;
2787 switch (kUseFastMixer) {
2788 case FastMixer_Never:
2789 initFastMixer = false;
2790 break;
2791 case FastMixer_Always:
2792 initFastMixer = true;
2793 break;
2794 case FastMixer_Static:
2795 case FastMixer_Dynamic:
2796 initFastMixer = mFrameCount < mNormalFrameCount;
2797 break;
2798 }
2799 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002800 audio_format_t fastMixerFormat;
2801 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2802 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2803 } else {
2804 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2805 }
2806 if (mFormat != fastMixerFormat) {
2807 // change our Sink format to accept our intermediate precision
2808 mFormat = fastMixerFormat;
2809 free(mSinkBuffer);
2810 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2811 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2812 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2813 }
Eric Laurent81784c32012-11-19 14:55:58 -08002814
2815 // create a MonoPipe to connect our submix to FastMixer
2816 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002817 // adjust format to match that of the Fast Mixer
2818 format.mFormat = fastMixerFormat;
2819 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2820
Eric Laurent81784c32012-11-19 14:55:58 -08002821 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2822 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2823 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2824 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2825 const NBAIO_Format offers[1] = {format};
2826 size_t numCounterOffers = 0;
2827 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2828 ALOG_ASSERT(index == 0);
2829 monoPipe->setAvgFrames((mScreenState & 1) ?
2830 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2831 mPipeSink = monoPipe;
2832
Glenn Kasten46909e72013-02-26 09:20:22 -08002833#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002834 if (mTeeSinkOutputEnabled) {
2835 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2836 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2837 numCounterOffers = 0;
2838 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2839 ALOG_ASSERT(index == 0);
2840 mTeeSink = teeSink;
2841 PipeReader *teeSource = new PipeReader(*teeSink);
2842 numCounterOffers = 0;
2843 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2844 ALOG_ASSERT(index == 0);
2845 mTeeSource = teeSource;
2846 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002847#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002848
2849 // create fast mixer and configure it initially with just one fast track for our submix
2850 mFastMixer = new FastMixer();
2851 FastMixerStateQueue *sq = mFastMixer->sq();
2852#ifdef STATE_QUEUE_DUMP
2853 sq->setObserverDump(&mStateQueueObserverDump);
2854 sq->setMutatorDump(&mStateQueueMutatorDump);
2855#endif
2856 FastMixerState *state = sq->begin();
2857 FastTrack *fastTrack = &state->mFastTracks[0];
2858 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2859 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2860 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002861 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2862 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002863 fastTrack->mGeneration++;
2864 state->mFastTracksGen++;
2865 state->mTrackMask = 1;
2866 // fast mixer will use the HAL output sink
2867 state->mOutputSink = mOutputSink.get();
2868 state->mOutputSinkGen++;
2869 state->mFrameCount = mFrameCount;
2870 state->mCommand = FastMixerState::COLD_IDLE;
2871 // already done in constructor initialization list
2872 //mFastMixerFutex = 0;
2873 state->mColdFutexAddr = &mFastMixerFutex;
2874 state->mColdGen++;
2875 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002876#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002877 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002878#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002879 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2880 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002881 sq->end();
2882 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2883
2884 // start the fast mixer
2885 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2886 pid_t tid = mFastMixer->getTid();
2887 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2888 if (err != 0) {
2889 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2890 kPriorityFastMixer, getpid_cached, tid, err);
2891 }
2892
2893#ifdef AUDIO_WATCHDOG
2894 // create and start the watchdog
2895 mAudioWatchdog = new AudioWatchdog();
2896 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2897 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2898 tid = mAudioWatchdog->getTid();
2899 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2900 if (err != 0) {
2901 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2902 kPriorityFastMixer, getpid_cached, tid, err);
2903 }
2904#endif
2905
Eric Laurent81784c32012-11-19 14:55:58 -08002906 }
2907
2908 switch (kUseFastMixer) {
2909 case FastMixer_Never:
2910 case FastMixer_Dynamic:
2911 mNormalSink = mOutputSink;
2912 break;
2913 case FastMixer_Always:
2914 mNormalSink = mPipeSink;
2915 break;
2916 case FastMixer_Static:
2917 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2918 break;
2919 }
2920}
2921
2922AudioFlinger::MixerThread::~MixerThread()
2923{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002924 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002925 FastMixerStateQueue *sq = mFastMixer->sq();
2926 FastMixerState *state = sq->begin();
2927 if (state->mCommand == FastMixerState::COLD_IDLE) {
2928 int32_t old = android_atomic_inc(&mFastMixerFutex);
2929 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002930 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002931 }
2932 }
2933 state->mCommand = FastMixerState::EXIT;
2934 sq->end();
2935 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2936 mFastMixer->join();
2937 // Though the fast mixer thread has exited, it's state queue is still valid.
2938 // We'll use that extract the final state which contains one remaining fast track
2939 // corresponding to our sub-mix.
2940 state = sq->begin();
2941 ALOG_ASSERT(state->mTrackMask == 1);
2942 FastTrack *fastTrack = &state->mFastTracks[0];
2943 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2944 delete fastTrack->mBufferProvider;
2945 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002946 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002947#ifdef AUDIO_WATCHDOG
2948 if (mAudioWatchdog != 0) {
2949 mAudioWatchdog->requestExit();
2950 mAudioWatchdog->requestExitAndWait();
2951 mAudioWatchdog.clear();
2952 }
2953#endif
2954 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002955 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002956 delete mAudioMixer;
2957}
2958
2959
2960uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2961{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002962 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002963 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2964 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2965 }
2966 return latency;
2967}
2968
2969
2970void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2971{
2972 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2973}
2974
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002976{
2977 // FIXME we should only do one push per cycle; confirm this is true
2978 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002979 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002980 FastMixerStateQueue *sq = mFastMixer->sq();
2981 FastMixerState *state = sq->begin();
2982 if (state->mCommand != FastMixerState::MIX_WRITE &&
2983 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2984 if (state->mCommand == FastMixerState::COLD_IDLE) {
2985 int32_t old = android_atomic_inc(&mFastMixerFutex);
2986 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002987 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002988 }
2989#ifdef AUDIO_WATCHDOG
2990 if (mAudioWatchdog != 0) {
2991 mAudioWatchdog->resume();
2992 }
2993#endif
2994 }
2995 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002996 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2997 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002998 sq->end();
2999 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3000 if (kUseFastMixer == FastMixer_Dynamic) {
3001 mNormalSink = mPipeSink;
3002 }
3003 } else {
3004 sq->end(false /*didModify*/);
3005 }
3006 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003007 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003008}
3009
3010void AudioFlinger::MixerThread::threadLoop_standby()
3011{
3012 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003013 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003014 FastMixerStateQueue *sq = mFastMixer->sq();
3015 FastMixerState *state = sq->begin();
3016 if (!(state->mCommand & FastMixerState::IDLE)) {
3017 state->mCommand = FastMixerState::COLD_IDLE;
3018 state->mColdFutexAddr = &mFastMixerFutex;
3019 state->mColdGen++;
3020 mFastMixerFutex = 0;
3021 sq->end();
3022 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3023 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3024 if (kUseFastMixer == FastMixer_Dynamic) {
3025 mNormalSink = mOutputSink;
3026 }
3027#ifdef AUDIO_WATCHDOG
3028 if (mAudioWatchdog != 0) {
3029 mAudioWatchdog->pause();
3030 }
3031#endif
3032 } else {
3033 sq->end(false /*didModify*/);
3034 }
3035 }
3036 PlaybackThread::threadLoop_standby();
3037}
3038
Eric Laurentbfb1b832013-01-07 09:53:42 -08003039bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3040{
3041 return false;
3042}
3043
3044bool AudioFlinger::PlaybackThread::shouldStandby_l()
3045{
3046 return !mStandby;
3047}
3048
3049bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3050{
3051 Mutex::Autolock _l(mLock);
3052 return waitingAsyncCallback_l();
3053}
3054
Eric Laurent81784c32012-11-19 14:55:58 -08003055// shared by MIXER and DIRECT, overridden by DUPLICATING
3056void AudioFlinger::PlaybackThread::threadLoop_standby()
3057{
3058 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3059 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003061 // discard any pending drain or write ack by incrementing sequence
3062 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3063 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003064 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003065 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3066 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003067 }
Eric Laurent81784c32012-11-19 14:55:58 -08003068}
3069
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003070void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3071{
3072 ALOGV("signal playback thread");
3073 broadcast_l();
3074}
3075
Eric Laurent81784c32012-11-19 14:55:58 -08003076void AudioFlinger::MixerThread::threadLoop_mix()
3077{
3078 // obtain the presentation timestamp of the next output buffer
3079 int64_t pts;
3080 status_t status = INVALID_OPERATION;
3081
3082 if (mNormalSink != 0) {
3083 status = mNormalSink->getNextWriteTimestamp(&pts);
3084 } else {
3085 status = mOutputSink->getNextWriteTimestamp(&pts);
3086 }
3087
3088 if (status != NO_ERROR) {
3089 pts = AudioBufferProvider::kInvalidPTS;
3090 }
3091
3092 // mix buffers...
3093 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003094 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003095 // increase sleep time progressively when application underrun condition clears.
3096 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3097 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3098 // such that we would underrun the audio HAL.
3099 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3100 sleepTimeShift--;
3101 }
3102 sleepTime = 0;
3103 standbyTime = systemTime() + standbyDelay;
3104 //TODO: delay standby when effects have a tail
3105}
3106
3107void AudioFlinger::MixerThread::threadLoop_sleepTime()
3108{
3109 // If no tracks are ready, sleep once for the duration of an output
3110 // buffer size, then write 0s to the output
3111 if (sleepTime == 0) {
3112 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3113 sleepTime = activeSleepTime >> sleepTimeShift;
3114 if (sleepTime < kMinThreadSleepTimeUs) {
3115 sleepTime = kMinThreadSleepTimeUs;
3116 }
3117 // reduce sleep time in case of consecutive application underruns to avoid
3118 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3119 // duration we would end up writing less data than needed by the audio HAL if
3120 // the condition persists.
3121 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3122 sleepTimeShift++;
3123 }
3124 } else {
3125 sleepTime = idleSleepTime;
3126 }
3127 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003128 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3129 // before effects processing or output.
3130 if (mMixerBufferValid) {
3131 memset(mMixerBuffer, 0, mMixerBufferSize);
3132 } else {
3133 memset(mSinkBuffer, 0, mSinkBufferSize);
3134 }
Eric Laurent81784c32012-11-19 14:55:58 -08003135 sleepTime = 0;
3136 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3137 "anticipated start");
3138 }
3139 // TODO add standby time extension fct of effect tail
3140}
3141
3142// prepareTracks_l() must be called with ThreadBase::mLock held
3143AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3144 Vector< sp<Track> > *tracksToRemove)
3145{
3146
3147 mixer_state mixerStatus = MIXER_IDLE;
3148 // find out which tracks need to be processed
3149 size_t count = mActiveTracks.size();
3150 size_t mixedTracks = 0;
3151 size_t tracksWithEffect = 0;
3152 // counts only _active_ fast tracks
3153 size_t fastTracks = 0;
3154 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3155
3156 float masterVolume = mMasterVolume;
3157 bool masterMute = mMasterMute;
3158
3159 if (masterMute) {
3160 masterVolume = 0;
3161 }
3162 // Delegate master volume control to effect in output mix effect chain if needed
3163 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3164 if (chain != 0) {
3165 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3166 chain->setVolume_l(&v, &v);
3167 masterVolume = (float)((v + (1 << 23)) >> 24);
3168 chain.clear();
3169 }
3170
3171 // prepare a new state to push
3172 FastMixerStateQueue *sq = NULL;
3173 FastMixerState *state = NULL;
3174 bool didModify = false;
3175 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003176 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003177 sq = mFastMixer->sq();
3178 state = sq->begin();
3179 }
3180
Andy Hung69aed5f2014-02-25 17:24:40 -08003181 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003182 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003183
Eric Laurent81784c32012-11-19 14:55:58 -08003184 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003185 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003186 if (t == 0) {
3187 continue;
3188 }
3189
3190 // this const just means the local variable doesn't change
3191 Track* const track = t.get();
3192
3193 // process fast tracks
3194 if (track->isFastTrack()) {
3195
3196 // It's theoretically possible (though unlikely) for a fast track to be created
3197 // and then removed within the same normal mix cycle. This is not a problem, as
3198 // the track never becomes active so it's fast mixer slot is never touched.
3199 // The converse, of removing an (active) track and then creating a new track
3200 // at the identical fast mixer slot within the same normal mix cycle,
3201 // is impossible because the slot isn't marked available until the end of each cycle.
3202 int j = track->mFastIndex;
3203 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3204 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3205 FastTrack *fastTrack = &state->mFastTracks[j];
3206
3207 // Determine whether the track is currently in underrun condition,
3208 // and whether it had a recent underrun.
3209 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3210 FastTrackUnderruns underruns = ftDump->mUnderruns;
3211 uint32_t recentFull = (underruns.mBitFields.mFull -
3212 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3213 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3214 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3215 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3216 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3217 uint32_t recentUnderruns = recentPartial + recentEmpty;
3218 track->mObservedUnderruns = underruns;
3219 // don't count underruns that occur while stopping or pausing
3220 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003221 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3222 recentUnderruns > 0) {
3223 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3224 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003225 }
3226
3227 // This is similar to the state machine for normal tracks,
3228 // with a few modifications for fast tracks.
3229 bool isActive = true;
3230 switch (track->mState) {
3231 case TrackBase::STOPPING_1:
3232 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003234 track->mState = TrackBase::STOPPING_2;
3235 }
3236 break;
3237 case TrackBase::PAUSING:
3238 // ramp down is not yet implemented
3239 track->setPaused();
3240 break;
3241 case TrackBase::RESUMING:
3242 // ramp up is not yet implemented
3243 track->mState = TrackBase::ACTIVE;
3244 break;
3245 case TrackBase::ACTIVE:
3246 if (recentFull > 0 || recentPartial > 0) {
3247 // track has provided at least some frames recently: reset retry count
3248 track->mRetryCount = kMaxTrackRetries;
3249 }
3250 if (recentUnderruns == 0) {
3251 // no recent underruns: stay active
3252 break;
3253 }
3254 // there has recently been an underrun of some kind
3255 if (track->sharedBuffer() == 0) {
3256 // were any of the recent underruns "empty" (no frames available)?
3257 if (recentEmpty == 0) {
3258 // no, then ignore the partial underruns as they are allowed indefinitely
3259 break;
3260 }
3261 // there has recently been an "empty" underrun: decrement the retry counter
3262 if (--(track->mRetryCount) > 0) {
3263 break;
3264 }
3265 // indicate to client process that the track was disabled because of underrun;
3266 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003267 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003268 // remove from active list, but state remains ACTIVE [confusing but true]
3269 isActive = false;
3270 break;
3271 }
3272 // fall through
3273 case TrackBase::STOPPING_2:
3274 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003275 case TrackBase::STOPPED:
3276 case TrackBase::FLUSHED: // flush() while active
3277 // Check for presentation complete if track is inactive
3278 // We have consumed all the buffers of this track.
3279 // This would be incomplete if we auto-paused on underrun
3280 {
3281 size_t audioHALFrames =
3282 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3283 size_t framesWritten = mBytesWritten / mFrameSize;
3284 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3285 // track stays in active list until presentation is complete
3286 break;
3287 }
3288 }
3289 if (track->isStopping_2()) {
3290 track->mState = TrackBase::STOPPED;
3291 }
3292 if (track->isStopped()) {
3293 // Can't reset directly, as fast mixer is still polling this track
3294 // track->reset();
3295 // So instead mark this track as needing to be reset after push with ack
3296 resetMask |= 1 << i;
3297 }
3298 isActive = false;
3299 break;
3300 case TrackBase::IDLE:
3301 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003302 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003303 }
3304
3305 if (isActive) {
3306 // was it previously inactive?
3307 if (!(state->mTrackMask & (1 << j))) {
3308 ExtendedAudioBufferProvider *eabp = track;
3309 VolumeProvider *vp = track;
3310 fastTrack->mBufferProvider = eabp;
3311 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003312 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003313 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003314 fastTrack->mGeneration++;
3315 state->mTrackMask |= 1 << j;
3316 didModify = true;
3317 // no acknowledgement required for newly active tracks
3318 }
3319 // cache the combined master volume and stream type volume for fast mixer; this
3320 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003321 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003322 ++fastTracks;
3323 } else {
3324 // was it previously active?
3325 if (state->mTrackMask & (1 << j)) {
3326 fastTrack->mBufferProvider = NULL;
3327 fastTrack->mGeneration++;
3328 state->mTrackMask &= ~(1 << j);
3329 didModify = true;
3330 // If any fast tracks were removed, we must wait for acknowledgement
3331 // because we're about to decrement the last sp<> on those tracks.
3332 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3333 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003334 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003335 }
3336 tracksToRemove->add(track);
3337 // Avoids a misleading display in dumpsys
3338 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3339 }
3340 continue;
3341 }
3342
3343 { // local variable scope to avoid goto warning
3344
3345 audio_track_cblk_t* cblk = track->cblk();
3346
3347 // The first time a track is added we wait
3348 // for all its buffers to be filled before processing it
3349 int name = track->name();
3350 // make sure that we have enough frames to mix one full buffer.
3351 // enforce this condition only once to enable draining the buffer in case the client
3352 // app does not call stop() and relies on underrun to stop:
3353 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3354 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003355 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003356 uint32_t sr = track->sampleRate();
3357 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003358 desiredFrames = mNormalFrameCount;
3359 } else {
3360 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003361 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003362 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003363 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003364 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003365#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003366 // the minimum track buffer size is normally twice the number of frames necessary
3367 // to fill one buffer and the resampler should not leave more than one buffer worth
3368 // of unreleased frames after each pass, but just in case...
3369 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003370#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003371 }
Eric Laurent81784c32012-11-19 14:55:58 -08003372 uint32_t minFrames = 1;
3373 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3374 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003375 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003377
3378 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003379 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003380 !track->isPaused() && !track->isTerminated())
3381 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003382 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003383
3384 mixedTracks++;
3385
Andy Hung69aed5f2014-02-25 17:24:40 -08003386 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3387 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003388 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003389 if (track->mainBuffer() != mSinkBuffer &&
3390 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003391 if (mEffectBufferEnabled) {
3392 mEffectBufferValid = true; // Later can set directly.
3393 }
Eric Laurent81784c32012-11-19 14:55:58 -08003394 chain = getEffectChain_l(track->sessionId());
3395 // Delegate volume control to effect in track effect chain if needed
3396 if (chain != 0) {
3397 tracksWithEffect++;
3398 } else {
3399 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3400 "session %d",
3401 name, track->sessionId());
3402 }
3403 }
3404
3405
3406 int param = AudioMixer::VOLUME;
3407 if (track->mFillingUpStatus == Track::FS_FILLED) {
3408 // no ramp for the first volume setting
3409 track->mFillingUpStatus = Track::FS_ACTIVE;
3410 if (track->mState == TrackBase::RESUMING) {
3411 track->mState = TrackBase::ACTIVE;
3412 param = AudioMixer::RAMP_VOLUME;
3413 }
3414 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003415 // FIXME should not make a decision based on mServer
3416 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003417 // If the track is stopped before the first frame was mixed,
3418 // do not apply ramp
3419 param = AudioMixer::RAMP_VOLUME;
3420 }
3421
3422 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003423 uint32_t vl, vr; // in U8.24 integer format
3424 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003425 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003426 vl = vr = 0;
3427 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003428 if (track->isPausing()) {
3429 track->setPaused();
3430 }
3431 } else {
3432
3433 // read original volumes with volume control
3434 float typeVolume = mStreamTypes[track->streamType()].volume;
3435 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003436 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003437 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003438 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3439 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003440 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003441 if (vlf > GAIN_FLOAT_UNITY) {
3442 ALOGV("Track left volume out of range: %.3g", vlf);
3443 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003444 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003445 if (vrf > GAIN_FLOAT_UNITY) {
3446 ALOGV("Track right volume out of range: %.3g", vrf);
3447 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003448 }
3449 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003450 vlf *= v;
3451 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003452 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003453 // then derive vl and vr as U8.24 versions for the effect chain
3454 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3455 vl = (uint32_t) (scaleto8_24 * vlf);
3456 vr = (uint32_t) (scaleto8_24 * vrf);
3457 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003458 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003459 // send level comes from shared memory and so may be corrupt
3460 if (sendLevel > MAX_GAIN_INT) {
3461 ALOGV("Track send level out of range: %04X", sendLevel);
3462 sendLevel = MAX_GAIN_INT;
3463 }
Andy Hung6be49402014-05-30 10:42:03 -07003464 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3465 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003467
Eric Laurent81784c32012-11-19 14:55:58 -08003468 // Delegate volume control to effect in track effect chain if needed
3469 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3470 // Do not ramp volume if volume is controlled by effect
3471 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003472 // Update remaining floating point volume levels
3473 vlf = (float)vl / (1 << 24);
3474 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 track->mHasVolumeController = true;
3476 } else {
3477 // force no volume ramp when volume controller was just disabled or removed
3478 // from effect chain to avoid volume spike
3479 if (track->mHasVolumeController) {
3480 param = AudioMixer::VOLUME;
3481 }
3482 track->mHasVolumeController = false;
3483 }
3484
Eric Laurent81784c32012-11-19 14:55:58 -08003485 // XXX: these things DON'T need to be done each time
3486 mAudioMixer->setBufferProvider(name, track);
3487 mAudioMixer->enable(name);
3488
Andy Hung6be49402014-05-30 10:42:03 -07003489 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3490 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3491 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003492 mAudioMixer->setParameter(
3493 name,
3494 AudioMixer::TRACK,
3495 AudioMixer::FORMAT, (void *)track->format());
3496 mAudioMixer->setParameter(
3497 name,
3498 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003499 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003500 mAudioMixer->setParameter(
3501 name,
3502 AudioMixer::TRACK,
3503 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003504 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003505 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003506 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003507 if (reqSampleRate == 0) {
3508 reqSampleRate = mSampleRate;
3509 } else if (reqSampleRate > maxSampleRate) {
3510 reqSampleRate = maxSampleRate;
3511 }
Eric Laurent81784c32012-11-19 14:55:58 -08003512 mAudioMixer->setParameter(
3513 name,
3514 AudioMixer::RESAMPLE,
3515 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003516 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003517 /*
3518 * Select the appropriate output buffer for the track.
3519 *
Andy Hung98ef9782014-03-04 14:46:50 -08003520 * Tracks with effects go into their own effects chain buffer
3521 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003522 *
3523 * Other tracks can use mMixerBuffer for higher precision
3524 * channel accumulation. If this buffer is enabled
3525 * (mMixerBufferEnabled true), then selected tracks will accumulate
3526 * into it.
3527 *
3528 */
3529 if (mMixerBufferEnabled
3530 && (track->mainBuffer() == mSinkBuffer
3531 || track->mainBuffer() == mMixerBuffer)) {
3532 mAudioMixer->setParameter(
3533 name,
3534 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003535 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003536 mAudioMixer->setParameter(
3537 name,
3538 AudioMixer::TRACK,
3539 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3540 // TODO: override track->mainBuffer()?
3541 mMixerBufferValid = true;
3542 } else {
3543 mAudioMixer->setParameter(
3544 name,
3545 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003546 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003547 mAudioMixer->setParameter(
3548 name,
3549 AudioMixer::TRACK,
3550 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3551 }
Eric Laurent81784c32012-11-19 14:55:58 -08003552 mAudioMixer->setParameter(
3553 name,
3554 AudioMixer::TRACK,
3555 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3556
3557 // reset retry count
3558 track->mRetryCount = kMaxTrackRetries;
3559
3560 // If one track is ready, set the mixer ready if:
3561 // - the mixer was not ready during previous round OR
3562 // - no other track is not ready
3563 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3564 mixerStatus != MIXER_TRACKS_ENABLED) {
3565 mixerStatus = MIXER_TRACKS_READY;
3566 }
3567 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003568 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003569 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003570 }
Eric Laurent81784c32012-11-19 14:55:58 -08003571 // clear effect chain input buffer if an active track underruns to avoid sending
3572 // previous audio buffer again to effects
3573 chain = getEffectChain_l(track->sessionId());
3574 if (chain != 0) {
3575 chain->clearInputBuffer();
3576 }
3577
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003578 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003579 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3580 track->isStopped() || track->isPaused()) {
3581 // We have consumed all the buffers of this track.
3582 // Remove it from the list of active tracks.
3583 // TODO: use actual buffer filling status instead of latency when available from
3584 // audio HAL
3585 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3586 size_t framesWritten = mBytesWritten / mFrameSize;
3587 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3588 if (track->isStopped()) {
3589 track->reset();
3590 }
3591 tracksToRemove->add(track);
3592 }
3593 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // No buffers for this track. Give it a few chances to
3595 // fill a buffer, then remove it from active list.
3596 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003597 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003598 tracksToRemove->add(track);
3599 // indicate to client process that the track was disabled because of underrun;
3600 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003601 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // If one track is not ready, mark the mixer also not ready if:
3603 // - the mixer was ready during previous round OR
3604 // - no other track is ready
3605 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3606 mixerStatus != MIXER_TRACKS_READY) {
3607 mixerStatus = MIXER_TRACKS_ENABLED;
3608 }
3609 }
3610 mAudioMixer->disable(name);
3611 }
3612
3613 } // local variable scope to avoid goto warning
3614track_is_ready: ;
3615
3616 }
3617
3618 // Push the new FastMixer state if necessary
3619 bool pauseAudioWatchdog = false;
3620 if (didModify) {
3621 state->mFastTracksGen++;
3622 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3623 if (kUseFastMixer == FastMixer_Dynamic &&
3624 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3625 state->mCommand = FastMixerState::COLD_IDLE;
3626 state->mColdFutexAddr = &mFastMixerFutex;
3627 state->mColdGen++;
3628 mFastMixerFutex = 0;
3629 if (kUseFastMixer == FastMixer_Dynamic) {
3630 mNormalSink = mOutputSink;
3631 }
3632 // If we go into cold idle, need to wait for acknowledgement
3633 // so that fast mixer stops doing I/O.
3634 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3635 pauseAudioWatchdog = true;
3636 }
Eric Laurent81784c32012-11-19 14:55:58 -08003637 }
3638 if (sq != NULL) {
3639 sq->end(didModify);
3640 sq->push(block);
3641 }
3642#ifdef AUDIO_WATCHDOG
3643 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3644 mAudioWatchdog->pause();
3645 }
3646#endif
3647
3648 // Now perform the deferred reset on fast tracks that have stopped
3649 while (resetMask != 0) {
3650 size_t i = __builtin_ctz(resetMask);
3651 ALOG_ASSERT(i < count);
3652 resetMask &= ~(1 << i);
3653 sp<Track> t = mActiveTracks[i].promote();
3654 if (t == 0) {
3655 continue;
3656 }
3657 Track* track = t.get();
3658 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3659 track->reset();
3660 }
3661
3662 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003663 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003664
Andy Hung69aed5f2014-02-25 17:24:40 -08003665 // sink or mix buffer must be cleared if all tracks are connected to an
3666 // effect chain as in this case the mixer will not write to the sink or mix buffer
3667 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3669 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003670 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003671 if (mMixerBufferValid) {
3672 memset(mMixerBuffer, 0, mMixerBufferSize);
3673 // TODO: In testing, mSinkBuffer below need not be cleared because
3674 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3675 // after mixing.
3676 //
3677 // To enforce this guarantee:
3678 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3679 // (mixedTracks == 0 && fastTracks > 0))
3680 // must imply MIXER_TRACKS_READY.
3681 // Later, we may clear buffers regardless, and skip much of this logic.
3682 }
Andy Hung98ef9782014-03-04 14:46:50 -08003683 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3684 if (mEffectBufferValid) {
3685 memset(mEffectBuffer, 0, mEffectBufferSize);
3686 }
3687 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003688 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003689 }
3690
3691 // if any fast tracks, then status is ready
3692 mMixerStatusIgnoringFastTracks = mixerStatus;
3693 if (fastTracks > 0) {
3694 mixerStatus = MIXER_TRACKS_READY;
3695 }
3696 return mixerStatus;
3697}
3698
3699// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003700int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3701 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003702{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003703 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003704}
3705
3706// deleteTrackName_l() must be called with ThreadBase::mLock held
3707void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3708{
3709 ALOGV("remove track (%d) and delete from mixer", name);
3710 mAudioMixer->deleteTrackName(name);
3711}
3712
Eric Laurent10351942014-05-08 18:49:52 -07003713// checkForNewParameter_l() must be called with ThreadBase::mLock held
3714bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3715 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003716{
Eric Laurent81784c32012-11-19 14:55:58 -08003717 bool reconfig = false;
3718
Eric Laurent10351942014-05-08 18:49:52 -07003719 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003720
Eric Laurent10351942014-05-08 18:49:52 -07003721 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3722 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003723 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003724 FastMixerStateQueue *sq = mFastMixer->sq();
3725 FastMixerState *state = sq->begin();
3726 if (!(state->mCommand & FastMixerState::IDLE)) {
3727 previousCommand = state->mCommand;
3728 state->mCommand = FastMixerState::HOT_IDLE;
3729 sq->end();
3730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3731 } else {
3732 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003733 }
Eric Laurent10351942014-05-08 18:49:52 -07003734 }
Eric Laurent81784c32012-11-19 14:55:58 -08003735
Eric Laurent10351942014-05-08 18:49:52 -07003736 AudioParameter param = AudioParameter(keyValuePair);
3737 int value;
3738 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3739 reconfig = true;
3740 }
3741 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003742 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003743 status = BAD_VALUE;
3744 } else {
3745 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003746 reconfig = true;
3747 }
Eric Laurent10351942014-05-08 18:49:52 -07003748 }
3749 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003750 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003751 status = BAD_VALUE;
3752 } else {
3753 // no need to save value, since it's constant
3754 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003755 }
Eric Laurent10351942014-05-08 18:49:52 -07003756 }
3757 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3758 // do not accept frame count changes if tracks are open as the track buffer
3759 // size depends on frame count and correct behavior would not be guaranteed
3760 // if frame count is changed after track creation
3761 if (!mTracks.isEmpty()) {
3762 status = INVALID_OPERATION;
3763 } else {
3764 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
Eric Laurent10351942014-05-08 18:49:52 -07003766 }
3767 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003768#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003769 // when changing the audio output device, call addBatteryData to notify
3770 // the change
3771 if (mOutDevice != value) {
3772 uint32_t params = 0;
3773 // check whether speaker is on
3774 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3775 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003776 }
Eric Laurent10351942014-05-08 18:49:52 -07003777
3778 audio_devices_t deviceWithoutSpeaker
3779 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3780 // check if any other device (except speaker) is on
3781 if (value & deviceWithoutSpeaker ) {
3782 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3783 }
3784
3785 if (params != 0) {
3786 addBatteryData(params);
3787 }
3788 }
Eric Laurent81784c32012-11-19 14:55:58 -08003789#endif
3790
Eric Laurent10351942014-05-08 18:49:52 -07003791 // forward device change to effects that have requested to be
3792 // aware of attached audio device.
3793 if (value != AUDIO_DEVICE_NONE) {
3794 mOutDevice = value;
3795 for (size_t i = 0; i < mEffectChains.size(); i++) {
3796 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003797 }
3798 }
Eric Laurent10351942014-05-08 18:49:52 -07003799 }
Eric Laurent81784c32012-11-19 14:55:58 -08003800
Eric Laurent10351942014-05-08 18:49:52 -07003801 if (status == NO_ERROR) {
3802 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3803 keyValuePair.string());
3804 if (!mStandby && status == INVALID_OPERATION) {
3805 mOutput->stream->common.standby(&mOutput->stream->common);
3806 mStandby = true;
3807 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003808 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003809 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003810 }
Eric Laurent10351942014-05-08 18:49:52 -07003811 if (status == NO_ERROR && reconfig) {
3812 readOutputParameters_l();
3813 delete mAudioMixer;
3814 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3815 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003816 int name = getTrackName_l(mTracks[i]->mChannelMask,
3817 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003818 if (name < 0) {
3819 break;
3820 }
3821 mTracks[i]->mName = name;
3822 }
3823 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3824 }
Eric Laurent81784c32012-11-19 14:55:58 -08003825 }
3826
3827 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003828 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003829 FastMixerStateQueue *sq = mFastMixer->sq();
3830 FastMixerState *state = sq->begin();
3831 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3832 state->mCommand = previousCommand;
3833 sq->end();
3834 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3835 }
3836
3837 return reconfig;
3838}
3839
3840
3841void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3842{
3843 const size_t SIZE = 256;
3844 char buffer[SIZE];
3845 String8 result;
3846
3847 PlaybackThread::dumpInternals(fd, args);
3848
Elliott Hughes87cebad2014-05-22 10:14:43 -07003849 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003850
3851 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003852 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003853 copy.dump(fd);
3854
3855#ifdef STATE_QUEUE_DUMP
3856 // Similar for state queue
3857 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3858 observerCopy.dump(fd);
3859 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3860 mutatorCopy.dump(fd);
3861#endif
3862
Glenn Kasten46909e72013-02-26 09:20:22 -08003863#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003864 // Write the tee output to a .wav file
3865 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003866#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003867
3868#ifdef AUDIO_WATCHDOG
3869 if (mAudioWatchdog != 0) {
3870 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3871 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3872 wdCopy.dump(fd);
3873 }
3874#endif
3875}
3876
3877uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3878{
3879 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3880}
3881
3882uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3883{
3884 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3885}
3886
3887void AudioFlinger::MixerThread::cacheParameters_l()
3888{
3889 PlaybackThread::cacheParameters_l();
3890
3891 // FIXME: Relaxed timing because of a certain device that can't meet latency
3892 // Should be reduced to 2x after the vendor fixes the driver issue
3893 // increase threshold again due to low power audio mode. The way this warning
3894 // threshold is calculated and its usefulness should be reconsidered anyway.
3895 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3896}
3897
3898// ----------------------------------------------------------------------------
3899
3900AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3901 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3902 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3903 // mLeftVolFloat, mRightVolFloat
3904{
3905}
3906
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3908 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3909 ThreadBase::type_t type)
3910 : PlaybackThread(audioFlinger, output, id, device, type)
3911 // mLeftVolFloat, mRightVolFloat
3912{
3913}
3914
Eric Laurent81784c32012-11-19 14:55:58 -08003915AudioFlinger::DirectOutputThread::~DirectOutputThread()
3916{
3917}
3918
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3920{
3921 audio_track_cblk_t* cblk = track->cblk();
3922 float left, right;
3923
3924 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3925 left = right = 0;
3926 } else {
3927 float typeVolume = mStreamTypes[track->streamType()].volume;
3928 float v = mMasterVolume * typeVolume;
3929 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003930 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3931 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3932 if (left > GAIN_FLOAT_UNITY) {
3933 left = GAIN_FLOAT_UNITY;
3934 }
3935 left *= v;
3936 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3937 if (right > GAIN_FLOAT_UNITY) {
3938 right = GAIN_FLOAT_UNITY;
3939 }
3940 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 }
3942
3943 if (lastTrack) {
3944 if (left != mLeftVolFloat || right != mRightVolFloat) {
3945 mLeftVolFloat = left;
3946 mRightVolFloat = right;
3947
3948 // Convert volumes from float to 8.24
3949 uint32_t vl = (uint32_t)(left * (1 << 24));
3950 uint32_t vr = (uint32_t)(right * (1 << 24));
3951
3952 // Delegate volume control to effect in track effect chain if needed
3953 // only one effect chain can be present on DirectOutputThread, so if
3954 // there is one, the track is connected to it
3955 if (!mEffectChains.isEmpty()) {
3956 mEffectChains[0]->setVolume_l(&vl, &vr);
3957 left = (float)vl / (1 << 24);
3958 right = (float)vr / (1 << 24);
3959 }
3960 if (mOutput->stream->set_volume) {
3961 mOutput->stream->set_volume(mOutput->stream, left, right);
3962 }
3963 }
3964 }
3965}
3966
3967
Eric Laurent81784c32012-11-19 14:55:58 -08003968AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3969 Vector< sp<Track> > *tracksToRemove
3970)
3971{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003972 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003973 mixer_state mixerStatus = MIXER_IDLE;
3974
3975 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003976 for (size_t i = 0; i < count; i++) {
3977 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003978 // The track died recently
3979 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003980 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003981 }
3982
3983 Track* const track = t.get();
3984 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003985 // Only consider last track started for volume and mixer state control.
3986 // In theory an older track could underrun and restart after the new one starts
3987 // but as we only care about the transition phase between two tracks on a
3988 // direct output, it is not a problem to ignore the underrun case.
3989 sp<Track> l = mLatestActiveTrack.promote();
3990 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003991
3992 // The first time a track is added we wait
3993 // for all its buffers to be filled before processing it
3994 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07003995 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003996 minFrames = mNormalFrameCount;
3997 } else {
3998 minFrames = 1;
3999 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004000
Eric Laurentab5cdba2014-06-09 17:22:27 -07004001 ALOGI("prepareTracks_l minFrames %d state %d frames ready %d, ",
4002 minFrames, track->mState, track->framesReady());
4003 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4004 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004005 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004006 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004007
4008 if (track->mFillingUpStatus == Track::FS_FILLED) {
4009 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004010 // make sure processVolume_l() will apply new volume even if 0
4011 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004012 if (track->mState == TrackBase::RESUMING) {
4013 track->mState = TrackBase::ACTIVE;
4014 }
4015 }
4016
4017 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004018 processVolume_l(track, last);
4019 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004020 // reset retry count
4021 track->mRetryCount = kMaxTrackRetriesDirect;
4022 mActiveTrack = t;
4023 mixerStatus = MIXER_TRACKS_READY;
4024 }
Eric Laurent81784c32012-11-19 14:55:58 -08004025 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004026 // clear effect chain input buffer if the last active track started underruns
4027 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004028 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004029 mEffectChains[0]->clearInputBuffer();
4030 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004031 if (track->isStopping_1()) {
4032 track->mState = TrackBase::STOPPING_2;
4033 }
4034 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4035 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004036 // We have consumed all the buffers of this track.
4037 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004038 size_t audioHALFrames;
4039 if (audio_is_linear_pcm(mFormat)) {
4040 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4041 } else {
4042 audioHALFrames = 0;
4043 }
4044
Eric Laurent81784c32012-11-19 14:55:58 -08004045 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004046 if (mStandby || !last ||
4047 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004048 if (track->isStopping_2()) {
4049 track->mState = TrackBase::STOPPED;
4050 }
Eric Laurent81784c32012-11-19 14:55:58 -08004051 if (track->isStopped()) {
4052 track->reset();
4053 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004054 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004055 }
4056 } else {
4057 // No buffers for this track. Give it a few chances to
4058 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004059 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004060 if (--(track->mRetryCount) <= 0) {
4061 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004062 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004063 // indicate to client process that the track was disabled because of underrun;
4064 // it will then automatically call start() when data is available
4065 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004066 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004067 mixerStatus = MIXER_TRACKS_ENABLED;
4068 }
4069 }
4070 }
4071 }
4072
Eric Laurent81784c32012-11-19 14:55:58 -08004073 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004074 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004075
4076 return mixerStatus;
4077}
4078
4079void AudioFlinger::DirectOutputThread::threadLoop_mix()
4080{
Eric Laurent81784c32012-11-19 14:55:58 -08004081 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004082 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004083 // output audio to hardware
4084 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004085 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004086 buffer.frameCount = frameCount;
4087 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004088 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004089 memset(curBuf, 0, frameCount * mFrameSize);
4090 break;
4091 }
4092 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4093 frameCount -= buffer.frameCount;
4094 curBuf += buffer.frameCount * mFrameSize;
4095 mActiveTrack->releaseBuffer(&buffer);
4096 }
Andy Hung2098f272014-02-27 14:00:06 -08004097 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 sleepTime = 0;
4099 standbyTime = systemTime() + standbyDelay;
4100 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004101}
4102
4103void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4104{
4105 if (sleepTime == 0) {
4106 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4107 sleepTime = activeSleepTime;
4108 } else {
4109 sleepTime = idleSleepTime;
4110 }
4111 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004112 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004113 sleepTime = 0;
4114 }
4115}
4116
4117// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004118int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004119 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004120{
4121 return 0;
4122}
4123
4124// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004125void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004126{
4127}
4128
Eric Laurent10351942014-05-08 18:49:52 -07004129// checkForNewParameter_l() must be called with ThreadBase::mLock held
4130bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4131 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004132{
4133 bool reconfig = false;
4134
Eric Laurent10351942014-05-08 18:49:52 -07004135 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004136
Eric Laurent10351942014-05-08 18:49:52 -07004137 AudioParameter param = AudioParameter(keyValuePair);
4138 int value;
4139 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4140 // forward device change to effects that have requested to be
4141 // aware of attached audio device.
4142 if (value != AUDIO_DEVICE_NONE) {
4143 mOutDevice = value;
4144 for (size_t i = 0; i < mEffectChains.size(); i++) {
4145 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004146 }
4147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148 }
Eric Laurent10351942014-05-08 18:49:52 -07004149 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4150 // do not accept frame count changes if tracks are open as the track buffer
4151 // size depends on frame count and correct behavior would not be garantied
4152 // if frame count is changed after track creation
4153 if (!mTracks.isEmpty()) {
4154 status = INVALID_OPERATION;
4155 } else {
4156 reconfig = true;
4157 }
4158 }
4159 if (status == NO_ERROR) {
4160 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4161 keyValuePair.string());
4162 if (!mStandby && status == INVALID_OPERATION) {
4163 mOutput->stream->common.standby(&mOutput->stream->common);
4164 mStandby = true;
4165 mBytesWritten = 0;
4166 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4167 keyValuePair.string());
4168 }
4169 if (status == NO_ERROR && reconfig) {
4170 readOutputParameters_l();
4171 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4172 }
4173 }
4174
Eric Laurent81784c32012-11-19 14:55:58 -08004175 return reconfig;
4176}
4177
4178uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4179{
4180 uint32_t time;
4181 if (audio_is_linear_pcm(mFormat)) {
4182 time = PlaybackThread::activeSleepTimeUs();
4183 } else {
4184 time = 10000;
4185 }
4186 return time;
4187}
4188
4189uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4190{
4191 uint32_t time;
4192 if (audio_is_linear_pcm(mFormat)) {
4193 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4194 } else {
4195 time = 10000;
4196 }
4197 return time;
4198}
4199
4200uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4201{
4202 uint32_t time;
4203 if (audio_is_linear_pcm(mFormat)) {
4204 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4205 } else {
4206 time = 10000;
4207 }
4208 return time;
4209}
4210
4211void AudioFlinger::DirectOutputThread::cacheParameters_l()
4212{
4213 PlaybackThread::cacheParameters_l();
4214
4215 // use shorter standby delay as on normal output to release
4216 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004217 if (audio_is_linear_pcm(mFormat)) {
4218 standbyDelay = microseconds(activeSleepTime*2);
4219 } else {
4220 standbyDelay = kOffloadStandbyDelayNs;
4221 }
Eric Laurent81784c32012-11-19 14:55:58 -08004222}
4223
4224// ----------------------------------------------------------------------------
4225
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004227 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004228 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004229 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004230 mWriteAckSequence(0),
4231 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004232{
4233}
4234
4235AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4236{
4237}
4238
4239void AudioFlinger::AsyncCallbackThread::onFirstRef()
4240{
4241 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4242}
4243
4244bool AudioFlinger::AsyncCallbackThread::threadLoop()
4245{
4246 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004247 uint32_t writeAckSequence;
4248 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249
4250 {
4251 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004252 while (!((mWriteAckSequence & 1) ||
4253 (mDrainSequence & 1) ||
4254 exitPending())) {
4255 mWaitWorkCV.wait(mLock);
4256 }
4257
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 if (exitPending()) {
4259 break;
4260 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004261 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4262 mWriteAckSequence, mDrainSequence);
4263 writeAckSequence = mWriteAckSequence;
4264 mWriteAckSequence &= ~1;
4265 drainSequence = mDrainSequence;
4266 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 }
4268 {
Eric Laurent4de95592013-09-26 15:28:21 -07004269 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4270 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004271 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004272 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004274 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004275 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276 }
4277 }
4278 }
4279 }
4280 return false;
4281}
4282
4283void AudioFlinger::AsyncCallbackThread::exit()
4284{
4285 ALOGV("AsyncCallbackThread::exit");
4286 Mutex::Autolock _l(mLock);
4287 requestExit();
4288 mWaitWorkCV.broadcast();
4289}
4290
Eric Laurent3b4529e2013-09-05 18:09:19 -07004291void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292{
4293 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004294 // bit 0 is cleared
4295 mWriteAckSequence = sequence << 1;
4296}
4297
4298void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4299{
4300 Mutex::Autolock _l(mLock);
4301 // ignore unexpected callbacks
4302 if (mWriteAckSequence & 2) {
4303 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304 mWaitWorkCV.signal();
4305 }
4306}
4307
Eric Laurent3b4529e2013-09-05 18:09:19 -07004308void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309{
4310 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004311 // bit 0 is cleared
4312 mDrainSequence = sequence << 1;
4313}
4314
4315void AudioFlinger::AsyncCallbackThread::resetDraining()
4316{
4317 Mutex::Autolock _l(mLock);
4318 // ignore unexpected callbacks
4319 if (mDrainSequence & 2) {
4320 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 mWaitWorkCV.signal();
4322 }
4323}
4324
4325
4326// ----------------------------------------------------------------------------
4327AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4328 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4329 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4330 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004331 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004332 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333{
Eric Laurentfd477972013-10-25 18:10:40 -07004334 //FIXME: mStandby should be set to true by ThreadBase constructor
4335 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336}
4337
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338void AudioFlinger::OffloadThread::threadLoop_exit()
4339{
4340 if (mFlushPending || mHwPaused) {
4341 // If a flush is pending or track was paused, just discard buffered data
4342 flushHw_l();
4343 } else {
4344 mMixerStatus = MIXER_DRAIN_ALL;
4345 threadLoop_drain();
4346 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004347 if (mUseAsyncWrite) {
4348 ALOG_ASSERT(mCallbackThread != 0);
4349 mCallbackThread->exit();
4350 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 PlaybackThread::threadLoop_exit();
4352}
4353
4354AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4355 Vector< sp<Track> > *tracksToRemove
4356)
4357{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004358 size_t count = mActiveTracks.size();
4359
4360 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004361 bool doHwPause = false;
4362 bool doHwResume = false;
4363
Eric Laurentede6c3b2013-09-19 14:37:46 -07004364 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4365
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366 // find out which tracks need to be processed
4367 for (size_t i = 0; i < count; i++) {
4368 sp<Track> t = mActiveTracks[i].promote();
4369 // The track died recently
4370 if (t == 0) {
4371 continue;
4372 }
4373 Track* const track = t.get();
4374 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004375 // Only consider last track started for volume and mixer state control.
4376 // In theory an older track could underrun and restart after the new one starts
4377 // but as we only care about the transition phase between two tracks on a
4378 // direct output, it is not a problem to ignore the underrun case.
4379 sp<Track> l = mLatestActiveTrack.promote();
4380 bool last = l.get() == track;
4381
Haynes Mathew George7844f672014-01-15 12:32:55 -08004382 if (track->isInvalid()) {
4383 ALOGW("An invalidated track shouldn't be in active list");
4384 tracksToRemove->add(track);
4385 continue;
4386 }
4387
4388 if (track->mState == TrackBase::IDLE) {
4389 ALOGW("An idle track shouldn't be in active list");
4390 continue;
4391 }
4392
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393 if (track->isPausing()) {
4394 track->setPaused();
4395 if (last) {
4396 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004397 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398 mHwPaused = true;
4399 }
4400 // If we were part way through writing the mixbuffer to
4401 // the HAL we must save this until we resume
4402 // BUG - this will be wrong if a different track is made active,
4403 // in that case we want to discard the pending data in the
4404 // mixbuffer and tell the client to present it again when the
4405 // track is resumed
4406 mPausedWriteLength = mCurrentWriteLength;
4407 mPausedBytesRemaining = mBytesRemaining;
4408 mBytesRemaining = 0; // stop writing
4409 }
4410 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004411 } else if (track->isFlushPending()) {
4412 track->flushAck();
4413 if (last) {
4414 mFlushPending = true;
4415 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004416 } else if (track->isResumePending()){
4417 track->resumeAck();
4418 if (last) {
4419 if (mPausedBytesRemaining) {
4420 // Need to continue write that was interrupted
4421 mCurrentWriteLength = mPausedWriteLength;
4422 mBytesRemaining = mPausedBytesRemaining;
4423 mPausedBytesRemaining = 0;
4424 }
4425 if (mHwPaused) {
4426 doHwResume = true;
4427 mHwPaused = false;
4428 // threadLoop_mix() will handle the case that we need to
4429 // resume an interrupted write
4430 }
4431 // enable write to audio HAL
4432 sleepTime = 0;
4433
4434 // Do not handle new data in this iteration even if track->framesReady()
4435 mixerStatus = MIXER_TRACKS_ENABLED;
4436 }
4437 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004438 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004439 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440 if (track->mFillingUpStatus == Track::FS_FILLED) {
4441 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004442 // make sure processVolume_l() will apply new volume even if 0
4443 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 }
4445
4446 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004447 sp<Track> previousTrack = mPreviousTrack.promote();
4448 if (previousTrack != 0) {
4449 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004450 // Flush any data still being written from last track
4451 mBytesRemaining = 0;
4452 if (mPausedBytesRemaining) {
4453 // Last track was paused so we also need to flush saved
4454 // mixbuffer state and invalidate track so that it will
4455 // re-submit that unwritten data when it is next resumed
4456 mPausedBytesRemaining = 0;
4457 // Invalidate is a bit drastic - would be more efficient
4458 // to have a flag to tell client that some of the
4459 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004460 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004461 }
4462 // flush data already sent to the DSP if changing audio session as audio
4463 // comes from a different source. Also invalidate previous track to force a
4464 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004465 if (previousTrack->sessionId() != track->sessionId()) {
4466 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004467 }
4468 }
4469 }
4470 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 // reset retry count
4472 track->mRetryCount = kMaxTrackRetriesOffload;
4473 mActiveTrack = t;
4474 mixerStatus = MIXER_TRACKS_READY;
4475 }
4476 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004477 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004478 if (track->isStopping_1()) {
4479 // Hardware buffer can hold a large amount of audio so we must
4480 // wait for all current track's data to drain before we say
4481 // that the track is stopped.
4482 if (mBytesRemaining == 0) {
4483 // Only start draining when all data in mixbuffer
4484 // has been written
4485 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4486 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004487 // do not drain if no data was ever sent to HAL (mStandby == true)
4488 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004489 // do not modify drain sequence if we are already draining. This happens
4490 // when resuming from pause after drain.
4491 if ((mDrainSequence & 1) == 0) {
4492 sleepTime = 0;
4493 standbyTime = systemTime() + standbyDelay;
4494 mixerStatus = MIXER_DRAIN_TRACK;
4495 mDrainSequence += 2;
4496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004497 if (mHwPaused) {
4498 // It is possible to move from PAUSED to STOPPING_1 without
4499 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004500 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004501 mHwPaused = false;
4502 }
4503 }
4504 }
4505 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004506 // Drain has completed or we are in standby, signal presentation complete
4507 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 track->mState = TrackBase::STOPPED;
4509 size_t audioHALFrames =
4510 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4511 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004512 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004513 track->presentationComplete(framesWritten, audioHALFrames);
4514 track->reset();
4515 tracksToRemove->add(track);
4516 }
4517 } else {
4518 // No buffers for this track. Give it a few chances to
4519 // fill a buffer, then remove it from active list.
4520 if (--(track->mRetryCount) <= 0) {
4521 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4522 track->name());
4523 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004524 // indicate to client process that the track was disabled because of underrun;
4525 // it will then automatically call start() when data is available
4526 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 } else if (last){
4528 mixerStatus = MIXER_TRACKS_ENABLED;
4529 }
4530 }
4531 }
4532 // compute volume for this track
4533 processVolume_l(track, last);
4534 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004535
Eric Laurentea0fade2013-10-04 16:23:48 -07004536 // make sure the pause/flush/resume sequence is executed in the right order.
4537 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4538 // before flush and then resume HW. This can happen in case of pause/flush/resume
4539 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004540 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004541 mOutput->stream->pause(mOutput->stream);
4542 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004543 if (mFlushPending) {
4544 flushHw_l();
4545 mFlushPending = false;
4546 }
Eric Laurentfd477972013-10-25 18:10:40 -07004547 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004548 mOutput->stream->resume(mOutput->stream);
4549 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004550
Eric Laurentbfb1b832013-01-07 09:53:42 -08004551 // remove all the tracks that need to be...
4552 removeTracks_l(*tracksToRemove);
4553
4554 return mixerStatus;
4555}
4556
Eric Laurentbfb1b832013-01-07 09:53:42 -08004557// must be called with thread mutex locked
4558bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4559{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004560 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4561 mWriteAckSequence, mDrainSequence);
4562 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004563 return true;
4564 }
4565 return false;
4566}
4567
4568// must be called with thread mutex locked
4569bool AudioFlinger::OffloadThread::shouldStandby_l()
4570{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004571 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004572
4573 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4574 // after a timeout and we will enter standby then.
4575 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004576 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004577 }
4578
Glenn Kastene6f35b12013-08-19 09:58:50 -07004579 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580}
4581
4582
4583bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4584{
4585 Mutex::Autolock _l(mLock);
4586 return waitingAsyncCallback_l();
4587}
4588
4589void AudioFlinger::OffloadThread::flushHw_l()
4590{
4591 mOutput->stream->flush(mOutput->stream);
4592 // Flush anything still waiting in the mixbuffer
4593 mCurrentWriteLength = 0;
4594 mBytesRemaining = 0;
4595 mPausedWriteLength = 0;
4596 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004597 mHwPaused = false;
4598
Eric Laurentbfb1b832013-01-07 09:53:42 -08004599 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004600 // discard any pending drain or write ack by incrementing sequence
4601 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4602 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004604 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4605 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004606 }
4607}
4608
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004609void AudioFlinger::OffloadThread::onAddNewTrack_l()
4610{
4611 sp<Track> previousTrack = mPreviousTrack.promote();
4612 sp<Track> latestTrack = mLatestActiveTrack.promote();
4613
4614 if (previousTrack != 0 && latestTrack != 0 &&
4615 (previousTrack->sessionId() != latestTrack->sessionId())) {
4616 mFlushPending = true;
4617 }
4618 PlaybackThread::onAddNewTrack_l();
4619}
4620
Eric Laurentbfb1b832013-01-07 09:53:42 -08004621// ----------------------------------------------------------------------------
4622
Eric Laurent81784c32012-11-19 14:55:58 -08004623AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4624 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4625 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4626 DUPLICATING),
4627 mWaitTimeMs(UINT_MAX)
4628{
4629 addOutputTrack(mainThread);
4630}
4631
4632AudioFlinger::DuplicatingThread::~DuplicatingThread()
4633{
4634 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4635 mOutputTracks[i]->destroy();
4636 }
4637}
4638
4639void AudioFlinger::DuplicatingThread::threadLoop_mix()
4640{
4641 // mix buffers...
4642 if (outputsReady(outputTracks)) {
4643 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4644 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004645 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004646 }
4647 sleepTime = 0;
4648 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004649 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004650 standbyTime = systemTime() + standbyDelay;
4651}
4652
4653void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4654{
4655 if (sleepTime == 0) {
4656 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4657 sleepTime = activeSleepTime;
4658 } else {
4659 sleepTime = idleSleepTime;
4660 }
4661 } else if (mBytesWritten != 0) {
4662 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4663 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004664 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004665 } else {
4666 // flush remaining overflow buffers in output tracks
4667 writeFrames = 0;
4668 }
4669 sleepTime = 0;
4670 }
4671}
4672
Eric Laurentbfb1b832013-01-07 09:53:42 -08004673ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004674{
4675 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004676 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4677 // for delivery downstream as needed. This in-place conversion is safe as
4678 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4679 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4680 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4681 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4682 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4683 }
4684 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004685 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004686 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004687 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004688}
4689
4690void AudioFlinger::DuplicatingThread::threadLoop_standby()
4691{
4692 // DuplicatingThread implements standby by stopping all tracks
4693 for (size_t i = 0; i < outputTracks.size(); i++) {
4694 outputTracks[i]->stop();
4695 }
4696}
4697
4698void AudioFlinger::DuplicatingThread::saveOutputTracks()
4699{
4700 outputTracks = mOutputTracks;
4701}
4702
4703void AudioFlinger::DuplicatingThread::clearOutputTracks()
4704{
4705 outputTracks.clear();
4706}
4707
4708void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4709{
4710 Mutex::Autolock _l(mLock);
4711 // FIXME explain this formula
4712 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004713 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4714 // due to current usage case and restrictions on the AudioBufferProvider.
4715 // Actual buffer conversion is done in threadLoop_write().
4716 //
4717 // TODO: This may change in the future, depending on multichannel
4718 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004719 OutputTrack *outputTrack = new OutputTrack(thread,
4720 this,
4721 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004722 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004723 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004724 frameCount,
4725 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004726 if (outputTrack->cblk() != NULL) {
4727 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4728 mOutputTracks.add(outputTrack);
4729 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4730 updateWaitTime_l();
4731 }
4732}
4733
4734void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4735{
4736 Mutex::Autolock _l(mLock);
4737 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4738 if (mOutputTracks[i]->thread() == thread) {
4739 mOutputTracks[i]->destroy();
4740 mOutputTracks.removeAt(i);
4741 updateWaitTime_l();
4742 return;
4743 }
4744 }
4745 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4746}
4747
4748// caller must hold mLock
4749void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4750{
4751 mWaitTimeMs = UINT_MAX;
4752 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4753 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4754 if (strong != 0) {
4755 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4756 if (waitTimeMs < mWaitTimeMs) {
4757 mWaitTimeMs = waitTimeMs;
4758 }
4759 }
4760 }
4761}
4762
4763
4764bool AudioFlinger::DuplicatingThread::outputsReady(
4765 const SortedVector< sp<OutputTrack> > &outputTracks)
4766{
4767 for (size_t i = 0; i < outputTracks.size(); i++) {
4768 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4769 if (thread == 0) {
4770 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4771 outputTracks[i].get());
4772 return false;
4773 }
4774 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4775 // see note at standby() declaration
4776 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4777 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4778 thread.get());
4779 return false;
4780 }
4781 }
4782 return true;
4783}
4784
4785uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4786{
4787 return (mWaitTimeMs * 1000) / 2;
4788}
4789
4790void AudioFlinger::DuplicatingThread::cacheParameters_l()
4791{
4792 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4793 updateWaitTime_l();
4794
4795 MixerThread::cacheParameters_l();
4796}
4797
4798// ----------------------------------------------------------------------------
4799// Record
4800// ----------------------------------------------------------------------------
4801
4802AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4803 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004804 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004805 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004806 audio_devices_t inDevice
4807#ifdef TEE_SINK
4808 , const sp<NBAIO_Sink>& teeSink
4809#endif
4810 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004811 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004812 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004813 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004814 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004815#ifdef TEE_SINK
4816 , mTeeSink(teeSink)
4817#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004818 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4819 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004820 // mFastCapture below
4821 , mFastCaptureFutex(0)
4822 // mInputSource
4823 // mPipeSink
4824 // mPipeSource
4825 , mPipeFramesP2(0)
4826 // mPipeMemory
4827 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004828 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004829{
4830 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004831 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004832
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004833 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004834
4835 // create an NBAIO source for the HAL input stream, and negotiate
4836 mInputSource = new AudioStreamInSource(input->stream);
4837 size_t numCounterOffers = 0;
4838 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4839 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4840 ALOG_ASSERT(index == 0);
4841
4842 // initialize fast capture depending on configuration
4843 bool initFastCapture;
4844 switch (kUseFastCapture) {
4845 case FastCapture_Never:
4846 initFastCapture = false;
4847 break;
4848 case FastCapture_Always:
4849 initFastCapture = true;
4850 break;
4851 case FastCapture_Static:
4852 uint32_t primaryOutputSampleRate;
4853 {
4854 AutoMutex _l(audioFlinger->mHardwareLock);
4855 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4856 }
4857 initFastCapture =
4858 // either capture sample rate is same as (a reasonable) primary output sample rate
4859 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4860 (mSampleRate == primaryOutputSampleRate)) ||
4861 // or primary output sample rate is unknown, and capture sample rate is reasonable
4862 ((primaryOutputSampleRate == 0) &&
4863 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004864 // and the buffer size is < 12 ms
4865 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004866 break;
4867 // case FastCapture_Dynamic:
4868 }
4869
4870 if (initFastCapture) {
4871 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4872 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004873 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004874 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4875 void *pipeBuffer;
4876 const sp<MemoryDealer> roHeap(readOnlyHeap());
4877 sp<IMemory> pipeMemory;
4878 if ((roHeap == 0) ||
4879 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4880 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4881 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4882 goto failed;
4883 }
4884 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4885 memset(pipeBuffer, 0, pipeSize);
4886 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4887 const NBAIO_Format offers[1] = {format};
4888 size_t numCounterOffers = 0;
4889 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4890 ALOG_ASSERT(index == 0);
4891 mPipeSink = pipe;
4892 PipeReader *pipeReader = new PipeReader(*pipe);
4893 numCounterOffers = 0;
4894 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4895 ALOG_ASSERT(index == 0);
4896 mPipeSource = pipeReader;
4897 mPipeFramesP2 = pipeFramesP2;
4898 mPipeMemory = pipeMemory;
4899
4900 // create fast capture
4901 mFastCapture = new FastCapture();
4902 FastCaptureStateQueue *sq = mFastCapture->sq();
4903#ifdef STATE_QUEUE_DUMP
4904 // FIXME
4905#endif
4906 FastCaptureState *state = sq->begin();
4907 state->mCblk = NULL;
4908 state->mInputSource = mInputSource.get();
4909 state->mInputSourceGen++;
4910 state->mPipeSink = pipe;
4911 state->mPipeSinkGen++;
4912 state->mFrameCount = mFrameCount;
4913 state->mCommand = FastCaptureState::COLD_IDLE;
4914 // already done in constructor initialization list
4915 //mFastCaptureFutex = 0;
4916 state->mColdFutexAddr = &mFastCaptureFutex;
4917 state->mColdGen++;
4918 state->mDumpState = &mFastCaptureDumpState;
4919#ifdef TEE_SINK
4920 // FIXME
4921#endif
4922 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4923 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4924 sq->end();
4925 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4926
4927 // start the fast capture
4928 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4929 pid_t tid = mFastCapture->getTid();
4930 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4931 if (err != 0) {
4932 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4933 kPriorityFastCapture, getpid_cached, tid, err);
4934 }
4935
4936#ifdef AUDIO_WATCHDOG
4937 // FIXME
4938#endif
4939
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004940 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004941 }
4942failed: ;
4943
4944 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004945}
4946
4947
4948AudioFlinger::RecordThread::~RecordThread()
4949{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004950 if (mFastCapture != 0) {
4951 FastCaptureStateQueue *sq = mFastCapture->sq();
4952 FastCaptureState *state = sq->begin();
4953 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4954 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4955 if (old == -1) {
4956 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4957 }
4958 }
4959 state->mCommand = FastCaptureState::EXIT;
4960 sq->end();
4961 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4962 mFastCapture->join();
4963 mFastCapture.clear();
4964 }
4965 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004966 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004967 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004968}
4969
4970void AudioFlinger::RecordThread::onFirstRef()
4971{
4972 run(mName, PRIORITY_URGENT_AUDIO);
4973}
4974
Eric Laurent81784c32012-11-19 14:55:58 -08004975bool AudioFlinger::RecordThread::threadLoop()
4976{
Eric Laurent81784c32012-11-19 14:55:58 -08004977 nsecs_t lastWarning = 0;
4978
4979 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004980
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004981reacquire_wakelock:
4982 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004983 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004984 {
4985 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004986 size_t size = mActiveTracks.size();
4987 activeTracksGen = mActiveTracksGen;
4988 if (size > 0) {
4989 // FIXME an arbitrary choice
4990 activeTrack = mActiveTracks[0];
4991 acquireWakeLock_l(activeTrack->uid());
4992 if (size > 1) {
4993 SortedVector<int> tmp;
4994 for (size_t i = 0; i < size; i++) {
4995 tmp.add(mActiveTracks[i]->uid());
4996 }
4997 updateWakeLockUids_l(tmp);
4998 }
4999 } else {
5000 acquireWakeLock_l(-1);
5001 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005002 }
5003
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005004 // used to request a deferred sleep, to be executed later while mutex is unlocked
5005 uint32_t sleepUs = 0;
5006
5007 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005008 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005009 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005010
Glenn Kasten5edadd42013-08-14 16:30:49 -07005011 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005012 if (sleepUs > 0) {
5013 usleep(sleepUs);
5014 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005015 }
5016
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005017 // activeTracks accumulates a copy of a subset of mActiveTracks
5018 Vector< sp<RecordTrack> > activeTracks;
5019
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005020 // reference to the (first and only) fast track
5021 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005022
Eric Laurent81784c32012-11-19 14:55:58 -08005023 { // scope for mLock
5024 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005025
Eric Laurent021cf962014-05-13 10:18:14 -07005026 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005027
Eric Laurent000a4192014-01-29 15:17:32 -08005028 // check exitPending here because checkForNewParameters_l() and
5029 // checkForNewParameters_l() can temporarily release mLock
5030 if (exitPending()) {
5031 break;
5032 }
5033
Glenn Kasten2b806402013-11-20 16:37:38 -08005034 // if no active track(s), then standby and release wakelock
5035 size_t size = mActiveTracks.size();
5036 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005037 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005038 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005039 releaseWakeLock_l();
5040 ALOGV("RecordThread: loop stopping");
5041 // go to sleep
5042 mWaitWorkCV.wait(mLock);
5043 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005044 goto reacquire_wakelock;
5045 }
5046
Glenn Kasten2b806402013-11-20 16:37:38 -08005047 if (mActiveTracksGen != activeTracksGen) {
5048 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005049 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005050 for (size_t i = 0; i < size; i++) {
5051 tmp.add(mActiveTracks[i]->uid());
5052 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005053 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005054 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005055
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005056 bool doBroadcast = false;
5057 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005058
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005059 activeTrack = mActiveTracks[i];
5060 if (activeTrack->isTerminated()) {
5061 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005062 mActiveTracks.remove(activeTrack);
5063 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005064 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005065 continue;
5066 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005067
5068 TrackBase::track_state activeTrackState = activeTrack->mState;
5069 switch (activeTrackState) {
5070
5071 case TrackBase::PAUSING:
5072 mActiveTracks.remove(activeTrack);
5073 mActiveTracksGen++;
5074 doBroadcast = true;
5075 size--;
5076 continue;
5077
5078 case TrackBase::STARTING_1:
5079 sleepUs = 10000;
5080 i++;
5081 continue;
5082
5083 case TrackBase::STARTING_2:
5084 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005085 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005086 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005087 break;
5088
5089 case TrackBase::ACTIVE:
5090 break;
5091
5092 case TrackBase::IDLE:
5093 i++;
5094 continue;
5095
5096 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005097 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005098 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005099
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005100 activeTracks.add(activeTrack);
5101 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005102
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005103 if (activeTrack->isFastTrack()) {
5104 ALOG_ASSERT(!mFastTrackAvail);
5105 ALOG_ASSERT(fastTrack == 0);
5106 fastTrack = activeTrack;
5107 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005108 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005109 if (doBroadcast) {
5110 mStartStopCond.broadcast();
5111 }
5112
5113 // sleep if there are no active tracks to process
5114 if (activeTracks.size() == 0) {
5115 if (sleepUs == 0) {
5116 sleepUs = kRecordThreadSleepUs;
5117 }
5118 continue;
5119 }
5120 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005121
Eric Laurent81784c32012-11-19 14:55:58 -08005122 lockEffectChains_l(effectChains);
5123 }
5124
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005125 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005126
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005127 size_t size = effectChains.size();
5128 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005129 // thread mutex is not locked, but effect chain is locked
5130 effectChains[i]->process_l();
5131 }
5132
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005133 // Start the fast capture if it's not already running
5134 if (mFastCapture != 0) {
5135 FastCaptureStateQueue *sq = mFastCapture->sq();
5136 FastCaptureState *state = sq->begin();
5137 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5138 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5139 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5140 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5141 if (old == -1) {
5142 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5143 }
5144 }
5145 state->mCommand = FastCaptureState::READ_WRITE;
5146#if 0 // FIXME
5147 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5148 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5149#endif
5150 state->mCblk = fastTrack != 0 ? fastTrack->cblk() : NULL;
5151 sq->end();
5152 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5153#if 0
5154 if (kUseFastCapture == FastCapture_Dynamic) {
5155 mNormalSource = mPipeSource;
5156 }
5157#endif
5158 } else {
5159 sq->end(false /*didModify*/);
5160 }
5161 }
5162
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005163 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5164 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5165 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5166 // If destination is non-contiguous, first read past the nominal end of buffer, then
5167 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005168
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005169 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005170 ssize_t framesRead;
5171
5172 // If an NBAIO source is present, use it to read the normal capture's data
5173 if (mPipeSource != 0) {
5174 size_t framesToRead = mBufferSize / mFrameSize;
5175 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5176 framesToRead, AudioBufferProvider::kInvalidPTS);
5177 if (framesRead == 0) {
5178 // since pipe is non-blocking, simulate blocking input
5179 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5180 }
5181 // otherwise use the HAL / AudioStreamIn directly
5182 } else {
5183 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5184 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5185 if (bytesRead < 0) {
5186 framesRead = bytesRead;
5187 } else {
5188 framesRead = bytesRead / mFrameSize;
5189 }
5190 }
5191
5192 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5193 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005194 // Force input into standby so that it tries to recover at next read attempt
5195 inputStandBy();
5196 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005197 }
5198 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005199 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005200 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005201 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005202
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005203 if (mTeeSink != 0) {
5204 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5205 }
5206 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005207 {
5208 size_t part1 = mRsmpInFramesP2 - rear;
5209 if ((size_t) framesRead > part1) {
5210 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5211 (framesRead - part1) * mFrameSize);
5212 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005213 }
5214 rear = mRsmpInRear += framesRead;
5215
5216 size = activeTracks.size();
5217 // loop over each active track
5218 for (size_t i = 0; i < size; i++) {
5219 activeTrack = activeTracks[i];
5220
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005221 // skip fast tracks, as those are handled directly by FastCapture
5222 if (activeTrack->isFastTrack()) {
5223 continue;
5224 }
5225
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005226 enum {
5227 OVERRUN_UNKNOWN,
5228 OVERRUN_TRUE,
5229 OVERRUN_FALSE
5230 } overrun = OVERRUN_UNKNOWN;
5231
5232 // loop over getNextBuffer to handle circular sink
5233 for (;;) {
5234
5235 activeTrack->mSink.frameCount = ~0;
5236 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5237 size_t framesOut = activeTrack->mSink.frameCount;
5238 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5239
5240 int32_t front = activeTrack->mRsmpInFront;
5241 ssize_t filled = rear - front;
5242 size_t framesIn;
5243
5244 if (filled < 0) {
5245 // should not happen, but treat like a massive overrun and re-sync
5246 framesIn = 0;
5247 activeTrack->mRsmpInFront = rear;
5248 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005249 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005250 framesIn = (size_t) filled;
5251 } else {
5252 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005253 framesIn = mRsmpInFrames;
5254 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005255 overrun = OVERRUN_TRUE;
5256 }
5257
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005258 if (framesOut == 0 || framesIn == 0) {
5259 break;
5260 }
5261
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005262 if (activeTrack->mResampler == NULL) {
5263 // no resampling
5264 if (framesIn > framesOut) {
5265 framesIn = framesOut;
5266 } else {
5267 framesOut = framesIn;
5268 }
5269 int8_t *dst = activeTrack->mSink.i8;
5270 while (framesIn > 0) {
5271 front &= mRsmpInFramesP2 - 1;
5272 size_t part1 = mRsmpInFramesP2 - front;
5273 if (part1 > framesIn) {
5274 part1 = framesIn;
5275 }
5276 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005277 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005278 memcpy(dst, src, part1 * mFrameSize);
5279 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005280 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005281 part1);
5282 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005283 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005284 part1);
5285 }
5286 dst += part1 * activeTrack->mFrameSize;
5287 front += part1;
5288 framesIn -= part1;
5289 }
5290 activeTrack->mRsmpInFront += framesOut;
5291
5292 } else {
5293 // resampling
5294 // FIXME framesInNeeded should really be part of resampler API, and should
5295 // depend on the SRC ratio
5296 // to keep mRsmpInBuffer full so resampler always has sufficient input
5297 size_t framesInNeeded;
5298 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005299 // Do not precompute in/out because floating point is not associative
5300 // e.g. a*b/c != a*(b/c).
5301 const double in(mSampleRate);
5302 const double out(activeTrack->mSampleRate);
5303 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005304 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005305 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005306 // Although we theoretically have framesIn in circular buffer, some of those are
5307 // unreleased frames, and thus must be discounted for purpose of budgeting.
5308 size_t unreleased = activeTrack->mRsmpInUnrel;
5309 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005310 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005311 ALOGV("not enough to resample: have %u frames in but need %u in to "
5312 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005313 framesIn, framesInNeeded, framesOut, in / out);
5314 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005315 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5316 if (newFramesOut == 0) {
5317 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005318 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005319 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005320 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005321 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005322 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5323 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5324 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005325 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005326 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005327 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005328 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005329 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005330 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005331 }
5332
5333 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5334 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005335 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005336 delete[] activeTrack->mRsmpOutBuffer;
5337 // resampler always outputs stereo
5338 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5339 activeTrack->mRsmpOutFrameCount = framesOut;
5340 }
5341
5342 // resampler accumulates, but we only have one source track
5343 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5344 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005345 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005346 activeTrack->mResamplerBufferProvider
5347 /*this*/ /* AudioBufferProvider* */);
5348 // ditherAndClamp() works as long as all buffers returned by
5349 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005350 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005351 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5353 framesOut);
5354 // the resampler always outputs stereo samples:
5355 // do post stereo to mono conversion
5356 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005357 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005358 } else {
5359 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5360 activeTrack->mRsmpOutBuffer, framesOut);
5361 }
5362 // now done with mRsmpOutBuffer
5363
5364 }
5365
5366 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5367 overrun = OVERRUN_FALSE;
5368 }
5369
5370 if (activeTrack->mFramesToDrop == 0) {
5371 if (framesOut > 0) {
5372 activeTrack->mSink.frameCount = framesOut;
5373 activeTrack->releaseBuffer(&activeTrack->mSink);
5374 }
5375 } else {
5376 // FIXME could do a partial drop of framesOut
5377 if (activeTrack->mFramesToDrop > 0) {
5378 activeTrack->mFramesToDrop -= framesOut;
5379 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005380 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005381 }
5382 } else {
5383 activeTrack->mFramesToDrop += framesOut;
5384 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5385 activeTrack->mSyncStartEvent->isCancelled()) {
5386 ALOGW("Synced record %s, session %d, trigger session %d",
5387 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5388 activeTrack->sessionId(),
5389 (activeTrack->mSyncStartEvent != 0) ?
5390 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005391 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005392 }
5393 }
5394 }
5395
5396 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005397 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005398 }
5399 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005400
5401 switch (overrun) {
5402 case OVERRUN_TRUE:
5403 // client isn't retrieving buffers fast enough
5404 if (!activeTrack->setOverflow()) {
5405 nsecs_t now = systemTime();
5406 // FIXME should lastWarning per track?
5407 if ((now - lastWarning) > kWarningThrottleNs) {
5408 ALOGW("RecordThread: buffer overflow");
5409 lastWarning = now;
5410 }
5411 }
5412 break;
5413 case OVERRUN_FALSE:
5414 activeTrack->clearOverflow();
5415 break;
5416 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005417 break;
5418 }
5419
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005420 }
5421
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005422unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005423 // enable changes in effect chain
5424 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005425 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005426 }
5427
Glenn Kasten93e471f2013-08-19 08:40:07 -07005428 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005429
5430 {
5431 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005432 for (size_t i = 0; i < mTracks.size(); i++) {
5433 sp<RecordTrack> track = mTracks[i];
5434 track->invalidate();
5435 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005436 mActiveTracks.clear();
5437 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005438 mStartStopCond.broadcast();
5439 }
5440
5441 releaseWakeLock();
5442
5443 ALOGV("RecordThread %p exiting", this);
5444 return false;
5445}
5446
Glenn Kasten93e471f2013-08-19 08:40:07 -07005447void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005448{
5449 if (!mStandby) {
5450 inputStandBy();
5451 mStandby = true;
5452 }
5453}
5454
5455void AudioFlinger::RecordThread::inputStandBy()
5456{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005457 // Idle the fast capture if it's currently running
5458 if (mFastCapture != 0) {
5459 FastCaptureStateQueue *sq = mFastCapture->sq();
5460 FastCaptureState *state = sq->begin();
5461 if (!(state->mCommand & FastCaptureState::IDLE)) {
5462 state->mCommand = FastCaptureState::COLD_IDLE;
5463 state->mColdFutexAddr = &mFastCaptureFutex;
5464 state->mColdGen++;
5465 mFastCaptureFutex = 0;
5466 sq->end();
5467 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5468 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5469#if 0
5470 if (kUseFastCapture == FastCapture_Dynamic) {
5471 // FIXME
5472 }
5473#endif
5474#ifdef AUDIO_WATCHDOG
5475 // FIXME
5476#endif
5477 } else {
5478 sq->end(false /*didModify*/);
5479 }
5480 }
Eric Laurent81784c32012-11-19 14:55:58 -08005481 mInput->stream->common.standby(&mInput->stream->common);
5482}
5483
Glenn Kasten05997e22014-03-13 15:08:33 -07005484// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005485sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005486 const sp<AudioFlinger::Client>& client,
5487 uint32_t sampleRate,
5488 audio_format_t format,
5489 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005490 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005491 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005492 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005493 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005494 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005495 pid_t tid,
5496 status_t *status)
5497{
Glenn Kasten74935e42013-12-19 08:56:45 -08005498 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005499 sp<RecordTrack> track;
5500 status_t lStatus;
5501
Glenn Kasten90e58b12013-07-31 16:16:02 -07005502 // client expresses a preference for FAST, but we get the final say
5503 if (*flags & IAudioFlinger::TRACK_FAST) {
5504 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005505 // use case: callback handler
5506 (tid != -1) &&
5507 // frame count is not specified, or is exactly the pipe depth
5508 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005509 // PCM data
5510 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005511 // native format
5512 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005513 // native channel mask
5514 (channelMask == mChannelMask) &&
5515 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005516 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005517 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005518 hasFastCapture() &&
5519 // there are sufficient fast track slots available
5520 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005521 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005522 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005523 frameCount, mFrameCount);
5524 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005525 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5526 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005527 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005528 frameCount, mFrameCount, mPipeFramesP2,
5529 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5530 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005531 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005532 }
5533 }
5534
5535 // compute track buffer size in frames, and suggest the notification frame count
5536 if (*flags & IAudioFlinger::TRACK_FAST) {
5537 // fast track: frame count is exactly the pipe depth
5538 frameCount = mPipeFramesP2;
5539 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5540 *notificationFrames = mFrameCount;
5541 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005542 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5543 // or 20 ms if there is a fast capture
5544 // TODO This could be a roundupRatio inline, and const
5545 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5546 * sampleRate + mSampleRate - 1) / mSampleRate;
5547 // minimum number of notification periods is at least kMinNotifications,
5548 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5549 static const size_t kMinNotifications = 3;
5550 static const uint32_t kMinMs = 30;
5551 // TODO This could be a roundupRatio inline
5552 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5553 // TODO This could be a roundupRatio inline
5554 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5555 maxNotificationFrames;
5556 const size_t minFrameCount = maxNotificationFrames *
5557 max(kMinNotifications, minNotificationsByMs);
5558 frameCount = max(frameCount, minFrameCount);
5559 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5560 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005561 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005562 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005563 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005564
Glenn Kasten15e57982013-09-24 11:52:37 -07005565 lStatus = initCheck();
5566 if (lStatus != NO_ERROR) {
5567 ALOGE("createRecordTrack_l() audio driver not initialized");
5568 goto Exit;
5569 }
Eric Laurent81784c32012-11-19 14:55:58 -08005570
5571 { // scope for mLock
5572 Mutex::Autolock _l(mLock);
5573
5574 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005575 format, channelMask, frameCount, NULL, sessionId, uid,
5576 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005577
Glenn Kasten03003332013-08-06 15:40:54 -07005578 lStatus = track->initCheck();
5579 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005580 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005581 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005582 goto Exit;
5583 }
5584 mTracks.add(track);
5585
5586 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5587 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5588 mAudioFlinger->btNrecIsOff();
5589 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5590 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005591
5592 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5593 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5594 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5595 // so ask activity manager to do this on our behalf
5596 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5597 }
Eric Laurent81784c32012-11-19 14:55:58 -08005598 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005599
Eric Laurent81784c32012-11-19 14:55:58 -08005600 lStatus = NO_ERROR;
5601
5602Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005603 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 return track;
5605}
5606
5607status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5608 AudioSystem::sync_event_t event,
5609 int triggerSession)
5610{
5611 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5612 sp<ThreadBase> strongMe = this;
5613 status_t status = NO_ERROR;
5614
5615 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005616 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005617 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005618 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005619 triggerSession,
5620 recordTrack->sessionId(),
5621 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005622 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 // Sync event can be cancelled by the trigger session if the track is not in a
5624 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005625 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005626 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005627 } else {
5628 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005629 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005630 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005631 }
5632 }
5633
5634 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005635 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005636 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5638 if (recordTrack->mState == TrackBase::PAUSING) {
5639 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005640 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641 } else {
5642 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005643 }
5644 return status;
5645 }
5646
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005647 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5648 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5649 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005651 mActiveTracks.add(recordTrack);
5652 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005653 status_t status = NO_ERROR;
5654 if (recordTrack->isExternalTrack()) {
5655 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005656 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005657 mLock.lock();
5658 // FIXME should verify that recordTrack is still in mActiveTracks
5659 if (status != NO_ERROR) {
5660 mActiveTracks.remove(recordTrack);
5661 mActiveTracksGen++;
5662 recordTrack->clearSyncStartEvent();
5663 ALOGV("RecordThread::start error %d", status);
5664 return status;
5665 }
Eric Laurent81784c32012-11-19 14:55:58 -08005666 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005667 // Catch up with current buffer indices if thread is already running.
5668 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5669 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5670 // see previously buffered data before it called start(), but with greater risk of overrun.
5671
5672 recordTrack->mRsmpInFront = mRsmpInRear;
5673 recordTrack->mRsmpInUnrel = 0;
5674 // FIXME why reset?
5675 if (recordTrack->mResampler != NULL) {
5676 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005679 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005680 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005681 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005682 ALOGV("Record failed to start");
5683 status = BAD_VALUE;
5684 goto startError;
5685 }
Eric Laurent81784c32012-11-19 14:55:58 -08005686 return status;
5687 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005688
Eric Laurent81784c32012-11-19 14:55:58 -08005689startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005690 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005691 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005692 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005693 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005694 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005695 return status;
5696}
5697
Eric Laurent81784c32012-11-19 14:55:58 -08005698void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5699{
5700 sp<SyncEvent> strongEvent = event.promote();
5701
5702 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005703 sp<RefBase> ptr = strongEvent->cookie().promote();
5704 if (ptr != 0) {
5705 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5706 recordTrack->handleSyncStartEvent(strongEvent);
5707 }
Eric Laurent81784c32012-11-19 14:55:58 -08005708 }
5709}
5710
Glenn Kastena8356f62013-07-25 14:37:52 -07005711bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005712 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005713 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005714 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005715 return false;
5716 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005717 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005718 recordTrack->mState = TrackBase::PAUSING;
5719 // do not wait for mStartStopCond if exiting
5720 if (exitPending()) {
5721 return true;
5722 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005723 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005724 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005725 // if we have been restarted, recordTrack is in mActiveTracks here
5726 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005727 ALOGV("Record stopped OK");
5728 return true;
5729 }
5730 return false;
5731}
5732
Glenn Kasten0f11b512014-01-31 16:18:54 -08005733bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005734{
5735 return false;
5736}
5737
Glenn Kasten0f11b512014-01-31 16:18:54 -08005738status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005739{
5740#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5741 if (!isValidSyncEvent(event)) {
5742 return BAD_VALUE;
5743 }
5744
5745 int eventSession = event->triggerSession();
5746 status_t ret = NAME_NOT_FOUND;
5747
5748 Mutex::Autolock _l(mLock);
5749
5750 for (size_t i = 0; i < mTracks.size(); i++) {
5751 sp<RecordTrack> track = mTracks[i];
5752 if (eventSession == track->sessionId()) {
5753 (void) track->setSyncEvent(event);
5754 ret = NO_ERROR;
5755 }
5756 }
5757 return ret;
5758#else
5759 return BAD_VALUE;
5760#endif
5761}
5762
5763// destroyTrack_l() must be called with ThreadBase::mLock held
5764void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5765{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005766 track->terminate();
5767 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005769 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005770 removeTrack_l(track);
5771 }
5772}
5773
5774void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5775{
5776 mTracks.remove(track);
5777 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005778 if (track->isFastTrack()) {
5779 ALOG_ASSERT(!mFastTrackAvail);
5780 mFastTrackAvail = true;
5781 }
Eric Laurent81784c32012-11-19 14:55:58 -08005782}
5783
5784void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5785{
5786 dumpInternals(fd, args);
5787 dumpTracks(fd, args);
5788 dumpEffectChains(fd, args);
5789}
5790
5791void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5792{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005793 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005794
Glenn Kasten2b806402013-11-20 16:37:38 -08005795 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005796 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005798 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005799 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005800 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005801 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005802
Eric Laurent81784c32012-11-19 14:55:58 -08005803 dumpBase(fd, args);
5804}
5805
Glenn Kasten0f11b512014-01-31 16:18:54 -08005806void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005807{
5808 const size_t SIZE = 256;
5809 char buffer[SIZE];
5810 String8 result;
5811
Marco Nelissenb2208842014-02-07 14:00:50 -08005812 size_t numtracks = mTracks.size();
5813 size_t numactive = mActiveTracks.size();
5814 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005815 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005816 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005817 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005818 RecordTrack::appendDumpHeader(result);
5819 for (size_t i = 0; i < numtracks ; ++i) {
5820 sp<RecordTrack> track = mTracks[i];
5821 if (track != 0) {
5822 bool active = mActiveTracks.indexOf(track) >= 0;
5823 if (active) {
5824 numactiveseen++;
5825 }
5826 track->dump(buffer, SIZE, active);
5827 result.append(buffer);
5828 }
Eric Laurent81784c32012-11-19 14:55:58 -08005829 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005830 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005831 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005832 }
5833
Marco Nelissenb2208842014-02-07 14:00:50 -08005834 if (numactiveseen != numactive) {
5835 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5836 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005837 result.append(buffer);
5838 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005839 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005840 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005841 if (mTracks.indexOf(track) < 0) {
5842 track->dump(buffer, SIZE, true);
5843 result.append(buffer);
5844 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005845 }
Eric Laurent81784c32012-11-19 14:55:58 -08005846
5847 }
5848 write(fd, result.string(), result.size());
5849}
5850
5851// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005852status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5853 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005854{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005855 RecordTrack *activeTrack = mRecordTrack;
5856 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5857 if (threadBase == 0) {
5858 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005859 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005860 return NOT_ENOUGH_DATA;
5861 }
5862 RecordThread *recordThread = (RecordThread *) threadBase.get();
5863 int32_t rear = recordThread->mRsmpInRear;
5864 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005865 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005866 // FIXME should not be P2 (don't want to increase latency)
5867 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005868 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005869 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005870 front &= recordThread->mRsmpInFramesP2 - 1;
5871 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005872 if (part1 > (size_t) filled) {
5873 part1 = filled;
5874 }
5875 size_t ask = buffer->frameCount;
5876 ALOG_ASSERT(ask > 0);
5877 if (part1 > ask) {
5878 part1 = ask;
5879 }
5880 if (part1 == 0) {
5881 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005882 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005883 buffer->raw = NULL;
5884 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005885 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005886 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005887 }
5888
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005890 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005891 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005892 return NO_ERROR;
5893}
5894
5895// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5897 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005898{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005900 size_t stepCount = buffer->frameCount;
5901 if (stepCount == 0) {
5902 return;
5903 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5905 activeTrack->mRsmpInUnrel -= stepCount;
5906 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005907 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005908 buffer->frameCount = 0;
5909}
5910
Eric Laurent10351942014-05-08 18:49:52 -07005911bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5912 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005913{
5914 bool reconfig = false;
5915
Eric Laurent10351942014-05-08 18:49:52 -07005916 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005917
Eric Laurent10351942014-05-08 18:49:52 -07005918 audio_format_t reqFormat = mFormat;
5919 uint32_t samplingRate = mSampleRate;
5920 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5921
5922 AudioParameter param = AudioParameter(keyValuePair);
5923 int value;
5924 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5925 // channel count change can be requested. Do we mandate the first client defines the
5926 // HAL sampling rate and channel count or do we allow changes on the fly?
5927 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5928 samplingRate = value;
5929 reconfig = true;
5930 }
5931 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5932 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5933 status = BAD_VALUE;
5934 } else {
5935 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005936 reconfig = true;
5937 }
Eric Laurent10351942014-05-08 18:49:52 -07005938 }
5939 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5940 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5941 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5942 status = BAD_VALUE;
5943 } else {
5944 channelMask = mask;
5945 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005946 }
Eric Laurent10351942014-05-08 18:49:52 -07005947 }
5948 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5949 // do not accept frame count changes if tracks are open as the track buffer
5950 // size depends on frame count and correct behavior would not be guaranteed
5951 // if frame count is changed after track creation
5952 if (mActiveTracks.size() > 0) {
5953 status = INVALID_OPERATION;
5954 } else {
5955 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005956 }
Eric Laurent10351942014-05-08 18:49:52 -07005957 }
5958 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5959 // forward device change to effects that have requested to be
5960 // aware of attached audio device.
5961 for (size_t i = 0; i < mEffectChains.size(); i++) {
5962 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
Eric Laurent81784c32012-11-19 14:55:58 -08005964
Eric Laurent10351942014-05-08 18:49:52 -07005965 // store input device and output device but do not forward output device to audio HAL.
5966 // Note that status is ignored by the caller for output device
5967 // (see AudioFlinger::setParameters()
5968 if (audio_is_output_devices(value)) {
5969 mOutDevice = value;
5970 status = BAD_VALUE;
5971 } else {
5972 mInDevice = value;
5973 // disable AEC and NS if the device is a BT SCO headset supporting those
5974 // pre processings
5975 if (mTracks.size() > 0) {
5976 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5977 mAudioFlinger->btNrecIsOff();
5978 for (size_t i = 0; i < mTracks.size(); i++) {
5979 sp<RecordTrack> track = mTracks[i];
5980 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5981 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005982 }
5983 }
5984 }
Eric Laurent10351942014-05-08 18:49:52 -07005985 }
5986 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5987 mAudioSource != (audio_source_t)value) {
5988 // forward device change to effects that have requested to be
5989 // aware of attached audio device.
5990 for (size_t i = 0; i < mEffectChains.size(); i++) {
5991 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005992 }
Eric Laurent10351942014-05-08 18:49:52 -07005993 mAudioSource = (audio_source_t)value;
5994 }
Glenn Kastene198c362013-08-13 09:13:36 -07005995
Eric Laurent10351942014-05-08 18:49:52 -07005996 if (status == NO_ERROR) {
5997 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5998 keyValuePair.string());
5999 if (status == INVALID_OPERATION) {
6000 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006001 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6002 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006003 }
6004 if (reconfig) {
6005 if (status == BAD_VALUE &&
6006 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6007 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6008 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6009 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006010 audio_channel_count_from_in_mask(
6011 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006012 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6013 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6014 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006015 }
Eric Laurent10351942014-05-08 18:49:52 -07006016 if (status == NO_ERROR) {
6017 readInputParameters_l();
6018 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006019 }
6020 }
Eric Laurent81784c32012-11-19 14:55:58 -08006021 }
Eric Laurent10351942014-05-08 18:49:52 -07006022
Eric Laurent81784c32012-11-19 14:55:58 -08006023 return reconfig;
6024}
6025
6026String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6027{
Eric Laurent81784c32012-11-19 14:55:58 -08006028 Mutex::Autolock _l(mLock);
6029 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006030 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006031 }
6032
Glenn Kastend8ea6992013-07-16 14:17:15 -07006033 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6034 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006035 free(s);
6036 return out_s8;
6037}
6038
Eric Laurent021cf962014-05-13 10:18:14 -07006039void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006040 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006041 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006042
6043 switch (event) {
6044 case AudioSystem::INPUT_OPENED:
6045 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006046 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006047 desc.samplingRate = mSampleRate;
6048 desc.format = mFormat;
6049 desc.frameCount = mFrameCount;
6050 desc.latency = 0;
6051 param2 = &desc;
6052 break;
6053
6054 case AudioSystem::INPUT_CLOSED:
6055 default:
6056 break;
6057 }
Eric Laurent021cf962014-05-13 10:18:14 -07006058 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006059}
6060
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006061void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006062{
Eric Laurent81784c32012-11-19 14:55:58 -08006063 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6064 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006065 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006066 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6067 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006068 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006069 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006070 }
Eric Laurent665470b2014-07-03 16:37:08 -07006071 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006072 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6073 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006074 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006075 // 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 -07006076 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006077 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 // A larger value should allow more old data to be read after a track calls start(),
6079 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006080 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006081 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006082 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006083
6084 // TODO optimize audio capture buffer sizes ...
6085 // Here we calculate the size of the sliding buffer used as a source
6086 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6087 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6088 // be better to have it derived from the pipe depth in the long term.
6089 // The current value is higher than necessary. However it should not add to latency.
6090
Glenn Kasten85948432013-08-19 12:09:05 -07006091 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6092 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006093
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006094 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6095 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006096}
6097
Glenn Kasten5f972c02014-01-13 09:59:31 -08006098uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006099{
6100 Mutex::Autolock _l(mLock);
6101 if (initCheck() != NO_ERROR) {
6102 return 0;
6103 }
6104
6105 return mInput->stream->get_input_frames_lost(mInput->stream);
6106}
6107
6108uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6109{
6110 Mutex::Autolock _l(mLock);
6111 uint32_t result = 0;
6112 if (getEffectChain_l(sessionId) != 0) {
6113 result = EFFECT_SESSION;
6114 }
6115
6116 for (size_t i = 0; i < mTracks.size(); ++i) {
6117 if (sessionId == mTracks[i]->sessionId()) {
6118 result |= TRACK_SESSION;
6119 break;
6120 }
6121 }
6122
6123 return result;
6124}
6125
6126KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6127{
6128 KeyedVector<int, bool> ids;
6129 Mutex::Autolock _l(mLock);
6130 for (size_t j = 0; j < mTracks.size(); ++j) {
6131 sp<RecordThread::RecordTrack> track = mTracks[j];
6132 int sessionId = track->sessionId();
6133 if (ids.indexOfKey(sessionId) < 0) {
6134 ids.add(sessionId, true);
6135 }
6136 }
6137 return ids;
6138}
6139
6140AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6141{
6142 Mutex::Autolock _l(mLock);
6143 AudioStreamIn *input = mInput;
6144 mInput = NULL;
6145 return input;
6146}
6147
6148// this method must always be called either with ThreadBase mLock held or inside the thread loop
6149audio_stream_t* AudioFlinger::RecordThread::stream() const
6150{
6151 if (mInput == NULL) {
6152 return NULL;
6153 }
6154 return &mInput->stream->common;
6155}
6156
6157status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6158{
6159 // only one chain per input thread
6160 if (mEffectChains.size() != 0) {
6161 return INVALID_OPERATION;
6162 }
6163 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6164
6165 chain->setInBuffer(NULL);
6166 chain->setOutBuffer(NULL);
6167
6168 checkSuspendOnAddEffectChain_l(chain);
6169
6170 mEffectChains.add(chain);
6171
6172 return NO_ERROR;
6173}
6174
6175size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6176{
6177 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6178 ALOGW_IF(mEffectChains.size() != 1,
6179 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6180 chain.get(), mEffectChains.size(), this);
6181 if (mEffectChains.size() == 1) {
6182 mEffectChains.removeAt(0);
6183 }
6184 return 0;
6185}
6186
Eric Laurent1c333e22014-05-20 10:48:17 -07006187status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6188 audio_patch_handle_t *handle)
6189{
6190 status_t status = NO_ERROR;
6191 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6192 // store new device and send to effects
6193 mInDevice = patch->sources[0].ext.device.type;
6194 for (size_t i = 0; i < mEffectChains.size(); i++) {
6195 mEffectChains[i]->setDevice_l(mInDevice);
6196 }
6197
6198 // disable AEC and NS if the device is a BT SCO headset supporting those
6199 // pre processings
6200 if (mTracks.size() > 0) {
6201 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6202 mAudioFlinger->btNrecIsOff();
6203 for (size_t i = 0; i < mTracks.size(); i++) {
6204 sp<RecordTrack> track = mTracks[i];
6205 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6206 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6207 }
6208 }
6209
6210 // store new source and send to effects
6211 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6212 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6213 for (size_t i = 0; i < mEffectChains.size(); i++) {
6214 mEffectChains[i]->setAudioSource_l(mAudioSource);
6215 }
6216 }
6217
6218 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6219 status = hwDevice->create_audio_patch(hwDevice,
6220 patch->num_sources,
6221 patch->sources,
6222 patch->num_sinks,
6223 patch->sinks,
6224 handle);
6225 } else {
6226 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6227 }
6228 return status;
6229}
6230
6231status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6232{
6233 status_t status = NO_ERROR;
6234 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6235 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6236 status = hwDevice->release_audio_patch(hwDevice, handle);
6237 } else {
6238 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6239 }
6240 return status;
6241}
6242
Eric Laurent83b88082014-06-20 18:31:16 -07006243void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6244{
6245 Mutex::Autolock _l(mLock);
6246 mTracks.add(record);
6247}
6248
6249void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6250{
6251 Mutex::Autolock _l(mLock);
6252 destroyTrack_l(record);
6253}
6254
6255void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6256{
6257 ThreadBase::getAudioPortConfig(config);
6258 config->role = AUDIO_PORT_ROLE_SINK;
6259 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6260 config->ext.mix.usecase.source = mAudioSource;
6261}
Eric Laurent1c333e22014-05-20 10:48:17 -07006262
Eric Laurent81784c32012-11-19 14:55:58 -08006263}; // namespace android