blob: 42251618a8c3f631fbab32d513408122713dfdeb [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070029#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070042#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043#include <media/nbaio/AudioStreamOutSink.h>
44#include <media/nbaio/MonoPipe.h>
45#include <media/nbaio/MonoPipeReader.h>
46#include <media/nbaio/Pipe.h>
47#include <media/nbaio/PipeReader.h>
48#include <media/nbaio/SourceAudioBufferProvider.h>
49
50#include <powermanager/PowerManager.h>
51
52#include <common_time/cc_helper.h>
53#include <common_time/local_clock.h>
54
55#include "AudioFlinger.h"
56#include "AudioMixer.h"
57#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "ServiceUtilities.h"
60#include "SchedulingPolicyService.h"
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef ADD_BATTERY_DATA
63#include <media/IMediaPlayerService.h>
64#include <media/IMediaDeathNotifier.h>
65#endif
66
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
71
72// ----------------------------------------------------------------------------
73
74// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
86
Glenn Kasten49d00ad2014-07-21 11:22:03 -070087#define max(a, b) ((a) > (b) ? (a) : (b))
88
Eric Laurent81784c32012-11-19 14:55:58 -080089namespace android {
90
91// retry counts for buffer fill timeout
92// 50 * ~20msecs = 1 second
93static const int8_t kMaxTrackRetries = 50;
94static const int8_t kMaxTrackStartupRetries = 50;
95// allow less retry attempts on direct output thread.
96// direct outputs can be a scarce resource in audio hardware and should
97// be released as quickly as possible.
98static const int8_t kMaxTrackRetriesDirect = 2;
99
100// don't warn about blocked writes or record buffer overflows more often than this
101static const nsecs_t kWarningThrottleNs = seconds(5);
102
103// RecordThread loop sleep time upon application overrun or audio HAL read error
104static const int kRecordThreadSleepUs = 5000;
105
Eric Laurent10351942014-05-08 18:49:52 -0700106// maximum time to wait in sendConfigEvent_l() for a status to be received
107static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109// minimum sleep time for the mixer thread loop when tracks are active but in underrun
110static const uint32_t kMinThreadSleepTimeUs = 5000;
111// maximum divider applied to the active sleep time in the mixer thread loop
112static const uint32_t kMaxThreadSleepTimeShift = 2;
113
Andy Hung09a50072014-02-27 14:30:47 -0800114// minimum normal sink buffer size, expressed in milliseconds rather than frames
115static const uint32_t kMinNormalSinkBufferSizeMs = 20;
116// maximum normal sink buffer size
117static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800118
Eric Laurent972a1732013-09-04 09:42:59 -0700119// Offloaded output thread standby delay: allows track transition without going to standby
120static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122// Whether to use fast mixer
123static const enum {
124 FastMixer_Never, // never initialize or use: for debugging only
125 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
126 // normal mixer multiplier is 1
127 FastMixer_Static, // initialize if needed, then use all the time if initialized,
128 // multiplier is calculated based on min & max normal mixer buffer size
129 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 // FIXME for FastMixer_Dynamic:
132 // Supporting this option will require fixing HALs that can't handle large writes.
133 // For example, one HAL implementation returns an error from a large write,
134 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
135 // We could either fix the HAL implementations, or provide a wrapper that breaks
136 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
137} kUseFastMixer = FastMixer_Static;
138
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139// Whether to use fast capture
140static const enum {
141 FastCapture_Never, // never initialize or use: for debugging only
142 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
143 FastCapture_Static, // initialize if needed, then use all the time if initialized
144} kUseFastCapture = FastCapture_Static;
145
Eric Laurent81784c32012-11-19 14:55:58 -0800146// Priorities for requestPriority
147static const int kPriorityAudioApp = 2;
148static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700149static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
152// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800153// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
154// So for now we just assume that client is double-buffered for fast tracks.
155// FIXME It would be better for client to tell AudioFlinger the value of N,
156// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800157// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700158
159// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800160static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
Glenn Kasten03490092014-05-27 12:30:54 -0700162// The minimum and maximum allowed values
163static const int kFastTrackMultiplierMin = 1;
164static const int kFastTrackMultiplierMax = 2;
165
166// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
167static int sFastTrackMultiplier = kFastTrackMultiplier;
168
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700169// See Thread::readOnlyHeap().
170// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
171// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
172// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700173static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700174
Andy Hungc25b84a2015-01-14 19:04:10 -0800175// Returns the source frames needed to resample to destination frames. This is not a precise
176// value and depends on the resampler (and possibly how it handles rounding internally).
177// If srcSampleRate and dstSampleRate are equal, then it returns destination frames, which
178// may not be a true if the resampler is asynchronous.
179static inline size_t sourceFramesNeeded(
180 uint32_t srcSampleRate, size_t dstFramesRequired, uint32_t dstSampleRate) {
181 // +1 for rounding - always do this even if matched ratio
182 // +1 for additional sample needed for interpolation
183 return srcSampleRate == dstSampleRate ? dstFramesRequired :
184 size_t((uint64_t)dstFramesRequired * srcSampleRate / dstSampleRate + 1 + 1);
185}
186
Eric Laurent81784c32012-11-19 14:55:58 -0800187// ----------------------------------------------------------------------------
188
Glenn Kasten03490092014-05-27 12:30:54 -0700189static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
190
191static void sFastTrackMultiplierInit()
192{
193 char value[PROPERTY_VALUE_MAX];
194 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
195 char *endptr;
196 unsigned long ul = strtoul(value, &endptr, 0);
197 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
198 sFastTrackMultiplier = (int) ul;
199 }
200 }
201}
202
203// ----------------------------------------------------------------------------
204
Eric Laurent81784c32012-11-19 14:55:58 -0800205#ifdef ADD_BATTERY_DATA
206// To collect the amplifier usage
207static void addBatteryData(uint32_t params) {
208 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
209 if (service == NULL) {
210 // it already logged
211 return;
212 }
213
214 service->addBatteryData(params);
215}
216#endif
217
218
219// ----------------------------------------------------------------------------
220// CPU Stats
221// ----------------------------------------------------------------------------
222
223class CpuStats {
224public:
225 CpuStats();
226 void sample(const String8 &title);
227#ifdef DEBUG_CPU_USAGE
228private:
229 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
230 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
231
232 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
233
234 int mCpuNum; // thread's current CPU number
235 int mCpukHz; // frequency of thread's current CPU in kHz
236#endif
237};
238
239CpuStats::CpuStats()
240#ifdef DEBUG_CPU_USAGE
241 : mCpuNum(-1), mCpukHz(-1)
242#endif
243{
244}
245
Glenn Kasten0f11b512014-01-31 16:18:54 -0800246void CpuStats::sample(const String8 &title
247#ifndef DEBUG_CPU_USAGE
248 __unused
249#endif
250 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800251#ifdef DEBUG_CPU_USAGE
252 // get current thread's delta CPU time in wall clock ns
253 double wcNs;
254 bool valid = mCpuUsage.sampleAndEnable(wcNs);
255
256 // record sample for wall clock statistics
257 if (valid) {
258 mWcStats.sample(wcNs);
259 }
260
261 // get the current CPU number
262 int cpuNum = sched_getcpu();
263
264 // get the current CPU frequency in kHz
265 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
266
267 // check if either CPU number or frequency changed
268 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
269 mCpuNum = cpuNum;
270 mCpukHz = cpukHz;
271 // ignore sample for purposes of cycles
272 valid = false;
273 }
274
275 // if no change in CPU number or frequency, then record sample for cycle statistics
276 if (valid && mCpukHz > 0) {
277 double cycles = wcNs * cpukHz * 0.000001;
278 mHzStats.sample(cycles);
279 }
280
281 unsigned n = mWcStats.n();
282 // mCpuUsage.elapsed() is expensive, so don't call it every loop
283 if ((n & 127) == 1) {
284 long long elapsed = mCpuUsage.elapsed();
285 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
286 double perLoop = elapsed / (double) n;
287 double perLoop100 = perLoop * 0.01;
288 double perLoop1k = perLoop * 0.001;
289 double mean = mWcStats.mean();
290 double stddev = mWcStats.stddev();
291 double minimum = mWcStats.minimum();
292 double maximum = mWcStats.maximum();
293 double meanCycles = mHzStats.mean();
294 double stddevCycles = mHzStats.stddev();
295 double minCycles = mHzStats.minimum();
296 double maxCycles = mHzStats.maximum();
297 mCpuUsage.resetElapsed();
298 mWcStats.reset();
299 mHzStats.reset();
300 ALOGD("CPU usage for %s over past %.1f secs\n"
301 " (%u mixer loops at %.1f mean ms per loop):\n"
302 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
303 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
304 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
305 title.string(),
306 elapsed * .000000001, n, perLoop * .000001,
307 mean * .001,
308 stddev * .001,
309 minimum * .001,
310 maximum * .001,
311 mean / perLoop100,
312 stddev / perLoop100,
313 minimum / perLoop100,
314 maximum / perLoop100,
315 meanCycles / perLoop1k,
316 stddevCycles / perLoop1k,
317 minCycles / perLoop1k,
318 maxCycles / perLoop1k);
319
320 }
321 }
322#endif
323};
324
325// ----------------------------------------------------------------------------
326// ThreadBase
327// ----------------------------------------------------------------------------
328
Glenn Kasten97b7b752014-09-28 13:04:24 -0700329// static
330const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
331{
332 switch (type) {
333 case MIXER:
334 return "MIXER";
335 case DIRECT:
336 return "DIRECT";
337 case DUPLICATING:
338 return "DUPLICATING";
339 case RECORD:
340 return "RECORD";
341 case OFFLOAD:
342 return "OFFLOAD";
343 default:
344 return "unknown";
345 }
346}
347
348static String8 outputFlagsToString(audio_output_flags_t flags)
349{
350 static const struct mapping {
351 audio_output_flags_t mFlag;
352 const char * mString;
353 } mappings[] = {
354 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
355 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
356 AUDIO_OUTPUT_FLAG_FAST, "FAST",
357 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
358 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAAD",
359 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
360 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
361 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
362 };
363 String8 result;
364 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
365 const mapping *entry;
366 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
367 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
368 if (flags & entry->mFlag) {
369 if (!result.isEmpty()) {
370 result.append("|");
371 }
372 result.append(entry->mString);
373 }
374 }
375 if (flags & ~allFlags) {
376 if (!result.isEmpty()) {
377 result.append("|");
378 }
379 result.appendFormat("0x%X", flags & ~allFlags);
380 }
381 if (result.isEmpty()) {
382 result.append(entry->mString);
383 }
384 return result;
385}
386
Eric Laurent81784c32012-11-19 14:55:58 -0800387AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
388 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
389 : Thread(false /*canCallJava*/),
390 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700391 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700392 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800393 // are set by PlaybackThread::readOutputParameters_l() or
394 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700395 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800396 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
397 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
398 // mName will be set by concrete (non-virtual) subclass
399 mDeathRecipient(new PMDeathRecipient(this))
400{
401}
402
403AudioFlinger::ThreadBase::~ThreadBase()
404{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700405 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700406 mConfigEvents.clear();
407
Eric Laurent81784c32012-11-19 14:55:58 -0800408 // do not lock the mutex in destructor
409 releaseWakeLock_l();
410 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800411 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800412 binder->unlinkToDeath(mDeathRecipient);
413 }
414}
415
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700416status_t AudioFlinger::ThreadBase::readyToRun()
417{
418 status_t status = initCheck();
419 if (status == NO_ERROR) {
420 ALOGI("AudioFlinger's thread %p ready to run", this);
421 } else {
422 ALOGE("No working audio driver found.");
423 }
424 return status;
425}
426
Eric Laurent81784c32012-11-19 14:55:58 -0800427void AudioFlinger::ThreadBase::exit()
428{
429 ALOGV("ThreadBase::exit");
430 // do any cleanup required for exit to succeed
431 preExit();
432 {
433 // This lock prevents the following race in thread (uniprocessor for illustration):
434 // if (!exitPending()) {
435 // // context switch from here to exit()
436 // // exit() calls requestExit(), what exitPending() observes
437 // // exit() calls signal(), which is dropped since no waiters
438 // // context switch back from exit() to here
439 // mWaitWorkCV.wait(...);
440 // // now thread is hung
441 // }
442 AutoMutex lock(mLock);
443 requestExit();
444 mWaitWorkCV.broadcast();
445 }
446 // When Thread::requestExitAndWait is made virtual and this method is renamed to
447 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
448 requestExitAndWait();
449}
450
451status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
452{
453 status_t status;
454
455 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
456 Mutex::Autolock _l(mLock);
457
Eric Laurent10351942014-05-08 18:49:52 -0700458 return sendSetParameterConfigEvent_l(keyValuePairs);
459}
460
461// sendConfigEvent_l() must be called with ThreadBase::mLock held
462// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
463status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
464{
465 status_t status = NO_ERROR;
466
467 mConfigEvents.add(event);
468 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700470 mLock.unlock();
471 {
472 Mutex::Autolock _l(event->mLock);
473 while (event->mWaitStatus) {
474 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
475 event->mStatus = TIMED_OUT;
476 event->mWaitStatus = false;
477 }
478 }
479 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800480 }
Eric Laurent10351942014-05-08 18:49:52 -0700481 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800482 return status;
483}
484
485void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
486{
487 Mutex::Autolock _l(mLock);
488 sendIoConfigEvent_l(event, param);
489}
490
491// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
492void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
493{
Eric Laurent10351942014-05-08 18:49:52 -0700494 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
495 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800496}
497
498// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
499void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
500{
Eric Laurent10351942014-05-08 18:49:52 -0700501 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
502 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800503}
504
Eric Laurent10351942014-05-08 18:49:52 -0700505// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
506status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800507{
Eric Laurent10351942014-05-08 18:49:52 -0700508 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
509 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700510}
511
Eric Laurent1c333e22014-05-20 10:48:17 -0700512status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
513 const struct audio_patch *patch,
514 audio_patch_handle_t *handle)
515{
516 Mutex::Autolock _l(mLock);
517 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
518 status_t status = sendConfigEvent_l(configEvent);
519 if (status == NO_ERROR) {
520 CreateAudioPatchConfigEventData *data =
521 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
522 *handle = data->mHandle;
523 }
524 return status;
525}
526
527status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
528 const audio_patch_handle_t handle)
529{
530 Mutex::Autolock _l(mLock);
531 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
532 return sendConfigEvent_l(configEvent);
533}
534
535
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700536// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700537void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700538{
Eric Laurent10351942014-05-08 18:49:52 -0700539 bool configChanged = false;
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700542 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
543 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800544 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700545 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700546 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700547 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
548 // FIXME Need to understand why this has to be done asynchronously
549 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700550 true /*asynchronous*/);
551 if (err != 0) {
552 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700553 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700554 }
555 } break;
556 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700557 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700558 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700559 } break;
560 case CFG_EVENT_SET_PARAMETER: {
561 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
562 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
563 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700564 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700565 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700566 case CFG_EVENT_CREATE_AUDIO_PATCH: {
567 CreateAudioPatchConfigEventData *data =
568 (CreateAudioPatchConfigEventData *)event->mData.get();
569 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
570 } break;
571 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
572 ReleaseAudioPatchConfigEventData *data =
573 (ReleaseAudioPatchConfigEventData *)event->mData.get();
574 event->mStatus = releaseAudioPatch_l(data->mHandle);
575 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700576 default:
Eric Laurent10351942014-05-08 18:49:52 -0700577 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700578 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800579 }
Eric Laurent10351942014-05-08 18:49:52 -0700580 {
581 Mutex::Autolock _l(event->mLock);
582 if (event->mWaitStatus) {
583 event->mWaitStatus = false;
584 event->mCond.signal();
585 }
586 }
587 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
588 }
589
590 if (configChanged) {
591 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800592 }
Eric Laurent81784c32012-11-19 14:55:58 -0800593}
594
Marco Nelissenb2208842014-02-07 14:00:50 -0800595String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
596 String8 s;
597 if (output) {
598 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
599 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
600 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
601 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
602 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
603 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
604 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
605 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
606 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
607 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
608 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
609 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
610 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
611 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
612 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
613 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
614 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
615 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
616 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
617 } else {
618 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
619 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
620 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
621 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
622 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
623 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
624 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
625 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
626 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
627 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
628 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
629 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
630 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
631 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
632 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
633 }
634 int len = s.length();
635 if (s.length() > 2) {
636 char *str = s.lockBuffer(len);
637 s.unlockBuffer(len - 2);
638 }
639 return s;
640}
641
Glenn Kasten0f11b512014-01-31 16:18:54 -0800642void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800643{
644 const size_t SIZE = 256;
645 char buffer[SIZE];
646 String8 result;
647
648 bool locked = AudioFlinger::dumpTryLock(mLock);
649 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700650 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800651 }
652
Elliott Hughes87cebad2014-05-22 10:14:43 -0700653 dprintf(fd, " I/O handle: %d\n", mId);
654 dprintf(fd, " TID: %d\n", getTid());
655 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700656 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700657 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700658 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700659 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700660 dprintf(fd, " Channel count: %u\n", mChannelCount);
661 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800662 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700663 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
664 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700665 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800666 size_t numConfig = mConfigEvents.size();
667 if (numConfig) {
668 for (size_t i = 0; i < numConfig; i++) {
669 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700670 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800671 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700672 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800673 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700674 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800675 }
Eric Laurent81784c32012-11-19 14:55:58 -0800676
677 if (locked) {
678 mLock.unlock();
679 }
680}
681
682void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
683{
684 const size_t SIZE = 256;
685 char buffer[SIZE];
686 String8 result;
687
Marco Nelissenb2208842014-02-07 14:00:50 -0800688 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000689 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800690 write(fd, buffer, strlen(buffer));
691
Marco Nelissenb2208842014-02-07 14:00:50 -0800692 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800693 sp<EffectChain> chain = mEffectChains[i];
694 if (chain != 0) {
695 chain->dump(fd, args);
696 }
697 }
698}
699
Marco Nelissene14a5d62013-10-03 08:51:24 -0700700void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
702 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700703 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800704}
705
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100706String16 AudioFlinger::ThreadBase::getWakeLockTag()
707{
708 switch (mType) {
709 case MIXER:
710 return String16("AudioMix");
711 case DIRECT:
712 return String16("AudioDirectOut");
713 case DUPLICATING:
714 return String16("AudioDup");
715 case RECORD:
716 return String16("AudioIn");
717 case OFFLOAD:
718 return String16("AudioOffload");
719 default:
720 ALOG_ASSERT(false);
721 return String16("AudioUnknown");
722 }
723}
724
Marco Nelissene14a5d62013-10-03 08:51:24 -0700725void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800726{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800727 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800728 if (mPowerManager != 0) {
729 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700730 status_t status;
731 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700732 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700733 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100734 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700735 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700736 uid,
737 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700738 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700739 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700740 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100741 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700742 String16("media"),
743 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700744 }
Eric Laurent81784c32012-11-19 14:55:58 -0800745 if (status == NO_ERROR) {
746 mWakeLockToken = binder;
747 }
748 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
749 }
750}
751
752void AudioFlinger::ThreadBase::releaseWakeLock()
753{
754 Mutex::Autolock _l(mLock);
755 releaseWakeLock_l();
756}
757
758void AudioFlinger::ThreadBase::releaseWakeLock_l()
759{
760 if (mWakeLockToken != 0) {
761 ALOGV("releaseWakeLock_l() %s", mName);
762 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700763 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
764 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800765 }
766 mWakeLockToken.clear();
767 }
768}
769
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800770void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
771 Mutex::Autolock _l(mLock);
772 updateWakeLockUids_l(uids);
773}
774
775void AudioFlinger::ThreadBase::getPowerManager_l() {
776
777 if (mPowerManager == 0) {
778 // use checkService() to avoid blocking if power service is not up yet
779 sp<IBinder> binder =
780 defaultServiceManager()->checkService(String16("power"));
781 if (binder == 0) {
782 ALOGW("Thread %s cannot connect to the power manager service", mName);
783 } else {
784 mPowerManager = interface_cast<IPowerManager>(binder);
785 binder->linkToDeath(mDeathRecipient);
786 }
787 }
788}
789
790void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
791
792 getPowerManager_l();
793 if (mWakeLockToken == NULL) {
794 ALOGE("no wake lock to update!");
795 return;
796 }
797 if (mPowerManager != 0) {
798 sp<IBinder> binder = new BBinder();
799 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700800 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
801 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800802 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
803 }
804}
805
Eric Laurent81784c32012-11-19 14:55:58 -0800806void AudioFlinger::ThreadBase::clearPowerManager()
807{
808 Mutex::Autolock _l(mLock);
809 releaseWakeLock_l();
810 mPowerManager.clear();
811}
812
Glenn Kasten0f11b512014-01-31 16:18:54 -0800813void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800814{
815 sp<ThreadBase> thread = mThread.promote();
816 if (thread != 0) {
817 thread->clearPowerManager();
818 }
819 ALOGW("power manager service died !!!");
820}
821
822void AudioFlinger::ThreadBase::setEffectSuspended(
823 const effect_uuid_t *type, bool suspend, int sessionId)
824{
825 Mutex::Autolock _l(mLock);
826 setEffectSuspended_l(type, suspend, sessionId);
827}
828
829void AudioFlinger::ThreadBase::setEffectSuspended_l(
830 const effect_uuid_t *type, bool suspend, int sessionId)
831{
832 sp<EffectChain> chain = getEffectChain_l(sessionId);
833 if (chain != 0) {
834 if (type != NULL) {
835 chain->setEffectSuspended_l(type, suspend);
836 } else {
837 chain->setEffectSuspendedAll_l(suspend);
838 }
839 }
840
841 updateSuspendedSessions_l(type, suspend, sessionId);
842}
843
844void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
845{
846 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
847 if (index < 0) {
848 return;
849 }
850
851 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
852 mSuspendedSessions.valueAt(index);
853
854 for (size_t i = 0; i < sessionEffects.size(); i++) {
855 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
856 for (int j = 0; j < desc->mRefCount; j++) {
857 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
858 chain->setEffectSuspendedAll_l(true);
859 } else {
860 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
861 desc->mType.timeLow);
862 chain->setEffectSuspended_l(&desc->mType, true);
863 }
864 }
865 }
866}
867
868void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
869 bool suspend,
870 int sessionId)
871{
872 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
873
874 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
875
876 if (suspend) {
877 if (index >= 0) {
878 sessionEffects = mSuspendedSessions.valueAt(index);
879 } else {
880 mSuspendedSessions.add(sessionId, sessionEffects);
881 }
882 } else {
883 if (index < 0) {
884 return;
885 }
886 sessionEffects = mSuspendedSessions.valueAt(index);
887 }
888
889
890 int key = EffectChain::kKeyForSuspendAll;
891 if (type != NULL) {
892 key = type->timeLow;
893 }
894 index = sessionEffects.indexOfKey(key);
895
896 sp<SuspendedSessionDesc> desc;
897 if (suspend) {
898 if (index >= 0) {
899 desc = sessionEffects.valueAt(index);
900 } else {
901 desc = new SuspendedSessionDesc();
902 if (type != NULL) {
903 desc->mType = *type;
904 }
905 sessionEffects.add(key, desc);
906 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
907 }
908 desc->mRefCount++;
909 } else {
910 if (index < 0) {
911 return;
912 }
913 desc = sessionEffects.valueAt(index);
914 if (--desc->mRefCount == 0) {
915 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
916 sessionEffects.removeItemsAt(index);
917 if (sessionEffects.isEmpty()) {
918 ALOGV("updateSuspendedSessions_l() restore removing session %d",
919 sessionId);
920 mSuspendedSessions.removeItem(sessionId);
921 }
922 }
923 }
924 if (!sessionEffects.isEmpty()) {
925 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
926 }
927}
928
929void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
930 bool enabled,
931 int sessionId)
932{
933 Mutex::Autolock _l(mLock);
934 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
935}
936
937void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
938 bool enabled,
939 int sessionId)
940{
941 if (mType != RECORD) {
942 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
943 // another session. This gives the priority to well behaved effect control panels
944 // and applications not using global effects.
945 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
946 // global effects
947 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
948 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
949 }
950 }
951
952 sp<EffectChain> chain = getEffectChain_l(sessionId);
953 if (chain != 0) {
954 chain->checkSuspendOnEffectEnabled(effect, enabled);
955 }
956}
957
958// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
959sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
960 const sp<AudioFlinger::Client>& client,
961 const sp<IEffectClient>& effectClient,
962 int32_t priority,
963 int sessionId,
964 effect_descriptor_t *desc,
965 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700966 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800967{
968 sp<EffectModule> effect;
969 sp<EffectHandle> handle;
970 status_t lStatus;
971 sp<EffectChain> chain;
972 bool chainCreated = false;
973 bool effectCreated = false;
974 bool effectRegistered = false;
975
976 lStatus = initCheck();
977 if (lStatus != NO_ERROR) {
978 ALOGW("createEffect_l() Audio driver not initialized.");
979 goto Exit;
980 }
981
Andy Hung98ef9782014-03-04 14:46:50 -0800982 // Reject any effect on Direct output threads for now, since the format of
983 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
984 if (mType == DIRECT) {
985 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
986 desc->name, mName);
987 lStatus = BAD_VALUE;
988 goto Exit;
989 }
990
Andy Hung389cfdb2014-08-07 17:49:53 -0700991 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700992 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700993 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
994 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
995 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700996 lStatus = BAD_VALUE;
997 goto Exit;
998 }
999
Eric Laurent5baf2af2013-09-12 17:37:00 -07001000 // Allow global effects only on offloaded and mixer threads
1001 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1002 switch (mType) {
1003 case MIXER:
1004 case OFFLOAD:
1005 break;
1006 case DIRECT:
1007 case DUPLICATING:
1008 case RECORD:
1009 default:
1010 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
1011 lStatus = BAD_VALUE;
1012 goto Exit;
1013 }
Eric Laurent81784c32012-11-19 14:55:58 -08001014 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001015
Eric Laurent81784c32012-11-19 14:55:58 -08001016 // Only Pre processor effects are allowed on input threads and only on input threads
1017 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1018 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1019 desc->name, desc->flags, mType);
1020 lStatus = BAD_VALUE;
1021 goto Exit;
1022 }
1023
1024 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1025
1026 { // scope for mLock
1027 Mutex::Autolock _l(mLock);
1028
1029 // check for existing effect chain with the requested audio session
1030 chain = getEffectChain_l(sessionId);
1031 if (chain == 0) {
1032 // create a new chain for this session
1033 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1034 chain = new EffectChain(this, sessionId);
1035 addEffectChain_l(chain);
1036 chain->setStrategy(getStrategyForSession_l(sessionId));
1037 chainCreated = true;
1038 } else {
1039 effect = chain->getEffectFromDesc_l(desc);
1040 }
1041
1042 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1043
1044 if (effect == 0) {
1045 int id = mAudioFlinger->nextUniqueId();
1046 // Check CPU and memory usage
1047 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1048 if (lStatus != NO_ERROR) {
1049 goto Exit;
1050 }
1051 effectRegistered = true;
1052 // create a new effect module if none present in the chain
1053 effect = new EffectModule(this, chain, desc, id, sessionId);
1054 lStatus = effect->status();
1055 if (lStatus != NO_ERROR) {
1056 goto Exit;
1057 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001058 effect->setOffloaded(mType == OFFLOAD, mId);
1059
Eric Laurent81784c32012-11-19 14:55:58 -08001060 lStatus = chain->addEffect_l(effect);
1061 if (lStatus != NO_ERROR) {
1062 goto Exit;
1063 }
1064 effectCreated = true;
1065
1066 effect->setDevice(mOutDevice);
1067 effect->setDevice(mInDevice);
1068 effect->setMode(mAudioFlinger->getMode());
1069 effect->setAudioSource(mAudioSource);
1070 }
1071 // create effect handle and connect it to effect module
1072 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001073 lStatus = handle->initCheck();
1074 if (lStatus == OK) {
1075 lStatus = effect->addHandle(handle.get());
1076 }
Eric Laurent81784c32012-11-19 14:55:58 -08001077 if (enabled != NULL) {
1078 *enabled = (int)effect->isEnabled();
1079 }
1080 }
1081
1082Exit:
1083 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1084 Mutex::Autolock _l(mLock);
1085 if (effectCreated) {
1086 chain->removeEffect_l(effect);
1087 }
1088 if (effectRegistered) {
1089 AudioSystem::unregisterEffect(effect->id());
1090 }
1091 if (chainCreated) {
1092 removeEffectChain_l(chain);
1093 }
1094 handle.clear();
1095 }
1096
Glenn Kasten9156ef32013-08-06 15:39:08 -07001097 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001098 return handle;
1099}
1100
1101sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1102{
1103 Mutex::Autolock _l(mLock);
1104 return getEffect_l(sessionId, effectId);
1105}
1106
1107sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1108{
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1111}
1112
1113// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1114// PlaybackThread::mLock held
1115status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1116{
1117 // check for existing effect chain with the requested audio session
1118 int sessionId = effect->sessionId();
1119 sp<EffectChain> chain = getEffectChain_l(sessionId);
1120 bool chainCreated = false;
1121
Eric Laurent5baf2af2013-09-12 17:37:00 -07001122 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1123 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1124 this, effect->desc().name, effect->desc().flags);
1125
Eric Laurent81784c32012-11-19 14:55:58 -08001126 if (chain == 0) {
1127 // create a new chain for this session
1128 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1129 chain = new EffectChain(this, sessionId);
1130 addEffectChain_l(chain);
1131 chain->setStrategy(getStrategyForSession_l(sessionId));
1132 chainCreated = true;
1133 }
1134 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1135
1136 if (chain->getEffectFromId_l(effect->id()) != 0) {
1137 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1138 this, effect->desc().name, chain.get());
1139 return BAD_VALUE;
1140 }
1141
Eric Laurent5baf2af2013-09-12 17:37:00 -07001142 effect->setOffloaded(mType == OFFLOAD, mId);
1143
Eric Laurent81784c32012-11-19 14:55:58 -08001144 status_t status = chain->addEffect_l(effect);
1145 if (status != NO_ERROR) {
1146 if (chainCreated) {
1147 removeEffectChain_l(chain);
1148 }
1149 return status;
1150 }
1151
1152 effect->setDevice(mOutDevice);
1153 effect->setDevice(mInDevice);
1154 effect->setMode(mAudioFlinger->getMode());
1155 effect->setAudioSource(mAudioSource);
1156 return NO_ERROR;
1157}
1158
1159void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1160
1161 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1162 effect_descriptor_t desc = effect->desc();
1163 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1164 detachAuxEffect_l(effect->id());
1165 }
1166
1167 sp<EffectChain> chain = effect->chain().promote();
1168 if (chain != 0) {
1169 // remove effect chain if removing last effect
1170 if (chain->removeEffect_l(effect) == 0) {
1171 removeEffectChain_l(chain);
1172 }
1173 } else {
1174 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1175 }
1176}
1177
1178void AudioFlinger::ThreadBase::lockEffectChains_l(
1179 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1180{
1181 effectChains = mEffectChains;
1182 for (size_t i = 0; i < mEffectChains.size(); i++) {
1183 mEffectChains[i]->lock();
1184 }
1185}
1186
1187void AudioFlinger::ThreadBase::unlockEffectChains(
1188 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1189{
1190 for (size_t i = 0; i < effectChains.size(); i++) {
1191 effectChains[i]->unlock();
1192 }
1193}
1194
1195sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1196{
1197 Mutex::Autolock _l(mLock);
1198 return getEffectChain_l(sessionId);
1199}
1200
1201sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1202{
1203 size_t size = mEffectChains.size();
1204 for (size_t i = 0; i < size; i++) {
1205 if (mEffectChains[i]->sessionId() == sessionId) {
1206 return mEffectChains[i];
1207 }
1208 }
1209 return 0;
1210}
1211
1212void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1213{
1214 Mutex::Autolock _l(mLock);
1215 size_t size = mEffectChains.size();
1216 for (size_t i = 0; i < size; i++) {
1217 mEffectChains[i]->setMode_l(mode);
1218 }
1219}
1220
Eric Laurent83b88082014-06-20 18:31:16 -07001221void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1222{
1223 config->type = AUDIO_PORT_TYPE_MIX;
1224 config->ext.mix.handle = mId;
1225 config->sample_rate = mSampleRate;
1226 config->format = mFormat;
1227 config->channel_mask = mChannelMask;
1228 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1229 AUDIO_PORT_CONFIG_FORMAT;
1230}
1231
1232
Eric Laurent81784c32012-11-19 14:55:58 -08001233// ----------------------------------------------------------------------------
1234// Playback
1235// ----------------------------------------------------------------------------
1236
1237AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1238 AudioStreamOut* output,
1239 audio_io_handle_t id,
1240 audio_devices_t device,
1241 type_t type)
1242 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001243 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001244 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001245 mMixerBuffer(NULL),
1246 mMixerBufferSize(0),
1247 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1248 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001249 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001250 mEffectBuffer(NULL),
1251 mEffectBufferSize(0),
1252 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1253 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001254 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001255 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001256 // mStreamTypes[] initialized in constructor body
1257 mOutput(output),
1258 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1259 mMixerStatus(MIXER_IDLE),
1260 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1261 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001262 mBytesRemaining(0),
1263 mCurrentWriteLength(0),
1264 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001265 mWriteAckSequence(0),
1266 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001267 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001268 mScreenState(AudioFlinger::mScreenState),
1269 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001270 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001271 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001272 // mLatchD, mLatchQ,
1273 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001274{
1275 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001276 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001277
1278 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1279 // it would be safer to explicitly pass initial masterVolume/masterMute as
1280 // parameter.
1281 //
1282 // If the HAL we are using has support for master volume or master mute,
1283 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1284 // and the mute set to false).
1285 mMasterVolume = audioFlinger->masterVolume_l();
1286 mMasterMute = audioFlinger->masterMute_l();
1287 if (mOutput && mOutput->audioHwDev) {
1288 if (mOutput->audioHwDev->canSetMasterVolume()) {
1289 mMasterVolume = 1.0;
1290 }
1291
1292 if (mOutput->audioHwDev->canSetMasterMute()) {
1293 mMasterMute = false;
1294 }
1295 }
1296
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001297 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001298
Eric Laurent223fd5c2014-11-11 13:43:36 -08001299 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001300 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001301 stream = (audio_stream_type_t) (stream + 1)) {
1302 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1303 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1304 }
Eric Laurent81784c32012-11-19 14:55:58 -08001305}
1306
1307AudioFlinger::PlaybackThread::~PlaybackThread()
1308{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001309 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001310 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001311 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001312 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001313}
1314
1315void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1316{
1317 dumpInternals(fd, args);
1318 dumpTracks(fd, args);
1319 dumpEffectChains(fd, args);
1320}
1321
Glenn Kasten0f11b512014-01-31 16:18:54 -08001322void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001323{
1324 const size_t SIZE = 256;
1325 char buffer[SIZE];
1326 String8 result;
1327
Marco Nelissenb2208842014-02-07 14:00:50 -08001328 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001329 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1330 const stream_type_t *st = &mStreamTypes[i];
1331 if (i > 0) {
1332 result.appendFormat(", ");
1333 }
1334 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1335 if (st->mute) {
1336 result.append("M");
1337 }
1338 }
1339 result.append("\n");
1340 write(fd, result.string(), result.length());
1341 result.clear();
1342
Eric Laurent81784c32012-11-19 14:55:58 -08001343 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1344 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001345 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001346 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001347
1348 size_t numtracks = mTracks.size();
1349 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001350 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001351 size_t numactiveseen = 0;
1352 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001353 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001354 Track::appendDumpHeader(result);
1355 for (size_t i = 0; i < numtracks; ++i) {
1356 sp<Track> track = mTracks[i];
1357 if (track != 0) {
1358 bool active = mActiveTracks.indexOf(track) >= 0;
1359 if (active) {
1360 numactiveseen++;
1361 }
1362 track->dump(buffer, SIZE, active);
1363 result.append(buffer);
1364 }
1365 }
1366 } else {
1367 result.append("\n");
1368 }
1369 if (numactiveseen != numactive) {
1370 // some tracks in the active list were not in the tracks list
1371 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1372 " not in the track list\n");
1373 result.append(buffer);
1374 Track::appendDumpHeader(result);
1375 for (size_t i = 0; i < numactive; ++i) {
1376 sp<Track> track = mActiveTracks[i].promote();
1377 if (track != 0 && mTracks.indexOf(track) < 0) {
1378 track->dump(buffer, SIZE, true);
1379 result.append(buffer);
1380 }
1381 }
1382 }
1383
1384 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001385}
1386
1387void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1388{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001389 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001390 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1391 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1392 dprintf(fd, " Total writes: %d\n", mNumWrites);
1393 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1394 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1395 dprintf(fd, " Suspend count: %d\n", mSuspended);
1396 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1397 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1398 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1399 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001400 AudioStreamOut *output = mOutput;
1401 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1402 String8 flagsAsString = outputFlagsToString(flags);
1403 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001404
1405 dumpBase(fd, args);
1406}
1407
1408// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001409
1410void AudioFlinger::PlaybackThread::onFirstRef()
1411{
1412 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1413}
1414
1415// ThreadBase virtuals
1416void AudioFlinger::PlaybackThread::preExit()
1417{
1418 ALOGV(" preExit()");
1419 // FIXME this is using hard-coded strings but in the future, this functionality will be
1420 // converted to use audio HAL extensions required to support tunneling
1421 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1422}
1423
1424// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1425sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1426 const sp<AudioFlinger::Client>& client,
1427 audio_stream_type_t streamType,
1428 uint32_t sampleRate,
1429 audio_format_t format,
1430 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001431 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001432 const sp<IMemory>& sharedBuffer,
1433 int sessionId,
1434 IAudioFlinger::track_flags_t *flags,
1435 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001436 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001437 status_t *status)
1438{
Glenn Kasten74935e42013-12-19 08:56:45 -08001439 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001440 sp<Track> track;
1441 status_t lStatus;
1442
1443 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1444
1445 // client expresses a preference for FAST, but we get the final say
1446 if (*flags & IAudioFlinger::TRACK_FAST) {
1447 if (
1448 // not timed
1449 (!isTimed) &&
1450 // either of these use cases:
1451 (
1452 // use case 1: shared buffer with any frame count
1453 (
1454 (sharedBuffer != 0)
1455 ) ||
1456 // use case 2: callback handler and frame count is default or at least as large as HAL
1457 (
1458 (tid != -1) &&
1459 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001460 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001461 )
1462 ) &&
1463 // PCM data
1464 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001465 // identical channel mask to sink, or mono in and stereo sink
1466 (channelMask == mChannelMask ||
1467 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1468 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001469 // hardware sample rate
1470 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001471 // normal mixer has an associated fast mixer
1472 hasFastMixer() &&
1473 // there are sufficient fast track slots available
1474 (mFastTrackAvailMask != 0)
1475 // FIXME test that MixerThread for this fast track has a capable output HAL
1476 // FIXME add a permission test also?
1477 ) {
1478 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1479 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001480 // read the fast track multiplier property the first time it is needed
1481 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1482 if (ok != 0) {
1483 ALOGE("%s pthread_once failed: %d", __func__, ok);
1484 }
1485 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001486 }
1487 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1488 frameCount, mFrameCount);
1489 } else {
1490 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001491 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1492 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001493 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001494 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001495 audio_is_linear_pcm(format),
1496 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1497 *flags &= ~IAudioFlinger::TRACK_FAST;
1498 // For compatibility with AudioTrack calculation, buffer depth is forced
1499 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1500 // This is probably too conservative, but legacy application code may depend on it.
1501 // If you change this calculation, also review the start threshold which is related.
1502 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1503 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1504 if (minBufCount < 2) {
1505 minBufCount = 2;
1506 }
1507 size_t minFrameCount = mNormalFrameCount * minBufCount;
1508 if (frameCount < minFrameCount) {
1509 frameCount = minFrameCount;
1510 }
1511 }
1512 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001513 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001514
Glenn Kastenc3df8382014-03-13 15:05:25 -07001515 switch (mType) {
1516
1517 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001518 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001519 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001520 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1521 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001522 sampleRate, format, channelMask, mOutput, mFormat);
1523 lStatus = BAD_VALUE;
1524 goto Exit;
1525 }
1526 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001527 break;
1528
1529 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001530 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001531 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1532 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001533 sampleRate, format, channelMask, mOutput, mFormat);
1534 lStatus = BAD_VALUE;
1535 goto Exit;
1536 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001537 break;
1538
1539 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001540 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001541 ALOGE("createTrack_l() Bad parameter: format %#x \""
1542 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001543 format, mOutput, mFormat);
1544 lStatus = BAD_VALUE;
1545 goto Exit;
1546 }
Andy Hungcd044842014-08-07 11:04:34 -07001547 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001548 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1549 lStatus = BAD_VALUE;
1550 goto Exit;
1551 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001552 break;
1553
Eric Laurent81784c32012-11-19 14:55:58 -08001554 }
1555
1556 lStatus = initCheck();
1557 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001558 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001559 goto Exit;
1560 }
1561
1562 { // scope for mLock
1563 Mutex::Autolock _l(mLock);
1564
1565 // all tracks in same audio session must share the same routing strategy otherwise
1566 // conflicts will happen when tracks are moved from one output to another by audio policy
1567 // manager
1568 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1569 for (size_t i = 0; i < mTracks.size(); ++i) {
1570 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001571 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001572 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1573 if (sessionId == t->sessionId() && strategy != actual) {
1574 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1575 strategy, actual);
1576 lStatus = BAD_VALUE;
1577 goto Exit;
1578 }
1579 }
1580 }
1581
1582 if (!isTimed) {
1583 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001584 channelMask, frameCount, NULL, sharedBuffer,
1585 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001586 } else {
1587 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001588 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001589 }
Glenn Kasten03003332013-08-06 15:40:54 -07001590
1591 // new Track always returns non-NULL,
1592 // but TimedTrack::create() is a factory that could fail by returning NULL
1593 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1594 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001595 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001596 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001597 goto Exit;
1598 }
1599 mTracks.add(track);
1600
1601 sp<EffectChain> chain = getEffectChain_l(sessionId);
1602 if (chain != 0) {
1603 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1604 track->setMainBuffer(chain->inBuffer());
1605 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1606 chain->incTrackCnt();
1607 }
1608
1609 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1610 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1611 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1612 // so ask activity manager to do this on our behalf
1613 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1614 }
1615 }
1616
1617 lStatus = NO_ERROR;
1618
1619Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001620 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001621 return track;
1622}
1623
1624uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1625{
1626 return latency;
1627}
1628
1629uint32_t AudioFlinger::PlaybackThread::latency() const
1630{
1631 Mutex::Autolock _l(mLock);
1632 return latency_l();
1633}
1634uint32_t AudioFlinger::PlaybackThread::latency_l() const
1635{
1636 if (initCheck() == NO_ERROR) {
1637 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1638 } else {
1639 return 0;
1640 }
1641}
1642
1643void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1644{
1645 Mutex::Autolock _l(mLock);
1646 // Don't apply master volume in SW if our HAL can do it for us.
1647 if (mOutput && mOutput->audioHwDev &&
1648 mOutput->audioHwDev->canSetMasterVolume()) {
1649 mMasterVolume = 1.0;
1650 } else {
1651 mMasterVolume = value;
1652 }
1653}
1654
1655void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1656{
1657 Mutex::Autolock _l(mLock);
1658 // Don't apply master mute in SW if our HAL can do it for us.
1659 if (mOutput && mOutput->audioHwDev &&
1660 mOutput->audioHwDev->canSetMasterMute()) {
1661 mMasterMute = false;
1662 } else {
1663 mMasterMute = muted;
1664 }
1665}
1666
1667void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1668{
1669 Mutex::Autolock _l(mLock);
1670 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001671 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001672}
1673
1674void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1675{
1676 Mutex::Autolock _l(mLock);
1677 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001678 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001679}
1680
1681float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1682{
1683 Mutex::Autolock _l(mLock);
1684 return mStreamTypes[stream].volume;
1685}
1686
1687// addTrack_l() must be called with ThreadBase::mLock held
1688status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1689{
1690 status_t status = ALREADY_EXISTS;
1691
1692 // set retry count for buffer fill
1693 track->mRetryCount = kMaxTrackStartupRetries;
1694 if (mActiveTracks.indexOf(track) < 0) {
1695 // the track is newly added, make sure it fills up all its
1696 // buffers before playing. This is to ensure the client will
1697 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001698 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001699 TrackBase::track_state state = track->mState;
1700 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001701 status = AudioSystem::startOutput(mId, track->streamType(),
1702 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001703 mLock.lock();
1704 // abort track was stopped/paused while we released the lock
1705 if (state != track->mState) {
1706 if (status == NO_ERROR) {
1707 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001708 AudioSystem::stopOutput(mId, track->streamType(),
1709 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001710 mLock.lock();
1711 }
1712 return INVALID_OPERATION;
1713 }
1714 // abort if start is rejected by audio policy manager
1715 if (status != NO_ERROR) {
1716 return PERMISSION_DENIED;
1717 }
1718#ifdef ADD_BATTERY_DATA
1719 // to track the speaker usage
1720 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1721#endif
1722 }
1723
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001724 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001725 track->mResetDone = false;
1726 track->mPresentationCompleteFrames = 0;
1727 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001728 mWakeLockUids.add(track->uid());
1729 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001730 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001731 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1732 if (chain != 0) {
1733 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1734 track->sessionId());
1735 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001736 }
1737
1738 status = NO_ERROR;
1739 }
1740
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001741 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001742 return status;
1743}
1744
Eric Laurentbfb1b832013-01-07 09:53:42 -08001745bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001746{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001748 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001749 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1750 track->mState = TrackBase::STOPPED;
1751 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001752 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001753 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001754 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001755 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756
1757 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001758}
1759
1760void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1761{
1762 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1763 mTracks.remove(track);
1764 deleteTrackName_l(track->name());
1765 // redundant as track is about to be destroyed, for dumpsys only
1766 track->mName = -1;
1767 if (track->isFastTrack()) {
1768 int index = track->mFastIndex;
1769 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1770 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1771 mFastTrackAvailMask |= 1 << index;
1772 // redundant as track is about to be destroyed, for dumpsys only
1773 track->mFastIndex = -1;
1774 }
1775 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1776 if (chain != 0) {
1777 chain->decTrackCnt();
1778 }
1779}
1780
Eric Laurentede6c3b2013-09-19 14:37:46 -07001781void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782{
1783 // Thread could be blocked waiting for async
1784 // so signal it to handle state changes immediately
1785 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1786 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1787 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001788 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001789}
1790
Eric Laurent81784c32012-11-19 14:55:58 -08001791String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1792{
Eric Laurent81784c32012-11-19 14:55:58 -08001793 Mutex::Autolock _l(mLock);
1794 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001795 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001796 }
1797
Glenn Kastend8ea6992013-07-16 14:17:15 -07001798 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1799 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001800 free(s);
1801 return out_s8;
1802}
1803
Eric Laurent021cf962014-05-13 10:18:14 -07001804void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001805 AudioSystem::OutputDescriptor desc;
1806 void *param2 = NULL;
1807
Eric Laurent021cf962014-05-13 10:18:14 -07001808 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001809 param);
1810
1811 switch (event) {
1812 case AudioSystem::OUTPUT_OPENED:
1813 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001814 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001815 desc.samplingRate = mSampleRate;
1816 desc.format = mFormat;
1817 desc.frameCount = mNormalFrameCount; // FIXME see
1818 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001819 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001820 param2 = &desc;
1821 break;
1822
1823 case AudioSystem::STREAM_CONFIG_CHANGED:
1824 param2 = &param;
1825 case AudioSystem::OUTPUT_CLOSED:
1826 default:
1827 break;
1828 }
Eric Laurent021cf962014-05-13 10:18:14 -07001829 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001830}
1831
Eric Laurentbfb1b832013-01-07 09:53:42 -08001832void AudioFlinger::PlaybackThread::writeCallback()
1833{
1834 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001835 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001836}
1837
1838void AudioFlinger::PlaybackThread::drainCallback()
1839{
1840 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001841 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001842}
1843
Eric Laurent3b4529e2013-09-05 18:09:19 -07001844void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845{
1846 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001847 // reject out of sequence requests
1848 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1849 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850 mWaitWorkCV.signal();
1851 }
1852}
1853
Eric Laurent3b4529e2013-09-05 18:09:19 -07001854void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855{
1856 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001857 // reject out of sequence requests
1858 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1859 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001860 mWaitWorkCV.signal();
1861 }
1862}
1863
1864// static
1865int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001866 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867 void *cookie)
1868{
1869 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1870 ALOGV("asyncCallback() event %d", event);
1871 switch (event) {
1872 case STREAM_CBK_EVENT_WRITE_READY:
1873 me->writeCallback();
1874 break;
1875 case STREAM_CBK_EVENT_DRAIN_READY:
1876 me->drainCallback();
1877 break;
1878 default:
1879 ALOGW("asyncCallback() unknown event %d", event);
1880 break;
1881 }
1882 return 0;
1883}
1884
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001885void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001886{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001887 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001888 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1889 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001890 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001891 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001892 }
Andy Hung9a592762014-07-21 21:56:01 -07001893 if ((mType == MIXER || mType == DUPLICATING)
1894 && !isValidPcmSinkChannelMask(mChannelMask)) {
1895 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1896 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001897 }
Andy Hunge5412692014-05-16 11:25:07 -07001898 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001899 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1900 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001901 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001902 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001903 }
Andy Hung6146c082014-03-18 11:56:15 -07001904 if ((mType == MIXER || mType == DUPLICATING)
1905 && !isValidPcmSinkFormat(mFormat)) {
1906 LOG_FATAL("HAL format %#x not supported for mixed output",
1907 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001908 }
Eric Laurent665470b2014-07-03 16:37:08 -07001909 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001910 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1911 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001912 if (mFrameCount & 15) {
1913 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1914 mFrameCount);
1915 }
1916
Eric Laurentbfb1b832013-01-07 09:53:42 -08001917 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1918 (mOutput->stream->set_callback != NULL)) {
1919 if (mOutput->stream->set_callback(mOutput->stream,
1920 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1921 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001922 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001923 }
1924 }
1925
Eric Laurentd1f69b02014-12-15 14:33:13 -08001926 mHwSupportsPause = false;
1927 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1928 if (mOutput->stream->pause != NULL) {
1929 if (mOutput->stream->resume != NULL) {
1930 mHwSupportsPause = true;
1931 } else {
1932 ALOGW("direct output implements pause but not resume");
1933 }
1934 } else if (mOutput->stream->resume != NULL) {
1935 ALOGW("direct output implements resume but not pause");
1936 }
1937 }
1938
Andy Hung09a50072014-02-27 14:30:47 -08001939 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001940 double multiplier = 1.0;
1941 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1942 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001943 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1944 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001945 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1946 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1947 maxNormalFrameCount = maxNormalFrameCount & ~15;
1948 if (maxNormalFrameCount < minNormalFrameCount) {
1949 maxNormalFrameCount = minNormalFrameCount;
1950 }
1951 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1952 if (multiplier <= 1.0) {
1953 multiplier = 1.0;
1954 } else if (multiplier <= 2.0) {
1955 if (2 * mFrameCount <= maxNormalFrameCount) {
1956 multiplier = 2.0;
1957 } else {
1958 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1959 }
1960 } else {
1961 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001962 // 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 -08001963 // track, but we sometimes have to do this to satisfy the maximum frame count
1964 // constraint)
1965 // FIXME this rounding up should not be done if no HAL SRC
1966 uint32_t truncMult = (uint32_t) multiplier;
1967 if ((truncMult & 1)) {
1968 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1969 ++truncMult;
1970 }
1971 }
1972 multiplier = (double) truncMult;
1973 }
1974 }
1975 mNormalFrameCount = multiplier * mFrameCount;
1976 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001977 if (mType == MIXER || mType == DUPLICATING) {
1978 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1979 }
Andy Hung09a50072014-02-27 14:30:47 -08001980 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001981 mNormalFrameCount);
1982
Andy Hung010a1a12014-03-13 13:57:33 -07001983 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1984 // Originally this was int16_t[] array, need to remove legacy implications.
1985 free(mSinkBuffer);
1986 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001987 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1988 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1989 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001990 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001991
Andy Hung69aed5f2014-02-25 17:24:40 -08001992 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1993 // drives the output.
1994 free(mMixerBuffer);
1995 mMixerBuffer = NULL;
1996 if (mMixerBufferEnabled) {
1997 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1998 mMixerBufferSize = mNormalFrameCount * mChannelCount
1999 * audio_bytes_per_sample(mMixerBufferFormat);
2000 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2001 }
Andy Hung98ef9782014-03-04 14:46:50 -08002002 free(mEffectBuffer);
2003 mEffectBuffer = NULL;
2004 if (mEffectBufferEnabled) {
2005 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2006 mEffectBufferSize = mNormalFrameCount * mChannelCount
2007 * audio_bytes_per_sample(mEffectBufferFormat);
2008 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2009 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002010
Eric Laurent81784c32012-11-19 14:55:58 -08002011 // force reconfiguration of effect chains and engines to take new buffer size and audio
2012 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002013 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002014 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2015 // matter.
2016 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2017 Vector< sp<EffectChain> > effectChains = mEffectChains;
2018 for (size_t i = 0; i < effectChains.size(); i ++) {
2019 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2020 }
2021}
2022
2023
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002024status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002025{
2026 if (halFrames == NULL || dspFrames == NULL) {
2027 return BAD_VALUE;
2028 }
2029 Mutex::Autolock _l(mLock);
2030 if (initCheck() != NO_ERROR) {
2031 return INVALID_OPERATION;
2032 }
2033 size_t framesWritten = mBytesWritten / mFrameSize;
2034 *halFrames = framesWritten;
2035
2036 if (isSuspended()) {
2037 // return an estimation of rendered frames when the output is suspended
2038 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2039 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2040 return NO_ERROR;
2041 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002042 status_t status;
2043 uint32_t frames;
2044 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2045 *dspFrames = (size_t)frames;
2046 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002047 }
2048}
2049
2050uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2051{
2052 Mutex::Autolock _l(mLock);
2053 uint32_t result = 0;
2054 if (getEffectChain_l(sessionId) != 0) {
2055 result = EFFECT_SESSION;
2056 }
2057
2058 for (size_t i = 0; i < mTracks.size(); ++i) {
2059 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002060 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002061 result |= TRACK_SESSION;
2062 break;
2063 }
2064 }
2065
2066 return result;
2067}
2068
2069uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2070{
2071 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2072 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2073 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2074 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
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 return AudioSystem::getStrategyForStream(track->streamType());
2080 }
2081 }
2082 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2083}
2084
2085
2086AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2087{
2088 Mutex::Autolock _l(mLock);
2089 return mOutput;
2090}
2091
2092AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2093{
2094 Mutex::Autolock _l(mLock);
2095 AudioStreamOut *output = mOutput;
2096 mOutput = NULL;
2097 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2098 // must push a NULL and wait for ack
2099 mOutputSink.clear();
2100 mPipeSink.clear();
2101 mNormalSink.clear();
2102 return output;
2103}
2104
2105// this method must always be called either with ThreadBase mLock held or inside the thread loop
2106audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2107{
2108 if (mOutput == NULL) {
2109 return NULL;
2110 }
2111 return &mOutput->stream->common;
2112}
2113
2114uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2115{
2116 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2117}
2118
2119status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2120{
2121 if (!isValidSyncEvent(event)) {
2122 return BAD_VALUE;
2123 }
2124
2125 Mutex::Autolock _l(mLock);
2126
2127 for (size_t i = 0; i < mTracks.size(); ++i) {
2128 sp<Track> track = mTracks[i];
2129 if (event->triggerSession() == track->sessionId()) {
2130 (void) track->setSyncEvent(event);
2131 return NO_ERROR;
2132 }
2133 }
2134
2135 return NAME_NOT_FOUND;
2136}
2137
2138bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2139{
2140 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2141}
2142
2143void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2144 const Vector< sp<Track> >& tracksToRemove)
2145{
2146 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002147 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002148 for (size_t i = 0 ; i < count ; i++) {
2149 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002150 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002151 AudioSystem::stopOutput(mId, track->streamType(),
2152 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153#ifdef ADD_BATTERY_DATA
2154 // to track the speaker usage
2155 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2156#endif
2157 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002158 AudioSystem::releaseOutput(mId, track->streamType(),
2159 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160 }
Eric Laurent81784c32012-11-19 14:55:58 -08002161 }
2162 }
2163 }
Eric Laurent81784c32012-11-19 14:55:58 -08002164}
2165
2166void AudioFlinger::PlaybackThread::checkSilentMode_l()
2167{
2168 if (!mMasterMute) {
2169 char value[PROPERTY_VALUE_MAX];
2170 if (property_get("ro.audio.silent", value, "0") > 0) {
2171 char *endptr;
2172 unsigned long ul = strtoul(value, &endptr, 0);
2173 if (*endptr == '\0' && ul != 0) {
2174 ALOGD("Silence is golden");
2175 // The setprop command will not allow a property to be changed after
2176 // the first time it is set, so we don't have to worry about un-muting.
2177 setMasterMute_l(true);
2178 }
2179 }
2180 }
2181}
2182
2183// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002185{
2186 // FIXME rewrite to reduce number of system calls
2187 mLastWriteTime = systemTime();
2188 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002190 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002191
2192 // If an NBAIO sink is present, use it to write the normal mixer's submix
2193 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002194
Andy Hung010a1a12014-03-13 13:57:33 -07002195 const size_t count = mBytesRemaining / mFrameSize;
2196
Simon Wilson2d590962012-11-29 15:18:50 -08002197 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002198 // update the setpoint when AudioFlinger::mScreenState changes
2199 uint32_t screenState = AudioFlinger::mScreenState;
2200 if (screenState != mScreenState) {
2201 mScreenState = screenState;
2202 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2203 if (pipe != NULL) {
2204 pipe->setAvgFrames((mScreenState & 1) ?
2205 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2206 }
2207 }
Andy Hung010a1a12014-03-13 13:57:33 -07002208 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002209 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002210 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002211 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002212 } else {
2213 bytesWritten = framesWritten;
2214 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002215 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002216 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002217 if (status == NO_ERROR) {
2218 size_t totalFramesWritten = mNormalSink->framesWritten();
2219 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2220 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002221 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002222 mLatchDValid = true;
2223 }
2224 }
Eric Laurent81784c32012-11-19 14:55:58 -08002225 // otherwise use the HAL / AudioStreamOut directly
2226 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002228
Eric Laurentbfb1b832013-01-07 09:53:42 -08002229 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002230 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2231 mWriteAckSequence += 2;
2232 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002234 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002236 // FIXME We should have an implementation of timestamps for direct output threads.
2237 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002239 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 if (mUseAsyncWrite &&
2241 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2242 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002243 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002245 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246 }
Eric Laurent81784c32012-11-19 14:55:58 -08002247 }
2248
Eric Laurent81784c32012-11-19 14:55:58 -08002249 mNumWrites++;
2250 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002251 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252 return bytesWritten;
2253}
2254
2255void AudioFlinger::PlaybackThread::threadLoop_drain()
2256{
2257 if (mOutput->stream->drain) {
2258 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2259 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002260 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2261 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002263 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264 }
2265 mOutput->stream->drain(mOutput->stream,
2266 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2267 : AUDIO_DRAIN_ALL);
2268 }
2269}
2270
2271void AudioFlinger::PlaybackThread::threadLoop_exit()
2272{
Eric Laurent275e8e92014-11-30 15:14:47 -08002273 {
2274 Mutex::Autolock _l(mLock);
2275 for (size_t i = 0; i < mTracks.size(); i++) {
2276 sp<Track> track = mTracks[i];
2277 track->invalidate();
2278 }
2279 }
Eric Laurent81784c32012-11-19 14:55:58 -08002280}
2281
2282/*
2283The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002284 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002285 - activeSleepTime from activeSleepTimeUs()
2286 - idleSleepTime from idleSleepTimeUs()
2287 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2288 - maxPeriod from frame count and sample rate (MIXER only)
2289
2290The parameters that affect these derived values are:
2291 - frame count
2292 - frame size
2293 - sample rate
2294 - device type: A2DP or not
2295 - device latency
2296 - format: PCM or not
2297 - active sleep time
2298 - idle sleep time
2299*/
2300
2301void AudioFlinger::PlaybackThread::cacheParameters_l()
2302{
Andy Hung25c2dac2014-02-27 14:56:00 -08002303 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002304 activeSleepTime = activeSleepTimeUs();
2305 idleSleepTime = idleSleepTimeUs();
2306}
2307
2308void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2309{
Glenn Kasten7c027242012-12-26 14:43:16 -08002310 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002311 this, streamType, mTracks.size());
2312 Mutex::Autolock _l(mLock);
2313
2314 size_t size = mTracks.size();
2315 for (size_t i = 0; i < size; i++) {
2316 sp<Track> t = mTracks[i];
2317 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002318 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002319 }
2320 }
2321}
2322
2323status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2324{
2325 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002326 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2327 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002328 bool ownsBuffer = false;
2329
2330 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2331 if (session > 0) {
2332 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002333 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002334 if (mType != DIRECT) {
2335 size_t numSamples = mNormalFrameCount * mChannelCount;
2336 buffer = new int16_t[numSamples];
2337 memset(buffer, 0, numSamples * sizeof(int16_t));
2338 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2339 ownsBuffer = true;
2340 }
2341
2342 // Attach all tracks with same session ID to this chain.
2343 for (size_t i = 0; i < mTracks.size(); ++i) {
2344 sp<Track> track = mTracks[i];
2345 if (session == track->sessionId()) {
2346 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2347 buffer);
2348 track->setMainBuffer(buffer);
2349 chain->incTrackCnt();
2350 }
2351 }
2352
2353 // indicate all active tracks in the chain
2354 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2355 sp<Track> track = mActiveTracks[i].promote();
2356 if (track == 0) {
2357 continue;
2358 }
2359 if (session == track->sessionId()) {
2360 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2361 chain->incActiveTrackCnt();
2362 }
2363 }
2364 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002365 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002366 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002367 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2368 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002369 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2370 // chains list in order to be processed last as it contains output stage effects
2371 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2372 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2373 // after track specific effects and before output stage
2374 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2375 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2376 // Effect chain for other sessions are inserted at beginning of effect
2377 // chains list to be processed before output mix effects. Relative order between other
2378 // sessions is not important
2379 size_t size = mEffectChains.size();
2380 size_t i = 0;
2381 for (i = 0; i < size; i++) {
2382 if (mEffectChains[i]->sessionId() < session) {
2383 break;
2384 }
2385 }
2386 mEffectChains.insertAt(chain, i);
2387 checkSuspendOnAddEffectChain_l(chain);
2388
2389 return NO_ERROR;
2390}
2391
2392size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2393{
2394 int session = chain->sessionId();
2395
2396 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2397
2398 for (size_t i = 0; i < mEffectChains.size(); i++) {
2399 if (chain == mEffectChains[i]) {
2400 mEffectChains.removeAt(i);
2401 // detach all active tracks from the chain
2402 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2403 sp<Track> track = mActiveTracks[i].promote();
2404 if (track == 0) {
2405 continue;
2406 }
2407 if (session == track->sessionId()) {
2408 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2409 chain.get(), session);
2410 chain->decActiveTrackCnt();
2411 }
2412 }
2413
2414 // detach all tracks with same session ID from this chain
2415 for (size_t i = 0; i < mTracks.size(); ++i) {
2416 sp<Track> track = mTracks[i];
2417 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002418 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002419 chain->decTrackCnt();
2420 }
2421 }
2422 break;
2423 }
2424 }
2425 return mEffectChains.size();
2426}
2427
2428status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2429 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2430{
2431 Mutex::Autolock _l(mLock);
2432 return attachAuxEffect_l(track, EffectId);
2433}
2434
2435status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2436 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2437{
2438 status_t status = NO_ERROR;
2439
2440 if (EffectId == 0) {
2441 track->setAuxBuffer(0, NULL);
2442 } else {
2443 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2444 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2445 if (effect != 0) {
2446 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2447 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2448 } else {
2449 status = INVALID_OPERATION;
2450 }
2451 } else {
2452 status = BAD_VALUE;
2453 }
2454 }
2455 return status;
2456}
2457
2458void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2459{
2460 for (size_t i = 0; i < mTracks.size(); ++i) {
2461 sp<Track> track = mTracks[i];
2462 if (track->auxEffectId() == effectId) {
2463 attachAuxEffect_l(track, 0);
2464 }
2465 }
2466}
2467
2468bool AudioFlinger::PlaybackThread::threadLoop()
2469{
2470 Vector< sp<Track> > tracksToRemove;
2471
2472 standbyTime = systemTime();
2473
2474 // MIXER
2475 nsecs_t lastWarning = 0;
2476
2477 // DUPLICATING
2478 // FIXME could this be made local to while loop?
2479 writeFrames = 0;
2480
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002481 int lastGeneration = 0;
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 cacheParameters_l();
2484 sleepTime = idleSleepTime;
2485
2486 if (mType == MIXER) {
2487 sleepTimeShift = 0;
2488 }
2489
2490 CpuStats cpuStats;
2491 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2492
2493 acquireWakeLock();
2494
Glenn Kasten9e58b552013-01-18 15:09:48 -08002495 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2496 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2497 // and then that string will be logged at the next convenient opportunity.
2498 const char *logString = NULL;
2499
Eric Laurent664539d2013-09-23 18:24:31 -07002500 checkSilentMode_l();
2501
Eric Laurent81784c32012-11-19 14:55:58 -08002502 while (!exitPending())
2503 {
2504 cpuStats.sample(myName);
2505
2506 Vector< sp<EffectChain> > effectChains;
2507
Eric Laurent81784c32012-11-19 14:55:58 -08002508 { // scope for mLock
2509
2510 Mutex::Autolock _l(mLock);
2511
Eric Laurent021cf962014-05-13 10:18:14 -07002512 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002513
Glenn Kasten9e58b552013-01-18 15:09:48 -08002514 if (logString != NULL) {
2515 mNBLogWriter->logTimestamp();
2516 mNBLogWriter->log(logString);
2517 logString = NULL;
2518 }
2519
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002520 // Gather the framesReleased counters for all active tracks,
2521 // and latch them atomically with the timestamp.
2522 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2523 mLatchD.mFramesReleased.clear();
2524 size_t size = mActiveTracks.size();
2525 for (size_t i = 0; i < size; i++) {
2526 sp<Track> t = mActiveTracks[i].promote();
2527 if (t != 0) {
2528 mLatchD.mFramesReleased.add(t.get(),
2529 t->mAudioTrackServerProxy->framesReleased());
2530 }
2531 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002532 if (mLatchDValid) {
2533 mLatchQ = mLatchD;
2534 mLatchDValid = false;
2535 mLatchQValid = true;
2536 }
2537
Eric Laurent81784c32012-11-19 14:55:58 -08002538 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002539 if (mSignalPending) {
2540 // A signal was raised while we were unlocked
2541 mSignalPending = false;
2542 } else if (waitingAsyncCallback_l()) {
2543 if (exitPending()) {
2544 break;
2545 }
2546 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002547 mWakeLockUids.clear();
2548 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002549 ALOGV("wait async completion");
2550 mWaitWorkCV.wait(mLock);
2551 ALOGV("async completion/wake");
2552 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002553 standbyTime = systemTime() + standbyDelay;
2554 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002555
2556 continue;
2557 }
2558 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002559 isSuspended()) {
2560 // put audio hardware into standby after short delay
2561 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002562
2563 threadLoop_standby();
2564
2565 mStandby = true;
2566 }
2567
2568 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2569 // we're about to wait, flush the binder command buffer
2570 IPCThreadState::self()->flushCommands();
2571
2572 clearOutputTracks();
2573
2574 if (exitPending()) {
2575 break;
2576 }
2577
2578 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002579 mWakeLockUids.clear();
2580 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002581 // wait until we have something to do...
2582 ALOGV("%s going to sleep", myName.string());
2583 mWaitWorkCV.wait(mLock);
2584 ALOGV("%s waking up", myName.string());
2585 acquireWakeLock_l();
2586
2587 mMixerStatus = MIXER_IDLE;
2588 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2589 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002591 checkSilentMode_l();
2592
2593 standbyTime = systemTime() + standbyDelay;
2594 sleepTime = idleSleepTime;
2595 if (mType == MIXER) {
2596 sleepTimeShift = 0;
2597 }
2598
2599 continue;
2600 }
2601 }
Eric Laurent81784c32012-11-19 14:55:58 -08002602 // mMixerStatusIgnoringFastTracks is also updated internally
2603 mMixerStatus = prepareTracks_l(&tracksToRemove);
2604
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002605 // compare with previously applied list
2606 if (lastGeneration != mActiveTracksGeneration) {
2607 // update wakelock
2608 updateWakeLockUids_l(mWakeLockUids);
2609 lastGeneration = mActiveTracksGeneration;
2610 }
2611
Eric Laurent81784c32012-11-19 14:55:58 -08002612 // prevent any changes in effect chain list and in each effect chain
2613 // during mixing and effect process as the audio buffers could be deleted
2614 // or modified if an effect is created or deleted
2615 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002616 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002617
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 if (mBytesRemaining == 0) {
2619 mCurrentWriteLength = 0;
2620 if (mMixerStatus == MIXER_TRACKS_READY) {
2621 // threadLoop_mix() sets mCurrentWriteLength
2622 threadLoop_mix();
2623 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2624 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2625 // threadLoop_sleepTime sets sleepTime to 0 if data
2626 // must be written to HAL
2627 threadLoop_sleepTime();
2628 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002629 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 }
2631 }
Andy Hung98ef9782014-03-04 14:46:50 -08002632 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2633 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2634 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2635 // or mSinkBuffer (if there are no effects).
2636 //
2637 // This is done pre-effects computation; if effects change to
2638 // support higher precision, this needs to move.
2639 //
2640 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2641 // TODO use sleepTime == 0 as an additional condition.
2642 if (mMixerBufferValid) {
2643 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2644 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2645
2646 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2647 mNormalFrameCount * mChannelCount);
2648 }
2649
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650 mBytesRemaining = mCurrentWriteLength;
2651 if (isSuspended()) {
2652 sleepTime = suspendSleepTimeUs();
2653 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002654 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 mBytesRemaining = 0;
2656 }
Eric Laurent81784c32012-11-19 14:55:58 -08002657
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002659 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 for (size_t i = 0; i < effectChains.size(); i ++) {
2661 effectChains[i]->process_l();
2662 }
Eric Laurent81784c32012-11-19 14:55:58 -08002663 }
2664 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002665 // Process effect chains for offloaded thread even if no audio
2666 // was read from audio track: process only updates effect state
2667 // and thus does have to be synchronized with audio writes but may have
2668 // to be called while waiting for async write callback
2669 if (mType == OFFLOAD) {
2670 for (size_t i = 0; i < effectChains.size(); i ++) {
2671 effectChains[i]->process_l();
2672 }
2673 }
Eric Laurent81784c32012-11-19 14:55:58 -08002674
Andy Hung98ef9782014-03-04 14:46:50 -08002675 // Only if the Effects buffer is enabled and there is data in the
2676 // Effects buffer (buffer valid), we need to
2677 // copy into the sink buffer.
2678 // TODO use sleepTime == 0 as an additional condition.
2679 if (mEffectBufferValid) {
2680 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2681 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2682 mNormalFrameCount * mChannelCount);
2683 }
2684
Eric Laurent81784c32012-11-19 14:55:58 -08002685 // enable changes in effect chain
2686 unlockEffectChains(effectChains);
2687
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 if (!waitingAsyncCallback()) {
2689 // sleepTime == 0 means we must write to audio hardware
2690 if (sleepTime == 0) {
2691 if (mBytesRemaining) {
2692 ssize_t ret = threadLoop_write();
2693 if (ret < 0) {
2694 mBytesRemaining = 0;
2695 } else {
2696 mBytesWritten += ret;
2697 mBytesRemaining -= ret;
2698 }
2699 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2700 (mMixerStatus == MIXER_DRAIN_ALL)) {
2701 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002702 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002703 if (mType == MIXER) {
2704 // write blocked detection
2705 nsecs_t now = systemTime();
2706 nsecs_t delta = now - mLastWriteTime;
2707 if (!mStandby && delta > maxPeriod) {
2708 mNumDelayedWrites++;
2709 if ((now - lastWarning) > kWarningThrottleNs) {
2710 ATRACE_NAME("underrun");
2711 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2712 ns2ms(delta), mNumDelayedWrites, this);
2713 lastWarning = now;
2714 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715 }
2716 }
Eric Laurent81784c32012-11-19 14:55:58 -08002717
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002719 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002721 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723 }
2724
2725 // Finally let go of removed track(s), without the lock held
2726 // since we can't guarantee the destructors won't acquire that
2727 // same lock. This will also mutate and push a new fast mixer state.
2728 threadLoop_removeTracks(tracksToRemove);
2729 tracksToRemove.clear();
2730
2731 // FIXME I don't understand the need for this here;
2732 // it was in the original code but maybe the
2733 // assignment in saveOutputTracks() makes this unnecessary?
2734 clearOutputTracks();
2735
2736 // Effect chains will be actually deleted here if they were removed from
2737 // mEffectChains list during mixing or effects processing
2738 effectChains.clear();
2739
2740 // FIXME Note that the above .clear() is no longer necessary since effectChains
2741 // is now local to this block, but will keep it for now (at least until merge done).
2742 }
2743
Eric Laurentbfb1b832013-01-07 09:53:42 -08002744 threadLoop_exit();
2745
Eric Laurentcf817a22014-08-04 20:36:31 -07002746 if (!mStandby) {
2747 threadLoop_standby();
2748 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002749 }
2750
2751 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002752 mWakeLockUids.clear();
2753 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002754
2755 ALOGV("Thread %p type %d exiting", this, mType);
2756 return false;
2757}
2758
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759// removeTracks_l() must be called with ThreadBase::mLock held
2760void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2761{
2762 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002763 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002764 for (size_t i=0 ; i<count ; i++) {
2765 const sp<Track>& track = tracksToRemove.itemAt(i);
2766 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002767 mWakeLockUids.remove(track->uid());
2768 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2770 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2771 if (chain != 0) {
2772 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2773 track->sessionId());
2774 chain->decActiveTrackCnt();
2775 }
2776 if (track->isTerminated()) {
2777 removeTrack_l(track);
2778 }
2779 }
2780 }
2781
2782}
Eric Laurent81784c32012-11-19 14:55:58 -08002783
Eric Laurentaccc1472013-09-20 09:36:34 -07002784status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2785{
2786 if (mNormalSink != 0) {
2787 return mNormalSink->getTimestamp(timestamp);
2788 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002789 if ((mType == OFFLOAD || mType == DIRECT)
2790 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002791 uint64_t position64;
2792 int ret = mOutput->stream->get_presentation_position(
2793 mOutput->stream, &position64, &timestamp.mTime);
2794 if (ret == 0) {
2795 timestamp.mPosition = (uint32_t)position64;
2796 return NO_ERROR;
2797 }
2798 }
2799 return INVALID_OPERATION;
2800}
Eric Laurent1c333e22014-05-20 10:48:17 -07002801
2802status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2803 audio_patch_handle_t *handle)
2804{
2805 status_t status = NO_ERROR;
2806 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2807 // store new device and send to effects
2808 audio_devices_t type = AUDIO_DEVICE_NONE;
2809 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2810 type |= patch->sinks[i].ext.device.type;
2811 }
2812 mOutDevice = type;
2813 for (size_t i = 0; i < mEffectChains.size(); i++) {
2814 mEffectChains[i]->setDevice_l(mOutDevice);
2815 }
2816
2817 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2818 status = hwDevice->create_audio_patch(hwDevice,
2819 patch->num_sources,
2820 patch->sources,
2821 patch->num_sinks,
2822 patch->sinks,
2823 handle);
2824 } else {
2825 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2826 }
2827 return status;
2828}
2829
2830status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2831{
2832 status_t status = NO_ERROR;
2833 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2834 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2835 status = hwDevice->release_audio_patch(hwDevice, handle);
2836 } else {
2837 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2838 }
2839 return status;
2840}
2841
Eric Laurent83b88082014-06-20 18:31:16 -07002842void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2843{
2844 Mutex::Autolock _l(mLock);
2845 mTracks.add(track);
2846}
2847
2848void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2849{
2850 Mutex::Autolock _l(mLock);
2851 destroyTrack_l(track);
2852}
2853
2854void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2855{
2856 ThreadBase::getAudioPortConfig(config);
2857 config->role = AUDIO_PORT_ROLE_SOURCE;
2858 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2859 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2860}
2861
Eric Laurent81784c32012-11-19 14:55:58 -08002862// ----------------------------------------------------------------------------
2863
2864AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2865 audio_io_handle_t id, audio_devices_t device, type_t type)
2866 : PlaybackThread(audioFlinger, output, id, device, type),
2867 // mAudioMixer below
2868 // mFastMixer below
2869 mFastMixerFutex(0)
2870 // mOutputSink below
2871 // mPipeSink below
2872 // mNormalSink below
2873{
2874 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002875 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002876 "mFrameCount=%d, mNormalFrameCount=%d",
2877 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2878 mNormalFrameCount);
2879 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2880
Eric Laurent81784c32012-11-19 14:55:58 -08002881 // create an NBAIO sink for the HAL output stream, and negotiate
2882 mOutputSink = new AudioStreamOutSink(output->stream);
2883 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002884 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002885 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2886 ALOG_ASSERT(index == 0);
2887
2888 // initialize fast mixer depending on configuration
2889 bool initFastMixer;
2890 switch (kUseFastMixer) {
2891 case FastMixer_Never:
2892 initFastMixer = false;
2893 break;
2894 case FastMixer_Always:
2895 initFastMixer = true;
2896 break;
2897 case FastMixer_Static:
2898 case FastMixer_Dynamic:
2899 initFastMixer = mFrameCount < mNormalFrameCount;
2900 break;
2901 }
2902 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002903 audio_format_t fastMixerFormat;
2904 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2905 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2906 } else {
2907 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2908 }
2909 if (mFormat != fastMixerFormat) {
2910 // change our Sink format to accept our intermediate precision
2911 mFormat = fastMixerFormat;
2912 free(mSinkBuffer);
2913 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2914 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2915 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2916 }
Eric Laurent81784c32012-11-19 14:55:58 -08002917
2918 // create a MonoPipe to connect our submix to FastMixer
2919 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002920 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002921 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002922 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002923 format.mFormat = fastMixerFormat;
2924 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2925
Eric Laurent81784c32012-11-19 14:55:58 -08002926 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2927 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2928 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2929 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2930 const NBAIO_Format offers[1] = {format};
2931 size_t numCounterOffers = 0;
2932 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2933 ALOG_ASSERT(index == 0);
2934 monoPipe->setAvgFrames((mScreenState & 1) ?
2935 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2936 mPipeSink = monoPipe;
2937
Glenn Kasten46909e72013-02-26 09:20:22 -08002938#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002939 if (mTeeSinkOutputEnabled) {
2940 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002941 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2942 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002943 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002944 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002945 ALOG_ASSERT(index == 0);
2946 mTeeSink = teeSink;
2947 PipeReader *teeSource = new PipeReader(*teeSink);
2948 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002949 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002950 ALOG_ASSERT(index == 0);
2951 mTeeSource = teeSource;
2952 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002953#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002954
2955 // create fast mixer and configure it initially with just one fast track for our submix
2956 mFastMixer = new FastMixer();
2957 FastMixerStateQueue *sq = mFastMixer->sq();
2958#ifdef STATE_QUEUE_DUMP
2959 sq->setObserverDump(&mStateQueueObserverDump);
2960 sq->setMutatorDump(&mStateQueueMutatorDump);
2961#endif
2962 FastMixerState *state = sq->begin();
2963 FastTrack *fastTrack = &state->mFastTracks[0];
2964 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2965 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2966 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002967 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2968 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002969 fastTrack->mGeneration++;
2970 state->mFastTracksGen++;
2971 state->mTrackMask = 1;
2972 // fast mixer will use the HAL output sink
2973 state->mOutputSink = mOutputSink.get();
2974 state->mOutputSinkGen++;
2975 state->mFrameCount = mFrameCount;
2976 state->mCommand = FastMixerState::COLD_IDLE;
2977 // already done in constructor initialization list
2978 //mFastMixerFutex = 0;
2979 state->mColdFutexAddr = &mFastMixerFutex;
2980 state->mColdGen++;
2981 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002982#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002983 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002984#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002985 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2986 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002987 sq->end();
2988 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2989
2990 // start the fast mixer
2991 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2992 pid_t tid = mFastMixer->getTid();
2993 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2994 if (err != 0) {
2995 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2996 kPriorityFastMixer, getpid_cached, tid, err);
2997 }
2998
2999#ifdef AUDIO_WATCHDOG
3000 // create and start the watchdog
3001 mAudioWatchdog = new AudioWatchdog();
3002 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3003 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3004 tid = mAudioWatchdog->getTid();
3005 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3006 if (err != 0) {
3007 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3008 kPriorityFastMixer, getpid_cached, tid, err);
3009 }
3010#endif
3011
Eric Laurent81784c32012-11-19 14:55:58 -08003012 }
3013
3014 switch (kUseFastMixer) {
3015 case FastMixer_Never:
3016 case FastMixer_Dynamic:
3017 mNormalSink = mOutputSink;
3018 break;
3019 case FastMixer_Always:
3020 mNormalSink = mPipeSink;
3021 break;
3022 case FastMixer_Static:
3023 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3024 break;
3025 }
3026}
3027
3028AudioFlinger::MixerThread::~MixerThread()
3029{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003030 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003031 FastMixerStateQueue *sq = mFastMixer->sq();
3032 FastMixerState *state = sq->begin();
3033 if (state->mCommand == FastMixerState::COLD_IDLE) {
3034 int32_t old = android_atomic_inc(&mFastMixerFutex);
3035 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003036 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 }
3038 }
3039 state->mCommand = FastMixerState::EXIT;
3040 sq->end();
3041 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3042 mFastMixer->join();
3043 // Though the fast mixer thread has exited, it's state queue is still valid.
3044 // We'll use that extract the final state which contains one remaining fast track
3045 // corresponding to our sub-mix.
3046 state = sq->begin();
3047 ALOG_ASSERT(state->mTrackMask == 1);
3048 FastTrack *fastTrack = &state->mFastTracks[0];
3049 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3050 delete fastTrack->mBufferProvider;
3051 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003052 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003053#ifdef AUDIO_WATCHDOG
3054 if (mAudioWatchdog != 0) {
3055 mAudioWatchdog->requestExit();
3056 mAudioWatchdog->requestExitAndWait();
3057 mAudioWatchdog.clear();
3058 }
3059#endif
3060 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003061 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003062 delete mAudioMixer;
3063}
3064
3065
3066uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3067{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003068 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003069 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3070 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3071 }
3072 return latency;
3073}
3074
3075
3076void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3077{
3078 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3079}
3080
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003082{
3083 // FIXME we should only do one push per cycle; confirm this is true
3084 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003085 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003086 FastMixerStateQueue *sq = mFastMixer->sq();
3087 FastMixerState *state = sq->begin();
3088 if (state->mCommand != FastMixerState::MIX_WRITE &&
3089 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3090 if (state->mCommand == FastMixerState::COLD_IDLE) {
3091 int32_t old = android_atomic_inc(&mFastMixerFutex);
3092 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003093 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003094 }
3095#ifdef AUDIO_WATCHDOG
3096 if (mAudioWatchdog != 0) {
3097 mAudioWatchdog->resume();
3098 }
3099#endif
3100 }
3101 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003102 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3103 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003104 sq->end();
3105 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3106 if (kUseFastMixer == FastMixer_Dynamic) {
3107 mNormalSink = mPipeSink;
3108 }
3109 } else {
3110 sq->end(false /*didModify*/);
3111 }
3112 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003114}
3115
3116void AudioFlinger::MixerThread::threadLoop_standby()
3117{
3118 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003119 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003120 FastMixerStateQueue *sq = mFastMixer->sq();
3121 FastMixerState *state = sq->begin();
3122 if (!(state->mCommand & FastMixerState::IDLE)) {
3123 state->mCommand = FastMixerState::COLD_IDLE;
3124 state->mColdFutexAddr = &mFastMixerFutex;
3125 state->mColdGen++;
3126 mFastMixerFutex = 0;
3127 sq->end();
3128 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3129 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3130 if (kUseFastMixer == FastMixer_Dynamic) {
3131 mNormalSink = mOutputSink;
3132 }
3133#ifdef AUDIO_WATCHDOG
3134 if (mAudioWatchdog != 0) {
3135 mAudioWatchdog->pause();
3136 }
3137#endif
3138 } else {
3139 sq->end(false /*didModify*/);
3140 }
3141 }
3142 PlaybackThread::threadLoop_standby();
3143}
3144
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3146{
3147 return false;
3148}
3149
3150bool AudioFlinger::PlaybackThread::shouldStandby_l()
3151{
3152 return !mStandby;
3153}
3154
3155bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3156{
3157 Mutex::Autolock _l(mLock);
3158 return waitingAsyncCallback_l();
3159}
3160
Eric Laurent81784c32012-11-19 14:55:58 -08003161// shared by MIXER and DIRECT, overridden by DUPLICATING
3162void AudioFlinger::PlaybackThread::threadLoop_standby()
3163{
3164 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3165 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003167 // discard any pending drain or write ack by incrementing sequence
3168 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3169 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003171 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3172 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003174 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003175}
3176
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003177void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3178{
3179 ALOGV("signal playback thread");
3180 broadcast_l();
3181}
3182
Eric Laurent81784c32012-11-19 14:55:58 -08003183void AudioFlinger::MixerThread::threadLoop_mix()
3184{
3185 // obtain the presentation timestamp of the next output buffer
3186 int64_t pts;
3187 status_t status = INVALID_OPERATION;
3188
3189 if (mNormalSink != 0) {
3190 status = mNormalSink->getNextWriteTimestamp(&pts);
3191 } else {
3192 status = mOutputSink->getNextWriteTimestamp(&pts);
3193 }
3194
3195 if (status != NO_ERROR) {
3196 pts = AudioBufferProvider::kInvalidPTS;
3197 }
3198
3199 // mix buffers...
3200 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003201 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003202 // increase sleep time progressively when application underrun condition clears.
3203 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3204 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3205 // such that we would underrun the audio HAL.
3206 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3207 sleepTimeShift--;
3208 }
3209 sleepTime = 0;
3210 standbyTime = systemTime() + standbyDelay;
3211 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003212
Eric Laurent81784c32012-11-19 14:55:58 -08003213}
3214
3215void AudioFlinger::MixerThread::threadLoop_sleepTime()
3216{
3217 // If no tracks are ready, sleep once for the duration of an output
3218 // buffer size, then write 0s to the output
3219 if (sleepTime == 0) {
3220 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3221 sleepTime = activeSleepTime >> sleepTimeShift;
3222 if (sleepTime < kMinThreadSleepTimeUs) {
3223 sleepTime = kMinThreadSleepTimeUs;
3224 }
3225 // reduce sleep time in case of consecutive application underruns to avoid
3226 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3227 // duration we would end up writing less data than needed by the audio HAL if
3228 // the condition persists.
3229 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3230 sleepTimeShift++;
3231 }
3232 } else {
3233 sleepTime = idleSleepTime;
3234 }
3235 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003236 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3237 // before effects processing or output.
3238 if (mMixerBufferValid) {
3239 memset(mMixerBuffer, 0, mMixerBufferSize);
3240 } else {
3241 memset(mSinkBuffer, 0, mSinkBufferSize);
3242 }
Eric Laurent81784c32012-11-19 14:55:58 -08003243 sleepTime = 0;
3244 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3245 "anticipated start");
3246 }
3247 // TODO add standby time extension fct of effect tail
3248}
3249
3250// prepareTracks_l() must be called with ThreadBase::mLock held
3251AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3252 Vector< sp<Track> > *tracksToRemove)
3253{
3254
3255 mixer_state mixerStatus = MIXER_IDLE;
3256 // find out which tracks need to be processed
3257 size_t count = mActiveTracks.size();
3258 size_t mixedTracks = 0;
3259 size_t tracksWithEffect = 0;
3260 // counts only _active_ fast tracks
3261 size_t fastTracks = 0;
3262 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3263
3264 float masterVolume = mMasterVolume;
3265 bool masterMute = mMasterMute;
3266
3267 if (masterMute) {
3268 masterVolume = 0;
3269 }
3270 // Delegate master volume control to effect in output mix effect chain if needed
3271 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3272 if (chain != 0) {
3273 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3274 chain->setVolume_l(&v, &v);
3275 masterVolume = (float)((v + (1 << 23)) >> 24);
3276 chain.clear();
3277 }
3278
3279 // prepare a new state to push
3280 FastMixerStateQueue *sq = NULL;
3281 FastMixerState *state = NULL;
3282 bool didModify = false;
3283 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003284 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003285 sq = mFastMixer->sq();
3286 state = sq->begin();
3287 }
3288
Andy Hung69aed5f2014-02-25 17:24:40 -08003289 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003290 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003291
Eric Laurent81784c32012-11-19 14:55:58 -08003292 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003293 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003294 if (t == 0) {
3295 continue;
3296 }
3297
3298 // this const just means the local variable doesn't change
3299 Track* const track = t.get();
3300
3301 // process fast tracks
3302 if (track->isFastTrack()) {
3303
3304 // It's theoretically possible (though unlikely) for a fast track to be created
3305 // and then removed within the same normal mix cycle. This is not a problem, as
3306 // the track never becomes active so it's fast mixer slot is never touched.
3307 // The converse, of removing an (active) track and then creating a new track
3308 // at the identical fast mixer slot within the same normal mix cycle,
3309 // is impossible because the slot isn't marked available until the end of each cycle.
3310 int j = track->mFastIndex;
3311 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3312 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3313 FastTrack *fastTrack = &state->mFastTracks[j];
3314
3315 // Determine whether the track is currently in underrun condition,
3316 // and whether it had a recent underrun.
3317 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3318 FastTrackUnderruns underruns = ftDump->mUnderruns;
3319 uint32_t recentFull = (underruns.mBitFields.mFull -
3320 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3321 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3322 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3323 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3324 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3325 uint32_t recentUnderruns = recentPartial + recentEmpty;
3326 track->mObservedUnderruns = underruns;
3327 // don't count underruns that occur while stopping or pausing
3328 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003329 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3330 recentUnderruns > 0) {
3331 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3332 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003333 }
3334
3335 // This is similar to the state machine for normal tracks,
3336 // with a few modifications for fast tracks.
3337 bool isActive = true;
3338 switch (track->mState) {
3339 case TrackBase::STOPPING_1:
3340 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003341 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003342 track->mState = TrackBase::STOPPING_2;
3343 }
3344 break;
3345 case TrackBase::PAUSING:
3346 // ramp down is not yet implemented
3347 track->setPaused();
3348 break;
3349 case TrackBase::RESUMING:
3350 // ramp up is not yet implemented
3351 track->mState = TrackBase::ACTIVE;
3352 break;
3353 case TrackBase::ACTIVE:
3354 if (recentFull > 0 || recentPartial > 0) {
3355 // track has provided at least some frames recently: reset retry count
3356 track->mRetryCount = kMaxTrackRetries;
3357 }
3358 if (recentUnderruns == 0) {
3359 // no recent underruns: stay active
3360 break;
3361 }
3362 // there has recently been an underrun of some kind
3363 if (track->sharedBuffer() == 0) {
3364 // were any of the recent underruns "empty" (no frames available)?
3365 if (recentEmpty == 0) {
3366 // no, then ignore the partial underruns as they are allowed indefinitely
3367 break;
3368 }
3369 // there has recently been an "empty" underrun: decrement the retry counter
3370 if (--(track->mRetryCount) > 0) {
3371 break;
3372 }
3373 // indicate to client process that the track was disabled because of underrun;
3374 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003375 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003376 // remove from active list, but state remains ACTIVE [confusing but true]
3377 isActive = false;
3378 break;
3379 }
3380 // fall through
3381 case TrackBase::STOPPING_2:
3382 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003383 case TrackBase::STOPPED:
3384 case TrackBase::FLUSHED: // flush() while active
3385 // Check for presentation complete if track is inactive
3386 // We have consumed all the buffers of this track.
3387 // This would be incomplete if we auto-paused on underrun
3388 {
3389 size_t audioHALFrames =
3390 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3391 size_t framesWritten = mBytesWritten / mFrameSize;
3392 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3393 // track stays in active list until presentation is complete
3394 break;
3395 }
3396 }
3397 if (track->isStopping_2()) {
3398 track->mState = TrackBase::STOPPED;
3399 }
3400 if (track->isStopped()) {
3401 // Can't reset directly, as fast mixer is still polling this track
3402 // track->reset();
3403 // So instead mark this track as needing to be reset after push with ack
3404 resetMask |= 1 << i;
3405 }
3406 isActive = false;
3407 break;
3408 case TrackBase::IDLE:
3409 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003410 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003411 }
3412
3413 if (isActive) {
3414 // was it previously inactive?
3415 if (!(state->mTrackMask & (1 << j))) {
3416 ExtendedAudioBufferProvider *eabp = track;
3417 VolumeProvider *vp = track;
3418 fastTrack->mBufferProvider = eabp;
3419 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003420 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003421 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003422 fastTrack->mGeneration++;
3423 state->mTrackMask |= 1 << j;
3424 didModify = true;
3425 // no acknowledgement required for newly active tracks
3426 }
3427 // cache the combined master volume and stream type volume for fast mixer; this
3428 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003429 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003430 ++fastTracks;
3431 } else {
3432 // was it previously active?
3433 if (state->mTrackMask & (1 << j)) {
3434 fastTrack->mBufferProvider = NULL;
3435 fastTrack->mGeneration++;
3436 state->mTrackMask &= ~(1 << j);
3437 didModify = true;
3438 // If any fast tracks were removed, we must wait for acknowledgement
3439 // because we're about to decrement the last sp<> on those tracks.
3440 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3441 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003442 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003443 }
3444 tracksToRemove->add(track);
3445 // Avoids a misleading display in dumpsys
3446 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3447 }
3448 continue;
3449 }
3450
3451 { // local variable scope to avoid goto warning
3452
3453 audio_track_cblk_t* cblk = track->cblk();
3454
3455 // The first time a track is added we wait
3456 // for all its buffers to be filled before processing it
3457 int name = track->name();
3458 // make sure that we have enough frames to mix one full buffer.
3459 // enforce this condition only once to enable draining the buffer in case the client
3460 // app does not call stop() and relies on underrun to stop:
3461 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3462 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003463 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003464 uint32_t sr = track->sampleRate();
3465 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003466 desiredFrames = mNormalFrameCount;
3467 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003468 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003469 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003470 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003471 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003472#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003473 // the minimum track buffer size is normally twice the number of frames necessary
3474 // to fill one buffer and the resampler should not leave more than one buffer worth
3475 // of unreleased frames after each pass, but just in case...
3476 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003477#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003478 }
Eric Laurent81784c32012-11-19 14:55:58 -08003479 uint32_t minFrames = 1;
3480 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3481 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003482 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003483 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003484
3485 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003486 if (ATRACE_ENABLED()) {
3487 // I wish we had formatted trace names
3488 char traceName[16];
3489 strcpy(traceName, "nRdy");
3490 int name = track->name();
3491 if (AudioMixer::TRACK0 <= name &&
3492 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3493 name -= AudioMixer::TRACK0;
3494 traceName[4] = (name / 10) + '0';
3495 traceName[5] = (name % 10) + '0';
3496 } else {
3497 traceName[4] = '?';
3498 traceName[5] = '?';
3499 }
3500 traceName[6] = '\0';
3501 ATRACE_INT(traceName, framesReady);
3502 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003503 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003504 !track->isPaused() && !track->isTerminated())
3505 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003506 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003507
3508 mixedTracks++;
3509
Andy Hung69aed5f2014-02-25 17:24:40 -08003510 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3511 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003512 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003513 if (track->mainBuffer() != mSinkBuffer &&
3514 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003515 if (mEffectBufferEnabled) {
3516 mEffectBufferValid = true; // Later can set directly.
3517 }
Eric Laurent81784c32012-11-19 14:55:58 -08003518 chain = getEffectChain_l(track->sessionId());
3519 // Delegate volume control to effect in track effect chain if needed
3520 if (chain != 0) {
3521 tracksWithEffect++;
3522 } else {
3523 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3524 "session %d",
3525 name, track->sessionId());
3526 }
3527 }
3528
3529
3530 int param = AudioMixer::VOLUME;
3531 if (track->mFillingUpStatus == Track::FS_FILLED) {
3532 // no ramp for the first volume setting
3533 track->mFillingUpStatus = Track::FS_ACTIVE;
3534 if (track->mState == TrackBase::RESUMING) {
3535 track->mState = TrackBase::ACTIVE;
3536 param = AudioMixer::RAMP_VOLUME;
3537 }
3538 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003539 // FIXME should not make a decision based on mServer
3540 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // If the track is stopped before the first frame was mixed,
3542 // do not apply ramp
3543 param = AudioMixer::RAMP_VOLUME;
3544 }
3545
3546 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003547 uint32_t vl, vr; // in U8.24 integer format
3548 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003549 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003550 vl = vr = 0;
3551 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003552 if (track->isPausing()) {
3553 track->setPaused();
3554 }
3555 } else {
3556
3557 // read original volumes with volume control
3558 float typeVolume = mStreamTypes[track->streamType()].volume;
3559 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003560 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003561 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003562 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3563 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003564 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003565 if (vlf > GAIN_FLOAT_UNITY) {
3566 ALOGV("Track left volume out of range: %.3g", vlf);
3567 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003568 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003569 if (vrf > GAIN_FLOAT_UNITY) {
3570 ALOGV("Track right volume out of range: %.3g", vrf);
3571 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003572 }
3573 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003574 vlf *= v;
3575 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003576 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003577 // then derive vl and vr as U8.24 versions for the effect chain
3578 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3579 vl = (uint32_t) (scaleto8_24 * vlf);
3580 vr = (uint32_t) (scaleto8_24 * vrf);
3581 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003582 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003583 // send level comes from shared memory and so may be corrupt
3584 if (sendLevel > MAX_GAIN_INT) {
3585 ALOGV("Track send level out of range: %04X", sendLevel);
3586 sendLevel = MAX_GAIN_INT;
3587 }
Andy Hung6be49402014-05-30 10:42:03 -07003588 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3589 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003590 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // Delegate volume control to effect in track effect chain if needed
3593 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3594 // Do not ramp volume if volume is controlled by effect
3595 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003596 // Update remaining floating point volume levels
3597 vlf = (float)vl / (1 << 24);
3598 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003599 track->mHasVolumeController = true;
3600 } else {
3601 // force no volume ramp when volume controller was just disabled or removed
3602 // from effect chain to avoid volume spike
3603 if (track->mHasVolumeController) {
3604 param = AudioMixer::VOLUME;
3605 }
3606 track->mHasVolumeController = false;
3607 }
3608
Eric Laurent81784c32012-11-19 14:55:58 -08003609 // XXX: these things DON'T need to be done each time
3610 mAudioMixer->setBufferProvider(name, track);
3611 mAudioMixer->enable(name);
3612
Andy Hung6be49402014-05-30 10:42:03 -07003613 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3614 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3615 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003616 mAudioMixer->setParameter(
3617 name,
3618 AudioMixer::TRACK,
3619 AudioMixer::FORMAT, (void *)track->format());
3620 mAudioMixer->setParameter(
3621 name,
3622 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003623 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003624 mAudioMixer->setParameter(
3625 name,
3626 AudioMixer::TRACK,
3627 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003628 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003629 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003630 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003631 if (reqSampleRate == 0) {
3632 reqSampleRate = mSampleRate;
3633 } else if (reqSampleRate > maxSampleRate) {
3634 reqSampleRate = maxSampleRate;
3635 }
Eric Laurent81784c32012-11-19 14:55:58 -08003636 mAudioMixer->setParameter(
3637 name,
3638 AudioMixer::RESAMPLE,
3639 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003640 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003641 /*
3642 * Select the appropriate output buffer for the track.
3643 *
Andy Hung98ef9782014-03-04 14:46:50 -08003644 * Tracks with effects go into their own effects chain buffer
3645 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003646 *
3647 * Other tracks can use mMixerBuffer for higher precision
3648 * channel accumulation. If this buffer is enabled
3649 * (mMixerBufferEnabled true), then selected tracks will accumulate
3650 * into it.
3651 *
3652 */
3653 if (mMixerBufferEnabled
3654 && (track->mainBuffer() == mSinkBuffer
3655 || track->mainBuffer() == mMixerBuffer)) {
3656 mAudioMixer->setParameter(
3657 name,
3658 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003659 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003660 mAudioMixer->setParameter(
3661 name,
3662 AudioMixer::TRACK,
3663 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3664 // TODO: override track->mainBuffer()?
3665 mMixerBufferValid = true;
3666 } else {
3667 mAudioMixer->setParameter(
3668 name,
3669 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003670 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003671 mAudioMixer->setParameter(
3672 name,
3673 AudioMixer::TRACK,
3674 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3675 }
Eric Laurent81784c32012-11-19 14:55:58 -08003676 mAudioMixer->setParameter(
3677 name,
3678 AudioMixer::TRACK,
3679 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3680
3681 // reset retry count
3682 track->mRetryCount = kMaxTrackRetries;
3683
3684 // If one track is ready, set the mixer ready if:
3685 // - the mixer was not ready during previous round OR
3686 // - no other track is not ready
3687 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3688 mixerStatus != MIXER_TRACKS_ENABLED) {
3689 mixerStatus = MIXER_TRACKS_READY;
3690 }
3691 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003692 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003693 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003694 }
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // clear effect chain input buffer if an active track underruns to avoid sending
3696 // previous audio buffer again to effects
3697 chain = getEffectChain_l(track->sessionId());
3698 if (chain != 0) {
3699 chain->clearInputBuffer();
3700 }
3701
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003702 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003703 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3704 track->isStopped() || track->isPaused()) {
3705 // We have consumed all the buffers of this track.
3706 // Remove it from the list of active tracks.
3707 // TODO: use actual buffer filling status instead of latency when available from
3708 // audio HAL
3709 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3710 size_t framesWritten = mBytesWritten / mFrameSize;
3711 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3712 if (track->isStopped()) {
3713 track->reset();
3714 }
3715 tracksToRemove->add(track);
3716 }
3717 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003718 // No buffers for this track. Give it a few chances to
3719 // fill a buffer, then remove it from active list.
3720 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003721 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003722 tracksToRemove->add(track);
3723 // indicate to client process that the track was disabled because of underrun;
3724 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003725 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003726 // If one track is not ready, mark the mixer also not ready if:
3727 // - the mixer was ready during previous round OR
3728 // - no other track is ready
3729 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3730 mixerStatus != MIXER_TRACKS_READY) {
3731 mixerStatus = MIXER_TRACKS_ENABLED;
3732 }
3733 }
3734 mAudioMixer->disable(name);
3735 }
3736
3737 } // local variable scope to avoid goto warning
3738track_is_ready: ;
3739
3740 }
3741
3742 // Push the new FastMixer state if necessary
3743 bool pauseAudioWatchdog = false;
3744 if (didModify) {
3745 state->mFastTracksGen++;
3746 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3747 if (kUseFastMixer == FastMixer_Dynamic &&
3748 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3749 state->mCommand = FastMixerState::COLD_IDLE;
3750 state->mColdFutexAddr = &mFastMixerFutex;
3751 state->mColdGen++;
3752 mFastMixerFutex = 0;
3753 if (kUseFastMixer == FastMixer_Dynamic) {
3754 mNormalSink = mOutputSink;
3755 }
3756 // If we go into cold idle, need to wait for acknowledgement
3757 // so that fast mixer stops doing I/O.
3758 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3759 pauseAudioWatchdog = true;
3760 }
Eric Laurent81784c32012-11-19 14:55:58 -08003761 }
3762 if (sq != NULL) {
3763 sq->end(didModify);
3764 sq->push(block);
3765 }
3766#ifdef AUDIO_WATCHDOG
3767 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3768 mAudioWatchdog->pause();
3769 }
3770#endif
3771
3772 // Now perform the deferred reset on fast tracks that have stopped
3773 while (resetMask != 0) {
3774 size_t i = __builtin_ctz(resetMask);
3775 ALOG_ASSERT(i < count);
3776 resetMask &= ~(1 << i);
3777 sp<Track> t = mActiveTracks[i].promote();
3778 if (t == 0) {
3779 continue;
3780 }
3781 Track* track = t.get();
3782 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3783 track->reset();
3784 }
3785
3786 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003787 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003788
Eric Laurent97d547d2014-09-02 14:45:53 -07003789 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3790 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003791 }
3792
3793 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003794 // as long as there are effects we should clear the effects buffer, to avoid
3795 // passing a non-clean buffer to the effect chain
3796 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003797 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003798 // sink or mix buffer must be cleared if all tracks are connected to an
3799 // effect chain as in this case the mixer will not write to the sink or mix buffer
3800 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003801 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3802 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003803 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003804 if (mMixerBufferValid) {
3805 memset(mMixerBuffer, 0, mMixerBufferSize);
3806 // TODO: In testing, mSinkBuffer below need not be cleared because
3807 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3808 // after mixing.
3809 //
3810 // To enforce this guarantee:
3811 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3812 // (mixedTracks == 0 && fastTracks > 0))
3813 // must imply MIXER_TRACKS_READY.
3814 // Later, we may clear buffers regardless, and skip much of this logic.
3815 }
Andy Hung98ef9782014-03-04 14:46:50 -08003816 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003817 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003818 }
3819
3820 // if any fast tracks, then status is ready
3821 mMixerStatusIgnoringFastTracks = mixerStatus;
3822 if (fastTracks > 0) {
3823 mixerStatus = MIXER_TRACKS_READY;
3824 }
3825 return mixerStatus;
3826}
3827
3828// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003829int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3830 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003831{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003832 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003833}
3834
3835// deleteTrackName_l() must be called with ThreadBase::mLock held
3836void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3837{
3838 ALOGV("remove track (%d) and delete from mixer", name);
3839 mAudioMixer->deleteTrackName(name);
3840}
3841
Eric Laurent10351942014-05-08 18:49:52 -07003842// checkForNewParameter_l() must be called with ThreadBase::mLock held
3843bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3844 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003845{
Eric Laurent81784c32012-11-19 14:55:58 -08003846 bool reconfig = false;
3847
Eric Laurent10351942014-05-08 18:49:52 -07003848 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003849
Eric Laurent10351942014-05-08 18:49:52 -07003850 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3851 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003852 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003853 FastMixerStateQueue *sq = mFastMixer->sq();
3854 FastMixerState *state = sq->begin();
3855 if (!(state->mCommand & FastMixerState::IDLE)) {
3856 previousCommand = state->mCommand;
3857 state->mCommand = FastMixerState::HOT_IDLE;
3858 sq->end();
3859 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3860 } else {
3861 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 }
Eric Laurent10351942014-05-08 18:49:52 -07003863 }
Eric Laurent81784c32012-11-19 14:55:58 -08003864
Eric Laurent10351942014-05-08 18:49:52 -07003865 AudioParameter param = AudioParameter(keyValuePair);
3866 int value;
3867 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3868 reconfig = true;
3869 }
3870 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003871 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003872 status = BAD_VALUE;
3873 } else {
3874 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003875 reconfig = true;
3876 }
Eric Laurent10351942014-05-08 18:49:52 -07003877 }
3878 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003879 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003880 status = BAD_VALUE;
3881 } else {
3882 // no need to save value, since it's constant
3883 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003884 }
Eric Laurent10351942014-05-08 18:49:52 -07003885 }
3886 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3887 // do not accept frame count changes if tracks are open as the track buffer
3888 // size depends on frame count and correct behavior would not be guaranteed
3889 // if frame count is changed after track creation
3890 if (!mTracks.isEmpty()) {
3891 status = INVALID_OPERATION;
3892 } else {
3893 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003894 }
Eric Laurent10351942014-05-08 18:49:52 -07003895 }
3896 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003897#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003898 // when changing the audio output device, call addBatteryData to notify
3899 // the change
3900 if (mOutDevice != value) {
3901 uint32_t params = 0;
3902 // check whether speaker is on
3903 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3904 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
Eric Laurent10351942014-05-08 18:49:52 -07003906
3907 audio_devices_t deviceWithoutSpeaker
3908 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3909 // check if any other device (except speaker) is on
3910 if (value & deviceWithoutSpeaker ) {
3911 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3912 }
3913
3914 if (params != 0) {
3915 addBatteryData(params);
3916 }
3917 }
Eric Laurent81784c32012-11-19 14:55:58 -08003918#endif
3919
Eric Laurent10351942014-05-08 18:49:52 -07003920 // forward device change to effects that have requested to be
3921 // aware of attached audio device.
3922 if (value != AUDIO_DEVICE_NONE) {
3923 mOutDevice = value;
3924 for (size_t i = 0; i < mEffectChains.size(); i++) {
3925 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003926 }
3927 }
Eric Laurent10351942014-05-08 18:49:52 -07003928 }
Eric Laurent81784c32012-11-19 14:55:58 -08003929
Eric Laurent10351942014-05-08 18:49:52 -07003930 if (status == NO_ERROR) {
3931 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3932 keyValuePair.string());
3933 if (!mStandby && status == INVALID_OPERATION) {
3934 mOutput->stream->common.standby(&mOutput->stream->common);
3935 mStandby = true;
3936 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003937 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003938 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
Eric Laurent10351942014-05-08 18:49:52 -07003940 if (status == NO_ERROR && reconfig) {
3941 readOutputParameters_l();
3942 delete mAudioMixer;
3943 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3944 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003945 int name = getTrackName_l(mTracks[i]->mChannelMask,
3946 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003947 if (name < 0) {
3948 break;
3949 }
3950 mTracks[i]->mName = name;
3951 }
3952 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3953 }
Eric Laurent81784c32012-11-19 14:55:58 -08003954 }
3955
3956 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003957 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003958 FastMixerStateQueue *sq = mFastMixer->sq();
3959 FastMixerState *state = sq->begin();
3960 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3961 state->mCommand = previousCommand;
3962 sq->end();
3963 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3964 }
3965
3966 return reconfig;
3967}
3968
3969
3970void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3971{
3972 const size_t SIZE = 256;
3973 char buffer[SIZE];
3974 String8 result;
3975
3976 PlaybackThread::dumpInternals(fd, args);
3977
Elliott Hughes87cebad2014-05-22 10:14:43 -07003978 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003979
3980 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003981 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003982 copy.dump(fd);
3983
3984#ifdef STATE_QUEUE_DUMP
3985 // Similar for state queue
3986 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3987 observerCopy.dump(fd);
3988 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3989 mutatorCopy.dump(fd);
3990#endif
3991
Glenn Kasten46909e72013-02-26 09:20:22 -08003992#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003993 // Write the tee output to a .wav file
3994 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003995#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003996
3997#ifdef AUDIO_WATCHDOG
3998 if (mAudioWatchdog != 0) {
3999 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4000 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4001 wdCopy.dump(fd);
4002 }
4003#endif
4004}
4005
4006uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4007{
4008 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4009}
4010
4011uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4012{
4013 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4014}
4015
4016void AudioFlinger::MixerThread::cacheParameters_l()
4017{
4018 PlaybackThread::cacheParameters_l();
4019
4020 // FIXME: Relaxed timing because of a certain device that can't meet latency
4021 // Should be reduced to 2x after the vendor fixes the driver issue
4022 // increase threshold again due to low power audio mode. The way this warning
4023 // threshold is calculated and its usefulness should be reconsidered anyway.
4024 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4025}
4026
4027// ----------------------------------------------------------------------------
4028
4029AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4030 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4031 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4032 // mLeftVolFloat, mRightVolFloat
4033{
4034}
4035
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4037 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4038 ThreadBase::type_t type)
4039 : PlaybackThread(audioFlinger, output, id, device, type)
4040 // mLeftVolFloat, mRightVolFloat
4041{
4042}
4043
Eric Laurent81784c32012-11-19 14:55:58 -08004044AudioFlinger::DirectOutputThread::~DirectOutputThread()
4045{
4046}
4047
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4049{
4050 audio_track_cblk_t* cblk = track->cblk();
4051 float left, right;
4052
4053 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4054 left = right = 0;
4055 } else {
4056 float typeVolume = mStreamTypes[track->streamType()].volume;
4057 float v = mMasterVolume * typeVolume;
4058 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004059 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4060 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4061 if (left > GAIN_FLOAT_UNITY) {
4062 left = GAIN_FLOAT_UNITY;
4063 }
4064 left *= v;
4065 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4066 if (right > GAIN_FLOAT_UNITY) {
4067 right = GAIN_FLOAT_UNITY;
4068 }
4069 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 }
4071
4072 if (lastTrack) {
4073 if (left != mLeftVolFloat || right != mRightVolFloat) {
4074 mLeftVolFloat = left;
4075 mRightVolFloat = right;
4076
4077 // Convert volumes from float to 8.24
4078 uint32_t vl = (uint32_t)(left * (1 << 24));
4079 uint32_t vr = (uint32_t)(right * (1 << 24));
4080
4081 // Delegate volume control to effect in track effect chain if needed
4082 // only one effect chain can be present on DirectOutputThread, so if
4083 // there is one, the track is connected to it
4084 if (!mEffectChains.isEmpty()) {
4085 mEffectChains[0]->setVolume_l(&vl, &vr);
4086 left = (float)vl / (1 << 24);
4087 right = (float)vr / (1 << 24);
4088 }
4089 if (mOutput->stream->set_volume) {
4090 mOutput->stream->set_volume(mOutput->stream, left, right);
4091 }
4092 }
4093 }
4094}
4095
4096
Eric Laurent81784c32012-11-19 14:55:58 -08004097AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4098 Vector< sp<Track> > *tracksToRemove
4099)
4100{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004101 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004102 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004103 bool doHwPause = false;
4104 bool doHwResume = false;
4105 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004106
4107 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004108 for (size_t i = 0; i < count; i++) {
4109 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // The track died recently
4111 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004112 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004113 }
4114
4115 Track* const track = t.get();
4116 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004117 // Only consider last track started for volume and mixer state control.
4118 // In theory an older track could underrun and restart after the new one starts
4119 // but as we only care about the transition phase between two tracks on a
4120 // direct output, it is not a problem to ignore the underrun case.
4121 sp<Track> l = mLatestActiveTrack.promote();
4122 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004123
Eric Laurentd1f69b02014-12-15 14:33:13 -08004124 if (mHwSupportsPause && track->isPausing()) {
4125 track->setPaused();
4126 if (last && !mHwPaused) {
4127 doHwPause = true;
4128 mHwPaused = true;
4129 }
4130 tracksToRemove->add(track);
4131 } else if (track->isFlushPending()) {
4132 track->flushAck();
4133 if (last) {
4134 flushPending = true;
4135 }
4136 } else if (mHwSupportsPause && track->isResumePending()){
4137 track->resumeAck();
4138 if (last) {
4139 if (mHwPaused) {
4140 doHwResume = true;
4141 mHwPaused = false;
4142 }
4143 }
4144 }
4145
Eric Laurent81784c32012-11-19 14:55:58 -08004146 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004147 // for all its buffers to be filled before processing it.
4148 // Allow draining the buffer in case the client
4149 // app does not call stop() and relies on underrun to stop:
4150 // hence the test on (track->mRetryCount > 1).
4151 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004152 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004153 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4154 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004155 minFrames = mNormalFrameCount;
4156 } else {
4157 minFrames = 1;
4158 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004159
Eric Laurentab5cdba2014-06-09 17:22:27 -07004160 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4161 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004162 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004163 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004164
4165 if (track->mFillingUpStatus == Track::FS_FILLED) {
4166 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004167 // make sure processVolume_l() will apply new volume even if 0
4168 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004169 if (!mHwSupportsPause) {
4170 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004171 }
4172 }
4173
4174 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175 processVolume_l(track, last);
4176 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004177 // reset retry count
4178 track->mRetryCount = kMaxTrackRetriesDirect;
4179 mActiveTrack = t;
4180 mixerStatus = MIXER_TRACKS_READY;
4181 }
Eric Laurent81784c32012-11-19 14:55:58 -08004182 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004183 // clear effect chain input buffer if the last active track started underruns
4184 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004185 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004186 mEffectChains[0]->clearInputBuffer();
4187 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004188 if (track->isStopping_1()) {
4189 track->mState = TrackBase::STOPPING_2;
4190 }
4191 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4192 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004193 // We have consumed all the buffers of this track.
4194 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004195 size_t audioHALFrames;
4196 if (audio_is_linear_pcm(mFormat)) {
4197 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4198 } else {
4199 audioHALFrames = 0;
4200 }
4201
Eric Laurent81784c32012-11-19 14:55:58 -08004202 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004203 if (mStandby || !last ||
4204 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004205 if (track->isStopping_2()) {
4206 track->mState = TrackBase::STOPPED;
4207 }
Eric Laurent81784c32012-11-19 14:55:58 -08004208 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004209 if (track->mState == TrackBase::FLUSHED) {
4210 flushHw_l();
4211 }
Eric Laurent81784c32012-11-19 14:55:58 -08004212 track->reset();
4213 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004214 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004215 }
4216 } else {
4217 // No buffers for this track. Give it a few chances to
4218 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004219 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004220 if (--(track->mRetryCount) <= 0) {
4221 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004222 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004223 // indicate to client process that the track was disabled because of underrun;
4224 // it will then automatically call start() when data is available
4225 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004227 mixerStatus = MIXER_TRACKS_ENABLED;
4228 }
4229 }
4230 }
4231 }
4232
Eric Laurentd1f69b02014-12-15 14:33:13 -08004233 // if an active track did not command a flush, check for pending flush on stopped tracks
4234 if (!flushPending) {
4235 for (size_t i = 0; i < mTracks.size(); i++) {
4236 if (mTracks[i]->isFlushPending()) {
4237 mTracks[i]->flushAck();
4238 flushPending = true;
4239 }
4240 }
4241 }
4242
4243 // make sure the pause/flush/resume sequence is executed in the right order.
4244 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4245 // before flush and then resume HW. This can happen in case of pause/flush/resume
4246 // if resume is received before pause is executed.
4247 if (mHwSupportsPause && !mStandby &&
4248 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4249 mOutput->stream->pause(mOutput->stream);
4250 }
4251 if (flushPending) {
4252 flushHw_l();
4253 }
4254 if (mHwSupportsPause && !mStandby && doHwResume) {
4255 mOutput->stream->resume(mOutput->stream);
4256 }
Eric Laurent81784c32012-11-19 14:55:58 -08004257 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004259
4260 return mixerStatus;
4261}
4262
4263void AudioFlinger::DirectOutputThread::threadLoop_mix()
4264{
Eric Laurent81784c32012-11-19 14:55:58 -08004265 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004266 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004267 // output audio to hardware
4268 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004269 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004270 buffer.frameCount = frameCount;
4271 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004272 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004273 memset(curBuf, 0, frameCount * mFrameSize);
4274 break;
4275 }
4276 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4277 frameCount -= buffer.frameCount;
4278 curBuf += buffer.frameCount * mFrameSize;
4279 mActiveTrack->releaseBuffer(&buffer);
4280 }
Andy Hung2098f272014-02-27 14:00:06 -08004281 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004282 sleepTime = 0;
4283 standbyTime = systemTime() + standbyDelay;
4284 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004285}
4286
4287void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4288{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004289 // do not write to HAL when paused
4290 if (mHwPaused) {
4291 sleepTime = idleSleepTime;
4292 return;
4293 }
Eric Laurent81784c32012-11-19 14:55:58 -08004294 if (sleepTime == 0) {
4295 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4296 sleepTime = activeSleepTime;
4297 } else {
4298 sleepTime = idleSleepTime;
4299 }
4300 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004301 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004302 sleepTime = 0;
4303 }
4304}
4305
Eric Laurentd1f69b02014-12-15 14:33:13 -08004306void AudioFlinger::DirectOutputThread::threadLoop_exit()
4307{
4308 {
4309 Mutex::Autolock _l(mLock);
4310 bool flushPending = false;
4311 for (size_t i = 0; i < mTracks.size(); i++) {
4312 if (mTracks[i]->isFlushPending()) {
4313 mTracks[i]->flushAck();
4314 flushPending = true;
4315 }
4316 }
4317 if (flushPending) {
4318 flushHw_l();
4319 }
4320 }
4321 PlaybackThread::threadLoop_exit();
4322}
4323
4324// must be called with thread mutex locked
4325bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4326{
4327 bool trackPaused = false;
4328
4329 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4330 // after a timeout and we will enter standby then.
4331 if (mTracks.size() > 0) {
4332 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4333 }
4334
4335 return !mStandby && !trackPaused;
4336}
4337
Eric Laurent81784c32012-11-19 14:55:58 -08004338// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004339int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004340 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004341{
4342 return 0;
4343}
4344
4345// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004346void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004347{
4348}
4349
Eric Laurent10351942014-05-08 18:49:52 -07004350// checkForNewParameter_l() must be called with ThreadBase::mLock held
4351bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4352 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004353{
4354 bool reconfig = false;
4355
Eric Laurent10351942014-05-08 18:49:52 -07004356 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004357
Eric Laurent10351942014-05-08 18:49:52 -07004358 AudioParameter param = AudioParameter(keyValuePair);
4359 int value;
4360 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4361 // forward device change to effects that have requested to be
4362 // aware of attached audio device.
4363 if (value != AUDIO_DEVICE_NONE) {
4364 mOutDevice = value;
4365 for (size_t i = 0; i < mEffectChains.size(); i++) {
4366 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004367 }
4368 }
Eric Laurent81784c32012-11-19 14:55:58 -08004369 }
Eric Laurent10351942014-05-08 18:49:52 -07004370 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4371 // do not accept frame count changes if tracks are open as the track buffer
4372 // size depends on frame count and correct behavior would not be garantied
4373 // if frame count is changed after track creation
4374 if (!mTracks.isEmpty()) {
4375 status = INVALID_OPERATION;
4376 } else {
4377 reconfig = true;
4378 }
4379 }
4380 if (status == NO_ERROR) {
4381 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4382 keyValuePair.string());
4383 if (!mStandby && status == INVALID_OPERATION) {
4384 mOutput->stream->common.standby(&mOutput->stream->common);
4385 mStandby = true;
4386 mBytesWritten = 0;
4387 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4388 keyValuePair.string());
4389 }
4390 if (status == NO_ERROR && reconfig) {
4391 readOutputParameters_l();
4392 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4393 }
4394 }
4395
Eric Laurent81784c32012-11-19 14:55:58 -08004396 return reconfig;
4397}
4398
4399uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4400{
4401 uint32_t time;
4402 if (audio_is_linear_pcm(mFormat)) {
4403 time = PlaybackThread::activeSleepTimeUs();
4404 } else {
4405 time = 10000;
4406 }
4407 return time;
4408}
4409
4410uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4411{
4412 uint32_t time;
4413 if (audio_is_linear_pcm(mFormat)) {
4414 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4415 } else {
4416 time = 10000;
4417 }
4418 return time;
4419}
4420
4421uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4422{
4423 uint32_t time;
4424 if (audio_is_linear_pcm(mFormat)) {
4425 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4426 } else {
4427 time = 10000;
4428 }
4429 return time;
4430}
4431
4432void AudioFlinger::DirectOutputThread::cacheParameters_l()
4433{
4434 PlaybackThread::cacheParameters_l();
4435
4436 // use shorter standby delay as on normal output to release
4437 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004438 if (audio_is_linear_pcm(mFormat)) {
4439 standbyDelay = microseconds(activeSleepTime*2);
4440 } else {
4441 standbyDelay = kOffloadStandbyDelayNs;
4442 }
Eric Laurent81784c32012-11-19 14:55:58 -08004443}
4444
Eric Laurente659ef42014-09-29 13:06:46 -07004445void AudioFlinger::DirectOutputThread::flushHw_l()
4446{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004447 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004448 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004449 }
4450 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004451}
4452
Eric Laurent81784c32012-11-19 14:55:58 -08004453// ----------------------------------------------------------------------------
4454
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004456 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004458 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004459 mWriteAckSequence(0),
4460 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004461{
4462}
4463
4464AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4465{
4466}
4467
4468void AudioFlinger::AsyncCallbackThread::onFirstRef()
4469{
4470 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4471}
4472
4473bool AudioFlinger::AsyncCallbackThread::threadLoop()
4474{
4475 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004476 uint32_t writeAckSequence;
4477 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004478
4479 {
4480 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004481 while (!((mWriteAckSequence & 1) ||
4482 (mDrainSequence & 1) ||
4483 exitPending())) {
4484 mWaitWorkCV.wait(mLock);
4485 }
4486
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487 if (exitPending()) {
4488 break;
4489 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004490 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4491 mWriteAckSequence, mDrainSequence);
4492 writeAckSequence = mWriteAckSequence;
4493 mWriteAckSequence &= ~1;
4494 drainSequence = mDrainSequence;
4495 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496 }
4497 {
Eric Laurent4de95592013-09-26 15:28:21 -07004498 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4499 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004500 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004501 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004502 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004503 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004504 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004505 }
4506 }
4507 }
4508 }
4509 return false;
4510}
4511
4512void AudioFlinger::AsyncCallbackThread::exit()
4513{
4514 ALOGV("AsyncCallbackThread::exit");
4515 Mutex::Autolock _l(mLock);
4516 requestExit();
4517 mWaitWorkCV.broadcast();
4518}
4519
Eric Laurent3b4529e2013-09-05 18:09:19 -07004520void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004521{
4522 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004523 // bit 0 is cleared
4524 mWriteAckSequence = sequence << 1;
4525}
4526
4527void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4528{
4529 Mutex::Autolock _l(mLock);
4530 // ignore unexpected callbacks
4531 if (mWriteAckSequence & 2) {
4532 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004533 mWaitWorkCV.signal();
4534 }
4535}
4536
Eric Laurent3b4529e2013-09-05 18:09:19 -07004537void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538{
4539 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004540 // bit 0 is cleared
4541 mDrainSequence = sequence << 1;
4542}
4543
4544void AudioFlinger::AsyncCallbackThread::resetDraining()
4545{
4546 Mutex::Autolock _l(mLock);
4547 // ignore unexpected callbacks
4548 if (mDrainSequence & 2) {
4549 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004550 mWaitWorkCV.signal();
4551 }
4552}
4553
4554
4555// ----------------------------------------------------------------------------
4556AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4557 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4558 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004559 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004560{
Eric Laurentfd477972013-10-25 18:10:40 -07004561 //FIXME: mStandby should be set to true by ThreadBase constructor
4562 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004563}
4564
Eric Laurentbfb1b832013-01-07 09:53:42 -08004565void AudioFlinger::OffloadThread::threadLoop_exit()
4566{
4567 if (mFlushPending || mHwPaused) {
4568 // If a flush is pending or track was paused, just discard buffered data
4569 flushHw_l();
4570 } else {
4571 mMixerStatus = MIXER_DRAIN_ALL;
4572 threadLoop_drain();
4573 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004574 if (mUseAsyncWrite) {
4575 ALOG_ASSERT(mCallbackThread != 0);
4576 mCallbackThread->exit();
4577 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004578 PlaybackThread::threadLoop_exit();
4579}
4580
4581AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4582 Vector< sp<Track> > *tracksToRemove
4583)
4584{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585 size_t count = mActiveTracks.size();
4586
4587 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004588 bool doHwPause = false;
4589 bool doHwResume = false;
4590
Eric Laurentede6c3b2013-09-19 14:37:46 -07004591 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4592
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593 // find out which tracks need to be processed
4594 for (size_t i = 0; i < count; i++) {
4595 sp<Track> t = mActiveTracks[i].promote();
4596 // The track died recently
4597 if (t == 0) {
4598 continue;
4599 }
4600 Track* const track = t.get();
4601 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004602 // Only consider last track started for volume and mixer state control.
4603 // In theory an older track could underrun and restart after the new one starts
4604 // but as we only care about the transition phase between two tracks on a
4605 // direct output, it is not a problem to ignore the underrun case.
4606 sp<Track> l = mLatestActiveTrack.promote();
4607 bool last = l.get() == track;
4608
Haynes Mathew George7844f672014-01-15 12:32:55 -08004609 if (track->isInvalid()) {
4610 ALOGW("An invalidated track shouldn't be in active list");
4611 tracksToRemove->add(track);
4612 continue;
4613 }
4614
4615 if (track->mState == TrackBase::IDLE) {
4616 ALOGW("An idle track shouldn't be in active list");
4617 continue;
4618 }
4619
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620 if (track->isPausing()) {
4621 track->setPaused();
4622 if (last) {
4623 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004624 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004625 mHwPaused = true;
4626 }
4627 // If we were part way through writing the mixbuffer to
4628 // the HAL we must save this until we resume
4629 // BUG - this will be wrong if a different track is made active,
4630 // in that case we want to discard the pending data in the
4631 // mixbuffer and tell the client to present it again when the
4632 // track is resumed
4633 mPausedWriteLength = mCurrentWriteLength;
4634 mPausedBytesRemaining = mBytesRemaining;
4635 mBytesRemaining = 0; // stop writing
4636 }
4637 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004638 } else if (track->isFlushPending()) {
4639 track->flushAck();
4640 if (last) {
4641 mFlushPending = true;
4642 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004643 } else if (track->isResumePending()){
4644 track->resumeAck();
4645 if (last) {
4646 if (mPausedBytesRemaining) {
4647 // Need to continue write that was interrupted
4648 mCurrentWriteLength = mPausedWriteLength;
4649 mBytesRemaining = mPausedBytesRemaining;
4650 mPausedBytesRemaining = 0;
4651 }
4652 if (mHwPaused) {
4653 doHwResume = true;
4654 mHwPaused = false;
4655 // threadLoop_mix() will handle the case that we need to
4656 // resume an interrupted write
4657 }
4658 // enable write to audio HAL
4659 sleepTime = 0;
4660
4661 // Do not handle new data in this iteration even if track->framesReady()
4662 mixerStatus = MIXER_TRACKS_ENABLED;
4663 }
4664 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004665 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004666 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004667 if (track->mFillingUpStatus == Track::FS_FILLED) {
4668 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004669 // make sure processVolume_l() will apply new volume even if 0
4670 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 }
4672
4673 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004674 sp<Track> previousTrack = mPreviousTrack.promote();
4675 if (previousTrack != 0) {
4676 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004677 // Flush any data still being written from last track
4678 mBytesRemaining = 0;
4679 if (mPausedBytesRemaining) {
4680 // Last track was paused so we also need to flush saved
4681 // mixbuffer state and invalidate track so that it will
4682 // re-submit that unwritten data when it is next resumed
4683 mPausedBytesRemaining = 0;
4684 // Invalidate is a bit drastic - would be more efficient
4685 // to have a flag to tell client that some of the
4686 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004687 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004688 }
4689 // flush data already sent to the DSP if changing audio session as audio
4690 // comes from a different source. Also invalidate previous track to force a
4691 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004692 if (previousTrack->sessionId() != track->sessionId()) {
4693 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004694 }
4695 }
4696 }
4697 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004698 // reset retry count
4699 track->mRetryCount = kMaxTrackRetriesOffload;
4700 mActiveTrack = t;
4701 mixerStatus = MIXER_TRACKS_READY;
4702 }
4703 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004704 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 if (track->isStopping_1()) {
4706 // Hardware buffer can hold a large amount of audio so we must
4707 // wait for all current track's data to drain before we say
4708 // that the track is stopped.
4709 if (mBytesRemaining == 0) {
4710 // Only start draining when all data in mixbuffer
4711 // has been written
4712 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4713 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004714 // do not drain if no data was ever sent to HAL (mStandby == true)
4715 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004716 // do not modify drain sequence if we are already draining. This happens
4717 // when resuming from pause after drain.
4718 if ((mDrainSequence & 1) == 0) {
4719 sleepTime = 0;
4720 standbyTime = systemTime() + standbyDelay;
4721 mixerStatus = MIXER_DRAIN_TRACK;
4722 mDrainSequence += 2;
4723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004724 if (mHwPaused) {
4725 // It is possible to move from PAUSED to STOPPING_1 without
4726 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004727 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728 mHwPaused = false;
4729 }
4730 }
4731 }
4732 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004733 // Drain has completed or we are in standby, signal presentation complete
4734 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 track->mState = TrackBase::STOPPED;
4736 size_t audioHALFrames =
4737 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4738 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004739 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004740 track->presentationComplete(framesWritten, audioHALFrames);
4741 track->reset();
4742 tracksToRemove->add(track);
4743 }
4744 } else {
4745 // No buffers for this track. Give it a few chances to
4746 // fill a buffer, then remove it from active list.
4747 if (--(track->mRetryCount) <= 0) {
4748 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4749 track->name());
4750 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004751 // indicate to client process that the track was disabled because of underrun;
4752 // it will then automatically call start() when data is available
4753 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754 } else if (last){
4755 mixerStatus = MIXER_TRACKS_ENABLED;
4756 }
4757 }
4758 }
4759 // compute volume for this track
4760 processVolume_l(track, last);
4761 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004762
Eric Laurentea0fade2013-10-04 16:23:48 -07004763 // make sure the pause/flush/resume sequence is executed in the right order.
4764 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4765 // before flush and then resume HW. This can happen in case of pause/flush/resume
4766 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004767 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004768 mOutput->stream->pause(mOutput->stream);
4769 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004770 if (mFlushPending) {
4771 flushHw_l();
4772 mFlushPending = false;
4773 }
Eric Laurentfd477972013-10-25 18:10:40 -07004774 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004775 mOutput->stream->resume(mOutput->stream);
4776 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004777
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 // remove all the tracks that need to be...
4779 removeTracks_l(*tracksToRemove);
4780
4781 return mixerStatus;
4782}
4783
Eric Laurentbfb1b832013-01-07 09:53:42 -08004784// must be called with thread mutex locked
4785bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4786{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004787 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4788 mWriteAckSequence, mDrainSequence);
4789 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004790 return true;
4791 }
4792 return false;
4793}
4794
Eric Laurentbfb1b832013-01-07 09:53:42 -08004795bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4796{
4797 Mutex::Autolock _l(mLock);
4798 return waitingAsyncCallback_l();
4799}
4800
4801void AudioFlinger::OffloadThread::flushHw_l()
4802{
Eric Laurente659ef42014-09-29 13:06:46 -07004803 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004804 // Flush anything still waiting in the mixbuffer
4805 mCurrentWriteLength = 0;
4806 mBytesRemaining = 0;
4807 mPausedWriteLength = 0;
4808 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004809
Eric Laurentbfb1b832013-01-07 09:53:42 -08004810 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004811 // discard any pending drain or write ack by incrementing sequence
4812 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4813 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004814 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004815 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4816 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 }
4818}
4819
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004820void AudioFlinger::OffloadThread::onAddNewTrack_l()
4821{
4822 sp<Track> previousTrack = mPreviousTrack.promote();
4823 sp<Track> latestTrack = mLatestActiveTrack.promote();
4824
4825 if (previousTrack != 0 && latestTrack != 0 &&
4826 (previousTrack->sessionId() != latestTrack->sessionId())) {
4827 mFlushPending = true;
4828 }
4829 PlaybackThread::onAddNewTrack_l();
4830}
4831
Eric Laurentbfb1b832013-01-07 09:53:42 -08004832// ----------------------------------------------------------------------------
4833
Eric Laurent81784c32012-11-19 14:55:58 -08004834AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4835 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4836 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4837 DUPLICATING),
4838 mWaitTimeMs(UINT_MAX)
4839{
4840 addOutputTrack(mainThread);
4841}
4842
4843AudioFlinger::DuplicatingThread::~DuplicatingThread()
4844{
4845 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4846 mOutputTracks[i]->destroy();
4847 }
4848}
4849
4850void AudioFlinger::DuplicatingThread::threadLoop_mix()
4851{
4852 // mix buffers...
4853 if (outputsReady(outputTracks)) {
4854 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4855 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004856 if (mMixerBufferValid) {
4857 memset(mMixerBuffer, 0, mMixerBufferSize);
4858 } else {
4859 memset(mSinkBuffer, 0, mSinkBufferSize);
4860 }
Eric Laurent81784c32012-11-19 14:55:58 -08004861 }
4862 sleepTime = 0;
4863 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004864 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004865 standbyTime = systemTime() + standbyDelay;
4866}
4867
4868void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4869{
4870 if (sleepTime == 0) {
4871 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4872 sleepTime = activeSleepTime;
4873 } else {
4874 sleepTime = idleSleepTime;
4875 }
4876 } else if (mBytesWritten != 0) {
4877 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4878 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004879 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004880 } else {
4881 // flush remaining overflow buffers in output tracks
4882 writeFrames = 0;
4883 }
4884 sleepTime = 0;
4885 }
4886}
4887
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004889{
4890 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004891 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004892 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004893 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004894 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004895}
4896
4897void AudioFlinger::DuplicatingThread::threadLoop_standby()
4898{
4899 // DuplicatingThread implements standby by stopping all tracks
4900 for (size_t i = 0; i < outputTracks.size(); i++) {
4901 outputTracks[i]->stop();
4902 }
4903}
4904
4905void AudioFlinger::DuplicatingThread::saveOutputTracks()
4906{
4907 outputTracks = mOutputTracks;
4908}
4909
4910void AudioFlinger::DuplicatingThread::clearOutputTracks()
4911{
4912 outputTracks.clear();
4913}
4914
4915void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4916{
4917 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004918 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4919 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4920 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4921 const size_t frameCount =
4922 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4923 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4924 // from different OutputTracks and their associated MixerThreads (e.g. one may
4925 // nearly empty and the other may be dropping data).
4926
4927 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004928 this,
4929 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004930 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004931 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004932 frameCount,
4933 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004934 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004935 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004936 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004937 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004938 updateWaitTime_l();
4939 }
4940}
4941
4942void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4943{
4944 Mutex::Autolock _l(mLock);
4945 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4946 if (mOutputTracks[i]->thread() == thread) {
4947 mOutputTracks[i]->destroy();
4948 mOutputTracks.removeAt(i);
4949 updateWaitTime_l();
4950 return;
4951 }
4952 }
4953 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4954}
4955
4956// caller must hold mLock
4957void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4958{
4959 mWaitTimeMs = UINT_MAX;
4960 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4961 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4962 if (strong != 0) {
4963 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4964 if (waitTimeMs < mWaitTimeMs) {
4965 mWaitTimeMs = waitTimeMs;
4966 }
4967 }
4968 }
4969}
4970
4971
4972bool AudioFlinger::DuplicatingThread::outputsReady(
4973 const SortedVector< sp<OutputTrack> > &outputTracks)
4974{
4975 for (size_t i = 0; i < outputTracks.size(); i++) {
4976 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4977 if (thread == 0) {
4978 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4979 outputTracks[i].get());
4980 return false;
4981 }
4982 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4983 // see note at standby() declaration
4984 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4985 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4986 thread.get());
4987 return false;
4988 }
4989 }
4990 return true;
4991}
4992
4993uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4994{
4995 return (mWaitTimeMs * 1000) / 2;
4996}
4997
4998void AudioFlinger::DuplicatingThread::cacheParameters_l()
4999{
5000 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5001 updateWaitTime_l();
5002
5003 MixerThread::cacheParameters_l();
5004}
5005
5006// ----------------------------------------------------------------------------
5007// Record
5008// ----------------------------------------------------------------------------
5009
5010AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5011 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005012 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005013 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005014 audio_devices_t inDevice
5015#ifdef TEE_SINK
5016 , const sp<NBAIO_Sink>& teeSink
5017#endif
5018 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005019 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005020 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005021 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005022 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005023#ifdef TEE_SINK
5024 , mTeeSink(teeSink)
5025#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005026 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5027 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005028 // mFastCapture below
5029 , mFastCaptureFutex(0)
5030 // mInputSource
5031 // mPipeSink
5032 // mPipeSource
5033 , mPipeFramesP2(0)
5034 // mPipeMemory
5035 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005036 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005037{
5038 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005039 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005040
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005041 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005042
5043 // create an NBAIO source for the HAL input stream, and negotiate
5044 mInputSource = new AudioStreamInSource(input->stream);
5045 size_t numCounterOffers = 0;
5046 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5047 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5048 ALOG_ASSERT(index == 0);
5049
5050 // initialize fast capture depending on configuration
5051 bool initFastCapture;
5052 switch (kUseFastCapture) {
5053 case FastCapture_Never:
5054 initFastCapture = false;
5055 break;
5056 case FastCapture_Always:
5057 initFastCapture = true;
5058 break;
5059 case FastCapture_Static:
5060 uint32_t primaryOutputSampleRate;
5061 {
5062 AutoMutex _l(audioFlinger->mHardwareLock);
5063 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5064 }
5065 initFastCapture =
5066 // either capture sample rate is same as (a reasonable) primary output sample rate
5067 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5068 (mSampleRate == primaryOutputSampleRate)) ||
5069 // or primary output sample rate is unknown, and capture sample rate is reasonable
5070 ((primaryOutputSampleRate == 0) &&
5071 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005072 // and the buffer size is < 12 ms
5073 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005074 break;
5075 // case FastCapture_Dynamic:
5076 }
5077
5078 if (initFastCapture) {
5079 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5080 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005081 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005082 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5083 void *pipeBuffer;
5084 const sp<MemoryDealer> roHeap(readOnlyHeap());
5085 sp<IMemory> pipeMemory;
5086 if ((roHeap == 0) ||
5087 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5088 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5089 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5090 goto failed;
5091 }
5092 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5093 memset(pipeBuffer, 0, pipeSize);
5094 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5095 const NBAIO_Format offers[1] = {format};
5096 size_t numCounterOffers = 0;
5097 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5098 ALOG_ASSERT(index == 0);
5099 mPipeSink = pipe;
5100 PipeReader *pipeReader = new PipeReader(*pipe);
5101 numCounterOffers = 0;
5102 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5103 ALOG_ASSERT(index == 0);
5104 mPipeSource = pipeReader;
5105 mPipeFramesP2 = pipeFramesP2;
5106 mPipeMemory = pipeMemory;
5107
5108 // create fast capture
5109 mFastCapture = new FastCapture();
5110 FastCaptureStateQueue *sq = mFastCapture->sq();
5111#ifdef STATE_QUEUE_DUMP
5112 // FIXME
5113#endif
5114 FastCaptureState *state = sq->begin();
5115 state->mCblk = NULL;
5116 state->mInputSource = mInputSource.get();
5117 state->mInputSourceGen++;
5118 state->mPipeSink = pipe;
5119 state->mPipeSinkGen++;
5120 state->mFrameCount = mFrameCount;
5121 state->mCommand = FastCaptureState::COLD_IDLE;
5122 // already done in constructor initialization list
5123 //mFastCaptureFutex = 0;
5124 state->mColdFutexAddr = &mFastCaptureFutex;
5125 state->mColdGen++;
5126 state->mDumpState = &mFastCaptureDumpState;
5127#ifdef TEE_SINK
5128 // FIXME
5129#endif
5130 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5131 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5132 sq->end();
5133 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5134
5135 // start the fast capture
5136 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5137 pid_t tid = mFastCapture->getTid();
5138 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5139 if (err != 0) {
5140 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5141 kPriorityFastCapture, getpid_cached, tid, err);
5142 }
5143
5144#ifdef AUDIO_WATCHDOG
5145 // FIXME
5146#endif
5147
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005148 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005149 }
5150failed: ;
5151
5152 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005153}
5154
5155
5156AudioFlinger::RecordThread::~RecordThread()
5157{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005158 if (mFastCapture != 0) {
5159 FastCaptureStateQueue *sq = mFastCapture->sq();
5160 FastCaptureState *state = sq->begin();
5161 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5162 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5163 if (old == -1) {
5164 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5165 }
5166 }
5167 state->mCommand = FastCaptureState::EXIT;
5168 sq->end();
5169 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5170 mFastCapture->join();
5171 mFastCapture.clear();
5172 }
5173 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005174 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005176}
5177
5178void AudioFlinger::RecordThread::onFirstRef()
5179{
5180 run(mName, PRIORITY_URGENT_AUDIO);
5181}
5182
Eric Laurent81784c32012-11-19 14:55:58 -08005183bool AudioFlinger::RecordThread::threadLoop()
5184{
Eric Laurent81784c32012-11-19 14:55:58 -08005185 nsecs_t lastWarning = 0;
5186
5187 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005188
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005189reacquire_wakelock:
5190 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005191 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005192 {
5193 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005194 size_t size = mActiveTracks.size();
5195 activeTracksGen = mActiveTracksGen;
5196 if (size > 0) {
5197 // FIXME an arbitrary choice
5198 activeTrack = mActiveTracks[0];
5199 acquireWakeLock_l(activeTrack->uid());
5200 if (size > 1) {
5201 SortedVector<int> tmp;
5202 for (size_t i = 0; i < size; i++) {
5203 tmp.add(mActiveTracks[i]->uid());
5204 }
5205 updateWakeLockUids_l(tmp);
5206 }
5207 } else {
5208 acquireWakeLock_l(-1);
5209 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005210 }
5211
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005212 // used to request a deferred sleep, to be executed later while mutex is unlocked
5213 uint32_t sleepUs = 0;
5214
5215 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005216 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005217 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005218
Glenn Kasten5edadd42013-08-14 16:30:49 -07005219 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005220 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005221 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005222 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005223 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005224 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005225 }
5226
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005227 // activeTracks accumulates a copy of a subset of mActiveTracks
5228 Vector< sp<RecordTrack> > activeTracks;
5229
Glenn Kasten735f45f2014-08-18 15:51:59 -07005230 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005231 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005232
Glenn Kasten735f45f2014-08-18 15:51:59 -07005233 // reference to a fast track which is about to be removed
5234 sp<RecordTrack> fastTrackToRemove;
5235
Eric Laurent81784c32012-11-19 14:55:58 -08005236 { // scope for mLock
5237 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005238
Eric Laurent021cf962014-05-13 10:18:14 -07005239 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005240
Eric Laurent000a4192014-01-29 15:17:32 -08005241 // check exitPending here because checkForNewParameters_l() and
5242 // checkForNewParameters_l() can temporarily release mLock
5243 if (exitPending()) {
5244 break;
5245 }
5246
Glenn Kasten2b806402013-11-20 16:37:38 -08005247 // if no active track(s), then standby and release wakelock
5248 size_t size = mActiveTracks.size();
5249 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005250 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005251 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005252 releaseWakeLock_l();
5253 ALOGV("RecordThread: loop stopping");
5254 // go to sleep
5255 mWaitWorkCV.wait(mLock);
5256 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005257 goto reacquire_wakelock;
5258 }
5259
Glenn Kasten2b806402013-11-20 16:37:38 -08005260 if (mActiveTracksGen != activeTracksGen) {
5261 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005262 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005263 for (size_t i = 0; i < size; i++) {
5264 tmp.add(mActiveTracks[i]->uid());
5265 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005266 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005267 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005268
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 bool doBroadcast = false;
5270 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005271
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005272 activeTrack = mActiveTracks[i];
5273 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005274 if (activeTrack->isFastTrack()) {
5275 ALOG_ASSERT(fastTrackToRemove == 0);
5276 fastTrackToRemove = activeTrack;
5277 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005278 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005279 mActiveTracks.remove(activeTrack);
5280 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005281 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005282 continue;
5283 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005284
5285 TrackBase::track_state activeTrackState = activeTrack->mState;
5286 switch (activeTrackState) {
5287
5288 case TrackBase::PAUSING:
5289 mActiveTracks.remove(activeTrack);
5290 mActiveTracksGen++;
5291 doBroadcast = true;
5292 size--;
5293 continue;
5294
5295 case TrackBase::STARTING_1:
5296 sleepUs = 10000;
5297 i++;
5298 continue;
5299
5300 case TrackBase::STARTING_2:
5301 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005302 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005303 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005304 break;
5305
5306 case TrackBase::ACTIVE:
5307 break;
5308
5309 case TrackBase::IDLE:
5310 i++;
5311 continue;
5312
5313 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005314 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005315 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005316
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005317 activeTracks.add(activeTrack);
5318 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005319
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005320 if (activeTrack->isFastTrack()) {
5321 ALOG_ASSERT(!mFastTrackAvail);
5322 ALOG_ASSERT(fastTrack == 0);
5323 fastTrack = activeTrack;
5324 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005325 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005326 if (doBroadcast) {
5327 mStartStopCond.broadcast();
5328 }
5329
5330 // sleep if there are no active tracks to process
5331 if (activeTracks.size() == 0) {
5332 if (sleepUs == 0) {
5333 sleepUs = kRecordThreadSleepUs;
5334 }
5335 continue;
5336 }
5337 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005338
Eric Laurent81784c32012-11-19 14:55:58 -08005339 lockEffectChains_l(effectChains);
5340 }
5341
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005342 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005344 size_t size = effectChains.size();
5345 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005346 // thread mutex is not locked, but effect chain is locked
5347 effectChains[i]->process_l();
5348 }
5349
Glenn Kasten735f45f2014-08-18 15:51:59 -07005350 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005351 if (mFastCapture != 0) {
5352 FastCaptureStateQueue *sq = mFastCapture->sq();
5353 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005354 bool didModify = false;
5355 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005356 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5357 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5358 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5359 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5360 if (old == -1) {
5361 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5362 }
5363 }
5364 state->mCommand = FastCaptureState::READ_WRITE;
5365#if 0 // FIXME
5366 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005367 FastCaptureDumpState::kSamplingNforLowRamDevice :
5368 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005369#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005370 didModify = true;
5371 }
5372 audio_track_cblk_t *cblkOld = state->mCblk;
5373 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5374 if (cblkNew != cblkOld) {
5375 state->mCblk = cblkNew;
5376 // block until acked if removing a fast track
5377 if (cblkOld != NULL) {
5378 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5379 }
5380 didModify = true;
5381 }
5382 sq->end(didModify);
5383 if (didModify) {
5384 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005385#if 0
5386 if (kUseFastCapture == FastCapture_Dynamic) {
5387 mNormalSource = mPipeSource;
5388 }
5389#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005390 }
5391 }
5392
Glenn Kasten735f45f2014-08-18 15:51:59 -07005393 // now run the fast track destructor with thread mutex unlocked
5394 fastTrackToRemove.clear();
5395
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005396 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5397 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5398 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5399 // If destination is non-contiguous, first read past the nominal end of buffer, then
5400 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005401
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005402 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005403 ssize_t framesRead;
5404
5405 // If an NBAIO source is present, use it to read the normal capture's data
5406 if (mPipeSource != 0) {
5407 size_t framesToRead = mBufferSize / mFrameSize;
5408 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5409 framesToRead, AudioBufferProvider::kInvalidPTS);
5410 if (framesRead == 0) {
5411 // since pipe is non-blocking, simulate blocking input
5412 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5413 }
5414 // otherwise use the HAL / AudioStreamIn directly
5415 } else {
5416 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5417 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5418 if (bytesRead < 0) {
5419 framesRead = bytesRead;
5420 } else {
5421 framesRead = bytesRead / mFrameSize;
5422 }
5423 }
5424
5425 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5426 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005427 // Force input into standby so that it tries to recover at next read attempt
5428 inputStandBy();
5429 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005430 }
5431 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005432 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005433 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005434 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005435
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005436 if (mTeeSink != 0) {
5437 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5438 }
5439 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005440 {
5441 size_t part1 = mRsmpInFramesP2 - rear;
5442 if ((size_t) framesRead > part1) {
5443 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5444 (framesRead - part1) * mFrameSize);
5445 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005446 }
5447 rear = mRsmpInRear += framesRead;
5448
5449 size = activeTracks.size();
5450 // loop over each active track
5451 for (size_t i = 0; i < size; i++) {
5452 activeTrack = activeTracks[i];
5453
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005454 // skip fast tracks, as those are handled directly by FastCapture
5455 if (activeTrack->isFastTrack()) {
5456 continue;
5457 }
5458
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005459 enum {
5460 OVERRUN_UNKNOWN,
5461 OVERRUN_TRUE,
5462 OVERRUN_FALSE
5463 } overrun = OVERRUN_UNKNOWN;
5464
5465 // loop over getNextBuffer to handle circular sink
5466 for (;;) {
5467
5468 activeTrack->mSink.frameCount = ~0;
5469 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5470 size_t framesOut = activeTrack->mSink.frameCount;
5471 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5472
5473 int32_t front = activeTrack->mRsmpInFront;
5474 ssize_t filled = rear - front;
5475 size_t framesIn;
5476
5477 if (filled < 0) {
5478 // should not happen, but treat like a massive overrun and re-sync
5479 framesIn = 0;
5480 activeTrack->mRsmpInFront = rear;
5481 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005482 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005483 framesIn = (size_t) filled;
5484 } else {
5485 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005486 framesIn = mRsmpInFrames;
5487 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005488 overrun = OVERRUN_TRUE;
5489 }
5490
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005491 if (framesOut == 0 || framesIn == 0) {
5492 break;
5493 }
5494
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005495 if (activeTrack->mResampler == NULL) {
5496 // no resampling
5497 if (framesIn > framesOut) {
5498 framesIn = framesOut;
5499 } else {
5500 framesOut = framesIn;
5501 }
5502 int8_t *dst = activeTrack->mSink.i8;
5503 while (framesIn > 0) {
5504 front &= mRsmpInFramesP2 - 1;
5505 size_t part1 = mRsmpInFramesP2 - front;
5506 if (part1 > framesIn) {
5507 part1 = framesIn;
5508 }
5509 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005510 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005511 memcpy(dst, src, part1 * mFrameSize);
5512 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005513 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005514 part1);
5515 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005516 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5517 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005518 }
5519 dst += part1 * activeTrack->mFrameSize;
5520 front += part1;
5521 framesIn -= part1;
5522 }
5523 activeTrack->mRsmpInFront += framesOut;
5524
5525 } else {
5526 // resampling
5527 // FIXME framesInNeeded should really be part of resampler API, and should
5528 // depend on the SRC ratio
5529 // to keep mRsmpInBuffer full so resampler always has sufficient input
5530 size_t framesInNeeded;
5531 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005532 // Do not precompute in/out because floating point is not associative
5533 // e.g. a*b/c != a*(b/c).
5534 const double in(mSampleRate);
5535 const double out(activeTrack->mSampleRate);
5536 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005537 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005538 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005539 // Although we theoretically have framesIn in circular buffer, some of those are
5540 // unreleased frames, and thus must be discounted for purpose of budgeting.
5541 size_t unreleased = activeTrack->mRsmpInUnrel;
5542 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005543 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005544 ALOGV("not enough to resample: have %u frames in but need %u in to "
5545 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005546 framesIn, framesInNeeded, framesOut, in / out);
5547 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005548 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5549 if (newFramesOut == 0) {
5550 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005551 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005552 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005553 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005554 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005555 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5556 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5557 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005558 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005559 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005560 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005561 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005562 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005563 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005564 }
5565
5566 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5567 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005568 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005569 delete[] activeTrack->mRsmpOutBuffer;
5570 // resampler always outputs stereo
5571 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5572 activeTrack->mRsmpOutFrameCount = framesOut;
5573 }
5574
5575 // resampler accumulates, but we only have one source track
5576 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5577 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005578 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005579 activeTrack->mResamplerBufferProvider
5580 /*this*/ /* AudioBufferProvider* */);
5581 // ditherAndClamp() works as long as all buffers returned by
5582 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005583 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005584 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005585 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5586 framesOut);
5587 // the resampler always outputs stereo samples:
5588 // do post stereo to mono conversion
5589 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005590 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 } else {
5592 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5593 activeTrack->mRsmpOutBuffer, framesOut);
5594 }
5595 // now done with mRsmpOutBuffer
5596
5597 }
5598
5599 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5600 overrun = OVERRUN_FALSE;
5601 }
5602
5603 if (activeTrack->mFramesToDrop == 0) {
5604 if (framesOut > 0) {
5605 activeTrack->mSink.frameCount = framesOut;
5606 activeTrack->releaseBuffer(&activeTrack->mSink);
5607 }
5608 } else {
5609 // FIXME could do a partial drop of framesOut
5610 if (activeTrack->mFramesToDrop > 0) {
5611 activeTrack->mFramesToDrop -= framesOut;
5612 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005613 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005614 }
5615 } else {
5616 activeTrack->mFramesToDrop += framesOut;
5617 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5618 activeTrack->mSyncStartEvent->isCancelled()) {
5619 ALOGW("Synced record %s, session %d, trigger session %d",
5620 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5621 activeTrack->sessionId(),
5622 (activeTrack->mSyncStartEvent != 0) ?
5623 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005624 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005625 }
5626 }
5627 }
5628
5629 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005630 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005631 }
5632 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005633
5634 switch (overrun) {
5635 case OVERRUN_TRUE:
5636 // client isn't retrieving buffers fast enough
5637 if (!activeTrack->setOverflow()) {
5638 nsecs_t now = systemTime();
5639 // FIXME should lastWarning per track?
5640 if ((now - lastWarning) > kWarningThrottleNs) {
5641 ALOGW("RecordThread: buffer overflow");
5642 lastWarning = now;
5643 }
5644 }
5645 break;
5646 case OVERRUN_FALSE:
5647 activeTrack->clearOverflow();
5648 break;
5649 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 break;
5651 }
5652
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005653 }
5654
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005655unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005656 // enable changes in effect chain
5657 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005658 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005659 }
5660
Glenn Kasten93e471f2013-08-19 08:40:07 -07005661 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005662
5663 {
5664 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005665 for (size_t i = 0; i < mTracks.size(); i++) {
5666 sp<RecordTrack> track = mTracks[i];
5667 track->invalidate();
5668 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005669 mActiveTracks.clear();
5670 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005671 mStartStopCond.broadcast();
5672 }
5673
5674 releaseWakeLock();
5675
5676 ALOGV("RecordThread %p exiting", this);
5677 return false;
5678}
5679
Glenn Kasten93e471f2013-08-19 08:40:07 -07005680void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005681{
5682 if (!mStandby) {
5683 inputStandBy();
5684 mStandby = true;
5685 }
5686}
5687
5688void AudioFlinger::RecordThread::inputStandBy()
5689{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005690 // Idle the fast capture if it's currently running
5691 if (mFastCapture != 0) {
5692 FastCaptureStateQueue *sq = mFastCapture->sq();
5693 FastCaptureState *state = sq->begin();
5694 if (!(state->mCommand & FastCaptureState::IDLE)) {
5695 state->mCommand = FastCaptureState::COLD_IDLE;
5696 state->mColdFutexAddr = &mFastCaptureFutex;
5697 state->mColdGen++;
5698 mFastCaptureFutex = 0;
5699 sq->end();
5700 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5701 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5702#if 0
5703 if (kUseFastCapture == FastCapture_Dynamic) {
5704 // FIXME
5705 }
5706#endif
5707#ifdef AUDIO_WATCHDOG
5708 // FIXME
5709#endif
5710 } else {
5711 sq->end(false /*didModify*/);
5712 }
5713 }
Eric Laurent81784c32012-11-19 14:55:58 -08005714 mInput->stream->common.standby(&mInput->stream->common);
5715}
5716
Glenn Kasten05997e22014-03-13 15:08:33 -07005717// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005718sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005719 const sp<AudioFlinger::Client>& client,
5720 uint32_t sampleRate,
5721 audio_format_t format,
5722 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005723 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005724 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005725 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005726 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005727 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005728 pid_t tid,
5729 status_t *status)
5730{
Glenn Kasten74935e42013-12-19 08:56:45 -08005731 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005732 sp<RecordTrack> track;
5733 status_t lStatus;
5734
Glenn Kasten90e58b12013-07-31 16:16:02 -07005735 // client expresses a preference for FAST, but we get the final say
5736 if (*flags & IAudioFlinger::TRACK_FAST) {
5737 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005738 // use case: callback handler
5739 (tid != -1) &&
5740 // frame count is not specified, or is exactly the pipe depth
5741 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005742 // PCM data
5743 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005744 // native format
5745 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005746 // native channel mask
5747 (channelMask == mChannelMask) &&
5748 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005749 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005750 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005751 hasFastCapture() &&
5752 // there are sufficient fast track slots available
5753 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005754 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005755 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005756 frameCount, mFrameCount);
5757 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005758 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5759 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005760 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005761 frameCount, mFrameCount, mPipeFramesP2,
5762 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5763 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005764 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005765 }
5766 }
5767
5768 // compute track buffer size in frames, and suggest the notification frame count
5769 if (*flags & IAudioFlinger::TRACK_FAST) {
5770 // fast track: frame count is exactly the pipe depth
5771 frameCount = mPipeFramesP2;
5772 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5773 *notificationFrames = mFrameCount;
5774 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005775 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5776 // or 20 ms if there is a fast capture
5777 // TODO This could be a roundupRatio inline, and const
5778 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5779 * sampleRate + mSampleRate - 1) / mSampleRate;
5780 // minimum number of notification periods is at least kMinNotifications,
5781 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5782 static const size_t kMinNotifications = 3;
5783 static const uint32_t kMinMs = 30;
5784 // TODO This could be a roundupRatio inline
5785 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5786 // TODO This could be a roundupRatio inline
5787 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5788 maxNotificationFrames;
5789 const size_t minFrameCount = maxNotificationFrames *
5790 max(kMinNotifications, minNotificationsByMs);
5791 frameCount = max(frameCount, minFrameCount);
5792 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5793 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005794 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005795 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005796 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005797
Glenn Kasten15e57982013-09-24 11:52:37 -07005798 lStatus = initCheck();
5799 if (lStatus != NO_ERROR) {
5800 ALOGE("createRecordTrack_l() audio driver not initialized");
5801 goto Exit;
5802 }
Eric Laurent81784c32012-11-19 14:55:58 -08005803
5804 { // scope for mLock
5805 Mutex::Autolock _l(mLock);
5806
5807 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005808 format, channelMask, frameCount, NULL, sessionId, uid,
5809 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005810
Glenn Kasten03003332013-08-06 15:40:54 -07005811 lStatus = track->initCheck();
5812 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005813 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005814 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005815 goto Exit;
5816 }
5817 mTracks.add(track);
5818
5819 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5820 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5821 mAudioFlinger->btNrecIsOff();
5822 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5823 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005824
5825 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5826 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5827 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5828 // so ask activity manager to do this on our behalf
5829 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5830 }
Eric Laurent81784c32012-11-19 14:55:58 -08005831 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005832
Eric Laurent81784c32012-11-19 14:55:58 -08005833 lStatus = NO_ERROR;
5834
5835Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005836 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005837 return track;
5838}
5839
5840status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5841 AudioSystem::sync_event_t event,
5842 int triggerSession)
5843{
5844 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5845 sp<ThreadBase> strongMe = this;
5846 status_t status = NO_ERROR;
5847
5848 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005849 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005850 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005851 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005852 triggerSession,
5853 recordTrack->sessionId(),
5854 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005855 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005856 // Sync event can be cancelled by the trigger session if the track is not in a
5857 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005859 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005860 } else {
5861 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005862 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005863 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005864 }
5865 }
5866
5867 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005868 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005869 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005870 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5871 if (recordTrack->mState == TrackBase::PAUSING) {
5872 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005873 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005874 } else {
5875 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
5877 return status;
5878 }
5879
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005880 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5881 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5882 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005883 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005884 mActiveTracks.add(recordTrack);
5885 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005886 status_t status = NO_ERROR;
5887 if (recordTrack->isExternalTrack()) {
5888 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005889 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005890 mLock.lock();
5891 // FIXME should verify that recordTrack is still in mActiveTracks
5892 if (status != NO_ERROR) {
5893 mActiveTracks.remove(recordTrack);
5894 mActiveTracksGen++;
5895 recordTrack->clearSyncStartEvent();
5896 ALOGV("RecordThread::start error %d", status);
5897 return status;
5898 }
Eric Laurent81784c32012-11-19 14:55:58 -08005899 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005900 // Catch up with current buffer indices if thread is already running.
5901 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5902 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5903 // see previously buffered data before it called start(), but with greater risk of overrun.
5904
5905 recordTrack->mRsmpInFront = mRsmpInRear;
5906 recordTrack->mRsmpInUnrel = 0;
5907 // FIXME why reset?
5908 if (recordTrack->mResampler != NULL) {
5909 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005910 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005911 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005912 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005913 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005914 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005915 ALOGV("Record failed to start");
5916 status = BAD_VALUE;
5917 goto startError;
5918 }
Eric Laurent81784c32012-11-19 14:55:58 -08005919 return status;
5920 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005921
Eric Laurent81784c32012-11-19 14:55:58 -08005922startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005923 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005924 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005925 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005926 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005928 return status;
5929}
5930
Eric Laurent81784c32012-11-19 14:55:58 -08005931void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5932{
5933 sp<SyncEvent> strongEvent = event.promote();
5934
5935 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005936 sp<RefBase> ptr = strongEvent->cookie().promote();
5937 if (ptr != 0) {
5938 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5939 recordTrack->handleSyncStartEvent(strongEvent);
5940 }
Eric Laurent81784c32012-11-19 14:55:58 -08005941 }
5942}
5943
Glenn Kastena8356f62013-07-25 14:37:52 -07005944bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005945 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005946 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005947 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005948 return false;
5949 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005950 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005951 recordTrack->mState = TrackBase::PAUSING;
5952 // do not wait for mStartStopCond if exiting
5953 if (exitPending()) {
5954 return true;
5955 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005956 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005957 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005958 // if we have been restarted, recordTrack is in mActiveTracks here
5959 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005960 ALOGV("Record stopped OK");
5961 return true;
5962 }
5963 return false;
5964}
5965
Glenn Kasten0f11b512014-01-31 16:18:54 -08005966bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005967{
5968 return false;
5969}
5970
Glenn Kasten0f11b512014-01-31 16:18:54 -08005971status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005972{
5973#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5974 if (!isValidSyncEvent(event)) {
5975 return BAD_VALUE;
5976 }
5977
5978 int eventSession = event->triggerSession();
5979 status_t ret = NAME_NOT_FOUND;
5980
5981 Mutex::Autolock _l(mLock);
5982
5983 for (size_t i = 0; i < mTracks.size(); i++) {
5984 sp<RecordTrack> track = mTracks[i];
5985 if (eventSession == track->sessionId()) {
5986 (void) track->setSyncEvent(event);
5987 ret = NO_ERROR;
5988 }
5989 }
5990 return ret;
5991#else
5992 return BAD_VALUE;
5993#endif
5994}
5995
5996// destroyTrack_l() must be called with ThreadBase::mLock held
5997void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5998{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005999 track->terminate();
6000 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006001 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006002 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006003 removeTrack_l(track);
6004 }
6005}
6006
6007void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6008{
6009 mTracks.remove(track);
6010 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006011 if (track->isFastTrack()) {
6012 ALOG_ASSERT(!mFastTrackAvail);
6013 mFastTrackAvail = true;
6014 }
Eric Laurent81784c32012-11-19 14:55:58 -08006015}
6016
6017void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6018{
6019 dumpInternals(fd, args);
6020 dumpTracks(fd, args);
6021 dumpEffectChains(fd, args);
6022}
6023
6024void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6025{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006026 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006027
Glenn Kasten2b806402013-11-20 16:37:38 -08006028 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006029 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006030 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006031 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006032 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006033 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006034 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006035
Eric Laurent81784c32012-11-19 14:55:58 -08006036 dumpBase(fd, args);
6037}
6038
Glenn Kasten0f11b512014-01-31 16:18:54 -08006039void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006040{
6041 const size_t SIZE = 256;
6042 char buffer[SIZE];
6043 String8 result;
6044
Marco Nelissenb2208842014-02-07 14:00:50 -08006045 size_t numtracks = mTracks.size();
6046 size_t numactive = mActiveTracks.size();
6047 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006048 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006049 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006050 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006051 RecordTrack::appendDumpHeader(result);
6052 for (size_t i = 0; i < numtracks ; ++i) {
6053 sp<RecordTrack> track = mTracks[i];
6054 if (track != 0) {
6055 bool active = mActiveTracks.indexOf(track) >= 0;
6056 if (active) {
6057 numactiveseen++;
6058 }
6059 track->dump(buffer, SIZE, active);
6060 result.append(buffer);
6061 }
Eric Laurent81784c32012-11-19 14:55:58 -08006062 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006063 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006064 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006065 }
6066
Marco Nelissenb2208842014-02-07 14:00:50 -08006067 if (numactiveseen != numactive) {
6068 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6069 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006070 result.append(buffer);
6071 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006072 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006073 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006074 if (mTracks.indexOf(track) < 0) {
6075 track->dump(buffer, SIZE, true);
6076 result.append(buffer);
6077 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006078 }
Eric Laurent81784c32012-11-19 14:55:58 -08006079
6080 }
6081 write(fd, result.string(), result.size());
6082}
6083
6084// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6086 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006087{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006088 RecordTrack *activeTrack = mRecordTrack;
6089 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6090 if (threadBase == 0) {
6091 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006092 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006093 return NOT_ENOUGH_DATA;
6094 }
6095 RecordThread *recordThread = (RecordThread *) threadBase.get();
6096 int32_t rear = recordThread->mRsmpInRear;
6097 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006098 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006099 // FIXME should not be P2 (don't want to increase latency)
6100 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006101 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006102 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 front &= recordThread->mRsmpInFramesP2 - 1;
6104 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006105 if (part1 > (size_t) filled) {
6106 part1 = filled;
6107 }
6108 size_t ask = buffer->frameCount;
6109 ALOG_ASSERT(ask > 0);
6110 if (part1 > ask) {
6111 part1 = ask;
6112 }
6113 if (part1 == 0) {
6114 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006115 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006116 buffer->raw = NULL;
6117 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006118 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006119 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006120 }
6121
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006123 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006125 return NO_ERROR;
6126}
6127
6128// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6130 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006131{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006133 size_t stepCount = buffer->frameCount;
6134 if (stepCount == 0) {
6135 return;
6136 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006137 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6138 activeTrack->mRsmpInUnrel -= stepCount;
6139 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006140 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006141 buffer->frameCount = 0;
6142}
6143
Eric Laurent10351942014-05-08 18:49:52 -07006144bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6145 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006146{
6147 bool reconfig = false;
6148
Eric Laurent10351942014-05-08 18:49:52 -07006149 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006150
Eric Laurent10351942014-05-08 18:49:52 -07006151 audio_format_t reqFormat = mFormat;
6152 uint32_t samplingRate = mSampleRate;
6153 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6154
6155 AudioParameter param = AudioParameter(keyValuePair);
6156 int value;
6157 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6158 // channel count change can be requested. Do we mandate the first client defines the
6159 // HAL sampling rate and channel count or do we allow changes on the fly?
6160 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6161 samplingRate = value;
6162 reconfig = true;
6163 }
6164 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6165 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6166 status = BAD_VALUE;
6167 } else {
6168 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006169 reconfig = true;
6170 }
Eric Laurent10351942014-05-08 18:49:52 -07006171 }
6172 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6173 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6174 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6175 status = BAD_VALUE;
6176 } else {
6177 channelMask = mask;
6178 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006179 }
Eric Laurent10351942014-05-08 18:49:52 -07006180 }
6181 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6182 // do not accept frame count changes if tracks are open as the track buffer
6183 // size depends on frame count and correct behavior would not be guaranteed
6184 // if frame count is changed after track creation
6185 if (mActiveTracks.size() > 0) {
6186 status = INVALID_OPERATION;
6187 } else {
6188 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006189 }
Eric Laurent10351942014-05-08 18:49:52 -07006190 }
6191 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6192 // forward device change to effects that have requested to be
6193 // aware of attached audio device.
6194 for (size_t i = 0; i < mEffectChains.size(); i++) {
6195 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006196 }
Eric Laurent81784c32012-11-19 14:55:58 -08006197
Eric Laurent10351942014-05-08 18:49:52 -07006198 // store input device and output device but do not forward output device to audio HAL.
6199 // Note that status is ignored by the caller for output device
6200 // (see AudioFlinger::setParameters()
6201 if (audio_is_output_devices(value)) {
6202 mOutDevice = value;
6203 status = BAD_VALUE;
6204 } else {
6205 mInDevice = value;
6206 // disable AEC and NS if the device is a BT SCO headset supporting those
6207 // pre processings
6208 if (mTracks.size() > 0) {
6209 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6210 mAudioFlinger->btNrecIsOff();
6211 for (size_t i = 0; i < mTracks.size(); i++) {
6212 sp<RecordTrack> track = mTracks[i];
6213 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6214 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006215 }
6216 }
6217 }
Eric Laurent10351942014-05-08 18:49:52 -07006218 }
6219 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6220 mAudioSource != (audio_source_t)value) {
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]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
Eric Laurent10351942014-05-08 18:49:52 -07006226 mAudioSource = (audio_source_t)value;
6227 }
Glenn Kastene198c362013-08-13 09:13:36 -07006228
Eric Laurent10351942014-05-08 18:49:52 -07006229 if (status == NO_ERROR) {
6230 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6231 keyValuePair.string());
6232 if (status == INVALID_OPERATION) {
6233 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006234 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6235 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006236 }
6237 if (reconfig) {
6238 if (status == BAD_VALUE &&
6239 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6240 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6241 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6242 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006243 audio_channel_count_from_in_mask(
6244 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006245 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6246 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6247 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
Eric Laurent10351942014-05-08 18:49:52 -07006249 if (status == NO_ERROR) {
6250 readInputParameters_l();
6251 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006252 }
6253 }
Eric Laurent81784c32012-11-19 14:55:58 -08006254 }
Eric Laurent10351942014-05-08 18:49:52 -07006255
Eric Laurent81784c32012-11-19 14:55:58 -08006256 return reconfig;
6257}
6258
6259String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6260{
Eric Laurent81784c32012-11-19 14:55:58 -08006261 Mutex::Autolock _l(mLock);
6262 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006263 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006264 }
6265
Glenn Kastend8ea6992013-07-16 14:17:15 -07006266 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6267 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006268 free(s);
6269 return out_s8;
6270}
6271
Eric Laurent021cf962014-05-13 10:18:14 -07006272void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006273 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006274 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006275
6276 switch (event) {
6277 case AudioSystem::INPUT_OPENED:
6278 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006279 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006280 desc.samplingRate = mSampleRate;
6281 desc.format = mFormat;
6282 desc.frameCount = mFrameCount;
6283 desc.latency = 0;
6284 param2 = &desc;
6285 break;
6286
6287 case AudioSystem::INPUT_CLOSED:
6288 default:
6289 break;
6290 }
Eric Laurent021cf962014-05-13 10:18:14 -07006291 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006292}
6293
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006294void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
Eric Laurent81784c32012-11-19 14:55:58 -08006296 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6297 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006298 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006299 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6300 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006301 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006302 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006303 }
Eric Laurent665470b2014-07-03 16:37:08 -07006304 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006305 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6306 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006308 // 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 -07006309 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006310 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 // A larger value should allow more old data to be read after a track calls start(),
6312 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006313 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006314 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006315 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006316
6317 // TODO optimize audio capture buffer sizes ...
6318 // Here we calculate the size of the sliding buffer used as a source
6319 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6320 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6321 // be better to have it derived from the pipe depth in the long term.
6322 // The current value is higher than necessary. However it should not add to latency.
6323
Glenn Kasten85948432013-08-19 12:09:05 -07006324 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6325 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006326
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006327 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6328 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006329}
6330
Glenn Kasten5f972c02014-01-13 09:59:31 -08006331uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006332{
6333 Mutex::Autolock _l(mLock);
6334 if (initCheck() != NO_ERROR) {
6335 return 0;
6336 }
6337
6338 return mInput->stream->get_input_frames_lost(mInput->stream);
6339}
6340
6341uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6342{
6343 Mutex::Autolock _l(mLock);
6344 uint32_t result = 0;
6345 if (getEffectChain_l(sessionId) != 0) {
6346 result = EFFECT_SESSION;
6347 }
6348
6349 for (size_t i = 0; i < mTracks.size(); ++i) {
6350 if (sessionId == mTracks[i]->sessionId()) {
6351 result |= TRACK_SESSION;
6352 break;
6353 }
6354 }
6355
6356 return result;
6357}
6358
6359KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6360{
6361 KeyedVector<int, bool> ids;
6362 Mutex::Autolock _l(mLock);
6363 for (size_t j = 0; j < mTracks.size(); ++j) {
6364 sp<RecordThread::RecordTrack> track = mTracks[j];
6365 int sessionId = track->sessionId();
6366 if (ids.indexOfKey(sessionId) < 0) {
6367 ids.add(sessionId, true);
6368 }
6369 }
6370 return ids;
6371}
6372
6373AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6374{
6375 Mutex::Autolock _l(mLock);
6376 AudioStreamIn *input = mInput;
6377 mInput = NULL;
6378 return input;
6379}
6380
6381// this method must always be called either with ThreadBase mLock held or inside the thread loop
6382audio_stream_t* AudioFlinger::RecordThread::stream() const
6383{
6384 if (mInput == NULL) {
6385 return NULL;
6386 }
6387 return &mInput->stream->common;
6388}
6389
6390status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6391{
6392 // only one chain per input thread
6393 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006394 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006395 return INVALID_OPERATION;
6396 }
6397 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006398 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006399 chain->setInBuffer(NULL);
6400 chain->setOutBuffer(NULL);
6401
6402 checkSuspendOnAddEffectChain_l(chain);
6403
Eric Laurent1b928682014-10-02 19:41:47 -07006404 // make sure enabled pre processing effects state is communicated to the HAL as we
6405 // just moved them to a new input stream.
6406 chain->syncHalEffectsState();
6407
Eric Laurent81784c32012-11-19 14:55:58 -08006408 mEffectChains.add(chain);
6409
6410 return NO_ERROR;
6411}
6412
6413size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6414{
6415 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6416 ALOGW_IF(mEffectChains.size() != 1,
6417 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6418 chain.get(), mEffectChains.size(), this);
6419 if (mEffectChains.size() == 1) {
6420 mEffectChains.removeAt(0);
6421 }
6422 return 0;
6423}
6424
Eric Laurent1c333e22014-05-20 10:48:17 -07006425status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6426 audio_patch_handle_t *handle)
6427{
6428 status_t status = NO_ERROR;
6429 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6430 // store new device and send to effects
6431 mInDevice = patch->sources[0].ext.device.type;
6432 for (size_t i = 0; i < mEffectChains.size(); i++) {
6433 mEffectChains[i]->setDevice_l(mInDevice);
6434 }
6435
6436 // disable AEC and NS if the device is a BT SCO headset supporting those
6437 // pre processings
6438 if (mTracks.size() > 0) {
6439 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6440 mAudioFlinger->btNrecIsOff();
6441 for (size_t i = 0; i < mTracks.size(); i++) {
6442 sp<RecordTrack> track = mTracks[i];
6443 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6444 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6445 }
6446 }
6447
6448 // store new source and send to effects
6449 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6450 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6451 for (size_t i = 0; i < mEffectChains.size(); i++) {
6452 mEffectChains[i]->setAudioSource_l(mAudioSource);
6453 }
6454 }
6455
6456 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6457 status = hwDevice->create_audio_patch(hwDevice,
6458 patch->num_sources,
6459 patch->sources,
6460 patch->num_sinks,
6461 patch->sinks,
6462 handle);
6463 } else {
6464 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6465 }
6466 return status;
6467}
6468
6469status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6470{
6471 status_t status = NO_ERROR;
6472 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6473 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6474 status = hwDevice->release_audio_patch(hwDevice, handle);
6475 } else {
6476 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6477 }
6478 return status;
6479}
6480
Eric Laurent83b88082014-06-20 18:31:16 -07006481void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6482{
6483 Mutex::Autolock _l(mLock);
6484 mTracks.add(record);
6485}
6486
6487void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6488{
6489 Mutex::Autolock _l(mLock);
6490 destroyTrack_l(record);
6491}
6492
6493void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6494{
6495 ThreadBase::getAudioPortConfig(config);
6496 config->role = AUDIO_PORT_ROLE_SINK;
6497 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6498 config->ext.mix.usecase.source = mAudioSource;
6499}
Eric Laurent1c333e22014-05-20 10:48:17 -07006500
Eric Laurent81784c32012-11-19 14:55:58 -08006501}; // namespace android