blob: 384bd257d5a6c9aed4784af896c2de43de14400f [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>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Andy Hungc25b84a2015-01-14 19:04:10 -0800177// Returns the source frames needed to resample to destination frames. This is not a precise
178// value and depends on the resampler (and possibly how it handles rounding internally).
179// If srcSampleRate and dstSampleRate are equal, then it returns destination frames, which
180// may not be a true if the resampler is asynchronous.
181static inline size_t sourceFramesNeeded(
182 uint32_t srcSampleRate, size_t dstFramesRequired, uint32_t dstSampleRate) {
183 // +1 for rounding - always do this even if matched ratio
184 // +1 for additional sample needed for interpolation
185 return srcSampleRate == dstSampleRate ? dstFramesRequired :
186 size_t((uint64_t)dstFramesRequired * srcSampleRate / dstSampleRate + 1 + 1);
187}
188
Eric Laurent81784c32012-11-19 14:55:58 -0800189// ----------------------------------------------------------------------------
190
Glenn Kasten03490092014-05-27 12:30:54 -0700191static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
192
193static void sFastTrackMultiplierInit()
194{
195 char value[PROPERTY_VALUE_MAX];
196 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
197 char *endptr;
198 unsigned long ul = strtoul(value, &endptr, 0);
199 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
200 sFastTrackMultiplier = (int) ul;
201 }
202 }
203}
204
205// ----------------------------------------------------------------------------
206
Eric Laurent81784c32012-11-19 14:55:58 -0800207#ifdef ADD_BATTERY_DATA
208// To collect the amplifier usage
209static void addBatteryData(uint32_t params) {
210 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
211 if (service == NULL) {
212 // it already logged
213 return;
214 }
215
216 service->addBatteryData(params);
217}
218#endif
219
220
221// ----------------------------------------------------------------------------
222// CPU Stats
223// ----------------------------------------------------------------------------
224
225class CpuStats {
226public:
227 CpuStats();
228 void sample(const String8 &title);
229#ifdef DEBUG_CPU_USAGE
230private:
231 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
232 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
233
234 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
235
236 int mCpuNum; // thread's current CPU number
237 int mCpukHz; // frequency of thread's current CPU in kHz
238#endif
239};
240
241CpuStats::CpuStats()
242#ifdef DEBUG_CPU_USAGE
243 : mCpuNum(-1), mCpukHz(-1)
244#endif
245{
246}
247
Glenn Kasten0f11b512014-01-31 16:18:54 -0800248void CpuStats::sample(const String8 &title
249#ifndef DEBUG_CPU_USAGE
250 __unused
251#endif
252 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800253#ifdef DEBUG_CPU_USAGE
254 // get current thread's delta CPU time in wall clock ns
255 double wcNs;
256 bool valid = mCpuUsage.sampleAndEnable(wcNs);
257
258 // record sample for wall clock statistics
259 if (valid) {
260 mWcStats.sample(wcNs);
261 }
262
263 // get the current CPU number
264 int cpuNum = sched_getcpu();
265
266 // get the current CPU frequency in kHz
267 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
268
269 // check if either CPU number or frequency changed
270 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
271 mCpuNum = cpuNum;
272 mCpukHz = cpukHz;
273 // ignore sample for purposes of cycles
274 valid = false;
275 }
276
277 // if no change in CPU number or frequency, then record sample for cycle statistics
278 if (valid && mCpukHz > 0) {
279 double cycles = wcNs * cpukHz * 0.000001;
280 mHzStats.sample(cycles);
281 }
282
283 unsigned n = mWcStats.n();
284 // mCpuUsage.elapsed() is expensive, so don't call it every loop
285 if ((n & 127) == 1) {
286 long long elapsed = mCpuUsage.elapsed();
287 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
288 double perLoop = elapsed / (double) n;
289 double perLoop100 = perLoop * 0.01;
290 double perLoop1k = perLoop * 0.001;
291 double mean = mWcStats.mean();
292 double stddev = mWcStats.stddev();
293 double minimum = mWcStats.minimum();
294 double maximum = mWcStats.maximum();
295 double meanCycles = mHzStats.mean();
296 double stddevCycles = mHzStats.stddev();
297 double minCycles = mHzStats.minimum();
298 double maxCycles = mHzStats.maximum();
299 mCpuUsage.resetElapsed();
300 mWcStats.reset();
301 mHzStats.reset();
302 ALOGD("CPU usage for %s over past %.1f secs\n"
303 " (%u mixer loops at %.1f mean ms per loop):\n"
304 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
305 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
306 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
307 title.string(),
308 elapsed * .000000001, n, perLoop * .000001,
309 mean * .001,
310 stddev * .001,
311 minimum * .001,
312 maximum * .001,
313 mean / perLoop100,
314 stddev / perLoop100,
315 minimum / perLoop100,
316 maximum / perLoop100,
317 meanCycles / perLoop1k,
318 stddevCycles / perLoop1k,
319 minCycles / perLoop1k,
320 maxCycles / perLoop1k);
321
322 }
323 }
324#endif
325};
326
327// ----------------------------------------------------------------------------
328// ThreadBase
329// ----------------------------------------------------------------------------
330
Glenn Kasten97b7b752014-09-28 13:04:24 -0700331// static
332const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
333{
334 switch (type) {
335 case MIXER:
336 return "MIXER";
337 case DIRECT:
338 return "DIRECT";
339 case DUPLICATING:
340 return "DUPLICATING";
341 case RECORD:
342 return "RECORD";
343 case OFFLOAD:
344 return "OFFLOAD";
345 default:
346 return "unknown";
347 }
348}
349
350static String8 outputFlagsToString(audio_output_flags_t flags)
351{
352 static const struct mapping {
353 audio_output_flags_t mFlag;
354 const char * mString;
355 } mappings[] = {
356 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
357 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
358 AUDIO_OUTPUT_FLAG_FAST, "FAST",
359 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
360 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAAD",
361 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
362 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
363 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
364 };
365 String8 result;
366 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
367 const mapping *entry;
368 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
369 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
370 if (flags & entry->mFlag) {
371 if (!result.isEmpty()) {
372 result.append("|");
373 }
374 result.append(entry->mString);
375 }
376 }
377 if (flags & ~allFlags) {
378 if (!result.isEmpty()) {
379 result.append("|");
380 }
381 result.appendFormat("0x%X", flags & ~allFlags);
382 }
383 if (result.isEmpty()) {
384 result.append(entry->mString);
385 }
386 return result;
387}
388
Eric Laurent81784c32012-11-19 14:55:58 -0800389AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
390 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
391 : Thread(false /*canCallJava*/),
392 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700393 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700394 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800395 // are set by PlaybackThread::readOutputParameters_l() or
396 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700397 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800398 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
399 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
400 // mName will be set by concrete (non-virtual) subclass
401 mDeathRecipient(new PMDeathRecipient(this))
402{
403}
404
405AudioFlinger::ThreadBase::~ThreadBase()
406{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700407 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700408 mConfigEvents.clear();
409
Eric Laurent81784c32012-11-19 14:55:58 -0800410 // do not lock the mutex in destructor
411 releaseWakeLock_l();
412 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800413 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800414 binder->unlinkToDeath(mDeathRecipient);
415 }
416}
417
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700418status_t AudioFlinger::ThreadBase::readyToRun()
419{
420 status_t status = initCheck();
421 if (status == NO_ERROR) {
422 ALOGI("AudioFlinger's thread %p ready to run", this);
423 } else {
424 ALOGE("No working audio driver found.");
425 }
426 return status;
427}
428
Eric Laurent81784c32012-11-19 14:55:58 -0800429void AudioFlinger::ThreadBase::exit()
430{
431 ALOGV("ThreadBase::exit");
432 // do any cleanup required for exit to succeed
433 preExit();
434 {
435 // This lock prevents the following race in thread (uniprocessor for illustration):
436 // if (!exitPending()) {
437 // // context switch from here to exit()
438 // // exit() calls requestExit(), what exitPending() observes
439 // // exit() calls signal(), which is dropped since no waiters
440 // // context switch back from exit() to here
441 // mWaitWorkCV.wait(...);
442 // // now thread is hung
443 // }
444 AutoMutex lock(mLock);
445 requestExit();
446 mWaitWorkCV.broadcast();
447 }
448 // When Thread::requestExitAndWait is made virtual and this method is renamed to
449 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
450 requestExitAndWait();
451}
452
453status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
454{
455 status_t status;
456
457 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
458 Mutex::Autolock _l(mLock);
459
Eric Laurent10351942014-05-08 18:49:52 -0700460 return sendSetParameterConfigEvent_l(keyValuePairs);
461}
462
463// sendConfigEvent_l() must be called with ThreadBase::mLock held
464// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
465status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
466{
467 status_t status = NO_ERROR;
468
469 mConfigEvents.add(event);
470 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800471 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700472 mLock.unlock();
473 {
474 Mutex::Autolock _l(event->mLock);
475 while (event->mWaitStatus) {
476 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
477 event->mStatus = TIMED_OUT;
478 event->mWaitStatus = false;
479 }
480 }
481 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800482 }
Eric Laurent10351942014-05-08 18:49:52 -0700483 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800484 return status;
485}
486
487void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
488{
489 Mutex::Autolock _l(mLock);
490 sendIoConfigEvent_l(event, param);
491}
492
493// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
494void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
495{
Eric Laurent10351942014-05-08 18:49:52 -0700496 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
497 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800498}
499
500// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
501void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
502{
Eric Laurent10351942014-05-08 18:49:52 -0700503 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
504 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800505}
506
Eric Laurent10351942014-05-08 18:49:52 -0700507// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
508status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800509{
Eric Laurent10351942014-05-08 18:49:52 -0700510 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
511 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700512}
513
Eric Laurent1c333e22014-05-20 10:48:17 -0700514status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
515 const struct audio_patch *patch,
516 audio_patch_handle_t *handle)
517{
518 Mutex::Autolock _l(mLock);
519 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
520 status_t status = sendConfigEvent_l(configEvent);
521 if (status == NO_ERROR) {
522 CreateAudioPatchConfigEventData *data =
523 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
524 *handle = data->mHandle;
525 }
526 return status;
527}
528
529status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
530 const audio_patch_handle_t handle)
531{
532 Mutex::Autolock _l(mLock);
533 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
534 return sendConfigEvent_l(configEvent);
535}
536
537
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700538// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700539void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700540{
Eric Laurent10351942014-05-08 18:49:52 -0700541 bool configChanged = false;
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700544 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
545 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800546 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700547 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700548 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700549 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
550 // FIXME Need to understand why this has to be done asynchronously
551 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700552 true /*asynchronous*/);
553 if (err != 0) {
554 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700555 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700556 }
557 } break;
558 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700559 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700560 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700561 } break;
562 case CFG_EVENT_SET_PARAMETER: {
563 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
564 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
565 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700566 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700567 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700568 case CFG_EVENT_CREATE_AUDIO_PATCH: {
569 CreateAudioPatchConfigEventData *data =
570 (CreateAudioPatchConfigEventData *)event->mData.get();
571 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
572 } break;
573 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
574 ReleaseAudioPatchConfigEventData *data =
575 (ReleaseAudioPatchConfigEventData *)event->mData.get();
576 event->mStatus = releaseAudioPatch_l(data->mHandle);
577 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700578 default:
Eric Laurent10351942014-05-08 18:49:52 -0700579 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700580 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800581 }
Eric Laurent10351942014-05-08 18:49:52 -0700582 {
583 Mutex::Autolock _l(event->mLock);
584 if (event->mWaitStatus) {
585 event->mWaitStatus = false;
586 event->mCond.signal();
587 }
588 }
589 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
590 }
591
592 if (configChanged) {
593 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800594 }
Eric Laurent81784c32012-11-19 14:55:58 -0800595}
596
Marco Nelissenb2208842014-02-07 14:00:50 -0800597String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
598 String8 s;
599 if (output) {
600 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
601 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
602 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
603 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
604 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
605 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
606 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
607 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
608 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
609 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
610 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
611 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
612 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
613 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
614 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
615 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
616 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
617 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
618 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
619 } else {
620 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
621 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
622 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
623 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
624 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
625 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
626 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
627 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
628 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
629 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
630 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
631 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
632 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
633 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
634 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
635 }
636 int len = s.length();
637 if (s.length() > 2) {
638 char *str = s.lockBuffer(len);
639 s.unlockBuffer(len - 2);
640 }
641 return s;
642}
643
Glenn Kasten0f11b512014-01-31 16:18:54 -0800644void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
646 const size_t SIZE = 256;
647 char buffer[SIZE];
648 String8 result;
649
650 bool locked = AudioFlinger::dumpTryLock(mLock);
651 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700652 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800653 }
654
Elliott Hughes87cebad2014-05-22 10:14:43 -0700655 dprintf(fd, " I/O handle: %d\n", mId);
656 dprintf(fd, " TID: %d\n", getTid());
657 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700658 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700659 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700660 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700661 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700662 dprintf(fd, " Channel count: %u\n", mChannelCount);
663 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800664 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700665 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
666 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700667 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800668 size_t numConfig = mConfigEvents.size();
669 if (numConfig) {
670 for (size_t i = 0; i < numConfig; i++) {
671 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700672 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800673 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700674 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800675 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700676 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800677 }
Eric Laurent81784c32012-11-19 14:55:58 -0800678
679 if (locked) {
680 mLock.unlock();
681 }
682}
683
684void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
685{
686 const size_t SIZE = 256;
687 char buffer[SIZE];
688 String8 result;
689
Marco Nelissenb2208842014-02-07 14:00:50 -0800690 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000691 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800692 write(fd, buffer, strlen(buffer));
693
Marco Nelissenb2208842014-02-07 14:00:50 -0800694 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800695 sp<EffectChain> chain = mEffectChains[i];
696 if (chain != 0) {
697 chain->dump(fd, args);
698 }
699 }
700}
701
Marco Nelissene14a5d62013-10-03 08:51:24 -0700702void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800703{
704 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700705 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800706}
707
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100708String16 AudioFlinger::ThreadBase::getWakeLockTag()
709{
710 switch (mType) {
711 case MIXER:
712 return String16("AudioMix");
713 case DIRECT:
714 return String16("AudioDirectOut");
715 case DUPLICATING:
716 return String16("AudioDup");
717 case RECORD:
718 return String16("AudioIn");
719 case OFFLOAD:
720 return String16("AudioOffload");
721 default:
722 ALOG_ASSERT(false);
723 return String16("AudioUnknown");
724 }
725}
726
Marco Nelissene14a5d62013-10-03 08:51:24 -0700727void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800728{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800729 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800730 if (mPowerManager != 0) {
731 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700732 status_t status;
733 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700734 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700735 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100736 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700737 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700738 uid,
739 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700740 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700741 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700742 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100743 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700744 String16("media"),
745 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700746 }
Eric Laurent81784c32012-11-19 14:55:58 -0800747 if (status == NO_ERROR) {
748 mWakeLockToken = binder;
749 }
750 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
751 }
752}
753
754void AudioFlinger::ThreadBase::releaseWakeLock()
755{
756 Mutex::Autolock _l(mLock);
757 releaseWakeLock_l();
758}
759
760void AudioFlinger::ThreadBase::releaseWakeLock_l()
761{
762 if (mWakeLockToken != 0) {
763 ALOGV("releaseWakeLock_l() %s", mName);
764 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700765 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
766 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
768 mWakeLockToken.clear();
769 }
770}
771
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800772void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
773 Mutex::Autolock _l(mLock);
774 updateWakeLockUids_l(uids);
775}
776
777void AudioFlinger::ThreadBase::getPowerManager_l() {
778
779 if (mPowerManager == 0) {
780 // use checkService() to avoid blocking if power service is not up yet
781 sp<IBinder> binder =
782 defaultServiceManager()->checkService(String16("power"));
783 if (binder == 0) {
784 ALOGW("Thread %s cannot connect to the power manager service", mName);
785 } else {
786 mPowerManager = interface_cast<IPowerManager>(binder);
787 binder->linkToDeath(mDeathRecipient);
788 }
789 }
790}
791
792void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
793
794 getPowerManager_l();
795 if (mWakeLockToken == NULL) {
796 ALOGE("no wake lock to update!");
797 return;
798 }
799 if (mPowerManager != 0) {
800 sp<IBinder> binder = new BBinder();
801 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700802 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
803 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800804 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
805 }
806}
807
Eric Laurent81784c32012-11-19 14:55:58 -0800808void AudioFlinger::ThreadBase::clearPowerManager()
809{
810 Mutex::Autolock _l(mLock);
811 releaseWakeLock_l();
812 mPowerManager.clear();
813}
814
Glenn Kasten0f11b512014-01-31 16:18:54 -0800815void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800816{
817 sp<ThreadBase> thread = mThread.promote();
818 if (thread != 0) {
819 thread->clearPowerManager();
820 }
821 ALOGW("power manager service died !!!");
822}
823
824void AudioFlinger::ThreadBase::setEffectSuspended(
825 const effect_uuid_t *type, bool suspend, int sessionId)
826{
827 Mutex::Autolock _l(mLock);
828 setEffectSuspended_l(type, suspend, sessionId);
829}
830
831void AudioFlinger::ThreadBase::setEffectSuspended_l(
832 const effect_uuid_t *type, bool suspend, int sessionId)
833{
834 sp<EffectChain> chain = getEffectChain_l(sessionId);
835 if (chain != 0) {
836 if (type != NULL) {
837 chain->setEffectSuspended_l(type, suspend);
838 } else {
839 chain->setEffectSuspendedAll_l(suspend);
840 }
841 }
842
843 updateSuspendedSessions_l(type, suspend, sessionId);
844}
845
846void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
847{
848 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
849 if (index < 0) {
850 return;
851 }
852
853 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
854 mSuspendedSessions.valueAt(index);
855
856 for (size_t i = 0; i < sessionEffects.size(); i++) {
857 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
858 for (int j = 0; j < desc->mRefCount; j++) {
859 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
860 chain->setEffectSuspendedAll_l(true);
861 } else {
862 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
863 desc->mType.timeLow);
864 chain->setEffectSuspended_l(&desc->mType, true);
865 }
866 }
867 }
868}
869
870void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
871 bool suspend,
872 int sessionId)
873{
874 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
875
876 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
877
878 if (suspend) {
879 if (index >= 0) {
880 sessionEffects = mSuspendedSessions.valueAt(index);
881 } else {
882 mSuspendedSessions.add(sessionId, sessionEffects);
883 }
884 } else {
885 if (index < 0) {
886 return;
887 }
888 sessionEffects = mSuspendedSessions.valueAt(index);
889 }
890
891
892 int key = EffectChain::kKeyForSuspendAll;
893 if (type != NULL) {
894 key = type->timeLow;
895 }
896 index = sessionEffects.indexOfKey(key);
897
898 sp<SuspendedSessionDesc> desc;
899 if (suspend) {
900 if (index >= 0) {
901 desc = sessionEffects.valueAt(index);
902 } else {
903 desc = new SuspendedSessionDesc();
904 if (type != NULL) {
905 desc->mType = *type;
906 }
907 sessionEffects.add(key, desc);
908 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
909 }
910 desc->mRefCount++;
911 } else {
912 if (index < 0) {
913 return;
914 }
915 desc = sessionEffects.valueAt(index);
916 if (--desc->mRefCount == 0) {
917 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
918 sessionEffects.removeItemsAt(index);
919 if (sessionEffects.isEmpty()) {
920 ALOGV("updateSuspendedSessions_l() restore removing session %d",
921 sessionId);
922 mSuspendedSessions.removeItem(sessionId);
923 }
924 }
925 }
926 if (!sessionEffects.isEmpty()) {
927 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
928 }
929}
930
931void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
932 bool enabled,
933 int sessionId)
934{
935 Mutex::Autolock _l(mLock);
936 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
937}
938
939void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
940 bool enabled,
941 int sessionId)
942{
943 if (mType != RECORD) {
944 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
945 // another session. This gives the priority to well behaved effect control panels
946 // and applications not using global effects.
947 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
948 // global effects
949 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
950 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
951 }
952 }
953
954 sp<EffectChain> chain = getEffectChain_l(sessionId);
955 if (chain != 0) {
956 chain->checkSuspendOnEffectEnabled(effect, enabled);
957 }
958}
959
960// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
961sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
962 const sp<AudioFlinger::Client>& client,
963 const sp<IEffectClient>& effectClient,
964 int32_t priority,
965 int sessionId,
966 effect_descriptor_t *desc,
967 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700968 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800969{
970 sp<EffectModule> effect;
971 sp<EffectHandle> handle;
972 status_t lStatus;
973 sp<EffectChain> chain;
974 bool chainCreated = false;
975 bool effectCreated = false;
976 bool effectRegistered = false;
977
978 lStatus = initCheck();
979 if (lStatus != NO_ERROR) {
980 ALOGW("createEffect_l() Audio driver not initialized.");
981 goto Exit;
982 }
983
Andy Hung98ef9782014-03-04 14:46:50 -0800984 // Reject any effect on Direct output threads for now, since the format of
985 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
986 if (mType == DIRECT) {
987 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
988 desc->name, mName);
989 lStatus = BAD_VALUE;
990 goto Exit;
991 }
992
Andy Hung389cfdb2014-08-07 17:49:53 -0700993 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700994 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700995 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
996 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
997 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700998 lStatus = BAD_VALUE;
999 goto Exit;
1000 }
1001
Eric Laurent5baf2af2013-09-12 17:37:00 -07001002 // Allow global effects only on offloaded and mixer threads
1003 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1004 switch (mType) {
1005 case MIXER:
1006 case OFFLOAD:
1007 break;
1008 case DIRECT:
1009 case DUPLICATING:
1010 case RECORD:
1011 default:
1012 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
1013 lStatus = BAD_VALUE;
1014 goto Exit;
1015 }
Eric Laurent81784c32012-11-19 14:55:58 -08001016 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001017
Eric Laurent81784c32012-11-19 14:55:58 -08001018 // Only Pre processor effects are allowed on input threads and only on input threads
1019 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1020 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1021 desc->name, desc->flags, mType);
1022 lStatus = BAD_VALUE;
1023 goto Exit;
1024 }
1025
1026 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1027
1028 { // scope for mLock
1029 Mutex::Autolock _l(mLock);
1030
1031 // check for existing effect chain with the requested audio session
1032 chain = getEffectChain_l(sessionId);
1033 if (chain == 0) {
1034 // create a new chain for this session
1035 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1036 chain = new EffectChain(this, sessionId);
1037 addEffectChain_l(chain);
1038 chain->setStrategy(getStrategyForSession_l(sessionId));
1039 chainCreated = true;
1040 } else {
1041 effect = chain->getEffectFromDesc_l(desc);
1042 }
1043
1044 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1045
1046 if (effect == 0) {
1047 int id = mAudioFlinger->nextUniqueId();
1048 // Check CPU and memory usage
1049 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1050 if (lStatus != NO_ERROR) {
1051 goto Exit;
1052 }
1053 effectRegistered = true;
1054 // create a new effect module if none present in the chain
1055 effect = new EffectModule(this, chain, desc, id, sessionId);
1056 lStatus = effect->status();
1057 if (lStatus != NO_ERROR) {
1058 goto Exit;
1059 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001060 effect->setOffloaded(mType == OFFLOAD, mId);
1061
Eric Laurent81784c32012-11-19 14:55:58 -08001062 lStatus = chain->addEffect_l(effect);
1063 if (lStatus != NO_ERROR) {
1064 goto Exit;
1065 }
1066 effectCreated = true;
1067
1068 effect->setDevice(mOutDevice);
1069 effect->setDevice(mInDevice);
1070 effect->setMode(mAudioFlinger->getMode());
1071 effect->setAudioSource(mAudioSource);
1072 }
1073 // create effect handle and connect it to effect module
1074 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001075 lStatus = handle->initCheck();
1076 if (lStatus == OK) {
1077 lStatus = effect->addHandle(handle.get());
1078 }
Eric Laurent81784c32012-11-19 14:55:58 -08001079 if (enabled != NULL) {
1080 *enabled = (int)effect->isEnabled();
1081 }
1082 }
1083
1084Exit:
1085 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1086 Mutex::Autolock _l(mLock);
1087 if (effectCreated) {
1088 chain->removeEffect_l(effect);
1089 }
1090 if (effectRegistered) {
1091 AudioSystem::unregisterEffect(effect->id());
1092 }
1093 if (chainCreated) {
1094 removeEffectChain_l(chain);
1095 }
1096 handle.clear();
1097 }
1098
Glenn Kasten9156ef32013-08-06 15:39:08 -07001099 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001100 return handle;
1101}
1102
1103sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1104{
1105 Mutex::Autolock _l(mLock);
1106 return getEffect_l(sessionId, effectId);
1107}
1108
1109sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1110{
1111 sp<EffectChain> chain = getEffectChain_l(sessionId);
1112 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1113}
1114
1115// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1116// PlaybackThread::mLock held
1117status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1118{
1119 // check for existing effect chain with the requested audio session
1120 int sessionId = effect->sessionId();
1121 sp<EffectChain> chain = getEffectChain_l(sessionId);
1122 bool chainCreated = false;
1123
Eric Laurent5baf2af2013-09-12 17:37:00 -07001124 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1125 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1126 this, effect->desc().name, effect->desc().flags);
1127
Eric Laurent81784c32012-11-19 14:55:58 -08001128 if (chain == 0) {
1129 // create a new chain for this session
1130 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1131 chain = new EffectChain(this, sessionId);
1132 addEffectChain_l(chain);
1133 chain->setStrategy(getStrategyForSession_l(sessionId));
1134 chainCreated = true;
1135 }
1136 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1137
1138 if (chain->getEffectFromId_l(effect->id()) != 0) {
1139 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1140 this, effect->desc().name, chain.get());
1141 return BAD_VALUE;
1142 }
1143
Eric Laurent5baf2af2013-09-12 17:37:00 -07001144 effect->setOffloaded(mType == OFFLOAD, mId);
1145
Eric Laurent81784c32012-11-19 14:55:58 -08001146 status_t status = chain->addEffect_l(effect);
1147 if (status != NO_ERROR) {
1148 if (chainCreated) {
1149 removeEffectChain_l(chain);
1150 }
1151 return status;
1152 }
1153
1154 effect->setDevice(mOutDevice);
1155 effect->setDevice(mInDevice);
1156 effect->setMode(mAudioFlinger->getMode());
1157 effect->setAudioSource(mAudioSource);
1158 return NO_ERROR;
1159}
1160
1161void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1162
1163 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1164 effect_descriptor_t desc = effect->desc();
1165 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1166 detachAuxEffect_l(effect->id());
1167 }
1168
1169 sp<EffectChain> chain = effect->chain().promote();
1170 if (chain != 0) {
1171 // remove effect chain if removing last effect
1172 if (chain->removeEffect_l(effect) == 0) {
1173 removeEffectChain_l(chain);
1174 }
1175 } else {
1176 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1177 }
1178}
1179
1180void AudioFlinger::ThreadBase::lockEffectChains_l(
1181 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1182{
1183 effectChains = mEffectChains;
1184 for (size_t i = 0; i < mEffectChains.size(); i++) {
1185 mEffectChains[i]->lock();
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::unlockEffectChains(
1190 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1191{
1192 for (size_t i = 0; i < effectChains.size(); i++) {
1193 effectChains[i]->unlock();
1194 }
1195}
1196
1197sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1198{
1199 Mutex::Autolock _l(mLock);
1200 return getEffectChain_l(sessionId);
1201}
1202
1203sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1204{
1205 size_t size = mEffectChains.size();
1206 for (size_t i = 0; i < size; i++) {
1207 if (mEffectChains[i]->sessionId() == sessionId) {
1208 return mEffectChains[i];
1209 }
1210 }
1211 return 0;
1212}
1213
1214void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1215{
1216 Mutex::Autolock _l(mLock);
1217 size_t size = mEffectChains.size();
1218 for (size_t i = 0; i < size; i++) {
1219 mEffectChains[i]->setMode_l(mode);
1220 }
1221}
1222
Eric Laurent83b88082014-06-20 18:31:16 -07001223void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1224{
1225 config->type = AUDIO_PORT_TYPE_MIX;
1226 config->ext.mix.handle = mId;
1227 config->sample_rate = mSampleRate;
1228 config->format = mFormat;
1229 config->channel_mask = mChannelMask;
1230 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1231 AUDIO_PORT_CONFIG_FORMAT;
1232}
1233
1234
Eric Laurent81784c32012-11-19 14:55:58 -08001235// ----------------------------------------------------------------------------
1236// Playback
1237// ----------------------------------------------------------------------------
1238
1239AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1240 AudioStreamOut* output,
1241 audio_io_handle_t id,
1242 audio_devices_t device,
1243 type_t type)
1244 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001245 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001246 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001247 mMixerBuffer(NULL),
1248 mMixerBufferSize(0),
1249 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1250 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001251 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001252 mEffectBuffer(NULL),
1253 mEffectBufferSize(0),
1254 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1255 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001256 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001257 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001258 // mStreamTypes[] initialized in constructor body
1259 mOutput(output),
1260 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1261 mMixerStatus(MIXER_IDLE),
1262 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1263 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001264 mBytesRemaining(0),
1265 mCurrentWriteLength(0),
1266 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001267 mWriteAckSequence(0),
1268 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001269 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001270 mScreenState(AudioFlinger::mScreenState),
1271 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001272 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001273 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001274 // mLatchD, mLatchQ,
1275 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001276{
1277 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001278 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001279
1280 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1281 // it would be safer to explicitly pass initial masterVolume/masterMute as
1282 // parameter.
1283 //
1284 // If the HAL we are using has support for master volume or master mute,
1285 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1286 // and the mute set to false).
1287 mMasterVolume = audioFlinger->masterVolume_l();
1288 mMasterMute = audioFlinger->masterMute_l();
1289 if (mOutput && mOutput->audioHwDev) {
1290 if (mOutput->audioHwDev->canSetMasterVolume()) {
1291 mMasterVolume = 1.0;
1292 }
1293
1294 if (mOutput->audioHwDev->canSetMasterMute()) {
1295 mMasterMute = false;
1296 }
1297 }
1298
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001299 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001300
Eric Laurent223fd5c2014-11-11 13:43:36 -08001301 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001302 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001303 stream = (audio_stream_type_t) (stream + 1)) {
1304 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1305 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1306 }
Eric Laurent81784c32012-11-19 14:55:58 -08001307}
1308
1309AudioFlinger::PlaybackThread::~PlaybackThread()
1310{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001311 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001312 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001313 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001314 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001315}
1316
1317void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1318{
1319 dumpInternals(fd, args);
1320 dumpTracks(fd, args);
1321 dumpEffectChains(fd, args);
1322}
1323
Glenn Kasten0f11b512014-01-31 16:18:54 -08001324void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001325{
1326 const size_t SIZE = 256;
1327 char buffer[SIZE];
1328 String8 result;
1329
Marco Nelissenb2208842014-02-07 14:00:50 -08001330 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001331 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1332 const stream_type_t *st = &mStreamTypes[i];
1333 if (i > 0) {
1334 result.appendFormat(", ");
1335 }
1336 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1337 if (st->mute) {
1338 result.append("M");
1339 }
1340 }
1341 result.append("\n");
1342 write(fd, result.string(), result.length());
1343 result.clear();
1344
Eric Laurent81784c32012-11-19 14:55:58 -08001345 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1346 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001347 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001348 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001349
1350 size_t numtracks = mTracks.size();
1351 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001352 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001353 size_t numactiveseen = 0;
1354 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001355 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001356 Track::appendDumpHeader(result);
1357 for (size_t i = 0; i < numtracks; ++i) {
1358 sp<Track> track = mTracks[i];
1359 if (track != 0) {
1360 bool active = mActiveTracks.indexOf(track) >= 0;
1361 if (active) {
1362 numactiveseen++;
1363 }
1364 track->dump(buffer, SIZE, active);
1365 result.append(buffer);
1366 }
1367 }
1368 } else {
1369 result.append("\n");
1370 }
1371 if (numactiveseen != numactive) {
1372 // some tracks in the active list were not in the tracks list
1373 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1374 " not in the track list\n");
1375 result.append(buffer);
1376 Track::appendDumpHeader(result);
1377 for (size_t i = 0; i < numactive; ++i) {
1378 sp<Track> track = mActiveTracks[i].promote();
1379 if (track != 0 && mTracks.indexOf(track) < 0) {
1380 track->dump(buffer, SIZE, true);
1381 result.append(buffer);
1382 }
1383 }
1384 }
1385
1386 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001387}
1388
1389void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1390{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001391 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001392 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1393 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1394 dprintf(fd, " Total writes: %d\n", mNumWrites);
1395 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1396 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1397 dprintf(fd, " Suspend count: %d\n", mSuspended);
1398 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1399 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1400 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1401 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001402 AudioStreamOut *output = mOutput;
1403 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1404 String8 flagsAsString = outputFlagsToString(flags);
1405 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001406
1407 dumpBase(fd, args);
1408}
1409
1410// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001411
1412void AudioFlinger::PlaybackThread::onFirstRef()
1413{
1414 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1415}
1416
1417// ThreadBase virtuals
1418void AudioFlinger::PlaybackThread::preExit()
1419{
1420 ALOGV(" preExit()");
1421 // FIXME this is using hard-coded strings but in the future, this functionality will be
1422 // converted to use audio HAL extensions required to support tunneling
1423 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1424}
1425
1426// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1427sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1428 const sp<AudioFlinger::Client>& client,
1429 audio_stream_type_t streamType,
1430 uint32_t sampleRate,
1431 audio_format_t format,
1432 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001433 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001434 const sp<IMemory>& sharedBuffer,
1435 int sessionId,
1436 IAudioFlinger::track_flags_t *flags,
1437 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001438 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001439 status_t *status)
1440{
Glenn Kasten74935e42013-12-19 08:56:45 -08001441 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001442 sp<Track> track;
1443 status_t lStatus;
1444
1445 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1446
1447 // client expresses a preference for FAST, but we get the final say
1448 if (*flags & IAudioFlinger::TRACK_FAST) {
1449 if (
1450 // not timed
1451 (!isTimed) &&
1452 // either of these use cases:
1453 (
1454 // use case 1: shared buffer with any frame count
1455 (
1456 (sharedBuffer != 0)
1457 ) ||
1458 // use case 2: callback handler and frame count is default or at least as large as HAL
1459 (
1460 (tid != -1) &&
1461 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001462 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001463 )
1464 ) &&
1465 // PCM data
1466 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001467 // identical channel mask to sink, or mono in and stereo sink
1468 (channelMask == mChannelMask ||
1469 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1470 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001471 // hardware sample rate
1472 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001473 // normal mixer has an associated fast mixer
1474 hasFastMixer() &&
1475 // there are sufficient fast track slots available
1476 (mFastTrackAvailMask != 0)
1477 // FIXME test that MixerThread for this fast track has a capable output HAL
1478 // FIXME add a permission test also?
1479 ) {
1480 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1481 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001482 // read the fast track multiplier property the first time it is needed
1483 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1484 if (ok != 0) {
1485 ALOGE("%s pthread_once failed: %d", __func__, ok);
1486 }
1487 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001488 }
1489 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1490 frameCount, mFrameCount);
1491 } else {
1492 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001493 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1494 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001495 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001496 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001497 audio_is_linear_pcm(format),
1498 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1499 *flags &= ~IAudioFlinger::TRACK_FAST;
1500 // For compatibility with AudioTrack calculation, buffer depth is forced
1501 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1502 // This is probably too conservative, but legacy application code may depend on it.
1503 // If you change this calculation, also review the start threshold which is related.
1504 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1505 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1506 if (minBufCount < 2) {
1507 minBufCount = 2;
1508 }
1509 size_t minFrameCount = mNormalFrameCount * minBufCount;
1510 if (frameCount < minFrameCount) {
1511 frameCount = minFrameCount;
1512 }
1513 }
1514 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001515 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001516
Glenn Kastenc3df8382014-03-13 15:05:25 -07001517 switch (mType) {
1518
1519 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001520 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001521 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001522 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1523 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001524 sampleRate, format, channelMask, mOutput, mFormat);
1525 lStatus = BAD_VALUE;
1526 goto Exit;
1527 }
1528 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001529 break;
1530
1531 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001532 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001533 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1534 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001535 sampleRate, format, channelMask, mOutput, mFormat);
1536 lStatus = BAD_VALUE;
1537 goto Exit;
1538 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001539 break;
1540
1541 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001542 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001543 ALOGE("createTrack_l() Bad parameter: format %#x \""
1544 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001545 format, mOutput, mFormat);
1546 lStatus = BAD_VALUE;
1547 goto Exit;
1548 }
Andy Hungcd044842014-08-07 11:04:34 -07001549 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001550 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1551 lStatus = BAD_VALUE;
1552 goto Exit;
1553 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001554 break;
1555
Eric Laurent81784c32012-11-19 14:55:58 -08001556 }
1557
1558 lStatus = initCheck();
1559 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001560 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001561 goto Exit;
1562 }
1563
1564 { // scope for mLock
1565 Mutex::Autolock _l(mLock);
1566
1567 // all tracks in same audio session must share the same routing strategy otherwise
1568 // conflicts will happen when tracks are moved from one output to another by audio policy
1569 // manager
1570 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1571 for (size_t i = 0; i < mTracks.size(); ++i) {
1572 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001573 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001574 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1575 if (sessionId == t->sessionId() && strategy != actual) {
1576 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1577 strategy, actual);
1578 lStatus = BAD_VALUE;
1579 goto Exit;
1580 }
1581 }
1582 }
1583
1584 if (!isTimed) {
1585 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001586 channelMask, frameCount, NULL, sharedBuffer,
1587 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001588 } else {
1589 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001590 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001591 }
Glenn Kasten03003332013-08-06 15:40:54 -07001592
1593 // new Track always returns non-NULL,
1594 // but TimedTrack::create() is a factory that could fail by returning NULL
1595 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1596 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001597 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001598 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001599 goto Exit;
1600 }
1601 mTracks.add(track);
1602
1603 sp<EffectChain> chain = getEffectChain_l(sessionId);
1604 if (chain != 0) {
1605 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1606 track->setMainBuffer(chain->inBuffer());
1607 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1608 chain->incTrackCnt();
1609 }
1610
1611 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1612 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1613 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1614 // so ask activity manager to do this on our behalf
1615 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1616 }
1617 }
1618
1619 lStatus = NO_ERROR;
1620
1621Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001622 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001623 return track;
1624}
1625
1626uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1627{
1628 return latency;
1629}
1630
1631uint32_t AudioFlinger::PlaybackThread::latency() const
1632{
1633 Mutex::Autolock _l(mLock);
1634 return latency_l();
1635}
1636uint32_t AudioFlinger::PlaybackThread::latency_l() const
1637{
1638 if (initCheck() == NO_ERROR) {
1639 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1640 } else {
1641 return 0;
1642 }
1643}
1644
1645void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1646{
1647 Mutex::Autolock _l(mLock);
1648 // Don't apply master volume in SW if our HAL can do it for us.
1649 if (mOutput && mOutput->audioHwDev &&
1650 mOutput->audioHwDev->canSetMasterVolume()) {
1651 mMasterVolume = 1.0;
1652 } else {
1653 mMasterVolume = value;
1654 }
1655}
1656
1657void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1658{
1659 Mutex::Autolock _l(mLock);
1660 // Don't apply master mute in SW if our HAL can do it for us.
1661 if (mOutput && mOutput->audioHwDev &&
1662 mOutput->audioHwDev->canSetMasterMute()) {
1663 mMasterMute = false;
1664 } else {
1665 mMasterMute = muted;
1666 }
1667}
1668
1669void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1670{
1671 Mutex::Autolock _l(mLock);
1672 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001673 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
1676void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1677{
1678 Mutex::Autolock _l(mLock);
1679 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001680 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001681}
1682
1683float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1684{
1685 Mutex::Autolock _l(mLock);
1686 return mStreamTypes[stream].volume;
1687}
1688
1689// addTrack_l() must be called with ThreadBase::mLock held
1690status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1691{
1692 status_t status = ALREADY_EXISTS;
1693
1694 // set retry count for buffer fill
1695 track->mRetryCount = kMaxTrackStartupRetries;
1696 if (mActiveTracks.indexOf(track) < 0) {
1697 // the track is newly added, make sure it fills up all its
1698 // buffers before playing. This is to ensure the client will
1699 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001700 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001701 TrackBase::track_state state = track->mState;
1702 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001703 status = AudioSystem::startOutput(mId, track->streamType(),
1704 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mLock.lock();
1706 // abort track was stopped/paused while we released the lock
1707 if (state != track->mState) {
1708 if (status == NO_ERROR) {
1709 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001710 AudioSystem::stopOutput(mId, track->streamType(),
1711 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001712 mLock.lock();
1713 }
1714 return INVALID_OPERATION;
1715 }
1716 // abort if start is rejected by audio policy manager
1717 if (status != NO_ERROR) {
1718 return PERMISSION_DENIED;
1719 }
1720#ifdef ADD_BATTERY_DATA
1721 // to track the speaker usage
1722 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1723#endif
1724 }
1725
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001726 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001727 track->mResetDone = false;
1728 track->mPresentationCompleteFrames = 0;
1729 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001730 mWakeLockUids.add(track->uid());
1731 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001732 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001733 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1734 if (chain != 0) {
1735 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1736 track->sessionId());
1737 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001738 }
1739
1740 status = NO_ERROR;
1741 }
1742
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001743 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001744 return status;
1745}
1746
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001748{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001749 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001750 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1752 track->mState = TrackBase::STOPPED;
1753 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001754 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001755 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001757 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001758
1759 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001760}
1761
1762void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1763{
1764 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1765 mTracks.remove(track);
1766 deleteTrackName_l(track->name());
1767 // redundant as track is about to be destroyed, for dumpsys only
1768 track->mName = -1;
1769 if (track->isFastTrack()) {
1770 int index = track->mFastIndex;
1771 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1772 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1773 mFastTrackAvailMask |= 1 << index;
1774 // redundant as track is about to be destroyed, for dumpsys only
1775 track->mFastIndex = -1;
1776 }
1777 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1778 if (chain != 0) {
1779 chain->decTrackCnt();
1780 }
1781}
1782
Eric Laurentede6c3b2013-09-19 14:37:46 -07001783void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784{
1785 // Thread could be blocked waiting for async
1786 // so signal it to handle state changes immediately
1787 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1788 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1789 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001790 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791}
1792
Eric Laurent81784c32012-11-19 14:55:58 -08001793String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1794{
Eric Laurent81784c32012-11-19 14:55:58 -08001795 Mutex::Autolock _l(mLock);
1796 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001797 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001798 }
1799
Glenn Kastend8ea6992013-07-16 14:17:15 -07001800 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1801 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001802 free(s);
1803 return out_s8;
1804}
1805
Eric Laurent021cf962014-05-13 10:18:14 -07001806void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001807 AudioSystem::OutputDescriptor desc;
1808 void *param2 = NULL;
1809
Eric Laurent021cf962014-05-13 10:18:14 -07001810 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001811 param);
1812
1813 switch (event) {
1814 case AudioSystem::OUTPUT_OPENED:
1815 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001816 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001817 desc.samplingRate = mSampleRate;
1818 desc.format = mFormat;
1819 desc.frameCount = mNormalFrameCount; // FIXME see
1820 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001821 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001822 param2 = &desc;
1823 break;
1824
1825 case AudioSystem::STREAM_CONFIG_CHANGED:
1826 param2 = &param;
1827 case AudioSystem::OUTPUT_CLOSED:
1828 default:
1829 break;
1830 }
Eric Laurent021cf962014-05-13 10:18:14 -07001831 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001832}
1833
Eric Laurentbfb1b832013-01-07 09:53:42 -08001834void AudioFlinger::PlaybackThread::writeCallback()
1835{
1836 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001837 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001838}
1839
1840void AudioFlinger::PlaybackThread::drainCallback()
1841{
1842 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001843 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001844}
1845
Eric Laurent3b4529e2013-09-05 18:09:19 -07001846void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001847{
1848 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001849 // reject out of sequence requests
1850 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1851 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852 mWaitWorkCV.signal();
1853 }
1854}
1855
Eric Laurent3b4529e2013-09-05 18:09:19 -07001856void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857{
1858 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001859 // reject out of sequence requests
1860 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1861 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 mWaitWorkCV.signal();
1863 }
1864}
1865
1866// static
1867int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001868 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 void *cookie)
1870{
1871 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1872 ALOGV("asyncCallback() event %d", event);
1873 switch (event) {
1874 case STREAM_CBK_EVENT_WRITE_READY:
1875 me->writeCallback();
1876 break;
1877 case STREAM_CBK_EVENT_DRAIN_READY:
1878 me->drainCallback();
1879 break;
1880 default:
1881 ALOGW("asyncCallback() unknown event %d", event);
1882 break;
1883 }
1884 return 0;
1885}
1886
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001887void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001889 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001890 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1891 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001892 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001893 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001894 }
Andy Hung9a592762014-07-21 21:56:01 -07001895 if ((mType == MIXER || mType == DUPLICATING)
1896 && !isValidPcmSinkChannelMask(mChannelMask)) {
1897 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1898 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001899 }
Andy Hunge5412692014-05-16 11:25:07 -07001900 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001901 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1902 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001903 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001904 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001905 }
Andy Hung6146c082014-03-18 11:56:15 -07001906 if ((mType == MIXER || mType == DUPLICATING)
1907 && !isValidPcmSinkFormat(mFormat)) {
1908 LOG_FATAL("HAL format %#x not supported for mixed output",
1909 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001910 }
Eric Laurent665470b2014-07-03 16:37:08 -07001911 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001912 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1913 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001914 if (mFrameCount & 15) {
1915 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1916 mFrameCount);
1917 }
1918
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1920 (mOutput->stream->set_callback != NULL)) {
1921 if (mOutput->stream->set_callback(mOutput->stream,
1922 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1923 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001924 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001925 }
1926 }
1927
Eric Laurentd1f69b02014-12-15 14:33:13 -08001928 mHwSupportsPause = false;
1929 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1930 if (mOutput->stream->pause != NULL) {
1931 if (mOutput->stream->resume != NULL) {
1932 mHwSupportsPause = true;
1933 } else {
1934 ALOGW("direct output implements pause but not resume");
1935 }
1936 } else if (mOutput->stream->resume != NULL) {
1937 ALOGW("direct output implements resume but not pause");
1938 }
1939 }
1940
Andy Hungfbfc3952015-01-15 13:33:51 -08001941 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
1942 // For best precision, we use float instead of the associated output
1943 // device format (typically PCM 16 bit).
1944
1945 mFormat = AUDIO_FORMAT_PCM_FLOAT;
1946 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
1947 mBufferSize = mFrameSize * mFrameCount;
1948
1949 // TODO: We currently use the associated output device channel mask and sample rate.
1950 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
1951 // (if a valid mask) to avoid premature downmix.
1952 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
1953 // instead of the output device sample rate to avoid loss of high frequency information.
1954 // This may need to be updated as MixerThread/OutputTracks are added and not here.
1955 }
1956
Andy Hung09a50072014-02-27 14:30:47 -08001957 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001958 double multiplier = 1.0;
1959 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1960 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001961 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1962 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001963 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1964 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1965 maxNormalFrameCount = maxNormalFrameCount & ~15;
1966 if (maxNormalFrameCount < minNormalFrameCount) {
1967 maxNormalFrameCount = minNormalFrameCount;
1968 }
1969 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1970 if (multiplier <= 1.0) {
1971 multiplier = 1.0;
1972 } else if (multiplier <= 2.0) {
1973 if (2 * mFrameCount <= maxNormalFrameCount) {
1974 multiplier = 2.0;
1975 } else {
1976 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1977 }
1978 } else {
1979 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001980 // 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 -08001981 // track, but we sometimes have to do this to satisfy the maximum frame count
1982 // constraint)
1983 // FIXME this rounding up should not be done if no HAL SRC
1984 uint32_t truncMult = (uint32_t) multiplier;
1985 if ((truncMult & 1)) {
1986 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1987 ++truncMult;
1988 }
1989 }
1990 multiplier = (double) truncMult;
1991 }
1992 }
1993 mNormalFrameCount = multiplier * mFrameCount;
1994 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001995 if (mType == MIXER || mType == DUPLICATING) {
1996 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1997 }
Andy Hung09a50072014-02-27 14:30:47 -08001998 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001999 mNormalFrameCount);
2000
Andy Hung010a1a12014-03-13 13:57:33 -07002001 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2002 // Originally this was int16_t[] array, need to remove legacy implications.
2003 free(mSinkBuffer);
2004 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002005 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2006 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2007 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002008 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002009
Andy Hung69aed5f2014-02-25 17:24:40 -08002010 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2011 // drives the output.
2012 free(mMixerBuffer);
2013 mMixerBuffer = NULL;
2014 if (mMixerBufferEnabled) {
2015 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2016 mMixerBufferSize = mNormalFrameCount * mChannelCount
2017 * audio_bytes_per_sample(mMixerBufferFormat);
2018 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2019 }
Andy Hung98ef9782014-03-04 14:46:50 -08002020 free(mEffectBuffer);
2021 mEffectBuffer = NULL;
2022 if (mEffectBufferEnabled) {
2023 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2024 mEffectBufferSize = mNormalFrameCount * mChannelCount
2025 * audio_bytes_per_sample(mEffectBufferFormat);
2026 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2027 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002028
Eric Laurent81784c32012-11-19 14:55:58 -08002029 // force reconfiguration of effect chains and engines to take new buffer size and audio
2030 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002031 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002032 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2033 // matter.
2034 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2035 Vector< sp<EffectChain> > effectChains = mEffectChains;
2036 for (size_t i = 0; i < effectChains.size(); i ++) {
2037 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2038 }
2039}
2040
2041
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002042status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002043{
2044 if (halFrames == NULL || dspFrames == NULL) {
2045 return BAD_VALUE;
2046 }
2047 Mutex::Autolock _l(mLock);
2048 if (initCheck() != NO_ERROR) {
2049 return INVALID_OPERATION;
2050 }
2051 size_t framesWritten = mBytesWritten / mFrameSize;
2052 *halFrames = framesWritten;
2053
2054 if (isSuspended()) {
2055 // return an estimation of rendered frames when the output is suspended
2056 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2057 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2058 return NO_ERROR;
2059 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002060 status_t status;
2061 uint32_t frames;
2062 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2063 *dspFrames = (size_t)frames;
2064 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002065 }
2066}
2067
2068uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2069{
2070 Mutex::Autolock _l(mLock);
2071 uint32_t result = 0;
2072 if (getEffectChain_l(sessionId) != 0) {
2073 result = EFFECT_SESSION;
2074 }
2075
2076 for (size_t i = 0; i < mTracks.size(); ++i) {
2077 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002078 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002079 result |= TRACK_SESSION;
2080 break;
2081 }
2082 }
2083
2084 return result;
2085}
2086
2087uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2088{
2089 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2090 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2091 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2092 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2093 }
2094 for (size_t i = 0; i < mTracks.size(); i++) {
2095 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002096 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002097 return AudioSystem::getStrategyForStream(track->streamType());
2098 }
2099 }
2100 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2101}
2102
2103
2104AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2105{
2106 Mutex::Autolock _l(mLock);
2107 return mOutput;
2108}
2109
2110AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2111{
2112 Mutex::Autolock _l(mLock);
2113 AudioStreamOut *output = mOutput;
2114 mOutput = NULL;
2115 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2116 // must push a NULL and wait for ack
2117 mOutputSink.clear();
2118 mPipeSink.clear();
2119 mNormalSink.clear();
2120 return output;
2121}
2122
2123// this method must always be called either with ThreadBase mLock held or inside the thread loop
2124audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2125{
2126 if (mOutput == NULL) {
2127 return NULL;
2128 }
2129 return &mOutput->stream->common;
2130}
2131
2132uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2133{
2134 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2135}
2136
2137status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2138{
2139 if (!isValidSyncEvent(event)) {
2140 return BAD_VALUE;
2141 }
2142
2143 Mutex::Autolock _l(mLock);
2144
2145 for (size_t i = 0; i < mTracks.size(); ++i) {
2146 sp<Track> track = mTracks[i];
2147 if (event->triggerSession() == track->sessionId()) {
2148 (void) track->setSyncEvent(event);
2149 return NO_ERROR;
2150 }
2151 }
2152
2153 return NAME_NOT_FOUND;
2154}
2155
2156bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2157{
2158 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2159}
2160
2161void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2162 const Vector< sp<Track> >& tracksToRemove)
2163{
2164 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002165 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002166 for (size_t i = 0 ; i < count ; i++) {
2167 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002168 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002169 AudioSystem::stopOutput(mId, track->streamType(),
2170 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171#ifdef ADD_BATTERY_DATA
2172 // to track the speaker usage
2173 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2174#endif
2175 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002176 AudioSystem::releaseOutput(mId, track->streamType(),
2177 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 }
Eric Laurent81784c32012-11-19 14:55:58 -08002179 }
2180 }
2181 }
Eric Laurent81784c32012-11-19 14:55:58 -08002182}
2183
2184void AudioFlinger::PlaybackThread::checkSilentMode_l()
2185{
2186 if (!mMasterMute) {
2187 char value[PROPERTY_VALUE_MAX];
2188 if (property_get("ro.audio.silent", value, "0") > 0) {
2189 char *endptr;
2190 unsigned long ul = strtoul(value, &endptr, 0);
2191 if (*endptr == '\0' && ul != 0) {
2192 ALOGD("Silence is golden");
2193 // The setprop command will not allow a property to be changed after
2194 // the first time it is set, so we don't have to worry about un-muting.
2195 setMasterMute_l(true);
2196 }
2197 }
2198 }
2199}
2200
2201// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002203{
2204 // FIXME rewrite to reduce number of system calls
2205 mLastWriteTime = systemTime();
2206 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002208 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002209
2210 // If an NBAIO sink is present, use it to write the normal mixer's submix
2211 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002212
Andy Hung010a1a12014-03-13 13:57:33 -07002213 const size_t count = mBytesRemaining / mFrameSize;
2214
Simon Wilson2d590962012-11-29 15:18:50 -08002215 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002216 // update the setpoint when AudioFlinger::mScreenState changes
2217 uint32_t screenState = AudioFlinger::mScreenState;
2218 if (screenState != mScreenState) {
2219 mScreenState = screenState;
2220 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2221 if (pipe != NULL) {
2222 pipe->setAvgFrames((mScreenState & 1) ?
2223 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2224 }
2225 }
Andy Hung010a1a12014-03-13 13:57:33 -07002226 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002227 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002228 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002229 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002230 } else {
2231 bytesWritten = framesWritten;
2232 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002233 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002234 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002235 if (status == NO_ERROR) {
2236 size_t totalFramesWritten = mNormalSink->framesWritten();
2237 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2238 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002239 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002240 mLatchDValid = true;
2241 }
2242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243 // otherwise use the HAL / AudioStreamOut directly
2244 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002246
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002248 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2249 mWriteAckSequence += 2;
2250 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002252 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002254 // FIXME We should have an implementation of timestamps for direct output threads.
2255 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002256 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002257 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258 if (mUseAsyncWrite &&
2259 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2260 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002261 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002263 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264 }
Eric Laurent81784c32012-11-19 14:55:58 -08002265 }
2266
Eric Laurent81784c32012-11-19 14:55:58 -08002267 mNumWrites++;
2268 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002269 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002270 return bytesWritten;
2271}
2272
2273void AudioFlinger::PlaybackThread::threadLoop_drain()
2274{
2275 if (mOutput->stream->drain) {
2276 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2277 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002278 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2279 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002281 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282 }
2283 mOutput->stream->drain(mOutput->stream,
2284 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2285 : AUDIO_DRAIN_ALL);
2286 }
2287}
2288
2289void AudioFlinger::PlaybackThread::threadLoop_exit()
2290{
Eric Laurent275e8e92014-11-30 15:14:47 -08002291 {
2292 Mutex::Autolock _l(mLock);
2293 for (size_t i = 0; i < mTracks.size(); i++) {
2294 sp<Track> track = mTracks[i];
2295 track->invalidate();
2296 }
2297 }
Eric Laurent81784c32012-11-19 14:55:58 -08002298}
2299
2300/*
2301The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002302 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002303 - activeSleepTime from activeSleepTimeUs()
2304 - idleSleepTime from idleSleepTimeUs()
2305 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2306 - maxPeriod from frame count and sample rate (MIXER only)
2307
2308The parameters that affect these derived values are:
2309 - frame count
2310 - frame size
2311 - sample rate
2312 - device type: A2DP or not
2313 - device latency
2314 - format: PCM or not
2315 - active sleep time
2316 - idle sleep time
2317*/
2318
2319void AudioFlinger::PlaybackThread::cacheParameters_l()
2320{
Andy Hung25c2dac2014-02-27 14:56:00 -08002321 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002322 activeSleepTime = activeSleepTimeUs();
2323 idleSleepTime = idleSleepTimeUs();
2324}
2325
2326void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2327{
Glenn Kasten7c027242012-12-26 14:43:16 -08002328 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002329 this, streamType, mTracks.size());
2330 Mutex::Autolock _l(mLock);
2331
2332 size_t size = mTracks.size();
2333 for (size_t i = 0; i < size; i++) {
2334 sp<Track> t = mTracks[i];
2335 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002336 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002337 }
2338 }
2339}
2340
2341status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2342{
2343 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002344 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2345 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002346 bool ownsBuffer = false;
2347
2348 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2349 if (session > 0) {
2350 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002351 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002352 if (mType != DIRECT) {
2353 size_t numSamples = mNormalFrameCount * mChannelCount;
2354 buffer = new int16_t[numSamples];
2355 memset(buffer, 0, numSamples * sizeof(int16_t));
2356 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2357 ownsBuffer = true;
2358 }
2359
2360 // Attach all tracks with same session ID to this chain.
2361 for (size_t i = 0; i < mTracks.size(); ++i) {
2362 sp<Track> track = mTracks[i];
2363 if (session == track->sessionId()) {
2364 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2365 buffer);
2366 track->setMainBuffer(buffer);
2367 chain->incTrackCnt();
2368 }
2369 }
2370
2371 // indicate all active tracks in the chain
2372 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2373 sp<Track> track = mActiveTracks[i].promote();
2374 if (track == 0) {
2375 continue;
2376 }
2377 if (session == track->sessionId()) {
2378 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2379 chain->incActiveTrackCnt();
2380 }
2381 }
2382 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002383 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002384 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002385 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2386 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002387 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2388 // chains list in order to be processed last as it contains output stage effects
2389 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2390 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2391 // after track specific effects and before output stage
2392 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2393 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2394 // Effect chain for other sessions are inserted at beginning of effect
2395 // chains list to be processed before output mix effects. Relative order between other
2396 // sessions is not important
2397 size_t size = mEffectChains.size();
2398 size_t i = 0;
2399 for (i = 0; i < size; i++) {
2400 if (mEffectChains[i]->sessionId() < session) {
2401 break;
2402 }
2403 }
2404 mEffectChains.insertAt(chain, i);
2405 checkSuspendOnAddEffectChain_l(chain);
2406
2407 return NO_ERROR;
2408}
2409
2410size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2411{
2412 int session = chain->sessionId();
2413
2414 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2415
2416 for (size_t i = 0; i < mEffectChains.size(); i++) {
2417 if (chain == mEffectChains[i]) {
2418 mEffectChains.removeAt(i);
2419 // detach all active tracks from the chain
2420 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2421 sp<Track> track = mActiveTracks[i].promote();
2422 if (track == 0) {
2423 continue;
2424 }
2425 if (session == track->sessionId()) {
2426 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2427 chain.get(), session);
2428 chain->decActiveTrackCnt();
2429 }
2430 }
2431
2432 // detach all tracks with same session ID from this chain
2433 for (size_t i = 0; i < mTracks.size(); ++i) {
2434 sp<Track> track = mTracks[i];
2435 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002436 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002437 chain->decTrackCnt();
2438 }
2439 }
2440 break;
2441 }
2442 }
2443 return mEffectChains.size();
2444}
2445
2446status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2447 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2448{
2449 Mutex::Autolock _l(mLock);
2450 return attachAuxEffect_l(track, EffectId);
2451}
2452
2453status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2454 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2455{
2456 status_t status = NO_ERROR;
2457
2458 if (EffectId == 0) {
2459 track->setAuxBuffer(0, NULL);
2460 } else {
2461 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2462 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2463 if (effect != 0) {
2464 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2465 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2466 } else {
2467 status = INVALID_OPERATION;
2468 }
2469 } else {
2470 status = BAD_VALUE;
2471 }
2472 }
2473 return status;
2474}
2475
2476void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2477{
2478 for (size_t i = 0; i < mTracks.size(); ++i) {
2479 sp<Track> track = mTracks[i];
2480 if (track->auxEffectId() == effectId) {
2481 attachAuxEffect_l(track, 0);
2482 }
2483 }
2484}
2485
2486bool AudioFlinger::PlaybackThread::threadLoop()
2487{
2488 Vector< sp<Track> > tracksToRemove;
2489
2490 standbyTime = systemTime();
2491
2492 // MIXER
2493 nsecs_t lastWarning = 0;
2494
2495 // DUPLICATING
2496 // FIXME could this be made local to while loop?
2497 writeFrames = 0;
2498
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002499 int lastGeneration = 0;
2500
Eric Laurent81784c32012-11-19 14:55:58 -08002501 cacheParameters_l();
2502 sleepTime = idleSleepTime;
2503
2504 if (mType == MIXER) {
2505 sleepTimeShift = 0;
2506 }
2507
2508 CpuStats cpuStats;
2509 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2510
2511 acquireWakeLock();
2512
Glenn Kasten9e58b552013-01-18 15:09:48 -08002513 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2514 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2515 // and then that string will be logged at the next convenient opportunity.
2516 const char *logString = NULL;
2517
Eric Laurent664539d2013-09-23 18:24:31 -07002518 checkSilentMode_l();
2519
Eric Laurent81784c32012-11-19 14:55:58 -08002520 while (!exitPending())
2521 {
2522 cpuStats.sample(myName);
2523
2524 Vector< sp<EffectChain> > effectChains;
2525
Eric Laurent81784c32012-11-19 14:55:58 -08002526 { // scope for mLock
2527
2528 Mutex::Autolock _l(mLock);
2529
Eric Laurent021cf962014-05-13 10:18:14 -07002530 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002531
Glenn Kasten9e58b552013-01-18 15:09:48 -08002532 if (logString != NULL) {
2533 mNBLogWriter->logTimestamp();
2534 mNBLogWriter->log(logString);
2535 logString = NULL;
2536 }
2537
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002538 // Gather the framesReleased counters for all active tracks,
2539 // and latch them atomically with the timestamp.
2540 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2541 mLatchD.mFramesReleased.clear();
2542 size_t size = mActiveTracks.size();
2543 for (size_t i = 0; i < size; i++) {
2544 sp<Track> t = mActiveTracks[i].promote();
2545 if (t != 0) {
2546 mLatchD.mFramesReleased.add(t.get(),
2547 t->mAudioTrackServerProxy->framesReleased());
2548 }
2549 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002550 if (mLatchDValid) {
2551 mLatchQ = mLatchD;
2552 mLatchDValid = false;
2553 mLatchQValid = true;
2554 }
2555
Eric Laurent81784c32012-11-19 14:55:58 -08002556 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002557 if (mSignalPending) {
2558 // A signal was raised while we were unlocked
2559 mSignalPending = false;
2560 } else if (waitingAsyncCallback_l()) {
2561 if (exitPending()) {
2562 break;
2563 }
2564 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002565 mWakeLockUids.clear();
2566 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567 ALOGV("wait async completion");
2568 mWaitWorkCV.wait(mLock);
2569 ALOGV("async completion/wake");
2570 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002571 standbyTime = systemTime() + standbyDelay;
2572 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002573
2574 continue;
2575 }
2576 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 isSuspended()) {
2578 // put audio hardware into standby after short delay
2579 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002580
2581 threadLoop_standby();
2582
2583 mStandby = true;
2584 }
2585
2586 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2587 // we're about to wait, flush the binder command buffer
2588 IPCThreadState::self()->flushCommands();
2589
2590 clearOutputTracks();
2591
2592 if (exitPending()) {
2593 break;
2594 }
2595
2596 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002597 mWakeLockUids.clear();
2598 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002599 // wait until we have something to do...
2600 ALOGV("%s going to sleep", myName.string());
2601 mWaitWorkCV.wait(mLock);
2602 ALOGV("%s waking up", myName.string());
2603 acquireWakeLock_l();
2604
2605 mMixerStatus = MIXER_IDLE;
2606 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2607 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002609 checkSilentMode_l();
2610
2611 standbyTime = systemTime() + standbyDelay;
2612 sleepTime = idleSleepTime;
2613 if (mType == MIXER) {
2614 sleepTimeShift = 0;
2615 }
2616
2617 continue;
2618 }
2619 }
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // mMixerStatusIgnoringFastTracks is also updated internally
2621 mMixerStatus = prepareTracks_l(&tracksToRemove);
2622
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002623 // compare with previously applied list
2624 if (lastGeneration != mActiveTracksGeneration) {
2625 // update wakelock
2626 updateWakeLockUids_l(mWakeLockUids);
2627 lastGeneration = mActiveTracksGeneration;
2628 }
2629
Eric Laurent81784c32012-11-19 14:55:58 -08002630 // prevent any changes in effect chain list and in each effect chain
2631 // during mixing and effect process as the audio buffers could be deleted
2632 // or modified if an effect is created or deleted
2633 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002634 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002635
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636 if (mBytesRemaining == 0) {
2637 mCurrentWriteLength = 0;
2638 if (mMixerStatus == MIXER_TRACKS_READY) {
2639 // threadLoop_mix() sets mCurrentWriteLength
2640 threadLoop_mix();
2641 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2642 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2643 // threadLoop_sleepTime sets sleepTime to 0 if data
2644 // must be written to HAL
2645 threadLoop_sleepTime();
2646 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002647 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 }
2649 }
Andy Hung98ef9782014-03-04 14:46:50 -08002650 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2651 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2652 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2653 // or mSinkBuffer (if there are no effects).
2654 //
2655 // This is done pre-effects computation; if effects change to
2656 // support higher precision, this needs to move.
2657 //
2658 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2659 // TODO use sleepTime == 0 as an additional condition.
2660 if (mMixerBufferValid) {
2661 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2662 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2663
2664 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2665 mNormalFrameCount * mChannelCount);
2666 }
2667
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 mBytesRemaining = mCurrentWriteLength;
2669 if (isSuspended()) {
2670 sleepTime = suspendSleepTimeUs();
2671 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002672 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 mBytesRemaining = 0;
2674 }
Eric Laurent81784c32012-11-19 14:55:58 -08002675
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002677 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 for (size_t i = 0; i < effectChains.size(); i ++) {
2679 effectChains[i]->process_l();
2680 }
Eric Laurent81784c32012-11-19 14:55:58 -08002681 }
2682 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002683 // Process effect chains for offloaded thread even if no audio
2684 // was read from audio track: process only updates effect state
2685 // and thus does have to be synchronized with audio writes but may have
2686 // to be called while waiting for async write callback
2687 if (mType == OFFLOAD) {
2688 for (size_t i = 0; i < effectChains.size(); i ++) {
2689 effectChains[i]->process_l();
2690 }
2691 }
Eric Laurent81784c32012-11-19 14:55:58 -08002692
Andy Hung98ef9782014-03-04 14:46:50 -08002693 // Only if the Effects buffer is enabled and there is data in the
2694 // Effects buffer (buffer valid), we need to
2695 // copy into the sink buffer.
2696 // TODO use sleepTime == 0 as an additional condition.
2697 if (mEffectBufferValid) {
2698 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2699 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2700 mNormalFrameCount * mChannelCount);
2701 }
2702
Eric Laurent81784c32012-11-19 14:55:58 -08002703 // enable changes in effect chain
2704 unlockEffectChains(effectChains);
2705
Eric Laurentbfb1b832013-01-07 09:53:42 -08002706 if (!waitingAsyncCallback()) {
2707 // sleepTime == 0 means we must write to audio hardware
2708 if (sleepTime == 0) {
2709 if (mBytesRemaining) {
2710 ssize_t ret = threadLoop_write();
2711 if (ret < 0) {
2712 mBytesRemaining = 0;
2713 } else {
2714 mBytesWritten += ret;
2715 mBytesRemaining -= ret;
2716 }
2717 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2718 (mMixerStatus == MIXER_DRAIN_ALL)) {
2719 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002720 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002721 if (mType == MIXER) {
2722 // write blocked detection
2723 nsecs_t now = systemTime();
2724 nsecs_t delta = now - mLastWriteTime;
2725 if (!mStandby && delta > maxPeriod) {
2726 mNumDelayedWrites++;
2727 if ((now - lastWarning) > kWarningThrottleNs) {
2728 ATRACE_NAME("underrun");
2729 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2730 ns2ms(delta), mNumDelayedWrites, this);
2731 lastWarning = now;
2732 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 }
2734 }
Eric Laurent81784c32012-11-19 14:55:58 -08002735
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002737 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002739 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740 }
Eric Laurent81784c32012-11-19 14:55:58 -08002741 }
2742
2743 // Finally let go of removed track(s), without the lock held
2744 // since we can't guarantee the destructors won't acquire that
2745 // same lock. This will also mutate and push a new fast mixer state.
2746 threadLoop_removeTracks(tracksToRemove);
2747 tracksToRemove.clear();
2748
2749 // FIXME I don't understand the need for this here;
2750 // it was in the original code but maybe the
2751 // assignment in saveOutputTracks() makes this unnecessary?
2752 clearOutputTracks();
2753
2754 // Effect chains will be actually deleted here if they were removed from
2755 // mEffectChains list during mixing or effects processing
2756 effectChains.clear();
2757
2758 // FIXME Note that the above .clear() is no longer necessary since effectChains
2759 // is now local to this block, but will keep it for now (at least until merge done).
2760 }
2761
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 threadLoop_exit();
2763
Eric Laurentcf817a22014-08-04 20:36:31 -07002764 if (!mStandby) {
2765 threadLoop_standby();
2766 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002767 }
2768
2769 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002770 mWakeLockUids.clear();
2771 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002772
2773 ALOGV("Thread %p type %d exiting", this, mType);
2774 return false;
2775}
2776
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777// removeTracks_l() must be called with ThreadBase::mLock held
2778void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2779{
2780 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002781 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002782 for (size_t i=0 ; i<count ; i++) {
2783 const sp<Track>& track = tracksToRemove.itemAt(i);
2784 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002785 mWakeLockUids.remove(track->uid());
2786 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002787 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2788 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2789 if (chain != 0) {
2790 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2791 track->sessionId());
2792 chain->decActiveTrackCnt();
2793 }
2794 if (track->isTerminated()) {
2795 removeTrack_l(track);
2796 }
2797 }
2798 }
2799
2800}
Eric Laurent81784c32012-11-19 14:55:58 -08002801
Eric Laurentaccc1472013-09-20 09:36:34 -07002802status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2803{
2804 if (mNormalSink != 0) {
2805 return mNormalSink->getTimestamp(timestamp);
2806 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002807 if ((mType == OFFLOAD || mType == DIRECT)
2808 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002809 uint64_t position64;
2810 int ret = mOutput->stream->get_presentation_position(
2811 mOutput->stream, &position64, &timestamp.mTime);
2812 if (ret == 0) {
2813 timestamp.mPosition = (uint32_t)position64;
2814 return NO_ERROR;
2815 }
2816 }
2817 return INVALID_OPERATION;
2818}
Eric Laurent1c333e22014-05-20 10:48:17 -07002819
2820status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2821 audio_patch_handle_t *handle)
2822{
2823 status_t status = NO_ERROR;
2824 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2825 // store new device and send to effects
2826 audio_devices_t type = AUDIO_DEVICE_NONE;
2827 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2828 type |= patch->sinks[i].ext.device.type;
2829 }
2830 mOutDevice = type;
2831 for (size_t i = 0; i < mEffectChains.size(); i++) {
2832 mEffectChains[i]->setDevice_l(mOutDevice);
2833 }
2834
2835 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2836 status = hwDevice->create_audio_patch(hwDevice,
2837 patch->num_sources,
2838 patch->sources,
2839 patch->num_sinks,
2840 patch->sinks,
2841 handle);
2842 } else {
2843 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2844 }
2845 return status;
2846}
2847
2848status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2849{
2850 status_t status = NO_ERROR;
2851 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2852 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2853 status = hwDevice->release_audio_patch(hwDevice, handle);
2854 } else {
2855 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2856 }
2857 return status;
2858}
2859
Eric Laurent83b88082014-06-20 18:31:16 -07002860void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2861{
2862 Mutex::Autolock _l(mLock);
2863 mTracks.add(track);
2864}
2865
2866void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2867{
2868 Mutex::Autolock _l(mLock);
2869 destroyTrack_l(track);
2870}
2871
2872void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2873{
2874 ThreadBase::getAudioPortConfig(config);
2875 config->role = AUDIO_PORT_ROLE_SOURCE;
2876 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2877 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2878}
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880// ----------------------------------------------------------------------------
2881
2882AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2883 audio_io_handle_t id, audio_devices_t device, type_t type)
2884 : PlaybackThread(audioFlinger, output, id, device, type),
2885 // mAudioMixer below
2886 // mFastMixer below
2887 mFastMixerFutex(0)
2888 // mOutputSink below
2889 // mPipeSink below
2890 // mNormalSink below
2891{
2892 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002893 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002894 "mFrameCount=%d, mNormalFrameCount=%d",
2895 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2896 mNormalFrameCount);
2897 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2898
Andy Hungfbfc3952015-01-15 13:33:51 -08002899 if (type == DUPLICATING) {
2900 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2901 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2902 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2903 return;
2904 }
Eric Laurent81784c32012-11-19 14:55:58 -08002905 // create an NBAIO sink for the HAL output stream, and negotiate
2906 mOutputSink = new AudioStreamOutSink(output->stream);
2907 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002908 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002909 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2910 ALOG_ASSERT(index == 0);
2911
2912 // initialize fast mixer depending on configuration
2913 bool initFastMixer;
2914 switch (kUseFastMixer) {
2915 case FastMixer_Never:
2916 initFastMixer = false;
2917 break;
2918 case FastMixer_Always:
2919 initFastMixer = true;
2920 break;
2921 case FastMixer_Static:
2922 case FastMixer_Dynamic:
2923 initFastMixer = mFrameCount < mNormalFrameCount;
2924 break;
2925 }
2926 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002927 audio_format_t fastMixerFormat;
2928 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2929 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2930 } else {
2931 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2932 }
2933 if (mFormat != fastMixerFormat) {
2934 // change our Sink format to accept our intermediate precision
2935 mFormat = fastMixerFormat;
2936 free(mSinkBuffer);
2937 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2938 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2939 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2940 }
Eric Laurent81784c32012-11-19 14:55:58 -08002941
2942 // create a MonoPipe to connect our submix to FastMixer
2943 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002944 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002945 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002946 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002947 format.mFormat = fastMixerFormat;
2948 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2949
Eric Laurent81784c32012-11-19 14:55:58 -08002950 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2951 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2952 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2953 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2954 const NBAIO_Format offers[1] = {format};
2955 size_t numCounterOffers = 0;
2956 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2957 ALOG_ASSERT(index == 0);
2958 monoPipe->setAvgFrames((mScreenState & 1) ?
2959 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2960 mPipeSink = monoPipe;
2961
Glenn Kasten46909e72013-02-26 09:20:22 -08002962#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002963 if (mTeeSinkOutputEnabled) {
2964 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002965 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2966 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002967 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002968 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002969 ALOG_ASSERT(index == 0);
2970 mTeeSink = teeSink;
2971 PipeReader *teeSource = new PipeReader(*teeSink);
2972 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002973 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002974 ALOG_ASSERT(index == 0);
2975 mTeeSource = teeSource;
2976 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002977#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002978
2979 // create fast mixer and configure it initially with just one fast track for our submix
2980 mFastMixer = new FastMixer();
2981 FastMixerStateQueue *sq = mFastMixer->sq();
2982#ifdef STATE_QUEUE_DUMP
2983 sq->setObserverDump(&mStateQueueObserverDump);
2984 sq->setMutatorDump(&mStateQueueMutatorDump);
2985#endif
2986 FastMixerState *state = sq->begin();
2987 FastTrack *fastTrack = &state->mFastTracks[0];
2988 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2989 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2990 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002991 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2992 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002993 fastTrack->mGeneration++;
2994 state->mFastTracksGen++;
2995 state->mTrackMask = 1;
2996 // fast mixer will use the HAL output sink
2997 state->mOutputSink = mOutputSink.get();
2998 state->mOutputSinkGen++;
2999 state->mFrameCount = mFrameCount;
3000 state->mCommand = FastMixerState::COLD_IDLE;
3001 // already done in constructor initialization list
3002 //mFastMixerFutex = 0;
3003 state->mColdFutexAddr = &mFastMixerFutex;
3004 state->mColdGen++;
3005 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003006#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003007 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003008#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003009 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3010 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003011 sq->end();
3012 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3013
3014 // start the fast mixer
3015 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3016 pid_t tid = mFastMixer->getTid();
3017 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3018 if (err != 0) {
3019 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3020 kPriorityFastMixer, getpid_cached, tid, err);
3021 }
3022
3023#ifdef AUDIO_WATCHDOG
3024 // create and start the watchdog
3025 mAudioWatchdog = new AudioWatchdog();
3026 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3027 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3028 tid = mAudioWatchdog->getTid();
3029 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3030 if (err != 0) {
3031 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3032 kPriorityFastMixer, getpid_cached, tid, err);
3033 }
3034#endif
3035
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
3037
3038 switch (kUseFastMixer) {
3039 case FastMixer_Never:
3040 case FastMixer_Dynamic:
3041 mNormalSink = mOutputSink;
3042 break;
3043 case FastMixer_Always:
3044 mNormalSink = mPipeSink;
3045 break;
3046 case FastMixer_Static:
3047 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3048 break;
3049 }
3050}
3051
3052AudioFlinger::MixerThread::~MixerThread()
3053{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003054 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003055 FastMixerStateQueue *sq = mFastMixer->sq();
3056 FastMixerState *state = sq->begin();
3057 if (state->mCommand == FastMixerState::COLD_IDLE) {
3058 int32_t old = android_atomic_inc(&mFastMixerFutex);
3059 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003060 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003061 }
3062 }
3063 state->mCommand = FastMixerState::EXIT;
3064 sq->end();
3065 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3066 mFastMixer->join();
3067 // Though the fast mixer thread has exited, it's state queue is still valid.
3068 // We'll use that extract the final state which contains one remaining fast track
3069 // corresponding to our sub-mix.
3070 state = sq->begin();
3071 ALOG_ASSERT(state->mTrackMask == 1);
3072 FastTrack *fastTrack = &state->mFastTracks[0];
3073 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3074 delete fastTrack->mBufferProvider;
3075 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003076 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003077#ifdef AUDIO_WATCHDOG
3078 if (mAudioWatchdog != 0) {
3079 mAudioWatchdog->requestExit();
3080 mAudioWatchdog->requestExitAndWait();
3081 mAudioWatchdog.clear();
3082 }
3083#endif
3084 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003085 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003086 delete mAudioMixer;
3087}
3088
3089
3090uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3091{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003092 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003093 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3094 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3095 }
3096 return latency;
3097}
3098
3099
3100void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3101{
3102 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3103}
3104
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003106{
3107 // FIXME we should only do one push per cycle; confirm this is true
3108 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003109 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003110 FastMixerStateQueue *sq = mFastMixer->sq();
3111 FastMixerState *state = sq->begin();
3112 if (state->mCommand != FastMixerState::MIX_WRITE &&
3113 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3114 if (state->mCommand == FastMixerState::COLD_IDLE) {
3115 int32_t old = android_atomic_inc(&mFastMixerFutex);
3116 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003117 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003118 }
3119#ifdef AUDIO_WATCHDOG
3120 if (mAudioWatchdog != 0) {
3121 mAudioWatchdog->resume();
3122 }
3123#endif
3124 }
3125 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003126 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3127 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003128 sq->end();
3129 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3130 if (kUseFastMixer == FastMixer_Dynamic) {
3131 mNormalSink = mPipeSink;
3132 }
3133 } else {
3134 sq->end(false /*didModify*/);
3135 }
3136 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003138}
3139
3140void AudioFlinger::MixerThread::threadLoop_standby()
3141{
3142 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003143 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003144 FastMixerStateQueue *sq = mFastMixer->sq();
3145 FastMixerState *state = sq->begin();
3146 if (!(state->mCommand & FastMixerState::IDLE)) {
3147 state->mCommand = FastMixerState::COLD_IDLE;
3148 state->mColdFutexAddr = &mFastMixerFutex;
3149 state->mColdGen++;
3150 mFastMixerFutex = 0;
3151 sq->end();
3152 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3153 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3154 if (kUseFastMixer == FastMixer_Dynamic) {
3155 mNormalSink = mOutputSink;
3156 }
3157#ifdef AUDIO_WATCHDOG
3158 if (mAudioWatchdog != 0) {
3159 mAudioWatchdog->pause();
3160 }
3161#endif
3162 } else {
3163 sq->end(false /*didModify*/);
3164 }
3165 }
3166 PlaybackThread::threadLoop_standby();
3167}
3168
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3170{
3171 return false;
3172}
3173
3174bool AudioFlinger::PlaybackThread::shouldStandby_l()
3175{
3176 return !mStandby;
3177}
3178
3179bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3180{
3181 Mutex::Autolock _l(mLock);
3182 return waitingAsyncCallback_l();
3183}
3184
Eric Laurent81784c32012-11-19 14:55:58 -08003185// shared by MIXER and DIRECT, overridden by DUPLICATING
3186void AudioFlinger::PlaybackThread::threadLoop_standby()
3187{
3188 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3189 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003190 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003191 // discard any pending drain or write ack by incrementing sequence
3192 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3193 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003194 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003195 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3196 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003197 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003198 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003199}
3200
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003201void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3202{
3203 ALOGV("signal playback thread");
3204 broadcast_l();
3205}
3206
Eric Laurent81784c32012-11-19 14:55:58 -08003207void AudioFlinger::MixerThread::threadLoop_mix()
3208{
3209 // obtain the presentation timestamp of the next output buffer
3210 int64_t pts;
3211 status_t status = INVALID_OPERATION;
3212
3213 if (mNormalSink != 0) {
3214 status = mNormalSink->getNextWriteTimestamp(&pts);
3215 } else {
3216 status = mOutputSink->getNextWriteTimestamp(&pts);
3217 }
3218
3219 if (status != NO_ERROR) {
3220 pts = AudioBufferProvider::kInvalidPTS;
3221 }
3222
3223 // mix buffers...
3224 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003225 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003226 // increase sleep time progressively when application underrun condition clears.
3227 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3228 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3229 // such that we would underrun the audio HAL.
3230 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3231 sleepTimeShift--;
3232 }
3233 sleepTime = 0;
3234 standbyTime = systemTime() + standbyDelay;
3235 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003236
Eric Laurent81784c32012-11-19 14:55:58 -08003237}
3238
3239void AudioFlinger::MixerThread::threadLoop_sleepTime()
3240{
3241 // If no tracks are ready, sleep once for the duration of an output
3242 // buffer size, then write 0s to the output
3243 if (sleepTime == 0) {
3244 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3245 sleepTime = activeSleepTime >> sleepTimeShift;
3246 if (sleepTime < kMinThreadSleepTimeUs) {
3247 sleepTime = kMinThreadSleepTimeUs;
3248 }
3249 // reduce sleep time in case of consecutive application underruns to avoid
3250 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3251 // duration we would end up writing less data than needed by the audio HAL if
3252 // the condition persists.
3253 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3254 sleepTimeShift++;
3255 }
3256 } else {
3257 sleepTime = idleSleepTime;
3258 }
3259 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003260 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3261 // before effects processing or output.
3262 if (mMixerBufferValid) {
3263 memset(mMixerBuffer, 0, mMixerBufferSize);
3264 } else {
3265 memset(mSinkBuffer, 0, mSinkBufferSize);
3266 }
Eric Laurent81784c32012-11-19 14:55:58 -08003267 sleepTime = 0;
3268 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3269 "anticipated start");
3270 }
3271 // TODO add standby time extension fct of effect tail
3272}
3273
3274// prepareTracks_l() must be called with ThreadBase::mLock held
3275AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3276 Vector< sp<Track> > *tracksToRemove)
3277{
3278
3279 mixer_state mixerStatus = MIXER_IDLE;
3280 // find out which tracks need to be processed
3281 size_t count = mActiveTracks.size();
3282 size_t mixedTracks = 0;
3283 size_t tracksWithEffect = 0;
3284 // counts only _active_ fast tracks
3285 size_t fastTracks = 0;
3286 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3287
3288 float masterVolume = mMasterVolume;
3289 bool masterMute = mMasterMute;
3290
3291 if (masterMute) {
3292 masterVolume = 0;
3293 }
3294 // Delegate master volume control to effect in output mix effect chain if needed
3295 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3296 if (chain != 0) {
3297 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3298 chain->setVolume_l(&v, &v);
3299 masterVolume = (float)((v + (1 << 23)) >> 24);
3300 chain.clear();
3301 }
3302
3303 // prepare a new state to push
3304 FastMixerStateQueue *sq = NULL;
3305 FastMixerState *state = NULL;
3306 bool didModify = false;
3307 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003308 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003309 sq = mFastMixer->sq();
3310 state = sq->begin();
3311 }
3312
Andy Hung69aed5f2014-02-25 17:24:40 -08003313 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003314 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003315
Eric Laurent81784c32012-11-19 14:55:58 -08003316 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003317 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003318 if (t == 0) {
3319 continue;
3320 }
3321
3322 // this const just means the local variable doesn't change
3323 Track* const track = t.get();
3324
3325 // process fast tracks
3326 if (track->isFastTrack()) {
3327
3328 // It's theoretically possible (though unlikely) for a fast track to be created
3329 // and then removed within the same normal mix cycle. This is not a problem, as
3330 // the track never becomes active so it's fast mixer slot is never touched.
3331 // The converse, of removing an (active) track and then creating a new track
3332 // at the identical fast mixer slot within the same normal mix cycle,
3333 // is impossible because the slot isn't marked available until the end of each cycle.
3334 int j = track->mFastIndex;
3335 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3336 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3337 FastTrack *fastTrack = &state->mFastTracks[j];
3338
3339 // Determine whether the track is currently in underrun condition,
3340 // and whether it had a recent underrun.
3341 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3342 FastTrackUnderruns underruns = ftDump->mUnderruns;
3343 uint32_t recentFull = (underruns.mBitFields.mFull -
3344 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3345 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3346 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3347 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3348 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3349 uint32_t recentUnderruns = recentPartial + recentEmpty;
3350 track->mObservedUnderruns = underruns;
3351 // don't count underruns that occur while stopping or pausing
3352 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003353 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3354 recentUnderruns > 0) {
3355 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3356 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003357 }
3358
3359 // This is similar to the state machine for normal tracks,
3360 // with a few modifications for fast tracks.
3361 bool isActive = true;
3362 switch (track->mState) {
3363 case TrackBase::STOPPING_1:
3364 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003366 track->mState = TrackBase::STOPPING_2;
3367 }
3368 break;
3369 case TrackBase::PAUSING:
3370 // ramp down is not yet implemented
3371 track->setPaused();
3372 break;
3373 case TrackBase::RESUMING:
3374 // ramp up is not yet implemented
3375 track->mState = TrackBase::ACTIVE;
3376 break;
3377 case TrackBase::ACTIVE:
3378 if (recentFull > 0 || recentPartial > 0) {
3379 // track has provided at least some frames recently: reset retry count
3380 track->mRetryCount = kMaxTrackRetries;
3381 }
3382 if (recentUnderruns == 0) {
3383 // no recent underruns: stay active
3384 break;
3385 }
3386 // there has recently been an underrun of some kind
3387 if (track->sharedBuffer() == 0) {
3388 // were any of the recent underruns "empty" (no frames available)?
3389 if (recentEmpty == 0) {
3390 // no, then ignore the partial underruns as they are allowed indefinitely
3391 break;
3392 }
3393 // there has recently been an "empty" underrun: decrement the retry counter
3394 if (--(track->mRetryCount) > 0) {
3395 break;
3396 }
3397 // indicate to client process that the track was disabled because of underrun;
3398 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003399 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003400 // remove from active list, but state remains ACTIVE [confusing but true]
3401 isActive = false;
3402 break;
3403 }
3404 // fall through
3405 case TrackBase::STOPPING_2:
3406 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003407 case TrackBase::STOPPED:
3408 case TrackBase::FLUSHED: // flush() while active
3409 // Check for presentation complete if track is inactive
3410 // We have consumed all the buffers of this track.
3411 // This would be incomplete if we auto-paused on underrun
3412 {
3413 size_t audioHALFrames =
3414 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3415 size_t framesWritten = mBytesWritten / mFrameSize;
3416 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3417 // track stays in active list until presentation is complete
3418 break;
3419 }
3420 }
3421 if (track->isStopping_2()) {
3422 track->mState = TrackBase::STOPPED;
3423 }
3424 if (track->isStopped()) {
3425 // Can't reset directly, as fast mixer is still polling this track
3426 // track->reset();
3427 // So instead mark this track as needing to be reset after push with ack
3428 resetMask |= 1 << i;
3429 }
3430 isActive = false;
3431 break;
3432 case TrackBase::IDLE:
3433 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003434 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003435 }
3436
3437 if (isActive) {
3438 // was it previously inactive?
3439 if (!(state->mTrackMask & (1 << j))) {
3440 ExtendedAudioBufferProvider *eabp = track;
3441 VolumeProvider *vp = track;
3442 fastTrack->mBufferProvider = eabp;
3443 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003444 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003445 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003446 fastTrack->mGeneration++;
3447 state->mTrackMask |= 1 << j;
3448 didModify = true;
3449 // no acknowledgement required for newly active tracks
3450 }
3451 // cache the combined master volume and stream type volume for fast mixer; this
3452 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003453 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003454 ++fastTracks;
3455 } else {
3456 // was it previously active?
3457 if (state->mTrackMask & (1 << j)) {
3458 fastTrack->mBufferProvider = NULL;
3459 fastTrack->mGeneration++;
3460 state->mTrackMask &= ~(1 << j);
3461 didModify = true;
3462 // If any fast tracks were removed, we must wait for acknowledgement
3463 // because we're about to decrement the last sp<> on those tracks.
3464 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3465 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003466 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003467 }
3468 tracksToRemove->add(track);
3469 // Avoids a misleading display in dumpsys
3470 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3471 }
3472 continue;
3473 }
3474
3475 { // local variable scope to avoid goto warning
3476
3477 audio_track_cblk_t* cblk = track->cblk();
3478
3479 // The first time a track is added we wait
3480 // for all its buffers to be filled before processing it
3481 int name = track->name();
3482 // make sure that we have enough frames to mix one full buffer.
3483 // enforce this condition only once to enable draining the buffer in case the client
3484 // app does not call stop() and relies on underrun to stop:
3485 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3486 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003487 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003488 uint32_t sr = track->sampleRate();
3489 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003490 desiredFrames = mNormalFrameCount;
3491 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003492 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003493 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003494 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003495 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003496#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003497 // the minimum track buffer size is normally twice the number of frames necessary
3498 // to fill one buffer and the resampler should not leave more than one buffer worth
3499 // of unreleased frames after each pass, but just in case...
3500 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003501#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003502 }
Eric Laurent81784c32012-11-19 14:55:58 -08003503 uint32_t minFrames = 1;
3504 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3505 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003506 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003507 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003508
3509 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003510 if (ATRACE_ENABLED()) {
3511 // I wish we had formatted trace names
3512 char traceName[16];
3513 strcpy(traceName, "nRdy");
3514 int name = track->name();
3515 if (AudioMixer::TRACK0 <= name &&
3516 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3517 name -= AudioMixer::TRACK0;
3518 traceName[4] = (name / 10) + '0';
3519 traceName[5] = (name % 10) + '0';
3520 } else {
3521 traceName[4] = '?';
3522 traceName[5] = '?';
3523 }
3524 traceName[6] = '\0';
3525 ATRACE_INT(traceName, framesReady);
3526 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003527 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003528 !track->isPaused() && !track->isTerminated())
3529 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003530 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003531
3532 mixedTracks++;
3533
Andy Hung69aed5f2014-02-25 17:24:40 -08003534 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3535 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003536 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003537 if (track->mainBuffer() != mSinkBuffer &&
3538 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003539 if (mEffectBufferEnabled) {
3540 mEffectBufferValid = true; // Later can set directly.
3541 }
Eric Laurent81784c32012-11-19 14:55:58 -08003542 chain = getEffectChain_l(track->sessionId());
3543 // Delegate volume control to effect in track effect chain if needed
3544 if (chain != 0) {
3545 tracksWithEffect++;
3546 } else {
3547 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3548 "session %d",
3549 name, track->sessionId());
3550 }
3551 }
3552
3553
3554 int param = AudioMixer::VOLUME;
3555 if (track->mFillingUpStatus == Track::FS_FILLED) {
3556 // no ramp for the first volume setting
3557 track->mFillingUpStatus = Track::FS_ACTIVE;
3558 if (track->mState == TrackBase::RESUMING) {
3559 track->mState = TrackBase::ACTIVE;
3560 param = AudioMixer::RAMP_VOLUME;
3561 }
3562 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003563 // FIXME should not make a decision based on mServer
3564 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003565 // If the track is stopped before the first frame was mixed,
3566 // do not apply ramp
3567 param = AudioMixer::RAMP_VOLUME;
3568 }
3569
3570 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003571 uint32_t vl, vr; // in U8.24 integer format
3572 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003573 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003574 vl = vr = 0;
3575 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003576 if (track->isPausing()) {
3577 track->setPaused();
3578 }
3579 } else {
3580
3581 // read original volumes with volume control
3582 float typeVolume = mStreamTypes[track->streamType()].volume;
3583 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003584 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003585 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003586 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3587 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003588 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003589 if (vlf > GAIN_FLOAT_UNITY) {
3590 ALOGV("Track left volume out of range: %.3g", vlf);
3591 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003592 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003593 if (vrf > GAIN_FLOAT_UNITY) {
3594 ALOGV("Track right volume out of range: %.3g", vrf);
3595 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003596 }
3597 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003598 vlf *= v;
3599 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003601 // then derive vl and vr as U8.24 versions for the effect chain
3602 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3603 vl = (uint32_t) (scaleto8_24 * vlf);
3604 vr = (uint32_t) (scaleto8_24 * vrf);
3605 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003606 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003607 // send level comes from shared memory and so may be corrupt
3608 if (sendLevel > MAX_GAIN_INT) {
3609 ALOGV("Track send level out of range: %04X", sendLevel);
3610 sendLevel = MAX_GAIN_INT;
3611 }
Andy Hung6be49402014-05-30 10:42:03 -07003612 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3613 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615
Eric Laurent81784c32012-11-19 14:55:58 -08003616 // Delegate volume control to effect in track effect chain if needed
3617 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3618 // Do not ramp volume if volume is controlled by effect
3619 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003620 // Update remaining floating point volume levels
3621 vlf = (float)vl / (1 << 24);
3622 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003623 track->mHasVolumeController = true;
3624 } else {
3625 // force no volume ramp when volume controller was just disabled or removed
3626 // from effect chain to avoid volume spike
3627 if (track->mHasVolumeController) {
3628 param = AudioMixer::VOLUME;
3629 }
3630 track->mHasVolumeController = false;
3631 }
3632
Eric Laurent81784c32012-11-19 14:55:58 -08003633 // XXX: these things DON'T need to be done each time
3634 mAudioMixer->setBufferProvider(name, track);
3635 mAudioMixer->enable(name);
3636
Andy Hung6be49402014-05-30 10:42:03 -07003637 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3638 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3639 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003640 mAudioMixer->setParameter(
3641 name,
3642 AudioMixer::TRACK,
3643 AudioMixer::FORMAT, (void *)track->format());
3644 mAudioMixer->setParameter(
3645 name,
3646 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003647 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003648 mAudioMixer->setParameter(
3649 name,
3650 AudioMixer::TRACK,
3651 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003652 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003653 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003654 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003655 if (reqSampleRate == 0) {
3656 reqSampleRate = mSampleRate;
3657 } else if (reqSampleRate > maxSampleRate) {
3658 reqSampleRate = maxSampleRate;
3659 }
Eric Laurent81784c32012-11-19 14:55:58 -08003660 mAudioMixer->setParameter(
3661 name,
3662 AudioMixer::RESAMPLE,
3663 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003664 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003665 /*
3666 * Select the appropriate output buffer for the track.
3667 *
Andy Hung98ef9782014-03-04 14:46:50 -08003668 * Tracks with effects go into their own effects chain buffer
3669 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003670 *
3671 * Other tracks can use mMixerBuffer for higher precision
3672 * channel accumulation. If this buffer is enabled
3673 * (mMixerBufferEnabled true), then selected tracks will accumulate
3674 * into it.
3675 *
3676 */
3677 if (mMixerBufferEnabled
3678 && (track->mainBuffer() == mSinkBuffer
3679 || track->mainBuffer() == mMixerBuffer)) {
3680 mAudioMixer->setParameter(
3681 name,
3682 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003683 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003684 mAudioMixer->setParameter(
3685 name,
3686 AudioMixer::TRACK,
3687 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3688 // TODO: override track->mainBuffer()?
3689 mMixerBufferValid = true;
3690 } else {
3691 mAudioMixer->setParameter(
3692 name,
3693 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003694 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003695 mAudioMixer->setParameter(
3696 name,
3697 AudioMixer::TRACK,
3698 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3699 }
Eric Laurent81784c32012-11-19 14:55:58 -08003700 mAudioMixer->setParameter(
3701 name,
3702 AudioMixer::TRACK,
3703 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3704
3705 // reset retry count
3706 track->mRetryCount = kMaxTrackRetries;
3707
3708 // If one track is ready, set the mixer ready if:
3709 // - the mixer was not ready during previous round OR
3710 // - no other track is not ready
3711 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3712 mixerStatus != MIXER_TRACKS_ENABLED) {
3713 mixerStatus = MIXER_TRACKS_READY;
3714 }
3715 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003716 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003717 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003718 }
Eric Laurent81784c32012-11-19 14:55:58 -08003719 // clear effect chain input buffer if an active track underruns to avoid sending
3720 // previous audio buffer again to effects
3721 chain = getEffectChain_l(track->sessionId());
3722 if (chain != 0) {
3723 chain->clearInputBuffer();
3724 }
3725
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003726 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3728 track->isStopped() || track->isPaused()) {
3729 // We have consumed all the buffers of this track.
3730 // Remove it from the list of active tracks.
3731 // TODO: use actual buffer filling status instead of latency when available from
3732 // audio HAL
3733 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3734 size_t framesWritten = mBytesWritten / mFrameSize;
3735 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3736 if (track->isStopped()) {
3737 track->reset();
3738 }
3739 tracksToRemove->add(track);
3740 }
3741 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003742 // No buffers for this track. Give it a few chances to
3743 // fill a buffer, then remove it from active list.
3744 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003745 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003746 tracksToRemove->add(track);
3747 // indicate to client process that the track was disabled because of underrun;
3748 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003749 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003750 // If one track is not ready, mark the mixer also not ready if:
3751 // - the mixer was ready during previous round OR
3752 // - no other track is ready
3753 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3754 mixerStatus != MIXER_TRACKS_READY) {
3755 mixerStatus = MIXER_TRACKS_ENABLED;
3756 }
3757 }
3758 mAudioMixer->disable(name);
3759 }
3760
3761 } // local variable scope to avoid goto warning
3762track_is_ready: ;
3763
3764 }
3765
3766 // Push the new FastMixer state if necessary
3767 bool pauseAudioWatchdog = false;
3768 if (didModify) {
3769 state->mFastTracksGen++;
3770 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3771 if (kUseFastMixer == FastMixer_Dynamic &&
3772 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3773 state->mCommand = FastMixerState::COLD_IDLE;
3774 state->mColdFutexAddr = &mFastMixerFutex;
3775 state->mColdGen++;
3776 mFastMixerFutex = 0;
3777 if (kUseFastMixer == FastMixer_Dynamic) {
3778 mNormalSink = mOutputSink;
3779 }
3780 // If we go into cold idle, need to wait for acknowledgement
3781 // so that fast mixer stops doing I/O.
3782 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3783 pauseAudioWatchdog = true;
3784 }
Eric Laurent81784c32012-11-19 14:55:58 -08003785 }
3786 if (sq != NULL) {
3787 sq->end(didModify);
3788 sq->push(block);
3789 }
3790#ifdef AUDIO_WATCHDOG
3791 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3792 mAudioWatchdog->pause();
3793 }
3794#endif
3795
3796 // Now perform the deferred reset on fast tracks that have stopped
3797 while (resetMask != 0) {
3798 size_t i = __builtin_ctz(resetMask);
3799 ALOG_ASSERT(i < count);
3800 resetMask &= ~(1 << i);
3801 sp<Track> t = mActiveTracks[i].promote();
3802 if (t == 0) {
3803 continue;
3804 }
3805 Track* track = t.get();
3806 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3807 track->reset();
3808 }
3809
3810 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003811 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003812
Eric Laurent97d547d2014-09-02 14:45:53 -07003813 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3814 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003815 }
3816
3817 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003818 // as long as there are effects we should clear the effects buffer, to avoid
3819 // passing a non-clean buffer to the effect chain
3820 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003821 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003822 // sink or mix buffer must be cleared if all tracks are connected to an
3823 // effect chain as in this case the mixer will not write to the sink or mix buffer
3824 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003825 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3826 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003827 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003828 if (mMixerBufferValid) {
3829 memset(mMixerBuffer, 0, mMixerBufferSize);
3830 // TODO: In testing, mSinkBuffer below need not be cleared because
3831 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3832 // after mixing.
3833 //
3834 // To enforce this guarantee:
3835 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3836 // (mixedTracks == 0 && fastTracks > 0))
3837 // must imply MIXER_TRACKS_READY.
3838 // Later, we may clear buffers regardless, and skip much of this logic.
3839 }
Andy Hung98ef9782014-03-04 14:46:50 -08003840 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003841 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003842 }
3843
3844 // if any fast tracks, then status is ready
3845 mMixerStatusIgnoringFastTracks = mixerStatus;
3846 if (fastTracks > 0) {
3847 mixerStatus = MIXER_TRACKS_READY;
3848 }
3849 return mixerStatus;
3850}
3851
3852// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003853int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3854 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003855{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003856 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003857}
3858
3859// deleteTrackName_l() must be called with ThreadBase::mLock held
3860void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3861{
3862 ALOGV("remove track (%d) and delete from mixer", name);
3863 mAudioMixer->deleteTrackName(name);
3864}
3865
Eric Laurent10351942014-05-08 18:49:52 -07003866// checkForNewParameter_l() must be called with ThreadBase::mLock held
3867bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3868 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003869{
Eric Laurent81784c32012-11-19 14:55:58 -08003870 bool reconfig = false;
3871
Eric Laurent10351942014-05-08 18:49:52 -07003872 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003873
Eric Laurent10351942014-05-08 18:49:52 -07003874 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3875 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003876 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003877 FastMixerStateQueue *sq = mFastMixer->sq();
3878 FastMixerState *state = sq->begin();
3879 if (!(state->mCommand & FastMixerState::IDLE)) {
3880 previousCommand = state->mCommand;
3881 state->mCommand = FastMixerState::HOT_IDLE;
3882 sq->end();
3883 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3884 } else {
3885 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003886 }
Eric Laurent10351942014-05-08 18:49:52 -07003887 }
Eric Laurent81784c32012-11-19 14:55:58 -08003888
Eric Laurent10351942014-05-08 18:49:52 -07003889 AudioParameter param = AudioParameter(keyValuePair);
3890 int value;
3891 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3892 reconfig = true;
3893 }
3894 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003895 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003896 status = BAD_VALUE;
3897 } else {
3898 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003899 reconfig = true;
3900 }
Eric Laurent10351942014-05-08 18:49:52 -07003901 }
3902 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003903 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003904 status = BAD_VALUE;
3905 } else {
3906 // no need to save value, since it's constant
3907 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003908 }
Eric Laurent10351942014-05-08 18:49:52 -07003909 }
3910 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3911 // do not accept frame count changes if tracks are open as the track buffer
3912 // size depends on frame count and correct behavior would not be guaranteed
3913 // if frame count is changed after track creation
3914 if (!mTracks.isEmpty()) {
3915 status = INVALID_OPERATION;
3916 } else {
3917 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003918 }
Eric Laurent10351942014-05-08 18:49:52 -07003919 }
3920 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003921#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003922 // when changing the audio output device, call addBatteryData to notify
3923 // the change
3924 if (mOutDevice != value) {
3925 uint32_t params = 0;
3926 // check whether speaker is on
3927 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3928 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003929 }
Eric Laurent10351942014-05-08 18:49:52 -07003930
3931 audio_devices_t deviceWithoutSpeaker
3932 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3933 // check if any other device (except speaker) is on
3934 if (value & deviceWithoutSpeaker ) {
3935 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3936 }
3937
3938 if (params != 0) {
3939 addBatteryData(params);
3940 }
3941 }
Eric Laurent81784c32012-11-19 14:55:58 -08003942#endif
3943
Eric Laurent10351942014-05-08 18:49:52 -07003944 // forward device change to effects that have requested to be
3945 // aware of attached audio device.
3946 if (value != AUDIO_DEVICE_NONE) {
3947 mOutDevice = value;
3948 for (size_t i = 0; i < mEffectChains.size(); i++) {
3949 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003950 }
3951 }
Eric Laurent10351942014-05-08 18:49:52 -07003952 }
Eric Laurent81784c32012-11-19 14:55:58 -08003953
Eric Laurent10351942014-05-08 18:49:52 -07003954 if (status == NO_ERROR) {
3955 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3956 keyValuePair.string());
3957 if (!mStandby && status == INVALID_OPERATION) {
3958 mOutput->stream->common.standby(&mOutput->stream->common);
3959 mStandby = true;
3960 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003961 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003962 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
Eric Laurent10351942014-05-08 18:49:52 -07003964 if (status == NO_ERROR && reconfig) {
3965 readOutputParameters_l();
3966 delete mAudioMixer;
3967 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3968 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003969 int name = getTrackName_l(mTracks[i]->mChannelMask,
3970 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003971 if (name < 0) {
3972 break;
3973 }
3974 mTracks[i]->mName = name;
3975 }
3976 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3977 }
Eric Laurent81784c32012-11-19 14:55:58 -08003978 }
3979
3980 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003981 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003982 FastMixerStateQueue *sq = mFastMixer->sq();
3983 FastMixerState *state = sq->begin();
3984 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3985 state->mCommand = previousCommand;
3986 sq->end();
3987 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3988 }
3989
3990 return reconfig;
3991}
3992
3993
3994void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3995{
3996 const size_t SIZE = 256;
3997 char buffer[SIZE];
3998 String8 result;
3999
4000 PlaybackThread::dumpInternals(fd, args);
4001
Elliott Hughes87cebad2014-05-22 10:14:43 -07004002 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004003
4004 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004005 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 copy.dump(fd);
4007
4008#ifdef STATE_QUEUE_DUMP
4009 // Similar for state queue
4010 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4011 observerCopy.dump(fd);
4012 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4013 mutatorCopy.dump(fd);
4014#endif
4015
Glenn Kasten46909e72013-02-26 09:20:22 -08004016#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004017 // Write the tee output to a .wav file
4018 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004019#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004020
4021#ifdef AUDIO_WATCHDOG
4022 if (mAudioWatchdog != 0) {
4023 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4024 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4025 wdCopy.dump(fd);
4026 }
4027#endif
4028}
4029
4030uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4031{
4032 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4033}
4034
4035uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4036{
4037 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4038}
4039
4040void AudioFlinger::MixerThread::cacheParameters_l()
4041{
4042 PlaybackThread::cacheParameters_l();
4043
4044 // FIXME: Relaxed timing because of a certain device that can't meet latency
4045 // Should be reduced to 2x after the vendor fixes the driver issue
4046 // increase threshold again due to low power audio mode. The way this warning
4047 // threshold is calculated and its usefulness should be reconsidered anyway.
4048 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4049}
4050
4051// ----------------------------------------------------------------------------
4052
4053AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4054 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4055 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4056 // mLeftVolFloat, mRightVolFloat
4057{
4058}
4059
Eric Laurentbfb1b832013-01-07 09:53:42 -08004060AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4061 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4062 ThreadBase::type_t type)
4063 : PlaybackThread(audioFlinger, output, id, device, type)
4064 // mLeftVolFloat, mRightVolFloat
4065{
4066}
4067
Eric Laurent81784c32012-11-19 14:55:58 -08004068AudioFlinger::DirectOutputThread::~DirectOutputThread()
4069{
4070}
4071
Eric Laurentbfb1b832013-01-07 09:53:42 -08004072void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4073{
4074 audio_track_cblk_t* cblk = track->cblk();
4075 float left, right;
4076
4077 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4078 left = right = 0;
4079 } else {
4080 float typeVolume = mStreamTypes[track->streamType()].volume;
4081 float v = mMasterVolume * typeVolume;
4082 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004083 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4084 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4085 if (left > GAIN_FLOAT_UNITY) {
4086 left = GAIN_FLOAT_UNITY;
4087 }
4088 left *= v;
4089 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4090 if (right > GAIN_FLOAT_UNITY) {
4091 right = GAIN_FLOAT_UNITY;
4092 }
4093 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004094 }
4095
4096 if (lastTrack) {
4097 if (left != mLeftVolFloat || right != mRightVolFloat) {
4098 mLeftVolFloat = left;
4099 mRightVolFloat = right;
4100
4101 // Convert volumes from float to 8.24
4102 uint32_t vl = (uint32_t)(left * (1 << 24));
4103 uint32_t vr = (uint32_t)(right * (1 << 24));
4104
4105 // Delegate volume control to effect in track effect chain if needed
4106 // only one effect chain can be present on DirectOutputThread, so if
4107 // there is one, the track is connected to it
4108 if (!mEffectChains.isEmpty()) {
4109 mEffectChains[0]->setVolume_l(&vl, &vr);
4110 left = (float)vl / (1 << 24);
4111 right = (float)vr / (1 << 24);
4112 }
4113 if (mOutput->stream->set_volume) {
4114 mOutput->stream->set_volume(mOutput->stream, left, right);
4115 }
4116 }
4117 }
4118}
4119
4120
Eric Laurent81784c32012-11-19 14:55:58 -08004121AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4122 Vector< sp<Track> > *tracksToRemove
4123)
4124{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004125 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004126 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004127 bool doHwPause = false;
4128 bool doHwResume = false;
4129 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004130
4131 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004132 for (size_t i = 0; i < count; i++) {
4133 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004134 // The track died recently
4135 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004136 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004137 }
4138
4139 Track* const track = t.get();
4140 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004141 // Only consider last track started for volume and mixer state control.
4142 // In theory an older track could underrun and restart after the new one starts
4143 // but as we only care about the transition phase between two tracks on a
4144 // direct output, it is not a problem to ignore the underrun case.
4145 sp<Track> l = mLatestActiveTrack.promote();
4146 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004147
Eric Laurentd1f69b02014-12-15 14:33:13 -08004148 if (mHwSupportsPause && track->isPausing()) {
4149 track->setPaused();
4150 if (last && !mHwPaused) {
4151 doHwPause = true;
4152 mHwPaused = true;
4153 }
4154 tracksToRemove->add(track);
4155 } else if (track->isFlushPending()) {
4156 track->flushAck();
4157 if (last) {
4158 flushPending = true;
4159 }
4160 } else if (mHwSupportsPause && track->isResumePending()){
4161 track->resumeAck();
4162 if (last) {
4163 if (mHwPaused) {
4164 doHwResume = true;
4165 mHwPaused = false;
4166 }
4167 }
4168 }
4169
Eric Laurent81784c32012-11-19 14:55:58 -08004170 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004171 // for all its buffers to be filled before processing it.
4172 // Allow draining the buffer in case the client
4173 // app does not call stop() and relies on underrun to stop:
4174 // hence the test on (track->mRetryCount > 1).
4175 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004176 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004177 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4178 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004179 minFrames = mNormalFrameCount;
4180 } else {
4181 minFrames = 1;
4182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183
Eric Laurentab5cdba2014-06-09 17:22:27 -07004184 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4185 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004186 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004187 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004188
4189 if (track->mFillingUpStatus == Track::FS_FILLED) {
4190 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004191 // make sure processVolume_l() will apply new volume even if 0
4192 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004193 if (!mHwSupportsPause) {
4194 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004195 }
4196 }
4197
4198 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004199 processVolume_l(track, last);
4200 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004201 // reset retry count
4202 track->mRetryCount = kMaxTrackRetriesDirect;
4203 mActiveTrack = t;
4204 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004205 if (usesHwAvSync() && mHwPaused) {
4206 doHwResume = true;
4207 mHwPaused = false;
4208 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004209 }
Eric Laurent81784c32012-11-19 14:55:58 -08004210 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004211 // clear effect chain input buffer if the last active track started underruns
4212 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004213 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004214 mEffectChains[0]->clearInputBuffer();
4215 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004216 if (track->isStopping_1()) {
4217 track->mState = TrackBase::STOPPING_2;
4218 }
4219 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4220 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004221 // We have consumed all the buffers of this track.
4222 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004223 size_t audioHALFrames;
4224 if (audio_is_linear_pcm(mFormat)) {
4225 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4226 } else {
4227 audioHALFrames = 0;
4228 }
4229
Eric Laurent81784c32012-11-19 14:55:58 -08004230 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004231 if (mStandby || !last ||
4232 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004233 if (track->isStopping_2()) {
4234 track->mState = TrackBase::STOPPED;
4235 }
Eric Laurent81784c32012-11-19 14:55:58 -08004236 if (track->isStopped()) {
4237 track->reset();
4238 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004239 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004240 }
4241 } else {
4242 // No buffers for this track. Give it a few chances to
4243 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004244 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004245 if (--(track->mRetryCount) <= 0) {
4246 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004247 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004248 // indicate to client process that the track was disabled because of underrun;
4249 // it will then automatically call start() when data is available
4250 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004251 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004252 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004253 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4254 doHwPause = true;
4255 mHwPaused = true;
4256 }
Eric Laurent81784c32012-11-19 14:55:58 -08004257 }
4258 }
4259 }
4260 }
4261
Eric Laurentd1f69b02014-12-15 14:33:13 -08004262 // if an active track did not command a flush, check for pending flush on stopped tracks
4263 if (!flushPending) {
4264 for (size_t i = 0; i < mTracks.size(); i++) {
4265 if (mTracks[i]->isFlushPending()) {
4266 mTracks[i]->flushAck();
4267 flushPending = true;
4268 }
4269 }
4270 }
4271
4272 // make sure the pause/flush/resume sequence is executed in the right order.
4273 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4274 // before flush and then resume HW. This can happen in case of pause/flush/resume
4275 // if resume is received before pause is executed.
4276 if (mHwSupportsPause && !mStandby &&
4277 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4278 mOutput->stream->pause(mOutput->stream);
4279 }
4280 if (flushPending) {
4281 flushHw_l();
4282 }
4283 if (mHwSupportsPause && !mStandby && doHwResume) {
4284 mOutput->stream->resume(mOutput->stream);
4285 }
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004287 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004288
4289 return mixerStatus;
4290}
4291
4292void AudioFlinger::DirectOutputThread::threadLoop_mix()
4293{
Eric Laurent81784c32012-11-19 14:55:58 -08004294 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004295 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004296 // output audio to hardware
4297 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004298 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004299 buffer.frameCount = frameCount;
4300 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004301 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004302 memset(curBuf, 0, frameCount * mFrameSize);
4303 break;
4304 }
4305 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4306 frameCount -= buffer.frameCount;
4307 curBuf += buffer.frameCount * mFrameSize;
4308 mActiveTrack->releaseBuffer(&buffer);
4309 }
Andy Hung2098f272014-02-27 14:00:06 -08004310 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 sleepTime = 0;
4312 standbyTime = systemTime() + standbyDelay;
4313 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004314}
4315
4316void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4317{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004318 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004319 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004320 sleepTime = idleSleepTime;
4321 return;
4322 }
Eric Laurent81784c32012-11-19 14:55:58 -08004323 if (sleepTime == 0) {
4324 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4325 sleepTime = activeSleepTime;
4326 } else {
4327 sleepTime = idleSleepTime;
4328 }
4329 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004330 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004331 sleepTime = 0;
4332 }
4333}
4334
Eric Laurentd1f69b02014-12-15 14:33:13 -08004335void AudioFlinger::DirectOutputThread::threadLoop_exit()
4336{
4337 {
4338 Mutex::Autolock _l(mLock);
4339 bool flushPending = false;
4340 for (size_t i = 0; i < mTracks.size(); i++) {
4341 if (mTracks[i]->isFlushPending()) {
4342 mTracks[i]->flushAck();
4343 flushPending = true;
4344 }
4345 }
4346 if (flushPending) {
4347 flushHw_l();
4348 }
4349 }
4350 PlaybackThread::threadLoop_exit();
4351}
4352
4353// must be called with thread mutex locked
4354bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4355{
4356 bool trackPaused = false;
4357
4358 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4359 // after a timeout and we will enter standby then.
4360 if (mTracks.size() > 0) {
4361 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4362 }
4363
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004364 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004365}
4366
Eric Laurent81784c32012-11-19 14:55:58 -08004367// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004368int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004369 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004370{
4371 return 0;
4372}
4373
4374// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004375void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004376{
4377}
4378
Eric Laurent10351942014-05-08 18:49:52 -07004379// checkForNewParameter_l() must be called with ThreadBase::mLock held
4380bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4381 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004382{
4383 bool reconfig = false;
4384
Eric Laurent10351942014-05-08 18:49:52 -07004385 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004386
Eric Laurent10351942014-05-08 18:49:52 -07004387 AudioParameter param = AudioParameter(keyValuePair);
4388 int value;
4389 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4390 // forward device change to effects that have requested to be
4391 // aware of attached audio device.
4392 if (value != AUDIO_DEVICE_NONE) {
4393 mOutDevice = value;
4394 for (size_t i = 0; i < mEffectChains.size(); i++) {
4395 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004396 }
4397 }
Eric Laurent81784c32012-11-19 14:55:58 -08004398 }
Eric Laurent10351942014-05-08 18:49:52 -07004399 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4400 // do not accept frame count changes if tracks are open as the track buffer
4401 // size depends on frame count and correct behavior would not be garantied
4402 // if frame count is changed after track creation
4403 if (!mTracks.isEmpty()) {
4404 status = INVALID_OPERATION;
4405 } else {
4406 reconfig = true;
4407 }
4408 }
4409 if (status == NO_ERROR) {
4410 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4411 keyValuePair.string());
4412 if (!mStandby && status == INVALID_OPERATION) {
4413 mOutput->stream->common.standby(&mOutput->stream->common);
4414 mStandby = true;
4415 mBytesWritten = 0;
4416 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4417 keyValuePair.string());
4418 }
4419 if (status == NO_ERROR && reconfig) {
4420 readOutputParameters_l();
4421 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4422 }
4423 }
4424
Eric Laurent81784c32012-11-19 14:55:58 -08004425 return reconfig;
4426}
4427
4428uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4429{
4430 uint32_t time;
4431 if (audio_is_linear_pcm(mFormat)) {
4432 time = PlaybackThread::activeSleepTimeUs();
4433 } else {
4434 time = 10000;
4435 }
4436 return time;
4437}
4438
4439uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4440{
4441 uint32_t time;
4442 if (audio_is_linear_pcm(mFormat)) {
4443 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4444 } else {
4445 time = 10000;
4446 }
4447 return time;
4448}
4449
4450uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4451{
4452 uint32_t time;
4453 if (audio_is_linear_pcm(mFormat)) {
4454 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4455 } else {
4456 time = 10000;
4457 }
4458 return time;
4459}
4460
4461void AudioFlinger::DirectOutputThread::cacheParameters_l()
4462{
4463 PlaybackThread::cacheParameters_l();
4464
4465 // use shorter standby delay as on normal output to release
4466 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004467 if (audio_is_linear_pcm(mFormat)) {
4468 standbyDelay = microseconds(activeSleepTime*2);
4469 } else {
4470 standbyDelay = kOffloadStandbyDelayNs;
4471 }
Eric Laurent81784c32012-11-19 14:55:58 -08004472}
4473
Eric Laurente659ef42014-09-29 13:06:46 -07004474void AudioFlinger::DirectOutputThread::flushHw_l()
4475{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004476 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004477 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004478 }
4479 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004480}
4481
Eric Laurent81784c32012-11-19 14:55:58 -08004482// ----------------------------------------------------------------------------
4483
Eric Laurentbfb1b832013-01-07 09:53:42 -08004484AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004485 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004486 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004487 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004488 mWriteAckSequence(0),
4489 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490{
4491}
4492
4493AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4494{
4495}
4496
4497void AudioFlinger::AsyncCallbackThread::onFirstRef()
4498{
4499 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4500}
4501
4502bool AudioFlinger::AsyncCallbackThread::threadLoop()
4503{
4504 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004505 uint32_t writeAckSequence;
4506 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004507
4508 {
4509 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004510 while (!((mWriteAckSequence & 1) ||
4511 (mDrainSequence & 1) ||
4512 exitPending())) {
4513 mWaitWorkCV.wait(mLock);
4514 }
4515
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 if (exitPending()) {
4517 break;
4518 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004519 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4520 mWriteAckSequence, mDrainSequence);
4521 writeAckSequence = mWriteAckSequence;
4522 mWriteAckSequence &= ~1;
4523 drainSequence = mDrainSequence;
4524 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 }
4526 {
Eric Laurent4de95592013-09-26 15:28:21 -07004527 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4528 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004529 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004530 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004531 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004532 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004533 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 }
4535 }
4536 }
4537 }
4538 return false;
4539}
4540
4541void AudioFlinger::AsyncCallbackThread::exit()
4542{
4543 ALOGV("AsyncCallbackThread::exit");
4544 Mutex::Autolock _l(mLock);
4545 requestExit();
4546 mWaitWorkCV.broadcast();
4547}
4548
Eric Laurent3b4529e2013-09-05 18:09:19 -07004549void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004550{
4551 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004552 // bit 0 is cleared
4553 mWriteAckSequence = sequence << 1;
4554}
4555
4556void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4557{
4558 Mutex::Autolock _l(mLock);
4559 // ignore unexpected callbacks
4560 if (mWriteAckSequence & 2) {
4561 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004562 mWaitWorkCV.signal();
4563 }
4564}
4565
Eric Laurent3b4529e2013-09-05 18:09:19 -07004566void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004567{
4568 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004569 // bit 0 is cleared
4570 mDrainSequence = sequence << 1;
4571}
4572
4573void AudioFlinger::AsyncCallbackThread::resetDraining()
4574{
4575 Mutex::Autolock _l(mLock);
4576 // ignore unexpected callbacks
4577 if (mDrainSequence & 2) {
4578 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004579 mWaitWorkCV.signal();
4580 }
4581}
4582
4583
4584// ----------------------------------------------------------------------------
4585AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4586 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4587 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004588 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004589{
Eric Laurentfd477972013-10-25 18:10:40 -07004590 //FIXME: mStandby should be set to true by ThreadBase constructor
4591 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004592}
4593
Eric Laurentbfb1b832013-01-07 09:53:42 -08004594void AudioFlinger::OffloadThread::threadLoop_exit()
4595{
4596 if (mFlushPending || mHwPaused) {
4597 // If a flush is pending or track was paused, just discard buffered data
4598 flushHw_l();
4599 } else {
4600 mMixerStatus = MIXER_DRAIN_ALL;
4601 threadLoop_drain();
4602 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004603 if (mUseAsyncWrite) {
4604 ALOG_ASSERT(mCallbackThread != 0);
4605 mCallbackThread->exit();
4606 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607 PlaybackThread::threadLoop_exit();
4608}
4609
4610AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4611 Vector< sp<Track> > *tracksToRemove
4612)
4613{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 size_t count = mActiveTracks.size();
4615
4616 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004617 bool doHwPause = false;
4618 bool doHwResume = false;
4619
Eric Laurentede6c3b2013-09-19 14:37:46 -07004620 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4621
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622 // find out which tracks need to be processed
4623 for (size_t i = 0; i < count; i++) {
4624 sp<Track> t = mActiveTracks[i].promote();
4625 // The track died recently
4626 if (t == 0) {
4627 continue;
4628 }
4629 Track* const track = t.get();
4630 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004631 // Only consider last track started for volume and mixer state control.
4632 // In theory an older track could underrun and restart after the new one starts
4633 // but as we only care about the transition phase between two tracks on a
4634 // direct output, it is not a problem to ignore the underrun case.
4635 sp<Track> l = mLatestActiveTrack.promote();
4636 bool last = l.get() == track;
4637
Haynes Mathew George7844f672014-01-15 12:32:55 -08004638 if (track->isInvalid()) {
4639 ALOGW("An invalidated track shouldn't be in active list");
4640 tracksToRemove->add(track);
4641 continue;
4642 }
4643
4644 if (track->mState == TrackBase::IDLE) {
4645 ALOGW("An idle track shouldn't be in active list");
4646 continue;
4647 }
4648
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 if (track->isPausing()) {
4650 track->setPaused();
4651 if (last) {
4652 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004653 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004654 mHwPaused = true;
4655 }
4656 // If we were part way through writing the mixbuffer to
4657 // the HAL we must save this until we resume
4658 // BUG - this will be wrong if a different track is made active,
4659 // in that case we want to discard the pending data in the
4660 // mixbuffer and tell the client to present it again when the
4661 // track is resumed
4662 mPausedWriteLength = mCurrentWriteLength;
4663 mPausedBytesRemaining = mBytesRemaining;
4664 mBytesRemaining = 0; // stop writing
4665 }
4666 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004667 } else if (track->isFlushPending()) {
4668 track->flushAck();
4669 if (last) {
4670 mFlushPending = true;
4671 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004672 } else if (track->isResumePending()){
4673 track->resumeAck();
4674 if (last) {
4675 if (mPausedBytesRemaining) {
4676 // Need to continue write that was interrupted
4677 mCurrentWriteLength = mPausedWriteLength;
4678 mBytesRemaining = mPausedBytesRemaining;
4679 mPausedBytesRemaining = 0;
4680 }
4681 if (mHwPaused) {
4682 doHwResume = true;
4683 mHwPaused = false;
4684 // threadLoop_mix() will handle the case that we need to
4685 // resume an interrupted write
4686 }
4687 // enable write to audio HAL
4688 sleepTime = 0;
4689
4690 // Do not handle new data in this iteration even if track->framesReady()
4691 mixerStatus = MIXER_TRACKS_ENABLED;
4692 }
4693 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004694 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004695 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004696 if (track->mFillingUpStatus == Track::FS_FILLED) {
4697 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004698 // make sure processVolume_l() will apply new volume even if 0
4699 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004700 }
4701
4702 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004703 sp<Track> previousTrack = mPreviousTrack.promote();
4704 if (previousTrack != 0) {
4705 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004706 // Flush any data still being written from last track
4707 mBytesRemaining = 0;
4708 if (mPausedBytesRemaining) {
4709 // Last track was paused so we also need to flush saved
4710 // mixbuffer state and invalidate track so that it will
4711 // re-submit that unwritten data when it is next resumed
4712 mPausedBytesRemaining = 0;
4713 // Invalidate is a bit drastic - would be more efficient
4714 // to have a flag to tell client that some of the
4715 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004716 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004717 }
4718 // flush data already sent to the DSP if changing audio session as audio
4719 // comes from a different source. Also invalidate previous track to force a
4720 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004721 if (previousTrack->sessionId() != track->sessionId()) {
4722 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004723 }
4724 }
4725 }
4726 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727 // reset retry count
4728 track->mRetryCount = kMaxTrackRetriesOffload;
4729 mActiveTrack = t;
4730 mixerStatus = MIXER_TRACKS_READY;
4731 }
4732 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004733 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734 if (track->isStopping_1()) {
4735 // Hardware buffer can hold a large amount of audio so we must
4736 // wait for all current track's data to drain before we say
4737 // that the track is stopped.
4738 if (mBytesRemaining == 0) {
4739 // Only start draining when all data in mixbuffer
4740 // has been written
4741 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4742 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004743 // do not drain if no data was ever sent to HAL (mStandby == true)
4744 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004745 // do not modify drain sequence if we are already draining. This happens
4746 // when resuming from pause after drain.
4747 if ((mDrainSequence & 1) == 0) {
4748 sleepTime = 0;
4749 standbyTime = systemTime() + standbyDelay;
4750 mixerStatus = MIXER_DRAIN_TRACK;
4751 mDrainSequence += 2;
4752 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004753 if (mHwPaused) {
4754 // It is possible to move from PAUSED to STOPPING_1 without
4755 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004756 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757 mHwPaused = false;
4758 }
4759 }
4760 }
4761 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004762 // Drain has completed or we are in standby, signal presentation complete
4763 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004764 track->mState = TrackBase::STOPPED;
4765 size_t audioHALFrames =
4766 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4767 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004768 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769 track->presentationComplete(framesWritten, audioHALFrames);
4770 track->reset();
4771 tracksToRemove->add(track);
4772 }
4773 } else {
4774 // No buffers for this track. Give it a few chances to
4775 // fill a buffer, then remove it from active list.
4776 if (--(track->mRetryCount) <= 0) {
4777 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4778 track->name());
4779 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004780 // indicate to client process that the track was disabled because of underrun;
4781 // it will then automatically call start() when data is available
4782 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783 } else if (last){
4784 mixerStatus = MIXER_TRACKS_ENABLED;
4785 }
4786 }
4787 }
4788 // compute volume for this track
4789 processVolume_l(track, last);
4790 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004791
Eric Laurentea0fade2013-10-04 16:23:48 -07004792 // make sure the pause/flush/resume sequence is executed in the right order.
4793 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4794 // before flush and then resume HW. This can happen in case of pause/flush/resume
4795 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004796 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004797 mOutput->stream->pause(mOutput->stream);
4798 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004799 if (mFlushPending) {
4800 flushHw_l();
4801 mFlushPending = false;
4802 }
Eric Laurentfd477972013-10-25 18:10:40 -07004803 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004804 mOutput->stream->resume(mOutput->stream);
4805 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004806
Eric Laurentbfb1b832013-01-07 09:53:42 -08004807 // remove all the tracks that need to be...
4808 removeTracks_l(*tracksToRemove);
4809
4810 return mixerStatus;
4811}
4812
Eric Laurentbfb1b832013-01-07 09:53:42 -08004813// must be called with thread mutex locked
4814bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4815{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004816 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4817 mWriteAckSequence, mDrainSequence);
4818 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 return true;
4820 }
4821 return false;
4822}
4823
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4825{
4826 Mutex::Autolock _l(mLock);
4827 return waitingAsyncCallback_l();
4828}
4829
4830void AudioFlinger::OffloadThread::flushHw_l()
4831{
Eric Laurente659ef42014-09-29 13:06:46 -07004832 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004833 // Flush anything still waiting in the mixbuffer
4834 mCurrentWriteLength = 0;
4835 mBytesRemaining = 0;
4836 mPausedWriteLength = 0;
4837 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004838
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004840 // discard any pending drain or write ack by incrementing sequence
4841 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4842 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004844 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4845 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004846 }
4847}
4848
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004849void AudioFlinger::OffloadThread::onAddNewTrack_l()
4850{
4851 sp<Track> previousTrack = mPreviousTrack.promote();
4852 sp<Track> latestTrack = mLatestActiveTrack.promote();
4853
4854 if (previousTrack != 0 && latestTrack != 0 &&
4855 (previousTrack->sessionId() != latestTrack->sessionId())) {
4856 mFlushPending = true;
4857 }
4858 PlaybackThread::onAddNewTrack_l();
4859}
4860
Eric Laurentbfb1b832013-01-07 09:53:42 -08004861// ----------------------------------------------------------------------------
4862
Eric Laurent81784c32012-11-19 14:55:58 -08004863AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4864 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4865 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4866 DUPLICATING),
4867 mWaitTimeMs(UINT_MAX)
4868{
4869 addOutputTrack(mainThread);
4870}
4871
4872AudioFlinger::DuplicatingThread::~DuplicatingThread()
4873{
4874 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4875 mOutputTracks[i]->destroy();
4876 }
4877}
4878
4879void AudioFlinger::DuplicatingThread::threadLoop_mix()
4880{
4881 // mix buffers...
4882 if (outputsReady(outputTracks)) {
4883 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4884 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004885 if (mMixerBufferValid) {
4886 memset(mMixerBuffer, 0, mMixerBufferSize);
4887 } else {
4888 memset(mSinkBuffer, 0, mSinkBufferSize);
4889 }
Eric Laurent81784c32012-11-19 14:55:58 -08004890 }
4891 sleepTime = 0;
4892 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004893 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004894 standbyTime = systemTime() + standbyDelay;
4895}
4896
4897void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4898{
4899 if (sleepTime == 0) {
4900 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4901 sleepTime = activeSleepTime;
4902 } else {
4903 sleepTime = idleSleepTime;
4904 }
4905 } else if (mBytesWritten != 0) {
4906 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4907 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004908 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004909 } else {
4910 // flush remaining overflow buffers in output tracks
4911 writeFrames = 0;
4912 }
4913 sleepTime = 0;
4914 }
4915}
4916
Eric Laurentbfb1b832013-01-07 09:53:42 -08004917ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004918{
4919 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004920 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004921 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004922 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004923 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004924}
4925
4926void AudioFlinger::DuplicatingThread::threadLoop_standby()
4927{
4928 // DuplicatingThread implements standby by stopping all tracks
4929 for (size_t i = 0; i < outputTracks.size(); i++) {
4930 outputTracks[i]->stop();
4931 }
4932}
4933
4934void AudioFlinger::DuplicatingThread::saveOutputTracks()
4935{
4936 outputTracks = mOutputTracks;
4937}
4938
4939void AudioFlinger::DuplicatingThread::clearOutputTracks()
4940{
4941 outputTracks.clear();
4942}
4943
4944void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4945{
4946 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004947 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4948 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4949 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4950 const size_t frameCount =
4951 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4952 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4953 // from different OutputTracks and their associated MixerThreads (e.g. one may
4954 // nearly empty and the other may be dropping data).
4955
4956 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004957 this,
4958 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004959 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004960 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004961 frameCount,
4962 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004963 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004964 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004965 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004966 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004967 updateWaitTime_l();
4968 }
4969}
4970
4971void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4972{
4973 Mutex::Autolock _l(mLock);
4974 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4975 if (mOutputTracks[i]->thread() == thread) {
4976 mOutputTracks[i]->destroy();
4977 mOutputTracks.removeAt(i);
4978 updateWaitTime_l();
4979 return;
4980 }
4981 }
4982 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4983}
4984
4985// caller must hold mLock
4986void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4987{
4988 mWaitTimeMs = UINT_MAX;
4989 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4990 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4991 if (strong != 0) {
4992 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4993 if (waitTimeMs < mWaitTimeMs) {
4994 mWaitTimeMs = waitTimeMs;
4995 }
4996 }
4997 }
4998}
4999
5000
5001bool AudioFlinger::DuplicatingThread::outputsReady(
5002 const SortedVector< sp<OutputTrack> > &outputTracks)
5003{
5004 for (size_t i = 0; i < outputTracks.size(); i++) {
5005 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5006 if (thread == 0) {
5007 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5008 outputTracks[i].get());
5009 return false;
5010 }
5011 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5012 // see note at standby() declaration
5013 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5014 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5015 thread.get());
5016 return false;
5017 }
5018 }
5019 return true;
5020}
5021
5022uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5023{
5024 return (mWaitTimeMs * 1000) / 2;
5025}
5026
5027void AudioFlinger::DuplicatingThread::cacheParameters_l()
5028{
5029 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5030 updateWaitTime_l();
5031
5032 MixerThread::cacheParameters_l();
5033}
5034
5035// ----------------------------------------------------------------------------
5036// Record
5037// ----------------------------------------------------------------------------
5038
5039AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5040 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005041 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005042 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005043 audio_devices_t inDevice
5044#ifdef TEE_SINK
5045 , const sp<NBAIO_Sink>& teeSink
5046#endif
5047 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005048 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005049 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005050 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005051 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005052#ifdef TEE_SINK
5053 , mTeeSink(teeSink)
5054#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005055 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5056 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005057 // mFastCapture below
5058 , mFastCaptureFutex(0)
5059 // mInputSource
5060 // mPipeSink
5061 // mPipeSource
5062 , mPipeFramesP2(0)
5063 // mPipeMemory
5064 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005065 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005066{
5067 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005068 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005069
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005070 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005071
5072 // create an NBAIO source for the HAL input stream, and negotiate
5073 mInputSource = new AudioStreamInSource(input->stream);
5074 size_t numCounterOffers = 0;
5075 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5076 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5077 ALOG_ASSERT(index == 0);
5078
5079 // initialize fast capture depending on configuration
5080 bool initFastCapture;
5081 switch (kUseFastCapture) {
5082 case FastCapture_Never:
5083 initFastCapture = false;
5084 break;
5085 case FastCapture_Always:
5086 initFastCapture = true;
5087 break;
5088 case FastCapture_Static:
5089 uint32_t primaryOutputSampleRate;
5090 {
5091 AutoMutex _l(audioFlinger->mHardwareLock);
5092 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5093 }
5094 initFastCapture =
5095 // either capture sample rate is same as (a reasonable) primary output sample rate
5096 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5097 (mSampleRate == primaryOutputSampleRate)) ||
5098 // or primary output sample rate is unknown, and capture sample rate is reasonable
5099 ((primaryOutputSampleRate == 0) &&
5100 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005101 // and the buffer size is < 12 ms
5102 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005103 break;
5104 // case FastCapture_Dynamic:
5105 }
5106
5107 if (initFastCapture) {
5108 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5109 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005110 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005111 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5112 void *pipeBuffer;
5113 const sp<MemoryDealer> roHeap(readOnlyHeap());
5114 sp<IMemory> pipeMemory;
5115 if ((roHeap == 0) ||
5116 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5117 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5118 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5119 goto failed;
5120 }
5121 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5122 memset(pipeBuffer, 0, pipeSize);
5123 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5124 const NBAIO_Format offers[1] = {format};
5125 size_t numCounterOffers = 0;
5126 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5127 ALOG_ASSERT(index == 0);
5128 mPipeSink = pipe;
5129 PipeReader *pipeReader = new PipeReader(*pipe);
5130 numCounterOffers = 0;
5131 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5132 ALOG_ASSERT(index == 0);
5133 mPipeSource = pipeReader;
5134 mPipeFramesP2 = pipeFramesP2;
5135 mPipeMemory = pipeMemory;
5136
5137 // create fast capture
5138 mFastCapture = new FastCapture();
5139 FastCaptureStateQueue *sq = mFastCapture->sq();
5140#ifdef STATE_QUEUE_DUMP
5141 // FIXME
5142#endif
5143 FastCaptureState *state = sq->begin();
5144 state->mCblk = NULL;
5145 state->mInputSource = mInputSource.get();
5146 state->mInputSourceGen++;
5147 state->mPipeSink = pipe;
5148 state->mPipeSinkGen++;
5149 state->mFrameCount = mFrameCount;
5150 state->mCommand = FastCaptureState::COLD_IDLE;
5151 // already done in constructor initialization list
5152 //mFastCaptureFutex = 0;
5153 state->mColdFutexAddr = &mFastCaptureFutex;
5154 state->mColdGen++;
5155 state->mDumpState = &mFastCaptureDumpState;
5156#ifdef TEE_SINK
5157 // FIXME
5158#endif
5159 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5160 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5161 sq->end();
5162 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5163
5164 // start the fast capture
5165 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5166 pid_t tid = mFastCapture->getTid();
5167 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5168 if (err != 0) {
5169 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5170 kPriorityFastCapture, getpid_cached, tid, err);
5171 }
5172
5173#ifdef AUDIO_WATCHDOG
5174 // FIXME
5175#endif
5176
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005177 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005178 }
5179failed: ;
5180
5181 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005182}
5183
5184
5185AudioFlinger::RecordThread::~RecordThread()
5186{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005187 if (mFastCapture != 0) {
5188 FastCaptureStateQueue *sq = mFastCapture->sq();
5189 FastCaptureState *state = sq->begin();
5190 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5191 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5192 if (old == -1) {
5193 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5194 }
5195 }
5196 state->mCommand = FastCaptureState::EXIT;
5197 sq->end();
5198 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5199 mFastCapture->join();
5200 mFastCapture.clear();
5201 }
5202 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005203 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005204 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005205}
5206
5207void AudioFlinger::RecordThread::onFirstRef()
5208{
5209 run(mName, PRIORITY_URGENT_AUDIO);
5210}
5211
Eric Laurent81784c32012-11-19 14:55:58 -08005212bool AudioFlinger::RecordThread::threadLoop()
5213{
Eric Laurent81784c32012-11-19 14:55:58 -08005214 nsecs_t lastWarning = 0;
5215
5216 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005217
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005218reacquire_wakelock:
5219 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005220 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005221 {
5222 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005223 size_t size = mActiveTracks.size();
5224 activeTracksGen = mActiveTracksGen;
5225 if (size > 0) {
5226 // FIXME an arbitrary choice
5227 activeTrack = mActiveTracks[0];
5228 acquireWakeLock_l(activeTrack->uid());
5229 if (size > 1) {
5230 SortedVector<int> tmp;
5231 for (size_t i = 0; i < size; i++) {
5232 tmp.add(mActiveTracks[i]->uid());
5233 }
5234 updateWakeLockUids_l(tmp);
5235 }
5236 } else {
5237 acquireWakeLock_l(-1);
5238 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005239 }
5240
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 // used to request a deferred sleep, to be executed later while mutex is unlocked
5242 uint32_t sleepUs = 0;
5243
5244 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005245 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005246 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005247
Glenn Kasten5edadd42013-08-14 16:30:49 -07005248 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005249 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005250 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005251 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005252 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005253 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005254 }
5255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005256 // activeTracks accumulates a copy of a subset of mActiveTracks
5257 Vector< sp<RecordTrack> > activeTracks;
5258
Glenn Kasten735f45f2014-08-18 15:51:59 -07005259 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005260 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005261
Glenn Kasten735f45f2014-08-18 15:51:59 -07005262 // reference to a fast track which is about to be removed
5263 sp<RecordTrack> fastTrackToRemove;
5264
Eric Laurent81784c32012-11-19 14:55:58 -08005265 { // scope for mLock
5266 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005267
Eric Laurent021cf962014-05-13 10:18:14 -07005268 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005269
Eric Laurent000a4192014-01-29 15:17:32 -08005270 // check exitPending here because checkForNewParameters_l() and
5271 // checkForNewParameters_l() can temporarily release mLock
5272 if (exitPending()) {
5273 break;
5274 }
5275
Glenn Kasten2b806402013-11-20 16:37:38 -08005276 // if no active track(s), then standby and release wakelock
5277 size_t size = mActiveTracks.size();
5278 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005279 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005280 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005281 releaseWakeLock_l();
5282 ALOGV("RecordThread: loop stopping");
5283 // go to sleep
5284 mWaitWorkCV.wait(mLock);
5285 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005286 goto reacquire_wakelock;
5287 }
5288
Glenn Kasten2b806402013-11-20 16:37:38 -08005289 if (mActiveTracksGen != activeTracksGen) {
5290 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005291 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005292 for (size_t i = 0; i < size; i++) {
5293 tmp.add(mActiveTracks[i]->uid());
5294 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005295 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005296 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005297
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 bool doBroadcast = false;
5299 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005301 activeTrack = mActiveTracks[i];
5302 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005303 if (activeTrack->isFastTrack()) {
5304 ALOG_ASSERT(fastTrackToRemove == 0);
5305 fastTrackToRemove = activeTrack;
5306 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005307 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005308 mActiveTracks.remove(activeTrack);
5309 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005310 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005311 continue;
5312 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005313
5314 TrackBase::track_state activeTrackState = activeTrack->mState;
5315 switch (activeTrackState) {
5316
5317 case TrackBase::PAUSING:
5318 mActiveTracks.remove(activeTrack);
5319 mActiveTracksGen++;
5320 doBroadcast = true;
5321 size--;
5322 continue;
5323
5324 case TrackBase::STARTING_1:
5325 sleepUs = 10000;
5326 i++;
5327 continue;
5328
5329 case TrackBase::STARTING_2:
5330 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005331 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005332 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005333 break;
5334
5335 case TrackBase::ACTIVE:
5336 break;
5337
5338 case TrackBase::IDLE:
5339 i++;
5340 continue;
5341
5342 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005343 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005344 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005345
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005346 activeTracks.add(activeTrack);
5347 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005348
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005349 if (activeTrack->isFastTrack()) {
5350 ALOG_ASSERT(!mFastTrackAvail);
5351 ALOG_ASSERT(fastTrack == 0);
5352 fastTrack = activeTrack;
5353 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005354 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005355 if (doBroadcast) {
5356 mStartStopCond.broadcast();
5357 }
5358
5359 // sleep if there are no active tracks to process
5360 if (activeTracks.size() == 0) {
5361 if (sleepUs == 0) {
5362 sleepUs = kRecordThreadSleepUs;
5363 }
5364 continue;
5365 }
5366 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005367
Eric Laurent81784c32012-11-19 14:55:58 -08005368 lockEffectChains_l(effectChains);
5369 }
5370
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005371 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005372
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005373 size_t size = effectChains.size();
5374 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005375 // thread mutex is not locked, but effect chain is locked
5376 effectChains[i]->process_l();
5377 }
5378
Glenn Kasten735f45f2014-08-18 15:51:59 -07005379 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005380 if (mFastCapture != 0) {
5381 FastCaptureStateQueue *sq = mFastCapture->sq();
5382 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005383 bool didModify = false;
5384 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005385 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5386 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5387 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5388 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5389 if (old == -1) {
5390 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5391 }
5392 }
5393 state->mCommand = FastCaptureState::READ_WRITE;
5394#if 0 // FIXME
5395 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005396 FastCaptureDumpState::kSamplingNforLowRamDevice :
5397 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005398#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005399 didModify = true;
5400 }
5401 audio_track_cblk_t *cblkOld = state->mCblk;
5402 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5403 if (cblkNew != cblkOld) {
5404 state->mCblk = cblkNew;
5405 // block until acked if removing a fast track
5406 if (cblkOld != NULL) {
5407 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5408 }
5409 didModify = true;
5410 }
5411 sq->end(didModify);
5412 if (didModify) {
5413 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005414#if 0
5415 if (kUseFastCapture == FastCapture_Dynamic) {
5416 mNormalSource = mPipeSource;
5417 }
5418#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005419 }
5420 }
5421
Glenn Kasten735f45f2014-08-18 15:51:59 -07005422 // now run the fast track destructor with thread mutex unlocked
5423 fastTrackToRemove.clear();
5424
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005425 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5426 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5427 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5428 // If destination is non-contiguous, first read past the nominal end of buffer, then
5429 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005430
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005431 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005432 ssize_t framesRead;
5433
5434 // If an NBAIO source is present, use it to read the normal capture's data
5435 if (mPipeSource != 0) {
5436 size_t framesToRead = mBufferSize / mFrameSize;
5437 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5438 framesToRead, AudioBufferProvider::kInvalidPTS);
5439 if (framesRead == 0) {
5440 // since pipe is non-blocking, simulate blocking input
5441 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5442 }
5443 // otherwise use the HAL / AudioStreamIn directly
5444 } else {
5445 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5446 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5447 if (bytesRead < 0) {
5448 framesRead = bytesRead;
5449 } else {
5450 framesRead = bytesRead / mFrameSize;
5451 }
5452 }
5453
5454 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5455 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005456 // Force input into standby so that it tries to recover at next read attempt
5457 inputStandBy();
5458 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005459 }
5460 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005461 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005462 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005463 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005464
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005465 if (mTeeSink != 0) {
5466 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5467 }
5468 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005469 {
5470 size_t part1 = mRsmpInFramesP2 - rear;
5471 if ((size_t) framesRead > part1) {
5472 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5473 (framesRead - part1) * mFrameSize);
5474 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005475 }
5476 rear = mRsmpInRear += framesRead;
5477
5478 size = activeTracks.size();
5479 // loop over each active track
5480 for (size_t i = 0; i < size; i++) {
5481 activeTrack = activeTracks[i];
5482
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005483 // skip fast tracks, as those are handled directly by FastCapture
5484 if (activeTrack->isFastTrack()) {
5485 continue;
5486 }
5487
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005488 enum {
5489 OVERRUN_UNKNOWN,
5490 OVERRUN_TRUE,
5491 OVERRUN_FALSE
5492 } overrun = OVERRUN_UNKNOWN;
5493
5494 // loop over getNextBuffer to handle circular sink
5495 for (;;) {
5496
5497 activeTrack->mSink.frameCount = ~0;
5498 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5499 size_t framesOut = activeTrack->mSink.frameCount;
5500 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5501
5502 int32_t front = activeTrack->mRsmpInFront;
5503 ssize_t filled = rear - front;
5504 size_t framesIn;
5505
5506 if (filled < 0) {
5507 // should not happen, but treat like a massive overrun and re-sync
5508 framesIn = 0;
5509 activeTrack->mRsmpInFront = rear;
5510 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005511 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005512 framesIn = (size_t) filled;
5513 } else {
5514 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005515 framesIn = mRsmpInFrames;
5516 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005517 overrun = OVERRUN_TRUE;
5518 }
5519
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005520 if (framesOut == 0 || framesIn == 0) {
5521 break;
5522 }
5523
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005524 if (activeTrack->mResampler == NULL) {
5525 // no resampling
5526 if (framesIn > framesOut) {
5527 framesIn = framesOut;
5528 } else {
5529 framesOut = framesIn;
5530 }
5531 int8_t *dst = activeTrack->mSink.i8;
5532 while (framesIn > 0) {
5533 front &= mRsmpInFramesP2 - 1;
5534 size_t part1 = mRsmpInFramesP2 - front;
5535 if (part1 > framesIn) {
5536 part1 = framesIn;
5537 }
5538 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005539 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005540 memcpy(dst, src, part1 * mFrameSize);
5541 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005542 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005543 part1);
5544 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005545 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5546 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005547 }
5548 dst += part1 * activeTrack->mFrameSize;
5549 front += part1;
5550 framesIn -= part1;
5551 }
5552 activeTrack->mRsmpInFront += framesOut;
5553
5554 } else {
5555 // resampling
5556 // FIXME framesInNeeded should really be part of resampler API, and should
5557 // depend on the SRC ratio
5558 // to keep mRsmpInBuffer full so resampler always has sufficient input
5559 size_t framesInNeeded;
5560 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005561 // Do not precompute in/out because floating point is not associative
5562 // e.g. a*b/c != a*(b/c).
5563 const double in(mSampleRate);
5564 const double out(activeTrack->mSampleRate);
5565 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005566 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005567 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005568 // Although we theoretically have framesIn in circular buffer, some of those are
5569 // unreleased frames, and thus must be discounted for purpose of budgeting.
5570 size_t unreleased = activeTrack->mRsmpInUnrel;
5571 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005572 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005573 ALOGV("not enough to resample: have %u frames in but need %u in to "
5574 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005575 framesIn, framesInNeeded, framesOut, in / out);
5576 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005577 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5578 if (newFramesOut == 0) {
5579 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005580 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005581 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005582 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005583 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005584 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5585 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5586 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005587 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005588 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005589 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005590 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005591 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005592 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005593 }
5594
5595 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5596 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005597 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005598 delete[] activeTrack->mRsmpOutBuffer;
5599 // resampler always outputs stereo
5600 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5601 activeTrack->mRsmpOutFrameCount = framesOut;
5602 }
5603
5604 // resampler accumulates, but we only have one source track
5605 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5606 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005607 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005608 activeTrack->mResamplerBufferProvider
5609 /*this*/ /* AudioBufferProvider* */);
5610 // ditherAndClamp() works as long as all buffers returned by
5611 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005612 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005613 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005614 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5615 framesOut);
5616 // the resampler always outputs stereo samples:
5617 // do post stereo to mono conversion
5618 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005619 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005620 } else {
5621 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5622 activeTrack->mRsmpOutBuffer, framesOut);
5623 }
5624 // now done with mRsmpOutBuffer
5625
5626 }
5627
5628 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5629 overrun = OVERRUN_FALSE;
5630 }
5631
5632 if (activeTrack->mFramesToDrop == 0) {
5633 if (framesOut > 0) {
5634 activeTrack->mSink.frameCount = framesOut;
5635 activeTrack->releaseBuffer(&activeTrack->mSink);
5636 }
5637 } else {
5638 // FIXME could do a partial drop of framesOut
5639 if (activeTrack->mFramesToDrop > 0) {
5640 activeTrack->mFramesToDrop -= framesOut;
5641 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005642 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005643 }
5644 } else {
5645 activeTrack->mFramesToDrop += framesOut;
5646 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5647 activeTrack->mSyncStartEvent->isCancelled()) {
5648 ALOGW("Synced record %s, session %d, trigger session %d",
5649 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5650 activeTrack->sessionId(),
5651 (activeTrack->mSyncStartEvent != 0) ?
5652 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005653 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005654 }
5655 }
5656 }
5657
5658 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005659 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005660 }
5661 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005662
5663 switch (overrun) {
5664 case OVERRUN_TRUE:
5665 // client isn't retrieving buffers fast enough
5666 if (!activeTrack->setOverflow()) {
5667 nsecs_t now = systemTime();
5668 // FIXME should lastWarning per track?
5669 if ((now - lastWarning) > kWarningThrottleNs) {
5670 ALOGW("RecordThread: buffer overflow");
5671 lastWarning = now;
5672 }
5673 }
5674 break;
5675 case OVERRUN_FALSE:
5676 activeTrack->clearOverflow();
5677 break;
5678 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005679 break;
5680 }
5681
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005682 }
5683
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005684unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005685 // enable changes in effect chain
5686 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005687 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005688 }
5689
Glenn Kasten93e471f2013-08-19 08:40:07 -07005690 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005691
5692 {
5693 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005694 for (size_t i = 0; i < mTracks.size(); i++) {
5695 sp<RecordTrack> track = mTracks[i];
5696 track->invalidate();
5697 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005698 mActiveTracks.clear();
5699 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005700 mStartStopCond.broadcast();
5701 }
5702
5703 releaseWakeLock();
5704
5705 ALOGV("RecordThread %p exiting", this);
5706 return false;
5707}
5708
Glenn Kasten93e471f2013-08-19 08:40:07 -07005709void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005710{
5711 if (!mStandby) {
5712 inputStandBy();
5713 mStandby = true;
5714 }
5715}
5716
5717void AudioFlinger::RecordThread::inputStandBy()
5718{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005719 // Idle the fast capture if it's currently running
5720 if (mFastCapture != 0) {
5721 FastCaptureStateQueue *sq = mFastCapture->sq();
5722 FastCaptureState *state = sq->begin();
5723 if (!(state->mCommand & FastCaptureState::IDLE)) {
5724 state->mCommand = FastCaptureState::COLD_IDLE;
5725 state->mColdFutexAddr = &mFastCaptureFutex;
5726 state->mColdGen++;
5727 mFastCaptureFutex = 0;
5728 sq->end();
5729 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5730 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5731#if 0
5732 if (kUseFastCapture == FastCapture_Dynamic) {
5733 // FIXME
5734 }
5735#endif
5736#ifdef AUDIO_WATCHDOG
5737 // FIXME
5738#endif
5739 } else {
5740 sq->end(false /*didModify*/);
5741 }
5742 }
Eric Laurent81784c32012-11-19 14:55:58 -08005743 mInput->stream->common.standby(&mInput->stream->common);
5744}
5745
Glenn Kasten05997e22014-03-13 15:08:33 -07005746// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005747sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005748 const sp<AudioFlinger::Client>& client,
5749 uint32_t sampleRate,
5750 audio_format_t format,
5751 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005752 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005753 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005754 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005755 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005756 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005757 pid_t tid,
5758 status_t *status)
5759{
Glenn Kasten74935e42013-12-19 08:56:45 -08005760 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005761 sp<RecordTrack> track;
5762 status_t lStatus;
5763
Glenn Kasten90e58b12013-07-31 16:16:02 -07005764 // client expresses a preference for FAST, but we get the final say
5765 if (*flags & IAudioFlinger::TRACK_FAST) {
5766 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005767 // use case: callback handler
5768 (tid != -1) &&
5769 // frame count is not specified, or is exactly the pipe depth
5770 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005771 // PCM data
5772 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005773 // native format
5774 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 // native channel mask
5776 (channelMask == mChannelMask) &&
5777 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005778 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005779 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005780 hasFastCapture() &&
5781 // there are sufficient fast track slots available
5782 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005783 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005784 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005785 frameCount, mFrameCount);
5786 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005787 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5788 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005789 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005790 frameCount, mFrameCount, mPipeFramesP2,
5791 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5792 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005793 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005794 }
5795 }
5796
5797 // compute track buffer size in frames, and suggest the notification frame count
5798 if (*flags & IAudioFlinger::TRACK_FAST) {
5799 // fast track: frame count is exactly the pipe depth
5800 frameCount = mPipeFramesP2;
5801 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5802 *notificationFrames = mFrameCount;
5803 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005804 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5805 // or 20 ms if there is a fast capture
5806 // TODO This could be a roundupRatio inline, and const
5807 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5808 * sampleRate + mSampleRate - 1) / mSampleRate;
5809 // minimum number of notification periods is at least kMinNotifications,
5810 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5811 static const size_t kMinNotifications = 3;
5812 static const uint32_t kMinMs = 30;
5813 // TODO This could be a roundupRatio inline
5814 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5815 // TODO This could be a roundupRatio inline
5816 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5817 maxNotificationFrames;
5818 const size_t minFrameCount = maxNotificationFrames *
5819 max(kMinNotifications, minNotificationsByMs);
5820 frameCount = max(frameCount, minFrameCount);
5821 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5822 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005823 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005824 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005825 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005826
Glenn Kasten15e57982013-09-24 11:52:37 -07005827 lStatus = initCheck();
5828 if (lStatus != NO_ERROR) {
5829 ALOGE("createRecordTrack_l() audio driver not initialized");
5830 goto Exit;
5831 }
Eric Laurent81784c32012-11-19 14:55:58 -08005832
5833 { // scope for mLock
5834 Mutex::Autolock _l(mLock);
5835
5836 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005837 format, channelMask, frameCount, NULL, sessionId, uid,
5838 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005839
Glenn Kasten03003332013-08-06 15:40:54 -07005840 lStatus = track->initCheck();
5841 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005842 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005843 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005844 goto Exit;
5845 }
5846 mTracks.add(track);
5847
5848 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5849 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5850 mAudioFlinger->btNrecIsOff();
5851 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5852 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005853
5854 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5855 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5856 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5857 // so ask activity manager to do this on our behalf
5858 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5859 }
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005861
Eric Laurent81784c32012-11-19 14:55:58 -08005862 lStatus = NO_ERROR;
5863
5864Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005865 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005866 return track;
5867}
5868
5869status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5870 AudioSystem::sync_event_t event,
5871 int triggerSession)
5872{
5873 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5874 sp<ThreadBase> strongMe = this;
5875 status_t status = NO_ERROR;
5876
5877 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005878 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005879 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005881 triggerSession,
5882 recordTrack->sessionId(),
5883 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005885 // Sync event can be cancelled by the trigger session if the track is not in a
5886 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005887 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005888 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005889 } else {
5890 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005891 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005892 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005893 }
5894 }
5895
5896 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005897 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005898 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5900 if (recordTrack->mState == TrackBase::PAUSING) {
5901 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005902 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 } else {
5904 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005905 }
5906 return status;
5907 }
5908
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005909 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5910 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5911 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005913 mActiveTracks.add(recordTrack);
5914 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005915 status_t status = NO_ERROR;
5916 if (recordTrack->isExternalTrack()) {
5917 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005918 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005919 mLock.lock();
5920 // FIXME should verify that recordTrack is still in mActiveTracks
5921 if (status != NO_ERROR) {
5922 mActiveTracks.remove(recordTrack);
5923 mActiveTracksGen++;
5924 recordTrack->clearSyncStartEvent();
5925 ALOGV("RecordThread::start error %d", status);
5926 return status;
5927 }
Eric Laurent81784c32012-11-19 14:55:58 -08005928 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005929 // Catch up with current buffer indices if thread is already running.
5930 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5931 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5932 // see previously buffered data before it called start(), but with greater risk of overrun.
5933
5934 recordTrack->mRsmpInFront = mRsmpInRear;
5935 recordTrack->mRsmpInUnrel = 0;
5936 // FIXME why reset?
5937 if (recordTrack->mResampler != NULL) {
5938 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005939 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005940 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005941 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005942 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005943 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 ALOGV("Record failed to start");
5945 status = BAD_VALUE;
5946 goto startError;
5947 }
Eric Laurent81784c32012-11-19 14:55:58 -08005948 return status;
5949 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005950
Eric Laurent81784c32012-11-19 14:55:58 -08005951startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005952 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005953 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005954 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005955 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005956 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005957 return status;
5958}
5959
Eric Laurent81784c32012-11-19 14:55:58 -08005960void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5961{
5962 sp<SyncEvent> strongEvent = event.promote();
5963
5964 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005965 sp<RefBase> ptr = strongEvent->cookie().promote();
5966 if (ptr != 0) {
5967 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5968 recordTrack->handleSyncStartEvent(strongEvent);
5969 }
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
5971}
5972
Glenn Kastena8356f62013-07-25 14:37:52 -07005973bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005974 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005975 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005976 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005977 return false;
5978 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005979 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005980 recordTrack->mState = TrackBase::PAUSING;
5981 // do not wait for mStartStopCond if exiting
5982 if (exitPending()) {
5983 return true;
5984 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005985 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005986 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005987 // if we have been restarted, recordTrack is in mActiveTracks here
5988 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005989 ALOGV("Record stopped OK");
5990 return true;
5991 }
5992 return false;
5993}
5994
Glenn Kasten0f11b512014-01-31 16:18:54 -08005995bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005996{
5997 return false;
5998}
5999
Glenn Kasten0f11b512014-01-31 16:18:54 -08006000status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006001{
6002#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6003 if (!isValidSyncEvent(event)) {
6004 return BAD_VALUE;
6005 }
6006
6007 int eventSession = event->triggerSession();
6008 status_t ret = NAME_NOT_FOUND;
6009
6010 Mutex::Autolock _l(mLock);
6011
6012 for (size_t i = 0; i < mTracks.size(); i++) {
6013 sp<RecordTrack> track = mTracks[i];
6014 if (eventSession == track->sessionId()) {
6015 (void) track->setSyncEvent(event);
6016 ret = NO_ERROR;
6017 }
6018 }
6019 return ret;
6020#else
6021 return BAD_VALUE;
6022#endif
6023}
6024
6025// destroyTrack_l() must be called with ThreadBase::mLock held
6026void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6027{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006028 track->terminate();
6029 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006030 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006031 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006032 removeTrack_l(track);
6033 }
6034}
6035
6036void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6037{
6038 mTracks.remove(track);
6039 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006040 if (track->isFastTrack()) {
6041 ALOG_ASSERT(!mFastTrackAvail);
6042 mFastTrackAvail = true;
6043 }
Eric Laurent81784c32012-11-19 14:55:58 -08006044}
6045
6046void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6047{
6048 dumpInternals(fd, args);
6049 dumpTracks(fd, args);
6050 dumpEffectChains(fd, args);
6051}
6052
6053void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6054{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006055 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006056
Glenn Kasten2b806402013-11-20 16:37:38 -08006057 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006058 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006060 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006061 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006062 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006063 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006064
Eric Laurent81784c32012-11-19 14:55:58 -08006065 dumpBase(fd, args);
6066}
6067
Glenn Kasten0f11b512014-01-31 16:18:54 -08006068void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006069{
6070 const size_t SIZE = 256;
6071 char buffer[SIZE];
6072 String8 result;
6073
Marco Nelissenb2208842014-02-07 14:00:50 -08006074 size_t numtracks = mTracks.size();
6075 size_t numactive = mActiveTracks.size();
6076 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006077 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006078 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006079 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006080 RecordTrack::appendDumpHeader(result);
6081 for (size_t i = 0; i < numtracks ; ++i) {
6082 sp<RecordTrack> track = mTracks[i];
6083 if (track != 0) {
6084 bool active = mActiveTracks.indexOf(track) >= 0;
6085 if (active) {
6086 numactiveseen++;
6087 }
6088 track->dump(buffer, SIZE, active);
6089 result.append(buffer);
6090 }
Eric Laurent81784c32012-11-19 14:55:58 -08006091 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006092 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006093 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006094 }
6095
Marco Nelissenb2208842014-02-07 14:00:50 -08006096 if (numactiveseen != numactive) {
6097 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6098 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006099 result.append(buffer);
6100 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006101 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006102 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006103 if (mTracks.indexOf(track) < 0) {
6104 track->dump(buffer, SIZE, true);
6105 result.append(buffer);
6106 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006107 }
Eric Laurent81784c32012-11-19 14:55:58 -08006108
6109 }
6110 write(fd, result.string(), result.size());
6111}
6112
6113// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006114status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6115 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006116{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 RecordTrack *activeTrack = mRecordTrack;
6118 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6119 if (threadBase == 0) {
6120 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006121 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 return NOT_ENOUGH_DATA;
6123 }
6124 RecordThread *recordThread = (RecordThread *) threadBase.get();
6125 int32_t rear = recordThread->mRsmpInRear;
6126 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006127 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006128 // FIXME should not be P2 (don't want to increase latency)
6129 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006130 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006131 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132 front &= recordThread->mRsmpInFramesP2 - 1;
6133 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006134 if (part1 > (size_t) filled) {
6135 part1 = filled;
6136 }
6137 size_t ask = buffer->frameCount;
6138 ALOG_ASSERT(ask > 0);
6139 if (part1 > ask) {
6140 part1 = ask;
6141 }
6142 if (part1 == 0) {
6143 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006144 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006145 buffer->raw = NULL;
6146 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006147 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006148 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006149 }
6150
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006152 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006153 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006154 return NO_ERROR;
6155}
6156
6157// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6159 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006160{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006162 size_t stepCount = buffer->frameCount;
6163 if (stepCount == 0) {
6164 return;
6165 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6167 activeTrack->mRsmpInUnrel -= stepCount;
6168 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006169 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006170 buffer->frameCount = 0;
6171}
6172
Eric Laurent10351942014-05-08 18:49:52 -07006173bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6174 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006175{
6176 bool reconfig = false;
6177
Eric Laurent10351942014-05-08 18:49:52 -07006178 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006179
Eric Laurent10351942014-05-08 18:49:52 -07006180 audio_format_t reqFormat = mFormat;
6181 uint32_t samplingRate = mSampleRate;
6182 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6183
6184 AudioParameter param = AudioParameter(keyValuePair);
6185 int value;
6186 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6187 // channel count change can be requested. Do we mandate the first client defines the
6188 // HAL sampling rate and channel count or do we allow changes on the fly?
6189 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6190 samplingRate = value;
6191 reconfig = true;
6192 }
6193 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6194 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6195 status = BAD_VALUE;
6196 } else {
6197 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006198 reconfig = true;
6199 }
Eric Laurent10351942014-05-08 18:49:52 -07006200 }
6201 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6202 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6203 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6204 status = BAD_VALUE;
6205 } else {
6206 channelMask = mask;
6207 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006208 }
Eric Laurent10351942014-05-08 18:49:52 -07006209 }
6210 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6211 // do not accept frame count changes if tracks are open as the track buffer
6212 // size depends on frame count and correct behavior would not be guaranteed
6213 // if frame count is changed after track creation
6214 if (mActiveTracks.size() > 0) {
6215 status = INVALID_OPERATION;
6216 } else {
6217 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 }
Eric Laurent10351942014-05-08 18:49:52 -07006219 }
6220 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6221 // forward device change to effects that have requested to be
6222 // aware of attached audio device.
6223 for (size_t i = 0; i < mEffectChains.size(); i++) {
6224 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
Eric Laurent81784c32012-11-19 14:55:58 -08006226
Eric Laurent10351942014-05-08 18:49:52 -07006227 // store input device and output device but do not forward output device to audio HAL.
6228 // Note that status is ignored by the caller for output device
6229 // (see AudioFlinger::setParameters()
6230 if (audio_is_output_devices(value)) {
6231 mOutDevice = value;
6232 status = BAD_VALUE;
6233 } else {
6234 mInDevice = value;
6235 // disable AEC and NS if the device is a BT SCO headset supporting those
6236 // pre processings
6237 if (mTracks.size() > 0) {
6238 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6239 mAudioFlinger->btNrecIsOff();
6240 for (size_t i = 0; i < mTracks.size(); i++) {
6241 sp<RecordTrack> track = mTracks[i];
6242 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6243 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006244 }
6245 }
6246 }
Eric Laurent10351942014-05-08 18:49:52 -07006247 }
6248 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6249 mAudioSource != (audio_source_t)value) {
6250 // forward device change to effects that have requested to be
6251 // aware of attached audio device.
6252 for (size_t i = 0; i < mEffectChains.size(); i++) {
6253 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006254 }
Eric Laurent10351942014-05-08 18:49:52 -07006255 mAudioSource = (audio_source_t)value;
6256 }
Glenn Kastene198c362013-08-13 09:13:36 -07006257
Eric Laurent10351942014-05-08 18:49:52 -07006258 if (status == NO_ERROR) {
6259 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6260 keyValuePair.string());
6261 if (status == INVALID_OPERATION) {
6262 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006263 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6264 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006265 }
6266 if (reconfig) {
6267 if (status == BAD_VALUE &&
6268 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6269 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6270 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6271 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006272 audio_channel_count_from_in_mask(
6273 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006274 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6275 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6276 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006277 }
Eric Laurent10351942014-05-08 18:49:52 -07006278 if (status == NO_ERROR) {
6279 readInputParameters_l();
6280 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006281 }
6282 }
Eric Laurent81784c32012-11-19 14:55:58 -08006283 }
Eric Laurent10351942014-05-08 18:49:52 -07006284
Eric Laurent81784c32012-11-19 14:55:58 -08006285 return reconfig;
6286}
6287
6288String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6289{
Eric Laurent81784c32012-11-19 14:55:58 -08006290 Mutex::Autolock _l(mLock);
6291 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006292 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006293 }
6294
Glenn Kastend8ea6992013-07-16 14:17:15 -07006295 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6296 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006297 free(s);
6298 return out_s8;
6299}
6300
Eric Laurent021cf962014-05-13 10:18:14 -07006301void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006302 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006303 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006304
6305 switch (event) {
6306 case AudioSystem::INPUT_OPENED:
6307 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006308 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006309 desc.samplingRate = mSampleRate;
6310 desc.format = mFormat;
6311 desc.frameCount = mFrameCount;
6312 desc.latency = 0;
6313 param2 = &desc;
6314 break;
6315
6316 case AudioSystem::INPUT_CLOSED:
6317 default:
6318 break;
6319 }
Eric Laurent021cf962014-05-13 10:18:14 -07006320 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006321}
6322
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006323void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006324{
Eric Laurent81784c32012-11-19 14:55:58 -08006325 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6326 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006327 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006328 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6329 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006330 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006331 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006332 }
Eric Laurent665470b2014-07-03 16:37:08 -07006333 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006334 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6335 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006336 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006337 // 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 -07006338 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006339 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006340 // A larger value should allow more old data to be read after a track calls start(),
6341 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006342 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006343 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006344 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006345
6346 // TODO optimize audio capture buffer sizes ...
6347 // Here we calculate the size of the sliding buffer used as a source
6348 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6349 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6350 // be better to have it derived from the pipe depth in the long term.
6351 // The current value is higher than necessary. However it should not add to latency.
6352
Glenn Kasten85948432013-08-19 12:09:05 -07006353 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6354 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006355
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006356 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6357 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006358}
6359
Glenn Kasten5f972c02014-01-13 09:59:31 -08006360uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006361{
6362 Mutex::Autolock _l(mLock);
6363 if (initCheck() != NO_ERROR) {
6364 return 0;
6365 }
6366
6367 return mInput->stream->get_input_frames_lost(mInput->stream);
6368}
6369
6370uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6371{
6372 Mutex::Autolock _l(mLock);
6373 uint32_t result = 0;
6374 if (getEffectChain_l(sessionId) != 0) {
6375 result = EFFECT_SESSION;
6376 }
6377
6378 for (size_t i = 0; i < mTracks.size(); ++i) {
6379 if (sessionId == mTracks[i]->sessionId()) {
6380 result |= TRACK_SESSION;
6381 break;
6382 }
6383 }
6384
6385 return result;
6386}
6387
6388KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6389{
6390 KeyedVector<int, bool> ids;
6391 Mutex::Autolock _l(mLock);
6392 for (size_t j = 0; j < mTracks.size(); ++j) {
6393 sp<RecordThread::RecordTrack> track = mTracks[j];
6394 int sessionId = track->sessionId();
6395 if (ids.indexOfKey(sessionId) < 0) {
6396 ids.add(sessionId, true);
6397 }
6398 }
6399 return ids;
6400}
6401
6402AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6403{
6404 Mutex::Autolock _l(mLock);
6405 AudioStreamIn *input = mInput;
6406 mInput = NULL;
6407 return input;
6408}
6409
6410// this method must always be called either with ThreadBase mLock held or inside the thread loop
6411audio_stream_t* AudioFlinger::RecordThread::stream() const
6412{
6413 if (mInput == NULL) {
6414 return NULL;
6415 }
6416 return &mInput->stream->common;
6417}
6418
6419status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6420{
6421 // only one chain per input thread
6422 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006423 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006424 return INVALID_OPERATION;
6425 }
6426 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006427 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006428 chain->setInBuffer(NULL);
6429 chain->setOutBuffer(NULL);
6430
6431 checkSuspendOnAddEffectChain_l(chain);
6432
Eric Laurent1b928682014-10-02 19:41:47 -07006433 // make sure enabled pre processing effects state is communicated to the HAL as we
6434 // just moved them to a new input stream.
6435 chain->syncHalEffectsState();
6436
Eric Laurent81784c32012-11-19 14:55:58 -08006437 mEffectChains.add(chain);
6438
6439 return NO_ERROR;
6440}
6441
6442size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6443{
6444 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6445 ALOGW_IF(mEffectChains.size() != 1,
6446 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6447 chain.get(), mEffectChains.size(), this);
6448 if (mEffectChains.size() == 1) {
6449 mEffectChains.removeAt(0);
6450 }
6451 return 0;
6452}
6453
Eric Laurent1c333e22014-05-20 10:48:17 -07006454status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6455 audio_patch_handle_t *handle)
6456{
6457 status_t status = NO_ERROR;
6458 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6459 // store new device and send to effects
6460 mInDevice = patch->sources[0].ext.device.type;
6461 for (size_t i = 0; i < mEffectChains.size(); i++) {
6462 mEffectChains[i]->setDevice_l(mInDevice);
6463 }
6464
6465 // disable AEC and NS if the device is a BT SCO headset supporting those
6466 // pre processings
6467 if (mTracks.size() > 0) {
6468 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6469 mAudioFlinger->btNrecIsOff();
6470 for (size_t i = 0; i < mTracks.size(); i++) {
6471 sp<RecordTrack> track = mTracks[i];
6472 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6473 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6474 }
6475 }
6476
6477 // store new source and send to effects
6478 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6479 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6480 for (size_t i = 0; i < mEffectChains.size(); i++) {
6481 mEffectChains[i]->setAudioSource_l(mAudioSource);
6482 }
6483 }
6484
6485 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6486 status = hwDevice->create_audio_patch(hwDevice,
6487 patch->num_sources,
6488 patch->sources,
6489 patch->num_sinks,
6490 patch->sinks,
6491 handle);
6492 } else {
6493 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6494 }
6495 return status;
6496}
6497
6498status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6499{
6500 status_t status = NO_ERROR;
6501 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6502 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6503 status = hwDevice->release_audio_patch(hwDevice, handle);
6504 } else {
6505 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6506 }
6507 return status;
6508}
6509
Eric Laurent83b88082014-06-20 18:31:16 -07006510void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6511{
6512 Mutex::Autolock _l(mLock);
6513 mTracks.add(record);
6514}
6515
6516void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6517{
6518 Mutex::Autolock _l(mLock);
6519 destroyTrack_l(record);
6520}
6521
6522void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6523{
6524 ThreadBase::getAudioPortConfig(config);
6525 config->role = AUDIO_PORT_ROLE_SINK;
6526 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6527 config->ext.mix.usecase.source = mAudioSource;
6528}
Eric Laurent1c333e22014-05-20 10:48:17 -07006529
Eric Laurent81784c32012-11-19 14:55:58 -08006530}; // namespace android