blob: 15dd4080c93bfa10cb4e32777229aaf80a459019 [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 Hungfbfc3952015-01-15 13:33:51 -08001939 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
1940 // For best precision, we use float instead of the associated output
1941 // device format (typically PCM 16 bit).
1942
1943 mFormat = AUDIO_FORMAT_PCM_FLOAT;
1944 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
1945 mBufferSize = mFrameSize * mFrameCount;
1946
1947 // TODO: We currently use the associated output device channel mask and sample rate.
1948 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
1949 // (if a valid mask) to avoid premature downmix.
1950 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
1951 // instead of the output device sample rate to avoid loss of high frequency information.
1952 // This may need to be updated as MixerThread/OutputTracks are added and not here.
1953 }
1954
Andy Hung09a50072014-02-27 14:30:47 -08001955 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001956 double multiplier = 1.0;
1957 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1958 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001959 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1960 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001961 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1962 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1963 maxNormalFrameCount = maxNormalFrameCount & ~15;
1964 if (maxNormalFrameCount < minNormalFrameCount) {
1965 maxNormalFrameCount = minNormalFrameCount;
1966 }
1967 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1968 if (multiplier <= 1.0) {
1969 multiplier = 1.0;
1970 } else if (multiplier <= 2.0) {
1971 if (2 * mFrameCount <= maxNormalFrameCount) {
1972 multiplier = 2.0;
1973 } else {
1974 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1975 }
1976 } else {
1977 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001978 // 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 -08001979 // track, but we sometimes have to do this to satisfy the maximum frame count
1980 // constraint)
1981 // FIXME this rounding up should not be done if no HAL SRC
1982 uint32_t truncMult = (uint32_t) multiplier;
1983 if ((truncMult & 1)) {
1984 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1985 ++truncMult;
1986 }
1987 }
1988 multiplier = (double) truncMult;
1989 }
1990 }
1991 mNormalFrameCount = multiplier * mFrameCount;
1992 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001993 if (mType == MIXER || mType == DUPLICATING) {
1994 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1995 }
Andy Hung09a50072014-02-27 14:30:47 -08001996 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001997 mNormalFrameCount);
1998
Andy Hung010a1a12014-03-13 13:57:33 -07001999 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2000 // Originally this was int16_t[] array, need to remove legacy implications.
2001 free(mSinkBuffer);
2002 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002003 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2004 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2005 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002006 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002007
Andy Hung69aed5f2014-02-25 17:24:40 -08002008 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2009 // drives the output.
2010 free(mMixerBuffer);
2011 mMixerBuffer = NULL;
2012 if (mMixerBufferEnabled) {
2013 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2014 mMixerBufferSize = mNormalFrameCount * mChannelCount
2015 * audio_bytes_per_sample(mMixerBufferFormat);
2016 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2017 }
Andy Hung98ef9782014-03-04 14:46:50 -08002018 free(mEffectBuffer);
2019 mEffectBuffer = NULL;
2020 if (mEffectBufferEnabled) {
2021 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2022 mEffectBufferSize = mNormalFrameCount * mChannelCount
2023 * audio_bytes_per_sample(mEffectBufferFormat);
2024 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2025 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002026
Eric Laurent81784c32012-11-19 14:55:58 -08002027 // force reconfiguration of effect chains and engines to take new buffer size and audio
2028 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002029 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002030 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2031 // matter.
2032 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2033 Vector< sp<EffectChain> > effectChains = mEffectChains;
2034 for (size_t i = 0; i < effectChains.size(); i ++) {
2035 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2036 }
2037}
2038
2039
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002040status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002041{
2042 if (halFrames == NULL || dspFrames == NULL) {
2043 return BAD_VALUE;
2044 }
2045 Mutex::Autolock _l(mLock);
2046 if (initCheck() != NO_ERROR) {
2047 return INVALID_OPERATION;
2048 }
2049 size_t framesWritten = mBytesWritten / mFrameSize;
2050 *halFrames = framesWritten;
2051
2052 if (isSuspended()) {
2053 // return an estimation of rendered frames when the output is suspended
2054 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2055 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2056 return NO_ERROR;
2057 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002058 status_t status;
2059 uint32_t frames;
2060 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2061 *dspFrames = (size_t)frames;
2062 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002063 }
2064}
2065
2066uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2067{
2068 Mutex::Autolock _l(mLock);
2069 uint32_t result = 0;
2070 if (getEffectChain_l(sessionId) != 0) {
2071 result = EFFECT_SESSION;
2072 }
2073
2074 for (size_t i = 0; i < mTracks.size(); ++i) {
2075 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002076 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002077 result |= TRACK_SESSION;
2078 break;
2079 }
2080 }
2081
2082 return result;
2083}
2084
2085uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2086{
2087 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2088 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2089 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2090 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2091 }
2092 for (size_t i = 0; i < mTracks.size(); i++) {
2093 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002094 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002095 return AudioSystem::getStrategyForStream(track->streamType());
2096 }
2097 }
2098 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2099}
2100
2101
2102AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2103{
2104 Mutex::Autolock _l(mLock);
2105 return mOutput;
2106}
2107
2108AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2109{
2110 Mutex::Autolock _l(mLock);
2111 AudioStreamOut *output = mOutput;
2112 mOutput = NULL;
2113 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2114 // must push a NULL and wait for ack
2115 mOutputSink.clear();
2116 mPipeSink.clear();
2117 mNormalSink.clear();
2118 return output;
2119}
2120
2121// this method must always be called either with ThreadBase mLock held or inside the thread loop
2122audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2123{
2124 if (mOutput == NULL) {
2125 return NULL;
2126 }
2127 return &mOutput->stream->common;
2128}
2129
2130uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2131{
2132 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2133}
2134
2135status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2136{
2137 if (!isValidSyncEvent(event)) {
2138 return BAD_VALUE;
2139 }
2140
2141 Mutex::Autolock _l(mLock);
2142
2143 for (size_t i = 0; i < mTracks.size(); ++i) {
2144 sp<Track> track = mTracks[i];
2145 if (event->triggerSession() == track->sessionId()) {
2146 (void) track->setSyncEvent(event);
2147 return NO_ERROR;
2148 }
2149 }
2150
2151 return NAME_NOT_FOUND;
2152}
2153
2154bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2155{
2156 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2157}
2158
2159void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2160 const Vector< sp<Track> >& tracksToRemove)
2161{
2162 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002163 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002164 for (size_t i = 0 ; i < count ; i++) {
2165 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002166 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002167 AudioSystem::stopOutput(mId, track->streamType(),
2168 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169#ifdef ADD_BATTERY_DATA
2170 // to track the speaker usage
2171 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2172#endif
2173 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002174 AudioSystem::releaseOutput(mId, track->streamType(),
2175 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176 }
Eric Laurent81784c32012-11-19 14:55:58 -08002177 }
2178 }
2179 }
Eric Laurent81784c32012-11-19 14:55:58 -08002180}
2181
2182void AudioFlinger::PlaybackThread::checkSilentMode_l()
2183{
2184 if (!mMasterMute) {
2185 char value[PROPERTY_VALUE_MAX];
2186 if (property_get("ro.audio.silent", value, "0") > 0) {
2187 char *endptr;
2188 unsigned long ul = strtoul(value, &endptr, 0);
2189 if (*endptr == '\0' && ul != 0) {
2190 ALOGD("Silence is golden");
2191 // The setprop command will not allow a property to be changed after
2192 // the first time it is set, so we don't have to worry about un-muting.
2193 setMasterMute_l(true);
2194 }
2195 }
2196 }
2197}
2198
2199// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002201{
2202 // FIXME rewrite to reduce number of system calls
2203 mLastWriteTime = systemTime();
2204 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002205 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002206 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002207
2208 // If an NBAIO sink is present, use it to write the normal mixer's submix
2209 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002210
Andy Hung010a1a12014-03-13 13:57:33 -07002211 const size_t count = mBytesRemaining / mFrameSize;
2212
Simon Wilson2d590962012-11-29 15:18:50 -08002213 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002214 // update the setpoint when AudioFlinger::mScreenState changes
2215 uint32_t screenState = AudioFlinger::mScreenState;
2216 if (screenState != mScreenState) {
2217 mScreenState = screenState;
2218 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2219 if (pipe != NULL) {
2220 pipe->setAvgFrames((mScreenState & 1) ?
2221 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2222 }
2223 }
Andy Hung010a1a12014-03-13 13:57:33 -07002224 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002225 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002226 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002227 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002228 } else {
2229 bytesWritten = framesWritten;
2230 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002231 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002232 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002233 if (status == NO_ERROR) {
2234 size_t totalFramesWritten = mNormalSink->framesWritten();
2235 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2236 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002237 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002238 mLatchDValid = true;
2239 }
2240 }
Eric Laurent81784c32012-11-19 14:55:58 -08002241 // otherwise use the HAL / AudioStreamOut directly
2242 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002244
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002246 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2247 mWriteAckSequence += 2;
2248 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002250 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002252 // FIXME We should have an implementation of timestamps for direct output threads.
2253 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002255 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002256 if (mUseAsyncWrite &&
2257 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2258 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002259 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002261 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262 }
Eric Laurent81784c32012-11-19 14:55:58 -08002263 }
2264
Eric Laurent81784c32012-11-19 14:55:58 -08002265 mNumWrites++;
2266 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002267 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268 return bytesWritten;
2269}
2270
2271void AudioFlinger::PlaybackThread::threadLoop_drain()
2272{
2273 if (mOutput->stream->drain) {
2274 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2275 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002276 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2277 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002279 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280 }
2281 mOutput->stream->drain(mOutput->stream,
2282 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2283 : AUDIO_DRAIN_ALL);
2284 }
2285}
2286
2287void AudioFlinger::PlaybackThread::threadLoop_exit()
2288{
Eric Laurent275e8e92014-11-30 15:14:47 -08002289 {
2290 Mutex::Autolock _l(mLock);
2291 for (size_t i = 0; i < mTracks.size(); i++) {
2292 sp<Track> track = mTracks[i];
2293 track->invalidate();
2294 }
2295 }
Eric Laurent81784c32012-11-19 14:55:58 -08002296}
2297
2298/*
2299The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002300 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002301 - activeSleepTime from activeSleepTimeUs()
2302 - idleSleepTime from idleSleepTimeUs()
2303 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2304 - maxPeriod from frame count and sample rate (MIXER only)
2305
2306The parameters that affect these derived values are:
2307 - frame count
2308 - frame size
2309 - sample rate
2310 - device type: A2DP or not
2311 - device latency
2312 - format: PCM or not
2313 - active sleep time
2314 - idle sleep time
2315*/
2316
2317void AudioFlinger::PlaybackThread::cacheParameters_l()
2318{
Andy Hung25c2dac2014-02-27 14:56:00 -08002319 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002320 activeSleepTime = activeSleepTimeUs();
2321 idleSleepTime = idleSleepTimeUs();
2322}
2323
2324void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2325{
Glenn Kasten7c027242012-12-26 14:43:16 -08002326 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002327 this, streamType, mTracks.size());
2328 Mutex::Autolock _l(mLock);
2329
2330 size_t size = mTracks.size();
2331 for (size_t i = 0; i < size; i++) {
2332 sp<Track> t = mTracks[i];
2333 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002334 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002335 }
2336 }
2337}
2338
2339status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2340{
2341 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002342 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2343 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002344 bool ownsBuffer = false;
2345
2346 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2347 if (session > 0) {
2348 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002349 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002350 if (mType != DIRECT) {
2351 size_t numSamples = mNormalFrameCount * mChannelCount;
2352 buffer = new int16_t[numSamples];
2353 memset(buffer, 0, numSamples * sizeof(int16_t));
2354 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2355 ownsBuffer = true;
2356 }
2357
2358 // Attach all tracks with same session ID to this chain.
2359 for (size_t i = 0; i < mTracks.size(); ++i) {
2360 sp<Track> track = mTracks[i];
2361 if (session == track->sessionId()) {
2362 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2363 buffer);
2364 track->setMainBuffer(buffer);
2365 chain->incTrackCnt();
2366 }
2367 }
2368
2369 // indicate all active tracks in the chain
2370 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2371 sp<Track> track = mActiveTracks[i].promote();
2372 if (track == 0) {
2373 continue;
2374 }
2375 if (session == track->sessionId()) {
2376 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2377 chain->incActiveTrackCnt();
2378 }
2379 }
2380 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002381 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002382 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002383 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2384 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002385 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2386 // chains list in order to be processed last as it contains output stage effects
2387 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2388 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2389 // after track specific effects and before output stage
2390 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2391 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2392 // Effect chain for other sessions are inserted at beginning of effect
2393 // chains list to be processed before output mix effects. Relative order between other
2394 // sessions is not important
2395 size_t size = mEffectChains.size();
2396 size_t i = 0;
2397 for (i = 0; i < size; i++) {
2398 if (mEffectChains[i]->sessionId() < session) {
2399 break;
2400 }
2401 }
2402 mEffectChains.insertAt(chain, i);
2403 checkSuspendOnAddEffectChain_l(chain);
2404
2405 return NO_ERROR;
2406}
2407
2408size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2409{
2410 int session = chain->sessionId();
2411
2412 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2413
2414 for (size_t i = 0; i < mEffectChains.size(); i++) {
2415 if (chain == mEffectChains[i]) {
2416 mEffectChains.removeAt(i);
2417 // detach all active tracks from the chain
2418 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2419 sp<Track> track = mActiveTracks[i].promote();
2420 if (track == 0) {
2421 continue;
2422 }
2423 if (session == track->sessionId()) {
2424 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2425 chain.get(), session);
2426 chain->decActiveTrackCnt();
2427 }
2428 }
2429
2430 // detach all tracks with same session ID from this chain
2431 for (size_t i = 0; i < mTracks.size(); ++i) {
2432 sp<Track> track = mTracks[i];
2433 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002434 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002435 chain->decTrackCnt();
2436 }
2437 }
2438 break;
2439 }
2440 }
2441 return mEffectChains.size();
2442}
2443
2444status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2445 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2446{
2447 Mutex::Autolock _l(mLock);
2448 return attachAuxEffect_l(track, EffectId);
2449}
2450
2451status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2452 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2453{
2454 status_t status = NO_ERROR;
2455
2456 if (EffectId == 0) {
2457 track->setAuxBuffer(0, NULL);
2458 } else {
2459 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2460 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2461 if (effect != 0) {
2462 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2463 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2464 } else {
2465 status = INVALID_OPERATION;
2466 }
2467 } else {
2468 status = BAD_VALUE;
2469 }
2470 }
2471 return status;
2472}
2473
2474void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2475{
2476 for (size_t i = 0; i < mTracks.size(); ++i) {
2477 sp<Track> track = mTracks[i];
2478 if (track->auxEffectId() == effectId) {
2479 attachAuxEffect_l(track, 0);
2480 }
2481 }
2482}
2483
2484bool AudioFlinger::PlaybackThread::threadLoop()
2485{
2486 Vector< sp<Track> > tracksToRemove;
2487
2488 standbyTime = systemTime();
2489
2490 // MIXER
2491 nsecs_t lastWarning = 0;
2492
2493 // DUPLICATING
2494 // FIXME could this be made local to while loop?
2495 writeFrames = 0;
2496
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002497 int lastGeneration = 0;
2498
Eric Laurent81784c32012-11-19 14:55:58 -08002499 cacheParameters_l();
2500 sleepTime = idleSleepTime;
2501
2502 if (mType == MIXER) {
2503 sleepTimeShift = 0;
2504 }
2505
2506 CpuStats cpuStats;
2507 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2508
2509 acquireWakeLock();
2510
Glenn Kasten9e58b552013-01-18 15:09:48 -08002511 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2512 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2513 // and then that string will be logged at the next convenient opportunity.
2514 const char *logString = NULL;
2515
Eric Laurent664539d2013-09-23 18:24:31 -07002516 checkSilentMode_l();
2517
Eric Laurent81784c32012-11-19 14:55:58 -08002518 while (!exitPending())
2519 {
2520 cpuStats.sample(myName);
2521
2522 Vector< sp<EffectChain> > effectChains;
2523
Eric Laurent81784c32012-11-19 14:55:58 -08002524 { // scope for mLock
2525
2526 Mutex::Autolock _l(mLock);
2527
Eric Laurent021cf962014-05-13 10:18:14 -07002528 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002529
Glenn Kasten9e58b552013-01-18 15:09:48 -08002530 if (logString != NULL) {
2531 mNBLogWriter->logTimestamp();
2532 mNBLogWriter->log(logString);
2533 logString = NULL;
2534 }
2535
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002536 // Gather the framesReleased counters for all active tracks,
2537 // and latch them atomically with the timestamp.
2538 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2539 mLatchD.mFramesReleased.clear();
2540 size_t size = mActiveTracks.size();
2541 for (size_t i = 0; i < size; i++) {
2542 sp<Track> t = mActiveTracks[i].promote();
2543 if (t != 0) {
2544 mLatchD.mFramesReleased.add(t.get(),
2545 t->mAudioTrackServerProxy->framesReleased());
2546 }
2547 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002548 if (mLatchDValid) {
2549 mLatchQ = mLatchD;
2550 mLatchDValid = false;
2551 mLatchQValid = true;
2552 }
2553
Eric Laurent81784c32012-11-19 14:55:58 -08002554 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002555 if (mSignalPending) {
2556 // A signal was raised while we were unlocked
2557 mSignalPending = false;
2558 } else if (waitingAsyncCallback_l()) {
2559 if (exitPending()) {
2560 break;
2561 }
2562 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002563 mWakeLockUids.clear();
2564 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 ALOGV("wait async completion");
2566 mWaitWorkCV.wait(mLock);
2567 ALOGV("async completion/wake");
2568 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002569 standbyTime = systemTime() + standbyDelay;
2570 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002571
2572 continue;
2573 }
2574 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 isSuspended()) {
2576 // put audio hardware into standby after short delay
2577 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578
2579 threadLoop_standby();
2580
2581 mStandby = true;
2582 }
2583
2584 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2585 // we're about to wait, flush the binder command buffer
2586 IPCThreadState::self()->flushCommands();
2587
2588 clearOutputTracks();
2589
2590 if (exitPending()) {
2591 break;
2592 }
2593
2594 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002595 mWakeLockUids.clear();
2596 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002597 // wait until we have something to do...
2598 ALOGV("%s going to sleep", myName.string());
2599 mWaitWorkCV.wait(mLock);
2600 ALOGV("%s waking up", myName.string());
2601 acquireWakeLock_l();
2602
2603 mMixerStatus = MIXER_IDLE;
2604 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2605 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002607 checkSilentMode_l();
2608
2609 standbyTime = systemTime() + standbyDelay;
2610 sleepTime = idleSleepTime;
2611 if (mType == MIXER) {
2612 sleepTimeShift = 0;
2613 }
2614
2615 continue;
2616 }
2617 }
Eric Laurent81784c32012-11-19 14:55:58 -08002618 // mMixerStatusIgnoringFastTracks is also updated internally
2619 mMixerStatus = prepareTracks_l(&tracksToRemove);
2620
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002621 // compare with previously applied list
2622 if (lastGeneration != mActiveTracksGeneration) {
2623 // update wakelock
2624 updateWakeLockUids_l(mWakeLockUids);
2625 lastGeneration = mActiveTracksGeneration;
2626 }
2627
Eric Laurent81784c32012-11-19 14:55:58 -08002628 // prevent any changes in effect chain list and in each effect chain
2629 // during mixing and effect process as the audio buffers could be deleted
2630 // or modified if an effect is created or deleted
2631 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002632 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002633
Eric Laurentbfb1b832013-01-07 09:53:42 -08002634 if (mBytesRemaining == 0) {
2635 mCurrentWriteLength = 0;
2636 if (mMixerStatus == MIXER_TRACKS_READY) {
2637 // threadLoop_mix() sets mCurrentWriteLength
2638 threadLoop_mix();
2639 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2640 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2641 // threadLoop_sleepTime sets sleepTime to 0 if data
2642 // must be written to HAL
2643 threadLoop_sleepTime();
2644 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002645 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 }
2647 }
Andy Hung98ef9782014-03-04 14:46:50 -08002648 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2649 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2650 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2651 // or mSinkBuffer (if there are no effects).
2652 //
2653 // This is done pre-effects computation; if effects change to
2654 // support higher precision, this needs to move.
2655 //
2656 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2657 // TODO use sleepTime == 0 as an additional condition.
2658 if (mMixerBufferValid) {
2659 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2660 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2661
2662 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2663 mNormalFrameCount * mChannelCount);
2664 }
2665
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 mBytesRemaining = mCurrentWriteLength;
2667 if (isSuspended()) {
2668 sleepTime = suspendSleepTimeUs();
2669 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002670 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 mBytesRemaining = 0;
2672 }
Eric Laurent81784c32012-11-19 14:55:58 -08002673
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002675 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 for (size_t i = 0; i < effectChains.size(); i ++) {
2677 effectChains[i]->process_l();
2678 }
Eric Laurent81784c32012-11-19 14:55:58 -08002679 }
2680 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002681 // Process effect chains for offloaded thread even if no audio
2682 // was read from audio track: process only updates effect state
2683 // and thus does have to be synchronized with audio writes but may have
2684 // to be called while waiting for async write callback
2685 if (mType == OFFLOAD) {
2686 for (size_t i = 0; i < effectChains.size(); i ++) {
2687 effectChains[i]->process_l();
2688 }
2689 }
Eric Laurent81784c32012-11-19 14:55:58 -08002690
Andy Hung98ef9782014-03-04 14:46:50 -08002691 // Only if the Effects buffer is enabled and there is data in the
2692 // Effects buffer (buffer valid), we need to
2693 // copy into the sink buffer.
2694 // TODO use sleepTime == 0 as an additional condition.
2695 if (mEffectBufferValid) {
2696 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2697 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2698 mNormalFrameCount * mChannelCount);
2699 }
2700
Eric Laurent81784c32012-11-19 14:55:58 -08002701 // enable changes in effect chain
2702 unlockEffectChains(effectChains);
2703
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 if (!waitingAsyncCallback()) {
2705 // sleepTime == 0 means we must write to audio hardware
2706 if (sleepTime == 0) {
2707 if (mBytesRemaining) {
2708 ssize_t ret = threadLoop_write();
2709 if (ret < 0) {
2710 mBytesRemaining = 0;
2711 } else {
2712 mBytesWritten += ret;
2713 mBytesRemaining -= ret;
2714 }
2715 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2716 (mMixerStatus == MIXER_DRAIN_ALL)) {
2717 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002718 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002719 if (mType == MIXER) {
2720 // write blocked detection
2721 nsecs_t now = systemTime();
2722 nsecs_t delta = now - mLastWriteTime;
2723 if (!mStandby && delta > maxPeriod) {
2724 mNumDelayedWrites++;
2725 if ((now - lastWarning) > kWarningThrottleNs) {
2726 ATRACE_NAME("underrun");
2727 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2728 ns2ms(delta), mNumDelayedWrites, this);
2729 lastWarning = now;
2730 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 }
2732 }
Eric Laurent81784c32012-11-19 14:55:58 -08002733
Eric Laurentbfb1b832013-01-07 09:53:42 -08002734 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002735 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002737 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 }
Eric Laurent81784c32012-11-19 14:55:58 -08002739 }
2740
2741 // Finally let go of removed track(s), without the lock held
2742 // since we can't guarantee the destructors won't acquire that
2743 // same lock. This will also mutate and push a new fast mixer state.
2744 threadLoop_removeTracks(tracksToRemove);
2745 tracksToRemove.clear();
2746
2747 // FIXME I don't understand the need for this here;
2748 // it was in the original code but maybe the
2749 // assignment in saveOutputTracks() makes this unnecessary?
2750 clearOutputTracks();
2751
2752 // Effect chains will be actually deleted here if they were removed from
2753 // mEffectChains list during mixing or effects processing
2754 effectChains.clear();
2755
2756 // FIXME Note that the above .clear() is no longer necessary since effectChains
2757 // is now local to this block, but will keep it for now (at least until merge done).
2758 }
2759
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 threadLoop_exit();
2761
Eric Laurentcf817a22014-08-04 20:36:31 -07002762 if (!mStandby) {
2763 threadLoop_standby();
2764 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002765 }
2766
2767 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002768 mWakeLockUids.clear();
2769 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002770
2771 ALOGV("Thread %p type %d exiting", this, mType);
2772 return false;
2773}
2774
Eric Laurentbfb1b832013-01-07 09:53:42 -08002775// removeTracks_l() must be called with ThreadBase::mLock held
2776void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2777{
2778 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002779 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 for (size_t i=0 ; i<count ; i++) {
2781 const sp<Track>& track = tracksToRemove.itemAt(i);
2782 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002783 mWakeLockUids.remove(track->uid());
2784 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2786 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2787 if (chain != 0) {
2788 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2789 track->sessionId());
2790 chain->decActiveTrackCnt();
2791 }
2792 if (track->isTerminated()) {
2793 removeTrack_l(track);
2794 }
2795 }
2796 }
2797
2798}
Eric Laurent81784c32012-11-19 14:55:58 -08002799
Eric Laurentaccc1472013-09-20 09:36:34 -07002800status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2801{
2802 if (mNormalSink != 0) {
2803 return mNormalSink->getTimestamp(timestamp);
2804 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002805 if ((mType == OFFLOAD || mType == DIRECT)
2806 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002807 uint64_t position64;
2808 int ret = mOutput->stream->get_presentation_position(
2809 mOutput->stream, &position64, &timestamp.mTime);
2810 if (ret == 0) {
2811 timestamp.mPosition = (uint32_t)position64;
2812 return NO_ERROR;
2813 }
2814 }
2815 return INVALID_OPERATION;
2816}
Eric Laurent1c333e22014-05-20 10:48:17 -07002817
2818status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2819 audio_patch_handle_t *handle)
2820{
2821 status_t status = NO_ERROR;
2822 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2823 // store new device and send to effects
2824 audio_devices_t type = AUDIO_DEVICE_NONE;
2825 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2826 type |= patch->sinks[i].ext.device.type;
2827 }
2828 mOutDevice = type;
2829 for (size_t i = 0; i < mEffectChains.size(); i++) {
2830 mEffectChains[i]->setDevice_l(mOutDevice);
2831 }
2832
2833 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2834 status = hwDevice->create_audio_patch(hwDevice,
2835 patch->num_sources,
2836 patch->sources,
2837 patch->num_sinks,
2838 patch->sinks,
2839 handle);
2840 } else {
2841 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2842 }
2843 return status;
2844}
2845
2846status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2847{
2848 status_t status = NO_ERROR;
2849 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2850 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2851 status = hwDevice->release_audio_patch(hwDevice, handle);
2852 } else {
2853 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2854 }
2855 return status;
2856}
2857
Eric Laurent83b88082014-06-20 18:31:16 -07002858void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2859{
2860 Mutex::Autolock _l(mLock);
2861 mTracks.add(track);
2862}
2863
2864void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2865{
2866 Mutex::Autolock _l(mLock);
2867 destroyTrack_l(track);
2868}
2869
2870void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2871{
2872 ThreadBase::getAudioPortConfig(config);
2873 config->role = AUDIO_PORT_ROLE_SOURCE;
2874 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2875 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2876}
2877
Eric Laurent81784c32012-11-19 14:55:58 -08002878// ----------------------------------------------------------------------------
2879
2880AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2881 audio_io_handle_t id, audio_devices_t device, type_t type)
2882 : PlaybackThread(audioFlinger, output, id, device, type),
2883 // mAudioMixer below
2884 // mFastMixer below
2885 mFastMixerFutex(0)
2886 // mOutputSink below
2887 // mPipeSink below
2888 // mNormalSink below
2889{
2890 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002891 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002892 "mFrameCount=%d, mNormalFrameCount=%d",
2893 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2894 mNormalFrameCount);
2895 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2896
Andy Hungfbfc3952015-01-15 13:33:51 -08002897 if (type == DUPLICATING) {
2898 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2899 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2900 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2901 return;
2902 }
Eric Laurent81784c32012-11-19 14:55:58 -08002903 // create an NBAIO sink for the HAL output stream, and negotiate
2904 mOutputSink = new AudioStreamOutSink(output->stream);
2905 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002906 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002907 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2908 ALOG_ASSERT(index == 0);
2909
2910 // initialize fast mixer depending on configuration
2911 bool initFastMixer;
2912 switch (kUseFastMixer) {
2913 case FastMixer_Never:
2914 initFastMixer = false;
2915 break;
2916 case FastMixer_Always:
2917 initFastMixer = true;
2918 break;
2919 case FastMixer_Static:
2920 case FastMixer_Dynamic:
2921 initFastMixer = mFrameCount < mNormalFrameCount;
2922 break;
2923 }
2924 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002925 audio_format_t fastMixerFormat;
2926 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2927 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2928 } else {
2929 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2930 }
2931 if (mFormat != fastMixerFormat) {
2932 // change our Sink format to accept our intermediate precision
2933 mFormat = fastMixerFormat;
2934 free(mSinkBuffer);
2935 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2936 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2937 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2938 }
Eric Laurent81784c32012-11-19 14:55:58 -08002939
2940 // create a MonoPipe to connect our submix to FastMixer
2941 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002942 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002943 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002944 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002945 format.mFormat = fastMixerFormat;
2946 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2947
Eric Laurent81784c32012-11-19 14:55:58 -08002948 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2949 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2950 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2951 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2952 const NBAIO_Format offers[1] = {format};
2953 size_t numCounterOffers = 0;
2954 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2955 ALOG_ASSERT(index == 0);
2956 monoPipe->setAvgFrames((mScreenState & 1) ?
2957 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2958 mPipeSink = monoPipe;
2959
Glenn Kasten46909e72013-02-26 09:20:22 -08002960#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002961 if (mTeeSinkOutputEnabled) {
2962 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002963 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2964 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002965 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002966 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002967 ALOG_ASSERT(index == 0);
2968 mTeeSink = teeSink;
2969 PipeReader *teeSource = new PipeReader(*teeSink);
2970 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002971 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002972 ALOG_ASSERT(index == 0);
2973 mTeeSource = teeSource;
2974 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002975#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002976
2977 // create fast mixer and configure it initially with just one fast track for our submix
2978 mFastMixer = new FastMixer();
2979 FastMixerStateQueue *sq = mFastMixer->sq();
2980#ifdef STATE_QUEUE_DUMP
2981 sq->setObserverDump(&mStateQueueObserverDump);
2982 sq->setMutatorDump(&mStateQueueMutatorDump);
2983#endif
2984 FastMixerState *state = sq->begin();
2985 FastTrack *fastTrack = &state->mFastTracks[0];
2986 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2987 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2988 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002989 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2990 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002991 fastTrack->mGeneration++;
2992 state->mFastTracksGen++;
2993 state->mTrackMask = 1;
2994 // fast mixer will use the HAL output sink
2995 state->mOutputSink = mOutputSink.get();
2996 state->mOutputSinkGen++;
2997 state->mFrameCount = mFrameCount;
2998 state->mCommand = FastMixerState::COLD_IDLE;
2999 // already done in constructor initialization list
3000 //mFastMixerFutex = 0;
3001 state->mColdFutexAddr = &mFastMixerFutex;
3002 state->mColdGen++;
3003 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003004#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003005 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003006#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003007 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3008 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003009 sq->end();
3010 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3011
3012 // start the fast mixer
3013 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3014 pid_t tid = mFastMixer->getTid();
3015 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3016 if (err != 0) {
3017 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3018 kPriorityFastMixer, getpid_cached, tid, err);
3019 }
3020
3021#ifdef AUDIO_WATCHDOG
3022 // create and start the watchdog
3023 mAudioWatchdog = new AudioWatchdog();
3024 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3025 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3026 tid = mAudioWatchdog->getTid();
3027 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3028 if (err != 0) {
3029 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3030 kPriorityFastMixer, getpid_cached, tid, err);
3031 }
3032#endif
3033
Eric Laurent81784c32012-11-19 14:55:58 -08003034 }
3035
3036 switch (kUseFastMixer) {
3037 case FastMixer_Never:
3038 case FastMixer_Dynamic:
3039 mNormalSink = mOutputSink;
3040 break;
3041 case FastMixer_Always:
3042 mNormalSink = mPipeSink;
3043 break;
3044 case FastMixer_Static:
3045 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3046 break;
3047 }
3048}
3049
3050AudioFlinger::MixerThread::~MixerThread()
3051{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003052 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003053 FastMixerStateQueue *sq = mFastMixer->sq();
3054 FastMixerState *state = sq->begin();
3055 if (state->mCommand == FastMixerState::COLD_IDLE) {
3056 int32_t old = android_atomic_inc(&mFastMixerFutex);
3057 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003058 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003059 }
3060 }
3061 state->mCommand = FastMixerState::EXIT;
3062 sq->end();
3063 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3064 mFastMixer->join();
3065 // Though the fast mixer thread has exited, it's state queue is still valid.
3066 // We'll use that extract the final state which contains one remaining fast track
3067 // corresponding to our sub-mix.
3068 state = sq->begin();
3069 ALOG_ASSERT(state->mTrackMask == 1);
3070 FastTrack *fastTrack = &state->mFastTracks[0];
3071 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3072 delete fastTrack->mBufferProvider;
3073 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003074 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003075#ifdef AUDIO_WATCHDOG
3076 if (mAudioWatchdog != 0) {
3077 mAudioWatchdog->requestExit();
3078 mAudioWatchdog->requestExitAndWait();
3079 mAudioWatchdog.clear();
3080 }
3081#endif
3082 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003083 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003084 delete mAudioMixer;
3085}
3086
3087
3088uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3089{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003090 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003091 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3092 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3093 }
3094 return latency;
3095}
3096
3097
3098void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3099{
3100 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3101}
3102
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003104{
3105 // FIXME we should only do one push per cycle; confirm this is true
3106 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003107 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003108 FastMixerStateQueue *sq = mFastMixer->sq();
3109 FastMixerState *state = sq->begin();
3110 if (state->mCommand != FastMixerState::MIX_WRITE &&
3111 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3112 if (state->mCommand == FastMixerState::COLD_IDLE) {
3113 int32_t old = android_atomic_inc(&mFastMixerFutex);
3114 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003115 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003116 }
3117#ifdef AUDIO_WATCHDOG
3118 if (mAudioWatchdog != 0) {
3119 mAudioWatchdog->resume();
3120 }
3121#endif
3122 }
3123 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003124 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3125 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003126 sq->end();
3127 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3128 if (kUseFastMixer == FastMixer_Dynamic) {
3129 mNormalSink = mPipeSink;
3130 }
3131 } else {
3132 sq->end(false /*didModify*/);
3133 }
3134 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003135 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003136}
3137
3138void AudioFlinger::MixerThread::threadLoop_standby()
3139{
3140 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003141 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003142 FastMixerStateQueue *sq = mFastMixer->sq();
3143 FastMixerState *state = sq->begin();
3144 if (!(state->mCommand & FastMixerState::IDLE)) {
3145 state->mCommand = FastMixerState::COLD_IDLE;
3146 state->mColdFutexAddr = &mFastMixerFutex;
3147 state->mColdGen++;
3148 mFastMixerFutex = 0;
3149 sq->end();
3150 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3151 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3152 if (kUseFastMixer == FastMixer_Dynamic) {
3153 mNormalSink = mOutputSink;
3154 }
3155#ifdef AUDIO_WATCHDOG
3156 if (mAudioWatchdog != 0) {
3157 mAudioWatchdog->pause();
3158 }
3159#endif
3160 } else {
3161 sq->end(false /*didModify*/);
3162 }
3163 }
3164 PlaybackThread::threadLoop_standby();
3165}
3166
Eric Laurentbfb1b832013-01-07 09:53:42 -08003167bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3168{
3169 return false;
3170}
3171
3172bool AudioFlinger::PlaybackThread::shouldStandby_l()
3173{
3174 return !mStandby;
3175}
3176
3177bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3178{
3179 Mutex::Autolock _l(mLock);
3180 return waitingAsyncCallback_l();
3181}
3182
Eric Laurent81784c32012-11-19 14:55:58 -08003183// shared by MIXER and DIRECT, overridden by DUPLICATING
3184void AudioFlinger::PlaybackThread::threadLoop_standby()
3185{
3186 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3187 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003189 // discard any pending drain or write ack by incrementing sequence
3190 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3191 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003193 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3194 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003196 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003197}
3198
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003199void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3200{
3201 ALOGV("signal playback thread");
3202 broadcast_l();
3203}
3204
Eric Laurent81784c32012-11-19 14:55:58 -08003205void AudioFlinger::MixerThread::threadLoop_mix()
3206{
3207 // obtain the presentation timestamp of the next output buffer
3208 int64_t pts;
3209 status_t status = INVALID_OPERATION;
3210
3211 if (mNormalSink != 0) {
3212 status = mNormalSink->getNextWriteTimestamp(&pts);
3213 } else {
3214 status = mOutputSink->getNextWriteTimestamp(&pts);
3215 }
3216
3217 if (status != NO_ERROR) {
3218 pts = AudioBufferProvider::kInvalidPTS;
3219 }
3220
3221 // mix buffers...
3222 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003223 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003224 // increase sleep time progressively when application underrun condition clears.
3225 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3226 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3227 // such that we would underrun the audio HAL.
3228 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3229 sleepTimeShift--;
3230 }
3231 sleepTime = 0;
3232 standbyTime = systemTime() + standbyDelay;
3233 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003234
Eric Laurent81784c32012-11-19 14:55:58 -08003235}
3236
3237void AudioFlinger::MixerThread::threadLoop_sleepTime()
3238{
3239 // If no tracks are ready, sleep once for the duration of an output
3240 // buffer size, then write 0s to the output
3241 if (sleepTime == 0) {
3242 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3243 sleepTime = activeSleepTime >> sleepTimeShift;
3244 if (sleepTime < kMinThreadSleepTimeUs) {
3245 sleepTime = kMinThreadSleepTimeUs;
3246 }
3247 // reduce sleep time in case of consecutive application underruns to avoid
3248 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3249 // duration we would end up writing less data than needed by the audio HAL if
3250 // the condition persists.
3251 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3252 sleepTimeShift++;
3253 }
3254 } else {
3255 sleepTime = idleSleepTime;
3256 }
3257 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003258 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3259 // before effects processing or output.
3260 if (mMixerBufferValid) {
3261 memset(mMixerBuffer, 0, mMixerBufferSize);
3262 } else {
3263 memset(mSinkBuffer, 0, mSinkBufferSize);
3264 }
Eric Laurent81784c32012-11-19 14:55:58 -08003265 sleepTime = 0;
3266 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3267 "anticipated start");
3268 }
3269 // TODO add standby time extension fct of effect tail
3270}
3271
3272// prepareTracks_l() must be called with ThreadBase::mLock held
3273AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3274 Vector< sp<Track> > *tracksToRemove)
3275{
3276
3277 mixer_state mixerStatus = MIXER_IDLE;
3278 // find out which tracks need to be processed
3279 size_t count = mActiveTracks.size();
3280 size_t mixedTracks = 0;
3281 size_t tracksWithEffect = 0;
3282 // counts only _active_ fast tracks
3283 size_t fastTracks = 0;
3284 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3285
3286 float masterVolume = mMasterVolume;
3287 bool masterMute = mMasterMute;
3288
3289 if (masterMute) {
3290 masterVolume = 0;
3291 }
3292 // Delegate master volume control to effect in output mix effect chain if needed
3293 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3294 if (chain != 0) {
3295 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3296 chain->setVolume_l(&v, &v);
3297 masterVolume = (float)((v + (1 << 23)) >> 24);
3298 chain.clear();
3299 }
3300
3301 // prepare a new state to push
3302 FastMixerStateQueue *sq = NULL;
3303 FastMixerState *state = NULL;
3304 bool didModify = false;
3305 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003306 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003307 sq = mFastMixer->sq();
3308 state = sq->begin();
3309 }
3310
Andy Hung69aed5f2014-02-25 17:24:40 -08003311 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003312 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003313
Eric Laurent81784c32012-11-19 14:55:58 -08003314 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003315 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003316 if (t == 0) {
3317 continue;
3318 }
3319
3320 // this const just means the local variable doesn't change
3321 Track* const track = t.get();
3322
3323 // process fast tracks
3324 if (track->isFastTrack()) {
3325
3326 // It's theoretically possible (though unlikely) for a fast track to be created
3327 // and then removed within the same normal mix cycle. This is not a problem, as
3328 // the track never becomes active so it's fast mixer slot is never touched.
3329 // The converse, of removing an (active) track and then creating a new track
3330 // at the identical fast mixer slot within the same normal mix cycle,
3331 // is impossible because the slot isn't marked available until the end of each cycle.
3332 int j = track->mFastIndex;
3333 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3334 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3335 FastTrack *fastTrack = &state->mFastTracks[j];
3336
3337 // Determine whether the track is currently in underrun condition,
3338 // and whether it had a recent underrun.
3339 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3340 FastTrackUnderruns underruns = ftDump->mUnderruns;
3341 uint32_t recentFull = (underruns.mBitFields.mFull -
3342 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3343 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3344 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3345 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3346 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3347 uint32_t recentUnderruns = recentPartial + recentEmpty;
3348 track->mObservedUnderruns = underruns;
3349 // don't count underruns that occur while stopping or pausing
3350 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003351 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3352 recentUnderruns > 0) {
3353 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3354 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003355 }
3356
3357 // This is similar to the state machine for normal tracks,
3358 // with a few modifications for fast tracks.
3359 bool isActive = true;
3360 switch (track->mState) {
3361 case TrackBase::STOPPING_1:
3362 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003364 track->mState = TrackBase::STOPPING_2;
3365 }
3366 break;
3367 case TrackBase::PAUSING:
3368 // ramp down is not yet implemented
3369 track->setPaused();
3370 break;
3371 case TrackBase::RESUMING:
3372 // ramp up is not yet implemented
3373 track->mState = TrackBase::ACTIVE;
3374 break;
3375 case TrackBase::ACTIVE:
3376 if (recentFull > 0 || recentPartial > 0) {
3377 // track has provided at least some frames recently: reset retry count
3378 track->mRetryCount = kMaxTrackRetries;
3379 }
3380 if (recentUnderruns == 0) {
3381 // no recent underruns: stay active
3382 break;
3383 }
3384 // there has recently been an underrun of some kind
3385 if (track->sharedBuffer() == 0) {
3386 // were any of the recent underruns "empty" (no frames available)?
3387 if (recentEmpty == 0) {
3388 // no, then ignore the partial underruns as they are allowed indefinitely
3389 break;
3390 }
3391 // there has recently been an "empty" underrun: decrement the retry counter
3392 if (--(track->mRetryCount) > 0) {
3393 break;
3394 }
3395 // indicate to client process that the track was disabled because of underrun;
3396 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003397 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003398 // remove from active list, but state remains ACTIVE [confusing but true]
3399 isActive = false;
3400 break;
3401 }
3402 // fall through
3403 case TrackBase::STOPPING_2:
3404 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003405 case TrackBase::STOPPED:
3406 case TrackBase::FLUSHED: // flush() while active
3407 // Check for presentation complete if track is inactive
3408 // We have consumed all the buffers of this track.
3409 // This would be incomplete if we auto-paused on underrun
3410 {
3411 size_t audioHALFrames =
3412 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3413 size_t framesWritten = mBytesWritten / mFrameSize;
3414 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3415 // track stays in active list until presentation is complete
3416 break;
3417 }
3418 }
3419 if (track->isStopping_2()) {
3420 track->mState = TrackBase::STOPPED;
3421 }
3422 if (track->isStopped()) {
3423 // Can't reset directly, as fast mixer is still polling this track
3424 // track->reset();
3425 // So instead mark this track as needing to be reset after push with ack
3426 resetMask |= 1 << i;
3427 }
3428 isActive = false;
3429 break;
3430 case TrackBase::IDLE:
3431 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003432 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003433 }
3434
3435 if (isActive) {
3436 // was it previously inactive?
3437 if (!(state->mTrackMask & (1 << j))) {
3438 ExtendedAudioBufferProvider *eabp = track;
3439 VolumeProvider *vp = track;
3440 fastTrack->mBufferProvider = eabp;
3441 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003442 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003443 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003444 fastTrack->mGeneration++;
3445 state->mTrackMask |= 1 << j;
3446 didModify = true;
3447 // no acknowledgement required for newly active tracks
3448 }
3449 // cache the combined master volume and stream type volume for fast mixer; this
3450 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003451 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003452 ++fastTracks;
3453 } else {
3454 // was it previously active?
3455 if (state->mTrackMask & (1 << j)) {
3456 fastTrack->mBufferProvider = NULL;
3457 fastTrack->mGeneration++;
3458 state->mTrackMask &= ~(1 << j);
3459 didModify = true;
3460 // If any fast tracks were removed, we must wait for acknowledgement
3461 // because we're about to decrement the last sp<> on those tracks.
3462 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3463 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003464 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003465 }
3466 tracksToRemove->add(track);
3467 // Avoids a misleading display in dumpsys
3468 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3469 }
3470 continue;
3471 }
3472
3473 { // local variable scope to avoid goto warning
3474
3475 audio_track_cblk_t* cblk = track->cblk();
3476
3477 // The first time a track is added we wait
3478 // for all its buffers to be filled before processing it
3479 int name = track->name();
3480 // make sure that we have enough frames to mix one full buffer.
3481 // enforce this condition only once to enable draining the buffer in case the client
3482 // app does not call stop() and relies on underrun to stop:
3483 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3484 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003485 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003486 uint32_t sr = track->sampleRate();
3487 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003488 desiredFrames = mNormalFrameCount;
3489 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003490 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003491 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003492 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003493 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003494#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003495 // the minimum track buffer size is normally twice the number of frames necessary
3496 // to fill one buffer and the resampler should not leave more than one buffer worth
3497 // of unreleased frames after each pass, but just in case...
3498 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003499#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003500 }
Eric Laurent81784c32012-11-19 14:55:58 -08003501 uint32_t minFrames = 1;
3502 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3503 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003504 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003505 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003506
3507 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003508 if (ATRACE_ENABLED()) {
3509 // I wish we had formatted trace names
3510 char traceName[16];
3511 strcpy(traceName, "nRdy");
3512 int name = track->name();
3513 if (AudioMixer::TRACK0 <= name &&
3514 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3515 name -= AudioMixer::TRACK0;
3516 traceName[4] = (name / 10) + '0';
3517 traceName[5] = (name % 10) + '0';
3518 } else {
3519 traceName[4] = '?';
3520 traceName[5] = '?';
3521 }
3522 traceName[6] = '\0';
3523 ATRACE_INT(traceName, framesReady);
3524 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003525 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003526 !track->isPaused() && !track->isTerminated())
3527 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003528 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003529
3530 mixedTracks++;
3531
Andy Hung69aed5f2014-02-25 17:24:40 -08003532 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3533 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003534 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003535 if (track->mainBuffer() != mSinkBuffer &&
3536 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003537 if (mEffectBufferEnabled) {
3538 mEffectBufferValid = true; // Later can set directly.
3539 }
Eric Laurent81784c32012-11-19 14:55:58 -08003540 chain = getEffectChain_l(track->sessionId());
3541 // Delegate volume control to effect in track effect chain if needed
3542 if (chain != 0) {
3543 tracksWithEffect++;
3544 } else {
3545 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3546 "session %d",
3547 name, track->sessionId());
3548 }
3549 }
3550
3551
3552 int param = AudioMixer::VOLUME;
3553 if (track->mFillingUpStatus == Track::FS_FILLED) {
3554 // no ramp for the first volume setting
3555 track->mFillingUpStatus = Track::FS_ACTIVE;
3556 if (track->mState == TrackBase::RESUMING) {
3557 track->mState = TrackBase::ACTIVE;
3558 param = AudioMixer::RAMP_VOLUME;
3559 }
3560 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003561 // FIXME should not make a decision based on mServer
3562 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // If the track is stopped before the first frame was mixed,
3564 // do not apply ramp
3565 param = AudioMixer::RAMP_VOLUME;
3566 }
3567
3568 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003569 uint32_t vl, vr; // in U8.24 integer format
3570 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003571 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003572 vl = vr = 0;
3573 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003574 if (track->isPausing()) {
3575 track->setPaused();
3576 }
3577 } else {
3578
3579 // read original volumes with volume control
3580 float typeVolume = mStreamTypes[track->streamType()].volume;
3581 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003582 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003583 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003584 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3585 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003587 if (vlf > GAIN_FLOAT_UNITY) {
3588 ALOGV("Track left volume out of range: %.3g", vlf);
3589 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003590 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003591 if (vrf > GAIN_FLOAT_UNITY) {
3592 ALOGV("Track right volume out of range: %.3g", vrf);
3593 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003594 }
3595 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003596 vlf *= v;
3597 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003599 // then derive vl and vr as U8.24 versions for the effect chain
3600 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3601 vl = (uint32_t) (scaleto8_24 * vlf);
3602 vr = (uint32_t) (scaleto8_24 * vrf);
3603 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003604 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003605 // send level comes from shared memory and so may be corrupt
3606 if (sendLevel > MAX_GAIN_INT) {
3607 ALOGV("Track send level out of range: %04X", sendLevel);
3608 sendLevel = MAX_GAIN_INT;
3609 }
Andy Hung6be49402014-05-30 10:42:03 -07003610 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3611 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003612 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613
Eric Laurent81784c32012-11-19 14:55:58 -08003614 // Delegate volume control to effect in track effect chain if needed
3615 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3616 // Do not ramp volume if volume is controlled by effect
3617 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003618 // Update remaining floating point volume levels
3619 vlf = (float)vl / (1 << 24);
3620 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003621 track->mHasVolumeController = true;
3622 } else {
3623 // force no volume ramp when volume controller was just disabled or removed
3624 // from effect chain to avoid volume spike
3625 if (track->mHasVolumeController) {
3626 param = AudioMixer::VOLUME;
3627 }
3628 track->mHasVolumeController = false;
3629 }
3630
Eric Laurent81784c32012-11-19 14:55:58 -08003631 // XXX: these things DON'T need to be done each time
3632 mAudioMixer->setBufferProvider(name, track);
3633 mAudioMixer->enable(name);
3634
Andy Hung6be49402014-05-30 10:42:03 -07003635 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3636 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3637 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003638 mAudioMixer->setParameter(
3639 name,
3640 AudioMixer::TRACK,
3641 AudioMixer::FORMAT, (void *)track->format());
3642 mAudioMixer->setParameter(
3643 name,
3644 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003645 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003646 mAudioMixer->setParameter(
3647 name,
3648 AudioMixer::TRACK,
3649 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003650 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003651 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003652 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003653 if (reqSampleRate == 0) {
3654 reqSampleRate = mSampleRate;
3655 } else if (reqSampleRate > maxSampleRate) {
3656 reqSampleRate = maxSampleRate;
3657 }
Eric Laurent81784c32012-11-19 14:55:58 -08003658 mAudioMixer->setParameter(
3659 name,
3660 AudioMixer::RESAMPLE,
3661 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003662 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003663 /*
3664 * Select the appropriate output buffer for the track.
3665 *
Andy Hung98ef9782014-03-04 14:46:50 -08003666 * Tracks with effects go into their own effects chain buffer
3667 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003668 *
3669 * Other tracks can use mMixerBuffer for higher precision
3670 * channel accumulation. If this buffer is enabled
3671 * (mMixerBufferEnabled true), then selected tracks will accumulate
3672 * into it.
3673 *
3674 */
3675 if (mMixerBufferEnabled
3676 && (track->mainBuffer() == mSinkBuffer
3677 || track->mainBuffer() == mMixerBuffer)) {
3678 mAudioMixer->setParameter(
3679 name,
3680 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003681 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003682 mAudioMixer->setParameter(
3683 name,
3684 AudioMixer::TRACK,
3685 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3686 // TODO: override track->mainBuffer()?
3687 mMixerBufferValid = true;
3688 } else {
3689 mAudioMixer->setParameter(
3690 name,
3691 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003692 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003693 mAudioMixer->setParameter(
3694 name,
3695 AudioMixer::TRACK,
3696 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3697 }
Eric Laurent81784c32012-11-19 14:55:58 -08003698 mAudioMixer->setParameter(
3699 name,
3700 AudioMixer::TRACK,
3701 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3702
3703 // reset retry count
3704 track->mRetryCount = kMaxTrackRetries;
3705
3706 // If one track is ready, set the mixer ready if:
3707 // - the mixer was not ready during previous round OR
3708 // - no other track is not ready
3709 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3710 mixerStatus != MIXER_TRACKS_ENABLED) {
3711 mixerStatus = MIXER_TRACKS_READY;
3712 }
3713 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003714 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003715 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003716 }
Eric Laurent81784c32012-11-19 14:55:58 -08003717 // clear effect chain input buffer if an active track underruns to avoid sending
3718 // previous audio buffer again to effects
3719 chain = getEffectChain_l(track->sessionId());
3720 if (chain != 0) {
3721 chain->clearInputBuffer();
3722 }
3723
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003724 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003725 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3726 track->isStopped() || track->isPaused()) {
3727 // We have consumed all the buffers of this track.
3728 // Remove it from the list of active tracks.
3729 // TODO: use actual buffer filling status instead of latency when available from
3730 // audio HAL
3731 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3732 size_t framesWritten = mBytesWritten / mFrameSize;
3733 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3734 if (track->isStopped()) {
3735 track->reset();
3736 }
3737 tracksToRemove->add(track);
3738 }
3739 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003740 // No buffers for this track. Give it a few chances to
3741 // fill a buffer, then remove it from active list.
3742 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003743 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003744 tracksToRemove->add(track);
3745 // indicate to client process that the track was disabled because of underrun;
3746 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003747 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003748 // If one track is not ready, mark the mixer also not ready if:
3749 // - the mixer was ready during previous round OR
3750 // - no other track is ready
3751 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3752 mixerStatus != MIXER_TRACKS_READY) {
3753 mixerStatus = MIXER_TRACKS_ENABLED;
3754 }
3755 }
3756 mAudioMixer->disable(name);
3757 }
3758
3759 } // local variable scope to avoid goto warning
3760track_is_ready: ;
3761
3762 }
3763
3764 // Push the new FastMixer state if necessary
3765 bool pauseAudioWatchdog = false;
3766 if (didModify) {
3767 state->mFastTracksGen++;
3768 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3769 if (kUseFastMixer == FastMixer_Dynamic &&
3770 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3771 state->mCommand = FastMixerState::COLD_IDLE;
3772 state->mColdFutexAddr = &mFastMixerFutex;
3773 state->mColdGen++;
3774 mFastMixerFutex = 0;
3775 if (kUseFastMixer == FastMixer_Dynamic) {
3776 mNormalSink = mOutputSink;
3777 }
3778 // If we go into cold idle, need to wait for acknowledgement
3779 // so that fast mixer stops doing I/O.
3780 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3781 pauseAudioWatchdog = true;
3782 }
Eric Laurent81784c32012-11-19 14:55:58 -08003783 }
3784 if (sq != NULL) {
3785 sq->end(didModify);
3786 sq->push(block);
3787 }
3788#ifdef AUDIO_WATCHDOG
3789 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3790 mAudioWatchdog->pause();
3791 }
3792#endif
3793
3794 // Now perform the deferred reset on fast tracks that have stopped
3795 while (resetMask != 0) {
3796 size_t i = __builtin_ctz(resetMask);
3797 ALOG_ASSERT(i < count);
3798 resetMask &= ~(1 << i);
3799 sp<Track> t = mActiveTracks[i].promote();
3800 if (t == 0) {
3801 continue;
3802 }
3803 Track* track = t.get();
3804 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3805 track->reset();
3806 }
3807
3808 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003810
Eric Laurent97d547d2014-09-02 14:45:53 -07003811 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3812 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003813 }
3814
3815 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003816 // as long as there are effects we should clear the effects buffer, to avoid
3817 // passing a non-clean buffer to the effect chain
3818 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003819 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003820 // sink or mix buffer must be cleared if all tracks are connected to an
3821 // effect chain as in this case the mixer will not write to the sink or mix buffer
3822 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003823 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3824 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003825 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003826 if (mMixerBufferValid) {
3827 memset(mMixerBuffer, 0, mMixerBufferSize);
3828 // TODO: In testing, mSinkBuffer below need not be cleared because
3829 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3830 // after mixing.
3831 //
3832 // To enforce this guarantee:
3833 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3834 // (mixedTracks == 0 && fastTracks > 0))
3835 // must imply MIXER_TRACKS_READY.
3836 // Later, we may clear buffers regardless, and skip much of this logic.
3837 }
Andy Hung98ef9782014-03-04 14:46:50 -08003838 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003839 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003840 }
3841
3842 // if any fast tracks, then status is ready
3843 mMixerStatusIgnoringFastTracks = mixerStatus;
3844 if (fastTracks > 0) {
3845 mixerStatus = MIXER_TRACKS_READY;
3846 }
3847 return mixerStatus;
3848}
3849
3850// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003851int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3852 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003853{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003854 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003855}
3856
3857// deleteTrackName_l() must be called with ThreadBase::mLock held
3858void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3859{
3860 ALOGV("remove track (%d) and delete from mixer", name);
3861 mAudioMixer->deleteTrackName(name);
3862}
3863
Eric Laurent10351942014-05-08 18:49:52 -07003864// checkForNewParameter_l() must be called with ThreadBase::mLock held
3865bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3866 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003867{
Eric Laurent81784c32012-11-19 14:55:58 -08003868 bool reconfig = false;
3869
Eric Laurent10351942014-05-08 18:49:52 -07003870 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003871
Eric Laurent10351942014-05-08 18:49:52 -07003872 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3873 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003874 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003875 FastMixerStateQueue *sq = mFastMixer->sq();
3876 FastMixerState *state = sq->begin();
3877 if (!(state->mCommand & FastMixerState::IDLE)) {
3878 previousCommand = state->mCommand;
3879 state->mCommand = FastMixerState::HOT_IDLE;
3880 sq->end();
3881 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3882 } else {
3883 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003884 }
Eric Laurent10351942014-05-08 18:49:52 -07003885 }
Eric Laurent81784c32012-11-19 14:55:58 -08003886
Eric Laurent10351942014-05-08 18:49:52 -07003887 AudioParameter param = AudioParameter(keyValuePair);
3888 int value;
3889 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3890 reconfig = true;
3891 }
3892 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003893 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003894 status = BAD_VALUE;
3895 } else {
3896 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003897 reconfig = true;
3898 }
Eric Laurent10351942014-05-08 18:49:52 -07003899 }
3900 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003901 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003902 status = BAD_VALUE;
3903 } else {
3904 // no need to save value, since it's constant
3905 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003906 }
Eric Laurent10351942014-05-08 18:49:52 -07003907 }
3908 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3909 // do not accept frame count changes if tracks are open as the track buffer
3910 // size depends on frame count and correct behavior would not be guaranteed
3911 // if frame count is changed after track creation
3912 if (!mTracks.isEmpty()) {
3913 status = INVALID_OPERATION;
3914 } else {
3915 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003916 }
Eric Laurent10351942014-05-08 18:49:52 -07003917 }
3918 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003919#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003920 // when changing the audio output device, call addBatteryData to notify
3921 // the change
3922 if (mOutDevice != value) {
3923 uint32_t params = 0;
3924 // check whether speaker is on
3925 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3926 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003927 }
Eric Laurent10351942014-05-08 18:49:52 -07003928
3929 audio_devices_t deviceWithoutSpeaker
3930 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3931 // check if any other device (except speaker) is on
3932 if (value & deviceWithoutSpeaker ) {
3933 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3934 }
3935
3936 if (params != 0) {
3937 addBatteryData(params);
3938 }
3939 }
Eric Laurent81784c32012-11-19 14:55:58 -08003940#endif
3941
Eric Laurent10351942014-05-08 18:49:52 -07003942 // forward device change to effects that have requested to be
3943 // aware of attached audio device.
3944 if (value != AUDIO_DEVICE_NONE) {
3945 mOutDevice = value;
3946 for (size_t i = 0; i < mEffectChains.size(); i++) {
3947 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003948 }
3949 }
Eric Laurent10351942014-05-08 18:49:52 -07003950 }
Eric Laurent81784c32012-11-19 14:55:58 -08003951
Eric Laurent10351942014-05-08 18:49:52 -07003952 if (status == NO_ERROR) {
3953 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3954 keyValuePair.string());
3955 if (!mStandby && status == INVALID_OPERATION) {
3956 mOutput->stream->common.standby(&mOutput->stream->common);
3957 mStandby = true;
3958 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003959 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003960 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003961 }
Eric Laurent10351942014-05-08 18:49:52 -07003962 if (status == NO_ERROR && reconfig) {
3963 readOutputParameters_l();
3964 delete mAudioMixer;
3965 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3966 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003967 int name = getTrackName_l(mTracks[i]->mChannelMask,
3968 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003969 if (name < 0) {
3970 break;
3971 }
3972 mTracks[i]->mName = name;
3973 }
3974 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3975 }
Eric Laurent81784c32012-11-19 14:55:58 -08003976 }
3977
3978 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003979 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003980 FastMixerStateQueue *sq = mFastMixer->sq();
3981 FastMixerState *state = sq->begin();
3982 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3983 state->mCommand = previousCommand;
3984 sq->end();
3985 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3986 }
3987
3988 return reconfig;
3989}
3990
3991
3992void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3993{
3994 const size_t SIZE = 256;
3995 char buffer[SIZE];
3996 String8 result;
3997
3998 PlaybackThread::dumpInternals(fd, args);
3999
Elliott Hughes87cebad2014-05-22 10:14:43 -07004000 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004001
4002 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004003 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004004 copy.dump(fd);
4005
4006#ifdef STATE_QUEUE_DUMP
4007 // Similar for state queue
4008 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4009 observerCopy.dump(fd);
4010 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4011 mutatorCopy.dump(fd);
4012#endif
4013
Glenn Kasten46909e72013-02-26 09:20:22 -08004014#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004015 // Write the tee output to a .wav file
4016 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004017#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004018
4019#ifdef AUDIO_WATCHDOG
4020 if (mAudioWatchdog != 0) {
4021 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4022 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4023 wdCopy.dump(fd);
4024 }
4025#endif
4026}
4027
4028uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4029{
4030 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4031}
4032
4033uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4034{
4035 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4036}
4037
4038void AudioFlinger::MixerThread::cacheParameters_l()
4039{
4040 PlaybackThread::cacheParameters_l();
4041
4042 // FIXME: Relaxed timing because of a certain device that can't meet latency
4043 // Should be reduced to 2x after the vendor fixes the driver issue
4044 // increase threshold again due to low power audio mode. The way this warning
4045 // threshold is calculated and its usefulness should be reconsidered anyway.
4046 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4047}
4048
4049// ----------------------------------------------------------------------------
4050
4051AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4052 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4053 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4054 // mLeftVolFloat, mRightVolFloat
4055{
4056}
4057
Eric Laurentbfb1b832013-01-07 09:53:42 -08004058AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4059 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4060 ThreadBase::type_t type)
4061 : PlaybackThread(audioFlinger, output, id, device, type)
4062 // mLeftVolFloat, mRightVolFloat
4063{
4064}
4065
Eric Laurent81784c32012-11-19 14:55:58 -08004066AudioFlinger::DirectOutputThread::~DirectOutputThread()
4067{
4068}
4069
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4071{
4072 audio_track_cblk_t* cblk = track->cblk();
4073 float left, right;
4074
4075 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4076 left = right = 0;
4077 } else {
4078 float typeVolume = mStreamTypes[track->streamType()].volume;
4079 float v = mMasterVolume * typeVolume;
4080 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004081 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4082 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4083 if (left > GAIN_FLOAT_UNITY) {
4084 left = GAIN_FLOAT_UNITY;
4085 }
4086 left *= v;
4087 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4088 if (right > GAIN_FLOAT_UNITY) {
4089 right = GAIN_FLOAT_UNITY;
4090 }
4091 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004092 }
4093
4094 if (lastTrack) {
4095 if (left != mLeftVolFloat || right != mRightVolFloat) {
4096 mLeftVolFloat = left;
4097 mRightVolFloat = right;
4098
4099 // Convert volumes from float to 8.24
4100 uint32_t vl = (uint32_t)(left * (1 << 24));
4101 uint32_t vr = (uint32_t)(right * (1 << 24));
4102
4103 // Delegate volume control to effect in track effect chain if needed
4104 // only one effect chain can be present on DirectOutputThread, so if
4105 // there is one, the track is connected to it
4106 if (!mEffectChains.isEmpty()) {
4107 mEffectChains[0]->setVolume_l(&vl, &vr);
4108 left = (float)vl / (1 << 24);
4109 right = (float)vr / (1 << 24);
4110 }
4111 if (mOutput->stream->set_volume) {
4112 mOutput->stream->set_volume(mOutput->stream, left, right);
4113 }
4114 }
4115 }
4116}
4117
4118
Eric Laurent81784c32012-11-19 14:55:58 -08004119AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4120 Vector< sp<Track> > *tracksToRemove
4121)
4122{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004123 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004124 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004125 bool doHwPause = false;
4126 bool doHwResume = false;
4127 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004128
4129 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004130 for (size_t i = 0; i < count; i++) {
4131 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004132 // The track died recently
4133 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004134 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004135 }
4136
4137 Track* const track = t.get();
4138 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004139 // Only consider last track started for volume and mixer state control.
4140 // In theory an older track could underrun and restart after the new one starts
4141 // but as we only care about the transition phase between two tracks on a
4142 // direct output, it is not a problem to ignore the underrun case.
4143 sp<Track> l = mLatestActiveTrack.promote();
4144 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004145
Eric Laurentd1f69b02014-12-15 14:33:13 -08004146 if (mHwSupportsPause && track->isPausing()) {
4147 track->setPaused();
4148 if (last && !mHwPaused) {
4149 doHwPause = true;
4150 mHwPaused = true;
4151 }
4152 tracksToRemove->add(track);
4153 } else if (track->isFlushPending()) {
4154 track->flushAck();
4155 if (last) {
4156 flushPending = true;
4157 }
4158 } else if (mHwSupportsPause && track->isResumePending()){
4159 track->resumeAck();
4160 if (last) {
4161 if (mHwPaused) {
4162 doHwResume = true;
4163 mHwPaused = false;
4164 }
4165 }
4166 }
4167
Eric Laurent81784c32012-11-19 14:55:58 -08004168 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004169 // for all its buffers to be filled before processing it.
4170 // Allow draining the buffer in case the client
4171 // app does not call stop() and relies on underrun to stop:
4172 // hence the test on (track->mRetryCount > 1).
4173 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004174 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004175 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4176 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004177 minFrames = mNormalFrameCount;
4178 } else {
4179 minFrames = 1;
4180 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181
Eric Laurentab5cdba2014-06-09 17:22:27 -07004182 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4183 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004184 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004185 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004186
4187 if (track->mFillingUpStatus == Track::FS_FILLED) {
4188 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004189 // make sure processVolume_l() will apply new volume even if 0
4190 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004191 if (!mHwSupportsPause) {
4192 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004193 }
4194 }
4195
4196 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 processVolume_l(track, last);
4198 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004199 // reset retry count
4200 track->mRetryCount = kMaxTrackRetriesDirect;
4201 mActiveTrack = t;
4202 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004203 if (usesHwAvSync() && mHwPaused) {
4204 doHwResume = true;
4205 mHwPaused = false;
4206 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004207 }
Eric Laurent81784c32012-11-19 14:55:58 -08004208 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004209 // clear effect chain input buffer if the last active track started underruns
4210 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004211 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004212 mEffectChains[0]->clearInputBuffer();
4213 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004214 if (track->isStopping_1()) {
4215 track->mState = TrackBase::STOPPING_2;
4216 }
4217 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4218 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004219 // We have consumed all the buffers of this track.
4220 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004221 size_t audioHALFrames;
4222 if (audio_is_linear_pcm(mFormat)) {
4223 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4224 } else {
4225 audioHALFrames = 0;
4226 }
4227
Eric Laurent81784c32012-11-19 14:55:58 -08004228 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004229 if (mStandby || !last ||
4230 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004231 if (track->isStopping_2()) {
4232 track->mState = TrackBase::STOPPED;
4233 }
Eric Laurent81784c32012-11-19 14:55:58 -08004234 if (track->isStopped()) {
4235 track->reset();
4236 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004237 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
4239 } else {
4240 // No buffers for this track. Give it a few chances to
4241 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004242 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004243 if (--(track->mRetryCount) <= 0) {
4244 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004245 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004246 // indicate to client process that the track was disabled because of underrun;
4247 // it will then automatically call start() when data is available
4248 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004250 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004251 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4252 doHwPause = true;
4253 mHwPaused = true;
4254 }
Eric Laurent81784c32012-11-19 14:55:58 -08004255 }
4256 }
4257 }
4258 }
4259
Eric Laurentd1f69b02014-12-15 14:33:13 -08004260 // if an active track did not command a flush, check for pending flush on stopped tracks
4261 if (!flushPending) {
4262 for (size_t i = 0; i < mTracks.size(); i++) {
4263 if (mTracks[i]->isFlushPending()) {
4264 mTracks[i]->flushAck();
4265 flushPending = true;
4266 }
4267 }
4268 }
4269
4270 // make sure the pause/flush/resume sequence is executed in the right order.
4271 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4272 // before flush and then resume HW. This can happen in case of pause/flush/resume
4273 // if resume is received before pause is executed.
4274 if (mHwSupportsPause && !mStandby &&
4275 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4276 mOutput->stream->pause(mOutput->stream);
4277 }
4278 if (flushPending) {
4279 flushHw_l();
4280 }
4281 if (mHwSupportsPause && !mStandby && doHwResume) {
4282 mOutput->stream->resume(mOutput->stream);
4283 }
Eric Laurent81784c32012-11-19 14:55:58 -08004284 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004286
4287 return mixerStatus;
4288}
4289
4290void AudioFlinger::DirectOutputThread::threadLoop_mix()
4291{
Eric Laurent81784c32012-11-19 14:55:58 -08004292 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004293 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004294 // output audio to hardware
4295 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004296 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 buffer.frameCount = frameCount;
4298 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004299 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004300 memset(curBuf, 0, frameCount * mFrameSize);
4301 break;
4302 }
4303 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4304 frameCount -= buffer.frameCount;
4305 curBuf += buffer.frameCount * mFrameSize;
4306 mActiveTrack->releaseBuffer(&buffer);
4307 }
Andy Hung2098f272014-02-27 14:00:06 -08004308 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004309 sleepTime = 0;
4310 standbyTime = systemTime() + standbyDelay;
4311 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004312}
4313
4314void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4315{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004316 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004317 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004318 sleepTime = idleSleepTime;
4319 return;
4320 }
Eric Laurent81784c32012-11-19 14:55:58 -08004321 if (sleepTime == 0) {
4322 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4323 sleepTime = activeSleepTime;
4324 } else {
4325 sleepTime = idleSleepTime;
4326 }
4327 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004328 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 sleepTime = 0;
4330 }
4331}
4332
Eric Laurentd1f69b02014-12-15 14:33:13 -08004333void AudioFlinger::DirectOutputThread::threadLoop_exit()
4334{
4335 {
4336 Mutex::Autolock _l(mLock);
4337 bool flushPending = false;
4338 for (size_t i = 0; i < mTracks.size(); i++) {
4339 if (mTracks[i]->isFlushPending()) {
4340 mTracks[i]->flushAck();
4341 flushPending = true;
4342 }
4343 }
4344 if (flushPending) {
4345 flushHw_l();
4346 }
4347 }
4348 PlaybackThread::threadLoop_exit();
4349}
4350
4351// must be called with thread mutex locked
4352bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4353{
4354 bool trackPaused = false;
4355
4356 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4357 // after a timeout and we will enter standby then.
4358 if (mTracks.size() > 0) {
4359 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4360 }
4361
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004362 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004363}
4364
Eric Laurent81784c32012-11-19 14:55:58 -08004365// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004366int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004367 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004368{
4369 return 0;
4370}
4371
4372// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004373void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004374{
4375}
4376
Eric Laurent10351942014-05-08 18:49:52 -07004377// checkForNewParameter_l() must be called with ThreadBase::mLock held
4378bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4379 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004380{
4381 bool reconfig = false;
4382
Eric Laurent10351942014-05-08 18:49:52 -07004383 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004384
Eric Laurent10351942014-05-08 18:49:52 -07004385 AudioParameter param = AudioParameter(keyValuePair);
4386 int value;
4387 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4388 // forward device change to effects that have requested to be
4389 // aware of attached audio device.
4390 if (value != AUDIO_DEVICE_NONE) {
4391 mOutDevice = value;
4392 for (size_t i = 0; i < mEffectChains.size(); i++) {
4393 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004394 }
4395 }
Eric Laurent81784c32012-11-19 14:55:58 -08004396 }
Eric Laurent10351942014-05-08 18:49:52 -07004397 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4398 // do not accept frame count changes if tracks are open as the track buffer
4399 // size depends on frame count and correct behavior would not be garantied
4400 // if frame count is changed after track creation
4401 if (!mTracks.isEmpty()) {
4402 status = INVALID_OPERATION;
4403 } else {
4404 reconfig = true;
4405 }
4406 }
4407 if (status == NO_ERROR) {
4408 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4409 keyValuePair.string());
4410 if (!mStandby && status == INVALID_OPERATION) {
4411 mOutput->stream->common.standby(&mOutput->stream->common);
4412 mStandby = true;
4413 mBytesWritten = 0;
4414 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4415 keyValuePair.string());
4416 }
4417 if (status == NO_ERROR && reconfig) {
4418 readOutputParameters_l();
4419 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4420 }
4421 }
4422
Eric Laurent81784c32012-11-19 14:55:58 -08004423 return reconfig;
4424}
4425
4426uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4427{
4428 uint32_t time;
4429 if (audio_is_linear_pcm(mFormat)) {
4430 time = PlaybackThread::activeSleepTimeUs();
4431 } else {
4432 time = 10000;
4433 }
4434 return time;
4435}
4436
4437uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4438{
4439 uint32_t time;
4440 if (audio_is_linear_pcm(mFormat)) {
4441 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4442 } else {
4443 time = 10000;
4444 }
4445 return time;
4446}
4447
4448uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4449{
4450 uint32_t time;
4451 if (audio_is_linear_pcm(mFormat)) {
4452 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4453 } else {
4454 time = 10000;
4455 }
4456 return time;
4457}
4458
4459void AudioFlinger::DirectOutputThread::cacheParameters_l()
4460{
4461 PlaybackThread::cacheParameters_l();
4462
4463 // use shorter standby delay as on normal output to release
4464 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004465 if (audio_is_linear_pcm(mFormat)) {
4466 standbyDelay = microseconds(activeSleepTime*2);
4467 } else {
4468 standbyDelay = kOffloadStandbyDelayNs;
4469 }
Eric Laurent81784c32012-11-19 14:55:58 -08004470}
4471
Eric Laurente659ef42014-09-29 13:06:46 -07004472void AudioFlinger::DirectOutputThread::flushHw_l()
4473{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004474 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004475 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004476 }
4477 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004478}
4479
Eric Laurent81784c32012-11-19 14:55:58 -08004480// ----------------------------------------------------------------------------
4481
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004483 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004484 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004485 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004486 mWriteAckSequence(0),
4487 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488{
4489}
4490
4491AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4492{
4493}
4494
4495void AudioFlinger::AsyncCallbackThread::onFirstRef()
4496{
4497 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4498}
4499
4500bool AudioFlinger::AsyncCallbackThread::threadLoop()
4501{
4502 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004503 uint32_t writeAckSequence;
4504 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004505
4506 {
4507 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004508 while (!((mWriteAckSequence & 1) ||
4509 (mDrainSequence & 1) ||
4510 exitPending())) {
4511 mWaitWorkCV.wait(mLock);
4512 }
4513
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 if (exitPending()) {
4515 break;
4516 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004517 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4518 mWriteAckSequence, mDrainSequence);
4519 writeAckSequence = mWriteAckSequence;
4520 mWriteAckSequence &= ~1;
4521 drainSequence = mDrainSequence;
4522 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523 }
4524 {
Eric Laurent4de95592013-09-26 15:28:21 -07004525 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4526 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004527 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004528 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004530 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004531 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004532 }
4533 }
4534 }
4535 }
4536 return false;
4537}
4538
4539void AudioFlinger::AsyncCallbackThread::exit()
4540{
4541 ALOGV("AsyncCallbackThread::exit");
4542 Mutex::Autolock _l(mLock);
4543 requestExit();
4544 mWaitWorkCV.broadcast();
4545}
4546
Eric Laurent3b4529e2013-09-05 18:09:19 -07004547void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004548{
4549 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004550 // bit 0 is cleared
4551 mWriteAckSequence = sequence << 1;
4552}
4553
4554void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4555{
4556 Mutex::Autolock _l(mLock);
4557 // ignore unexpected callbacks
4558 if (mWriteAckSequence & 2) {
4559 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004560 mWaitWorkCV.signal();
4561 }
4562}
4563
Eric Laurent3b4529e2013-09-05 18:09:19 -07004564void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004565{
4566 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004567 // bit 0 is cleared
4568 mDrainSequence = sequence << 1;
4569}
4570
4571void AudioFlinger::AsyncCallbackThread::resetDraining()
4572{
4573 Mutex::Autolock _l(mLock);
4574 // ignore unexpected callbacks
4575 if (mDrainSequence & 2) {
4576 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004577 mWaitWorkCV.signal();
4578 }
4579}
4580
4581
4582// ----------------------------------------------------------------------------
4583AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4584 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4585 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004586 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587{
Eric Laurentfd477972013-10-25 18:10:40 -07004588 //FIXME: mStandby should be set to true by ThreadBase constructor
4589 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590}
4591
Eric Laurentbfb1b832013-01-07 09:53:42 -08004592void AudioFlinger::OffloadThread::threadLoop_exit()
4593{
4594 if (mFlushPending || mHwPaused) {
4595 // If a flush is pending or track was paused, just discard buffered data
4596 flushHw_l();
4597 } else {
4598 mMixerStatus = MIXER_DRAIN_ALL;
4599 threadLoop_drain();
4600 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004601 if (mUseAsyncWrite) {
4602 ALOG_ASSERT(mCallbackThread != 0);
4603 mCallbackThread->exit();
4604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605 PlaybackThread::threadLoop_exit();
4606}
4607
4608AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4609 Vector< sp<Track> > *tracksToRemove
4610)
4611{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004612 size_t count = mActiveTracks.size();
4613
4614 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004615 bool doHwPause = false;
4616 bool doHwResume = false;
4617
Eric Laurentede6c3b2013-09-19 14:37:46 -07004618 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4619
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620 // find out which tracks need to be processed
4621 for (size_t i = 0; i < count; i++) {
4622 sp<Track> t = mActiveTracks[i].promote();
4623 // The track died recently
4624 if (t == 0) {
4625 continue;
4626 }
4627 Track* const track = t.get();
4628 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004629 // Only consider last track started for volume and mixer state control.
4630 // In theory an older track could underrun and restart after the new one starts
4631 // but as we only care about the transition phase between two tracks on a
4632 // direct output, it is not a problem to ignore the underrun case.
4633 sp<Track> l = mLatestActiveTrack.promote();
4634 bool last = l.get() == track;
4635
Haynes Mathew George7844f672014-01-15 12:32:55 -08004636 if (track->isInvalid()) {
4637 ALOGW("An invalidated track shouldn't be in active list");
4638 tracksToRemove->add(track);
4639 continue;
4640 }
4641
4642 if (track->mState == TrackBase::IDLE) {
4643 ALOGW("An idle track shouldn't be in active list");
4644 continue;
4645 }
4646
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 if (track->isPausing()) {
4648 track->setPaused();
4649 if (last) {
4650 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004651 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004652 mHwPaused = true;
4653 }
4654 // If we were part way through writing the mixbuffer to
4655 // the HAL we must save this until we resume
4656 // BUG - this will be wrong if a different track is made active,
4657 // in that case we want to discard the pending data in the
4658 // mixbuffer and tell the client to present it again when the
4659 // track is resumed
4660 mPausedWriteLength = mCurrentWriteLength;
4661 mPausedBytesRemaining = mBytesRemaining;
4662 mBytesRemaining = 0; // stop writing
4663 }
4664 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004665 } else if (track->isFlushPending()) {
4666 track->flushAck();
4667 if (last) {
4668 mFlushPending = true;
4669 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004670 } else if (track->isResumePending()){
4671 track->resumeAck();
4672 if (last) {
4673 if (mPausedBytesRemaining) {
4674 // Need to continue write that was interrupted
4675 mCurrentWriteLength = mPausedWriteLength;
4676 mBytesRemaining = mPausedBytesRemaining;
4677 mPausedBytesRemaining = 0;
4678 }
4679 if (mHwPaused) {
4680 doHwResume = true;
4681 mHwPaused = false;
4682 // threadLoop_mix() will handle the case that we need to
4683 // resume an interrupted write
4684 }
4685 // enable write to audio HAL
4686 sleepTime = 0;
4687
4688 // Do not handle new data in this iteration even if track->framesReady()
4689 mixerStatus = MIXER_TRACKS_ENABLED;
4690 }
4691 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004692 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004693 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004694 if (track->mFillingUpStatus == Track::FS_FILLED) {
4695 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004696 // make sure processVolume_l() will apply new volume even if 0
4697 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004698 }
4699
4700 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004701 sp<Track> previousTrack = mPreviousTrack.promote();
4702 if (previousTrack != 0) {
4703 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004704 // Flush any data still being written from last track
4705 mBytesRemaining = 0;
4706 if (mPausedBytesRemaining) {
4707 // Last track was paused so we also need to flush saved
4708 // mixbuffer state and invalidate track so that it will
4709 // re-submit that unwritten data when it is next resumed
4710 mPausedBytesRemaining = 0;
4711 // Invalidate is a bit drastic - would be more efficient
4712 // to have a flag to tell client that some of the
4713 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004714 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004715 }
4716 // flush data already sent to the DSP if changing audio session as audio
4717 // comes from a different source. Also invalidate previous track to force a
4718 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004719 if (previousTrack->sessionId() != track->sessionId()) {
4720 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004721 }
4722 }
4723 }
4724 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004725 // reset retry count
4726 track->mRetryCount = kMaxTrackRetriesOffload;
4727 mActiveTrack = t;
4728 mixerStatus = MIXER_TRACKS_READY;
4729 }
4730 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004731 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004732 if (track->isStopping_1()) {
4733 // Hardware buffer can hold a large amount of audio so we must
4734 // wait for all current track's data to drain before we say
4735 // that the track is stopped.
4736 if (mBytesRemaining == 0) {
4737 // Only start draining when all data in mixbuffer
4738 // has been written
4739 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4740 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004741 // do not drain if no data was ever sent to HAL (mStandby == true)
4742 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004743 // do not modify drain sequence if we are already draining. This happens
4744 // when resuming from pause after drain.
4745 if ((mDrainSequence & 1) == 0) {
4746 sleepTime = 0;
4747 standbyTime = systemTime() + standbyDelay;
4748 mixerStatus = MIXER_DRAIN_TRACK;
4749 mDrainSequence += 2;
4750 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004751 if (mHwPaused) {
4752 // It is possible to move from PAUSED to STOPPING_1 without
4753 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004754 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755 mHwPaused = false;
4756 }
4757 }
4758 }
4759 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004760 // Drain has completed or we are in standby, signal presentation complete
4761 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004762 track->mState = TrackBase::STOPPED;
4763 size_t audioHALFrames =
4764 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4765 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004766 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767 track->presentationComplete(framesWritten, audioHALFrames);
4768 track->reset();
4769 tracksToRemove->add(track);
4770 }
4771 } else {
4772 // No buffers for this track. Give it a few chances to
4773 // fill a buffer, then remove it from active list.
4774 if (--(track->mRetryCount) <= 0) {
4775 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4776 track->name());
4777 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004778 // indicate to client process that the track was disabled because of underrun;
4779 // it will then automatically call start() when data is available
4780 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781 } else if (last){
4782 mixerStatus = MIXER_TRACKS_ENABLED;
4783 }
4784 }
4785 }
4786 // compute volume for this track
4787 processVolume_l(track, last);
4788 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004789
Eric Laurentea0fade2013-10-04 16:23:48 -07004790 // make sure the pause/flush/resume sequence is executed in the right order.
4791 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4792 // before flush and then resume HW. This can happen in case of pause/flush/resume
4793 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004794 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004795 mOutput->stream->pause(mOutput->stream);
4796 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004797 if (mFlushPending) {
4798 flushHw_l();
4799 mFlushPending = false;
4800 }
Eric Laurentfd477972013-10-25 18:10:40 -07004801 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004802 mOutput->stream->resume(mOutput->stream);
4803 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004804
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805 // remove all the tracks that need to be...
4806 removeTracks_l(*tracksToRemove);
4807
4808 return mixerStatus;
4809}
4810
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811// must be called with thread mutex locked
4812bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4813{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004814 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4815 mWriteAckSequence, mDrainSequence);
4816 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 return true;
4818 }
4819 return false;
4820}
4821
Eric Laurentbfb1b832013-01-07 09:53:42 -08004822bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4823{
4824 Mutex::Autolock _l(mLock);
4825 return waitingAsyncCallback_l();
4826}
4827
4828void AudioFlinger::OffloadThread::flushHw_l()
4829{
Eric Laurente659ef42014-09-29 13:06:46 -07004830 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 // Flush anything still waiting in the mixbuffer
4832 mCurrentWriteLength = 0;
4833 mBytesRemaining = 0;
4834 mPausedWriteLength = 0;
4835 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004836
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004838 // discard any pending drain or write ack by incrementing sequence
4839 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4840 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004842 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4843 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004844 }
4845}
4846
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004847void AudioFlinger::OffloadThread::onAddNewTrack_l()
4848{
4849 sp<Track> previousTrack = mPreviousTrack.promote();
4850 sp<Track> latestTrack = mLatestActiveTrack.promote();
4851
4852 if (previousTrack != 0 && latestTrack != 0 &&
4853 (previousTrack->sessionId() != latestTrack->sessionId())) {
4854 mFlushPending = true;
4855 }
4856 PlaybackThread::onAddNewTrack_l();
4857}
4858
Eric Laurentbfb1b832013-01-07 09:53:42 -08004859// ----------------------------------------------------------------------------
4860
Eric Laurent81784c32012-11-19 14:55:58 -08004861AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4862 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4863 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4864 DUPLICATING),
4865 mWaitTimeMs(UINT_MAX)
4866{
4867 addOutputTrack(mainThread);
4868}
4869
4870AudioFlinger::DuplicatingThread::~DuplicatingThread()
4871{
4872 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4873 mOutputTracks[i]->destroy();
4874 }
4875}
4876
4877void AudioFlinger::DuplicatingThread::threadLoop_mix()
4878{
4879 // mix buffers...
4880 if (outputsReady(outputTracks)) {
4881 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4882 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004883 if (mMixerBufferValid) {
4884 memset(mMixerBuffer, 0, mMixerBufferSize);
4885 } else {
4886 memset(mSinkBuffer, 0, mSinkBufferSize);
4887 }
Eric Laurent81784c32012-11-19 14:55:58 -08004888 }
4889 sleepTime = 0;
4890 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004891 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004892 standbyTime = systemTime() + standbyDelay;
4893}
4894
4895void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4896{
4897 if (sleepTime == 0) {
4898 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4899 sleepTime = activeSleepTime;
4900 } else {
4901 sleepTime = idleSleepTime;
4902 }
4903 } else if (mBytesWritten != 0) {
4904 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4905 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004906 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004907 } else {
4908 // flush remaining overflow buffers in output tracks
4909 writeFrames = 0;
4910 }
4911 sleepTime = 0;
4912 }
4913}
4914
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004916{
4917 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004918 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004919 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004920 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004921 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004922}
4923
4924void AudioFlinger::DuplicatingThread::threadLoop_standby()
4925{
4926 // DuplicatingThread implements standby by stopping all tracks
4927 for (size_t i = 0; i < outputTracks.size(); i++) {
4928 outputTracks[i]->stop();
4929 }
4930}
4931
4932void AudioFlinger::DuplicatingThread::saveOutputTracks()
4933{
4934 outputTracks = mOutputTracks;
4935}
4936
4937void AudioFlinger::DuplicatingThread::clearOutputTracks()
4938{
4939 outputTracks.clear();
4940}
4941
4942void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4943{
4944 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004945 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4946 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4947 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4948 const size_t frameCount =
4949 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4950 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4951 // from different OutputTracks and their associated MixerThreads (e.g. one may
4952 // nearly empty and the other may be dropping data).
4953
4954 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004955 this,
4956 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004957 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004958 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004959 frameCount,
4960 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004961 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004962 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004963 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004964 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004965 updateWaitTime_l();
4966 }
4967}
4968
4969void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4970{
4971 Mutex::Autolock _l(mLock);
4972 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4973 if (mOutputTracks[i]->thread() == thread) {
4974 mOutputTracks[i]->destroy();
4975 mOutputTracks.removeAt(i);
4976 updateWaitTime_l();
4977 return;
4978 }
4979 }
4980 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4981}
4982
4983// caller must hold mLock
4984void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4985{
4986 mWaitTimeMs = UINT_MAX;
4987 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4988 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4989 if (strong != 0) {
4990 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4991 if (waitTimeMs < mWaitTimeMs) {
4992 mWaitTimeMs = waitTimeMs;
4993 }
4994 }
4995 }
4996}
4997
4998
4999bool AudioFlinger::DuplicatingThread::outputsReady(
5000 const SortedVector< sp<OutputTrack> > &outputTracks)
5001{
5002 for (size_t i = 0; i < outputTracks.size(); i++) {
5003 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5004 if (thread == 0) {
5005 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5006 outputTracks[i].get());
5007 return false;
5008 }
5009 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5010 // see note at standby() declaration
5011 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5012 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5013 thread.get());
5014 return false;
5015 }
5016 }
5017 return true;
5018}
5019
5020uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5021{
5022 return (mWaitTimeMs * 1000) / 2;
5023}
5024
5025void AudioFlinger::DuplicatingThread::cacheParameters_l()
5026{
5027 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5028 updateWaitTime_l();
5029
5030 MixerThread::cacheParameters_l();
5031}
5032
5033// ----------------------------------------------------------------------------
5034// Record
5035// ----------------------------------------------------------------------------
5036
5037AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5038 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005039 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005040 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005041 audio_devices_t inDevice
5042#ifdef TEE_SINK
5043 , const sp<NBAIO_Sink>& teeSink
5044#endif
5045 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005046 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005047 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005048 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005049 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005050#ifdef TEE_SINK
5051 , mTeeSink(teeSink)
5052#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005053 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5054 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005055 // mFastCapture below
5056 , mFastCaptureFutex(0)
5057 // mInputSource
5058 // mPipeSink
5059 // mPipeSource
5060 , mPipeFramesP2(0)
5061 // mPipeMemory
5062 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005063 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005064{
5065 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005066 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005067
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005068 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005069
5070 // create an NBAIO source for the HAL input stream, and negotiate
5071 mInputSource = new AudioStreamInSource(input->stream);
5072 size_t numCounterOffers = 0;
5073 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5074 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5075 ALOG_ASSERT(index == 0);
5076
5077 // initialize fast capture depending on configuration
5078 bool initFastCapture;
5079 switch (kUseFastCapture) {
5080 case FastCapture_Never:
5081 initFastCapture = false;
5082 break;
5083 case FastCapture_Always:
5084 initFastCapture = true;
5085 break;
5086 case FastCapture_Static:
5087 uint32_t primaryOutputSampleRate;
5088 {
5089 AutoMutex _l(audioFlinger->mHardwareLock);
5090 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5091 }
5092 initFastCapture =
5093 // either capture sample rate is same as (a reasonable) primary output sample rate
5094 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5095 (mSampleRate == primaryOutputSampleRate)) ||
5096 // or primary output sample rate is unknown, and capture sample rate is reasonable
5097 ((primaryOutputSampleRate == 0) &&
5098 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005099 // and the buffer size is < 12 ms
5100 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005101 break;
5102 // case FastCapture_Dynamic:
5103 }
5104
5105 if (initFastCapture) {
5106 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5107 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005108 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005109 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5110 void *pipeBuffer;
5111 const sp<MemoryDealer> roHeap(readOnlyHeap());
5112 sp<IMemory> pipeMemory;
5113 if ((roHeap == 0) ||
5114 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5115 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5116 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5117 goto failed;
5118 }
5119 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5120 memset(pipeBuffer, 0, pipeSize);
5121 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5122 const NBAIO_Format offers[1] = {format};
5123 size_t numCounterOffers = 0;
5124 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5125 ALOG_ASSERT(index == 0);
5126 mPipeSink = pipe;
5127 PipeReader *pipeReader = new PipeReader(*pipe);
5128 numCounterOffers = 0;
5129 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5130 ALOG_ASSERT(index == 0);
5131 mPipeSource = pipeReader;
5132 mPipeFramesP2 = pipeFramesP2;
5133 mPipeMemory = pipeMemory;
5134
5135 // create fast capture
5136 mFastCapture = new FastCapture();
5137 FastCaptureStateQueue *sq = mFastCapture->sq();
5138#ifdef STATE_QUEUE_DUMP
5139 // FIXME
5140#endif
5141 FastCaptureState *state = sq->begin();
5142 state->mCblk = NULL;
5143 state->mInputSource = mInputSource.get();
5144 state->mInputSourceGen++;
5145 state->mPipeSink = pipe;
5146 state->mPipeSinkGen++;
5147 state->mFrameCount = mFrameCount;
5148 state->mCommand = FastCaptureState::COLD_IDLE;
5149 // already done in constructor initialization list
5150 //mFastCaptureFutex = 0;
5151 state->mColdFutexAddr = &mFastCaptureFutex;
5152 state->mColdGen++;
5153 state->mDumpState = &mFastCaptureDumpState;
5154#ifdef TEE_SINK
5155 // FIXME
5156#endif
5157 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5158 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5159 sq->end();
5160 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5161
5162 // start the fast capture
5163 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5164 pid_t tid = mFastCapture->getTid();
5165 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5166 if (err != 0) {
5167 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5168 kPriorityFastCapture, getpid_cached, tid, err);
5169 }
5170
5171#ifdef AUDIO_WATCHDOG
5172 // FIXME
5173#endif
5174
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005175 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005176 }
5177failed: ;
5178
5179 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005180}
5181
5182
5183AudioFlinger::RecordThread::~RecordThread()
5184{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005185 if (mFastCapture != 0) {
5186 FastCaptureStateQueue *sq = mFastCapture->sq();
5187 FastCaptureState *state = sq->begin();
5188 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5189 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5190 if (old == -1) {
5191 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5192 }
5193 }
5194 state->mCommand = FastCaptureState::EXIT;
5195 sq->end();
5196 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5197 mFastCapture->join();
5198 mFastCapture.clear();
5199 }
5200 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005201 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005202 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005203}
5204
5205void AudioFlinger::RecordThread::onFirstRef()
5206{
5207 run(mName, PRIORITY_URGENT_AUDIO);
5208}
5209
Eric Laurent81784c32012-11-19 14:55:58 -08005210bool AudioFlinger::RecordThread::threadLoop()
5211{
Eric Laurent81784c32012-11-19 14:55:58 -08005212 nsecs_t lastWarning = 0;
5213
5214 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005215
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005216reacquire_wakelock:
5217 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005218 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005219 {
5220 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005221 size_t size = mActiveTracks.size();
5222 activeTracksGen = mActiveTracksGen;
5223 if (size > 0) {
5224 // FIXME an arbitrary choice
5225 activeTrack = mActiveTracks[0];
5226 acquireWakeLock_l(activeTrack->uid());
5227 if (size > 1) {
5228 SortedVector<int> tmp;
5229 for (size_t i = 0; i < size; i++) {
5230 tmp.add(mActiveTracks[i]->uid());
5231 }
5232 updateWakeLockUids_l(tmp);
5233 }
5234 } else {
5235 acquireWakeLock_l(-1);
5236 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005237 }
5238
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005239 // used to request a deferred sleep, to be executed later while mutex is unlocked
5240 uint32_t sleepUs = 0;
5241
5242 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005243 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005244 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005245
Glenn Kasten5edadd42013-08-14 16:30:49 -07005246 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005247 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005248 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005249 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005250 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005251 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005252 }
5253
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005254 // activeTracks accumulates a copy of a subset of mActiveTracks
5255 Vector< sp<RecordTrack> > activeTracks;
5256
Glenn Kasten735f45f2014-08-18 15:51:59 -07005257 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005258 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005259
Glenn Kasten735f45f2014-08-18 15:51:59 -07005260 // reference to a fast track which is about to be removed
5261 sp<RecordTrack> fastTrackToRemove;
5262
Eric Laurent81784c32012-11-19 14:55:58 -08005263 { // scope for mLock
5264 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005265
Eric Laurent021cf962014-05-13 10:18:14 -07005266 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005267
Eric Laurent000a4192014-01-29 15:17:32 -08005268 // check exitPending here because checkForNewParameters_l() and
5269 // checkForNewParameters_l() can temporarily release mLock
5270 if (exitPending()) {
5271 break;
5272 }
5273
Glenn Kasten2b806402013-11-20 16:37:38 -08005274 // if no active track(s), then standby and release wakelock
5275 size_t size = mActiveTracks.size();
5276 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005277 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005278 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005279 releaseWakeLock_l();
5280 ALOGV("RecordThread: loop stopping");
5281 // go to sleep
5282 mWaitWorkCV.wait(mLock);
5283 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005284 goto reacquire_wakelock;
5285 }
5286
Glenn Kasten2b806402013-11-20 16:37:38 -08005287 if (mActiveTracksGen != activeTracksGen) {
5288 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005289 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005290 for (size_t i = 0; i < size; i++) {
5291 tmp.add(mActiveTracks[i]->uid());
5292 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005293 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005294 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005295
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005296 bool doBroadcast = false;
5297 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005298
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005299 activeTrack = mActiveTracks[i];
5300 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005301 if (activeTrack->isFastTrack()) {
5302 ALOG_ASSERT(fastTrackToRemove == 0);
5303 fastTrackToRemove = activeTrack;
5304 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005305 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005306 mActiveTracks.remove(activeTrack);
5307 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005308 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005309 continue;
5310 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005311
5312 TrackBase::track_state activeTrackState = activeTrack->mState;
5313 switch (activeTrackState) {
5314
5315 case TrackBase::PAUSING:
5316 mActiveTracks.remove(activeTrack);
5317 mActiveTracksGen++;
5318 doBroadcast = true;
5319 size--;
5320 continue;
5321
5322 case TrackBase::STARTING_1:
5323 sleepUs = 10000;
5324 i++;
5325 continue;
5326
5327 case TrackBase::STARTING_2:
5328 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005329 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005330 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005331 break;
5332
5333 case TrackBase::ACTIVE:
5334 break;
5335
5336 case TrackBase::IDLE:
5337 i++;
5338 continue;
5339
5340 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005341 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005342 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005344 activeTracks.add(activeTrack);
5345 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005346
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005347 if (activeTrack->isFastTrack()) {
5348 ALOG_ASSERT(!mFastTrackAvail);
5349 ALOG_ASSERT(fastTrack == 0);
5350 fastTrack = activeTrack;
5351 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005353 if (doBroadcast) {
5354 mStartStopCond.broadcast();
5355 }
5356
5357 // sleep if there are no active tracks to process
5358 if (activeTracks.size() == 0) {
5359 if (sleepUs == 0) {
5360 sleepUs = kRecordThreadSleepUs;
5361 }
5362 continue;
5363 }
5364 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005365
Eric Laurent81784c32012-11-19 14:55:58 -08005366 lockEffectChains_l(effectChains);
5367 }
5368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005369 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005370
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005371 size_t size = effectChains.size();
5372 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005373 // thread mutex is not locked, but effect chain is locked
5374 effectChains[i]->process_l();
5375 }
5376
Glenn Kasten735f45f2014-08-18 15:51:59 -07005377 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005378 if (mFastCapture != 0) {
5379 FastCaptureStateQueue *sq = mFastCapture->sq();
5380 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005381 bool didModify = false;
5382 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005383 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5384 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5385 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5386 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5387 if (old == -1) {
5388 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5389 }
5390 }
5391 state->mCommand = FastCaptureState::READ_WRITE;
5392#if 0 // FIXME
5393 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005394 FastCaptureDumpState::kSamplingNforLowRamDevice :
5395 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005396#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005397 didModify = true;
5398 }
5399 audio_track_cblk_t *cblkOld = state->mCblk;
5400 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5401 if (cblkNew != cblkOld) {
5402 state->mCblk = cblkNew;
5403 // block until acked if removing a fast track
5404 if (cblkOld != NULL) {
5405 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5406 }
5407 didModify = true;
5408 }
5409 sq->end(didModify);
5410 if (didModify) {
5411 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005412#if 0
5413 if (kUseFastCapture == FastCapture_Dynamic) {
5414 mNormalSource = mPipeSource;
5415 }
5416#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005417 }
5418 }
5419
Glenn Kasten735f45f2014-08-18 15:51:59 -07005420 // now run the fast track destructor with thread mutex unlocked
5421 fastTrackToRemove.clear();
5422
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005423 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5424 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5425 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5426 // If destination is non-contiguous, first read past the nominal end of buffer, then
5427 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005428
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005430 ssize_t framesRead;
5431
5432 // If an NBAIO source is present, use it to read the normal capture's data
5433 if (mPipeSource != 0) {
5434 size_t framesToRead = mBufferSize / mFrameSize;
5435 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5436 framesToRead, AudioBufferProvider::kInvalidPTS);
5437 if (framesRead == 0) {
5438 // since pipe is non-blocking, simulate blocking input
5439 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5440 }
5441 // otherwise use the HAL / AudioStreamIn directly
5442 } else {
5443 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5444 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5445 if (bytesRead < 0) {
5446 framesRead = bytesRead;
5447 } else {
5448 framesRead = bytesRead / mFrameSize;
5449 }
5450 }
5451
5452 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5453 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 // Force input into standby so that it tries to recover at next read attempt
5455 inputStandBy();
5456 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005457 }
5458 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005459 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005460 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005461 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005462
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005463 if (mTeeSink != 0) {
5464 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5465 }
5466 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005467 {
5468 size_t part1 = mRsmpInFramesP2 - rear;
5469 if ((size_t) framesRead > part1) {
5470 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5471 (framesRead - part1) * mFrameSize);
5472 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 }
5474 rear = mRsmpInRear += framesRead;
5475
5476 size = activeTracks.size();
5477 // loop over each active track
5478 for (size_t i = 0; i < size; i++) {
5479 activeTrack = activeTracks[i];
5480
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005481 // skip fast tracks, as those are handled directly by FastCapture
5482 if (activeTrack->isFastTrack()) {
5483 continue;
5484 }
5485
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005486 enum {
5487 OVERRUN_UNKNOWN,
5488 OVERRUN_TRUE,
5489 OVERRUN_FALSE
5490 } overrun = OVERRUN_UNKNOWN;
5491
5492 // loop over getNextBuffer to handle circular sink
5493 for (;;) {
5494
5495 activeTrack->mSink.frameCount = ~0;
5496 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5497 size_t framesOut = activeTrack->mSink.frameCount;
5498 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5499
5500 int32_t front = activeTrack->mRsmpInFront;
5501 ssize_t filled = rear - front;
5502 size_t framesIn;
5503
5504 if (filled < 0) {
5505 // should not happen, but treat like a massive overrun and re-sync
5506 framesIn = 0;
5507 activeTrack->mRsmpInFront = rear;
5508 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005509 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005510 framesIn = (size_t) filled;
5511 } else {
5512 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005513 framesIn = mRsmpInFrames;
5514 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005515 overrun = OVERRUN_TRUE;
5516 }
5517
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005518 if (framesOut == 0 || framesIn == 0) {
5519 break;
5520 }
5521
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005522 if (activeTrack->mResampler == NULL) {
5523 // no resampling
5524 if (framesIn > framesOut) {
5525 framesIn = framesOut;
5526 } else {
5527 framesOut = framesIn;
5528 }
5529 int8_t *dst = activeTrack->mSink.i8;
5530 while (framesIn > 0) {
5531 front &= mRsmpInFramesP2 - 1;
5532 size_t part1 = mRsmpInFramesP2 - front;
5533 if (part1 > framesIn) {
5534 part1 = framesIn;
5535 }
5536 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005537 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005538 memcpy(dst, src, part1 * mFrameSize);
5539 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005540 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005541 part1);
5542 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005543 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5544 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005545 }
5546 dst += part1 * activeTrack->mFrameSize;
5547 front += part1;
5548 framesIn -= part1;
5549 }
5550 activeTrack->mRsmpInFront += framesOut;
5551
5552 } else {
5553 // resampling
5554 // FIXME framesInNeeded should really be part of resampler API, and should
5555 // depend on the SRC ratio
5556 // to keep mRsmpInBuffer full so resampler always has sufficient input
5557 size_t framesInNeeded;
5558 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005559 // Do not precompute in/out because floating point is not associative
5560 // e.g. a*b/c != a*(b/c).
5561 const double in(mSampleRate);
5562 const double out(activeTrack->mSampleRate);
5563 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005564 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005565 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005566 // Although we theoretically have framesIn in circular buffer, some of those are
5567 // unreleased frames, and thus must be discounted for purpose of budgeting.
5568 size_t unreleased = activeTrack->mRsmpInUnrel;
5569 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005570 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005571 ALOGV("not enough to resample: have %u frames in but need %u in to "
5572 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005573 framesIn, framesInNeeded, framesOut, in / out);
5574 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005575 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5576 if (newFramesOut == 0) {
5577 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005578 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005579 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005580 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005581 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005582 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5583 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5584 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005585 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005586 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005587 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005588 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005589 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005590 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 }
5592
5593 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5594 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005595 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005596 delete[] activeTrack->mRsmpOutBuffer;
5597 // resampler always outputs stereo
5598 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5599 activeTrack->mRsmpOutFrameCount = framesOut;
5600 }
5601
5602 // resampler accumulates, but we only have one source track
5603 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5604 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005605 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005606 activeTrack->mResamplerBufferProvider
5607 /*this*/ /* AudioBufferProvider* */);
5608 // ditherAndClamp() works as long as all buffers returned by
5609 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005610 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005611 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005612 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5613 framesOut);
5614 // the resampler always outputs stereo samples:
5615 // do post stereo to mono conversion
5616 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005617 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005618 } else {
5619 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5620 activeTrack->mRsmpOutBuffer, framesOut);
5621 }
5622 // now done with mRsmpOutBuffer
5623
5624 }
5625
5626 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5627 overrun = OVERRUN_FALSE;
5628 }
5629
5630 if (activeTrack->mFramesToDrop == 0) {
5631 if (framesOut > 0) {
5632 activeTrack->mSink.frameCount = framesOut;
5633 activeTrack->releaseBuffer(&activeTrack->mSink);
5634 }
5635 } else {
5636 // FIXME could do a partial drop of framesOut
5637 if (activeTrack->mFramesToDrop > 0) {
5638 activeTrack->mFramesToDrop -= framesOut;
5639 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005640 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641 }
5642 } else {
5643 activeTrack->mFramesToDrop += framesOut;
5644 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5645 activeTrack->mSyncStartEvent->isCancelled()) {
5646 ALOGW("Synced record %s, session %d, trigger session %d",
5647 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5648 activeTrack->sessionId(),
5649 (activeTrack->mSyncStartEvent != 0) ?
5650 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005651 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 }
5653 }
5654 }
5655
5656 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005657 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005658 }
5659 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005660
5661 switch (overrun) {
5662 case OVERRUN_TRUE:
5663 // client isn't retrieving buffers fast enough
5664 if (!activeTrack->setOverflow()) {
5665 nsecs_t now = systemTime();
5666 // FIXME should lastWarning per track?
5667 if ((now - lastWarning) > kWarningThrottleNs) {
5668 ALOGW("RecordThread: buffer overflow");
5669 lastWarning = now;
5670 }
5671 }
5672 break;
5673 case OVERRUN_FALSE:
5674 activeTrack->clearOverflow();
5675 break;
5676 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005677 break;
5678 }
5679
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005680 }
5681
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005682unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005683 // enable changes in effect chain
5684 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005685 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005686 }
5687
Glenn Kasten93e471f2013-08-19 08:40:07 -07005688 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005689
5690 {
5691 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005692 for (size_t i = 0; i < mTracks.size(); i++) {
5693 sp<RecordTrack> track = mTracks[i];
5694 track->invalidate();
5695 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005696 mActiveTracks.clear();
5697 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005698 mStartStopCond.broadcast();
5699 }
5700
5701 releaseWakeLock();
5702
5703 ALOGV("RecordThread %p exiting", this);
5704 return false;
5705}
5706
Glenn Kasten93e471f2013-08-19 08:40:07 -07005707void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005708{
5709 if (!mStandby) {
5710 inputStandBy();
5711 mStandby = true;
5712 }
5713}
5714
5715void AudioFlinger::RecordThread::inputStandBy()
5716{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005717 // Idle the fast capture if it's currently running
5718 if (mFastCapture != 0) {
5719 FastCaptureStateQueue *sq = mFastCapture->sq();
5720 FastCaptureState *state = sq->begin();
5721 if (!(state->mCommand & FastCaptureState::IDLE)) {
5722 state->mCommand = FastCaptureState::COLD_IDLE;
5723 state->mColdFutexAddr = &mFastCaptureFutex;
5724 state->mColdGen++;
5725 mFastCaptureFutex = 0;
5726 sq->end();
5727 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5728 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5729#if 0
5730 if (kUseFastCapture == FastCapture_Dynamic) {
5731 // FIXME
5732 }
5733#endif
5734#ifdef AUDIO_WATCHDOG
5735 // FIXME
5736#endif
5737 } else {
5738 sq->end(false /*didModify*/);
5739 }
5740 }
Eric Laurent81784c32012-11-19 14:55:58 -08005741 mInput->stream->common.standby(&mInput->stream->common);
5742}
5743
Glenn Kasten05997e22014-03-13 15:08:33 -07005744// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005745sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005746 const sp<AudioFlinger::Client>& client,
5747 uint32_t sampleRate,
5748 audio_format_t format,
5749 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005750 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005751 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005752 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005753 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005754 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005755 pid_t tid,
5756 status_t *status)
5757{
Glenn Kasten74935e42013-12-19 08:56:45 -08005758 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005759 sp<RecordTrack> track;
5760 status_t lStatus;
5761
Glenn Kasten90e58b12013-07-31 16:16:02 -07005762 // client expresses a preference for FAST, but we get the final say
5763 if (*flags & IAudioFlinger::TRACK_FAST) {
5764 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005765 // use case: callback handler
5766 (tid != -1) &&
5767 // frame count is not specified, or is exactly the pipe depth
5768 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005769 // PCM data
5770 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005771 // native format
5772 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005773 // native channel mask
5774 (channelMask == mChannelMask) &&
5775 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005776 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005777 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005778 hasFastCapture() &&
5779 // there are sufficient fast track slots available
5780 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005781 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005782 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005783 frameCount, mFrameCount);
5784 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005785 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5786 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005787 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005788 frameCount, mFrameCount, mPipeFramesP2,
5789 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5790 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005791 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005792 }
5793 }
5794
5795 // compute track buffer size in frames, and suggest the notification frame count
5796 if (*flags & IAudioFlinger::TRACK_FAST) {
5797 // fast track: frame count is exactly the pipe depth
5798 frameCount = mPipeFramesP2;
5799 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5800 *notificationFrames = mFrameCount;
5801 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005802 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5803 // or 20 ms if there is a fast capture
5804 // TODO This could be a roundupRatio inline, and const
5805 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5806 * sampleRate + mSampleRate - 1) / mSampleRate;
5807 // minimum number of notification periods is at least kMinNotifications,
5808 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5809 static const size_t kMinNotifications = 3;
5810 static const uint32_t kMinMs = 30;
5811 // TODO This could be a roundupRatio inline
5812 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5813 // TODO This could be a roundupRatio inline
5814 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5815 maxNotificationFrames;
5816 const size_t minFrameCount = maxNotificationFrames *
5817 max(kMinNotifications, minNotificationsByMs);
5818 frameCount = max(frameCount, minFrameCount);
5819 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5820 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005821 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005822 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005823 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005824
Glenn Kasten15e57982013-09-24 11:52:37 -07005825 lStatus = initCheck();
5826 if (lStatus != NO_ERROR) {
5827 ALOGE("createRecordTrack_l() audio driver not initialized");
5828 goto Exit;
5829 }
Eric Laurent81784c32012-11-19 14:55:58 -08005830
5831 { // scope for mLock
5832 Mutex::Autolock _l(mLock);
5833
5834 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005835 format, channelMask, frameCount, NULL, sessionId, uid,
5836 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005837
Glenn Kasten03003332013-08-06 15:40:54 -07005838 lStatus = track->initCheck();
5839 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005840 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005841 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005842 goto Exit;
5843 }
5844 mTracks.add(track);
5845
5846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5847 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5848 mAudioFlinger->btNrecIsOff();
5849 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5850 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005851
5852 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5853 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5854 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5855 // so ask activity manager to do this on our behalf
5856 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5857 }
Eric Laurent81784c32012-11-19 14:55:58 -08005858 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005859
Eric Laurent81784c32012-11-19 14:55:58 -08005860 lStatus = NO_ERROR;
5861
5862Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005863 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005864 return track;
5865}
5866
5867status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5868 AudioSystem::sync_event_t event,
5869 int triggerSession)
5870{
5871 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5872 sp<ThreadBase> strongMe = this;
5873 status_t status = NO_ERROR;
5874
5875 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005876 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005877 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005878 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005879 triggerSession,
5880 recordTrack->sessionId(),
5881 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005883 // Sync event can be cancelled by the trigger session if the track is not in a
5884 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005885 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005886 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005887 } else {
5888 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005890 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005891 }
5892 }
5893
5894 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005895 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005896 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005897 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5898 if (recordTrack->mState == TrackBase::PAUSING) {
5899 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005900 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901 } else {
5902 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005903 }
5904 return status;
5905 }
5906
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005907 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5908 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5909 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005910 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005911 mActiveTracks.add(recordTrack);
5912 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005913 status_t status = NO_ERROR;
5914 if (recordTrack->isExternalTrack()) {
5915 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005916 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005917 mLock.lock();
5918 // FIXME should verify that recordTrack is still in mActiveTracks
5919 if (status != NO_ERROR) {
5920 mActiveTracks.remove(recordTrack);
5921 mActiveTracksGen++;
5922 recordTrack->clearSyncStartEvent();
5923 ALOGV("RecordThread::start error %d", status);
5924 return status;
5925 }
Eric Laurent81784c32012-11-19 14:55:58 -08005926 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 // Catch up with current buffer indices if thread is already running.
5928 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5929 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5930 // see previously buffered data before it called start(), but with greater risk of overrun.
5931
5932 recordTrack->mRsmpInFront = mRsmpInRear;
5933 recordTrack->mRsmpInUnrel = 0;
5934 // FIXME why reset?
5935 if (recordTrack->mResampler != NULL) {
5936 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005937 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005938 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005939 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005940 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005941 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005942 ALOGV("Record failed to start");
5943 status = BAD_VALUE;
5944 goto startError;
5945 }
Eric Laurent81784c32012-11-19 14:55:58 -08005946 return status;
5947 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005948
Eric Laurent81784c32012-11-19 14:55:58 -08005949startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005950 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005951 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005952 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005953 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005954 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005955 return status;
5956}
5957
Eric Laurent81784c32012-11-19 14:55:58 -08005958void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5959{
5960 sp<SyncEvent> strongEvent = event.promote();
5961
5962 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005963 sp<RefBase> ptr = strongEvent->cookie().promote();
5964 if (ptr != 0) {
5965 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5966 recordTrack->handleSyncStartEvent(strongEvent);
5967 }
Eric Laurent81784c32012-11-19 14:55:58 -08005968 }
5969}
5970
Glenn Kastena8356f62013-07-25 14:37:52 -07005971bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005972 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005973 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005974 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005975 return false;
5976 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005977 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005978 recordTrack->mState = TrackBase::PAUSING;
5979 // do not wait for mStartStopCond if exiting
5980 if (exitPending()) {
5981 return true;
5982 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005983 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005984 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005985 // if we have been restarted, recordTrack is in mActiveTracks here
5986 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005987 ALOGV("Record stopped OK");
5988 return true;
5989 }
5990 return false;
5991}
5992
Glenn Kasten0f11b512014-01-31 16:18:54 -08005993bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005994{
5995 return false;
5996}
5997
Glenn Kasten0f11b512014-01-31 16:18:54 -08005998status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005999{
6000#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6001 if (!isValidSyncEvent(event)) {
6002 return BAD_VALUE;
6003 }
6004
6005 int eventSession = event->triggerSession();
6006 status_t ret = NAME_NOT_FOUND;
6007
6008 Mutex::Autolock _l(mLock);
6009
6010 for (size_t i = 0; i < mTracks.size(); i++) {
6011 sp<RecordTrack> track = mTracks[i];
6012 if (eventSession == track->sessionId()) {
6013 (void) track->setSyncEvent(event);
6014 ret = NO_ERROR;
6015 }
6016 }
6017 return ret;
6018#else
6019 return BAD_VALUE;
6020#endif
6021}
6022
6023// destroyTrack_l() must be called with ThreadBase::mLock held
6024void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6025{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006026 track->terminate();
6027 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006028 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006029 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006030 removeTrack_l(track);
6031 }
6032}
6033
6034void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6035{
6036 mTracks.remove(track);
6037 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006038 if (track->isFastTrack()) {
6039 ALOG_ASSERT(!mFastTrackAvail);
6040 mFastTrackAvail = true;
6041 }
Eric Laurent81784c32012-11-19 14:55:58 -08006042}
6043
6044void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6045{
6046 dumpInternals(fd, args);
6047 dumpTracks(fd, args);
6048 dumpEffectChains(fd, args);
6049}
6050
6051void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6052{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006053 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006054
Glenn Kasten2b806402013-11-20 16:37:38 -08006055 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006056 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006057 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006058 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006059 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006060 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006061 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006062
Eric Laurent81784c32012-11-19 14:55:58 -08006063 dumpBase(fd, args);
6064}
6065
Glenn Kasten0f11b512014-01-31 16:18:54 -08006066void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006067{
6068 const size_t SIZE = 256;
6069 char buffer[SIZE];
6070 String8 result;
6071
Marco Nelissenb2208842014-02-07 14:00:50 -08006072 size_t numtracks = mTracks.size();
6073 size_t numactive = mActiveTracks.size();
6074 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006075 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006076 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006077 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006078 RecordTrack::appendDumpHeader(result);
6079 for (size_t i = 0; i < numtracks ; ++i) {
6080 sp<RecordTrack> track = mTracks[i];
6081 if (track != 0) {
6082 bool active = mActiveTracks.indexOf(track) >= 0;
6083 if (active) {
6084 numactiveseen++;
6085 }
6086 track->dump(buffer, SIZE, active);
6087 result.append(buffer);
6088 }
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006090 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006091 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006092 }
6093
Marco Nelissenb2208842014-02-07 14:00:50 -08006094 if (numactiveseen != numactive) {
6095 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6096 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006097 result.append(buffer);
6098 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006099 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006100 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006101 if (mTracks.indexOf(track) < 0) {
6102 track->dump(buffer, SIZE, true);
6103 result.append(buffer);
6104 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006105 }
Eric Laurent81784c32012-11-19 14:55:58 -08006106
6107 }
6108 write(fd, result.string(), result.size());
6109}
6110
6111// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006112status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6113 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006114{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 RecordTrack *activeTrack = mRecordTrack;
6116 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6117 if (threadBase == 0) {
6118 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006119 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 return NOT_ENOUGH_DATA;
6121 }
6122 RecordThread *recordThread = (RecordThread *) threadBase.get();
6123 int32_t rear = recordThread->mRsmpInRear;
6124 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006125 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 // FIXME should not be P2 (don't want to increase latency)
6127 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006128 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006129 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006130 front &= recordThread->mRsmpInFramesP2 - 1;
6131 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006132 if (part1 > (size_t) filled) {
6133 part1 = filled;
6134 }
6135 size_t ask = buffer->frameCount;
6136 ALOG_ASSERT(ask > 0);
6137 if (part1 > ask) {
6138 part1 = ask;
6139 }
6140 if (part1 == 0) {
6141 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006142 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006143 buffer->raw = NULL;
6144 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006146 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006147 }
6148
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006150 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 return NO_ERROR;
6153}
6154
6155// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6157 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006158{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006160 size_t stepCount = buffer->frameCount;
6161 if (stepCount == 0) {
6162 return;
6163 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6165 activeTrack->mRsmpInUnrel -= stepCount;
6166 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006167 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006168 buffer->frameCount = 0;
6169}
6170
Eric Laurent10351942014-05-08 18:49:52 -07006171bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6172 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006173{
6174 bool reconfig = false;
6175
Eric Laurent10351942014-05-08 18:49:52 -07006176 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006177
Eric Laurent10351942014-05-08 18:49:52 -07006178 audio_format_t reqFormat = mFormat;
6179 uint32_t samplingRate = mSampleRate;
6180 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6181
6182 AudioParameter param = AudioParameter(keyValuePair);
6183 int value;
6184 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6185 // channel count change can be requested. Do we mandate the first client defines the
6186 // HAL sampling rate and channel count or do we allow changes on the fly?
6187 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6188 samplingRate = value;
6189 reconfig = true;
6190 }
6191 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6192 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6193 status = BAD_VALUE;
6194 } else {
6195 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006196 reconfig = true;
6197 }
Eric Laurent10351942014-05-08 18:49:52 -07006198 }
6199 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6200 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6201 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6202 status = BAD_VALUE;
6203 } else {
6204 channelMask = mask;
6205 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006206 }
Eric Laurent10351942014-05-08 18:49:52 -07006207 }
6208 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6209 // do not accept frame count changes if tracks are open as the track buffer
6210 // size depends on frame count and correct behavior would not be guaranteed
6211 // if frame count is changed after track creation
6212 if (mActiveTracks.size() > 0) {
6213 status = INVALID_OPERATION;
6214 } else {
6215 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 }
Eric Laurent10351942014-05-08 18:49:52 -07006217 }
6218 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6219 // forward device change to effects that have requested to be
6220 // aware of attached audio device.
6221 for (size_t i = 0; i < mEffectChains.size(); i++) {
6222 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
Eric Laurent81784c32012-11-19 14:55:58 -08006224
Eric Laurent10351942014-05-08 18:49:52 -07006225 // store input device and output device but do not forward output device to audio HAL.
6226 // Note that status is ignored by the caller for output device
6227 // (see AudioFlinger::setParameters()
6228 if (audio_is_output_devices(value)) {
6229 mOutDevice = value;
6230 status = BAD_VALUE;
6231 } else {
6232 mInDevice = value;
6233 // disable AEC and NS if the device is a BT SCO headset supporting those
6234 // pre processings
6235 if (mTracks.size() > 0) {
6236 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6237 mAudioFlinger->btNrecIsOff();
6238 for (size_t i = 0; i < mTracks.size(); i++) {
6239 sp<RecordTrack> track = mTracks[i];
6240 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6241 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006242 }
6243 }
6244 }
Eric Laurent10351942014-05-08 18:49:52 -07006245 }
6246 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6247 mAudioSource != (audio_source_t)value) {
6248 // forward device change to effects that have requested to be
6249 // aware of attached audio device.
6250 for (size_t i = 0; i < mEffectChains.size(); i++) {
6251 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006252 }
Eric Laurent10351942014-05-08 18:49:52 -07006253 mAudioSource = (audio_source_t)value;
6254 }
Glenn Kastene198c362013-08-13 09:13:36 -07006255
Eric Laurent10351942014-05-08 18:49:52 -07006256 if (status == NO_ERROR) {
6257 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6258 keyValuePair.string());
6259 if (status == INVALID_OPERATION) {
6260 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006261 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6262 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006263 }
6264 if (reconfig) {
6265 if (status == BAD_VALUE &&
6266 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6267 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6268 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6269 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006270 audio_channel_count_from_in_mask(
6271 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006272 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6273 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6274 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006275 }
Eric Laurent10351942014-05-08 18:49:52 -07006276 if (status == NO_ERROR) {
6277 readInputParameters_l();
6278 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006279 }
6280 }
Eric Laurent81784c32012-11-19 14:55:58 -08006281 }
Eric Laurent10351942014-05-08 18:49:52 -07006282
Eric Laurent81784c32012-11-19 14:55:58 -08006283 return reconfig;
6284}
6285
6286String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6287{
Eric Laurent81784c32012-11-19 14:55:58 -08006288 Mutex::Autolock _l(mLock);
6289 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006290 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006291 }
6292
Glenn Kastend8ea6992013-07-16 14:17:15 -07006293 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6294 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006295 free(s);
6296 return out_s8;
6297}
6298
Eric Laurent021cf962014-05-13 10:18:14 -07006299void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006300 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006301 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006302
6303 switch (event) {
6304 case AudioSystem::INPUT_OPENED:
6305 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006306 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006307 desc.samplingRate = mSampleRate;
6308 desc.format = mFormat;
6309 desc.frameCount = mFrameCount;
6310 desc.latency = 0;
6311 param2 = &desc;
6312 break;
6313
6314 case AudioSystem::INPUT_CLOSED:
6315 default:
6316 break;
6317 }
Eric Laurent021cf962014-05-13 10:18:14 -07006318 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006319}
6320
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006321void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006322{
Eric Laurent81784c32012-11-19 14:55:58 -08006323 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6324 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006325 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006326 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6327 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006328 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006329 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006330 }
Eric Laurent665470b2014-07-03 16:37:08 -07006331 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006332 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6333 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006335 // 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 -07006336 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006337 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 // A larger value should allow more old data to be read after a track calls start(),
6339 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006340 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006341 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006342 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006343
6344 // TODO optimize audio capture buffer sizes ...
6345 // Here we calculate the size of the sliding buffer used as a source
6346 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6347 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6348 // be better to have it derived from the pipe depth in the long term.
6349 // The current value is higher than necessary. However it should not add to latency.
6350
Glenn Kasten85948432013-08-19 12:09:05 -07006351 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6352 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006353
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006354 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6355 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006356}
6357
Glenn Kasten5f972c02014-01-13 09:59:31 -08006358uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006359{
6360 Mutex::Autolock _l(mLock);
6361 if (initCheck() != NO_ERROR) {
6362 return 0;
6363 }
6364
6365 return mInput->stream->get_input_frames_lost(mInput->stream);
6366}
6367
6368uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6369{
6370 Mutex::Autolock _l(mLock);
6371 uint32_t result = 0;
6372 if (getEffectChain_l(sessionId) != 0) {
6373 result = EFFECT_SESSION;
6374 }
6375
6376 for (size_t i = 0; i < mTracks.size(); ++i) {
6377 if (sessionId == mTracks[i]->sessionId()) {
6378 result |= TRACK_SESSION;
6379 break;
6380 }
6381 }
6382
6383 return result;
6384}
6385
6386KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6387{
6388 KeyedVector<int, bool> ids;
6389 Mutex::Autolock _l(mLock);
6390 for (size_t j = 0; j < mTracks.size(); ++j) {
6391 sp<RecordThread::RecordTrack> track = mTracks[j];
6392 int sessionId = track->sessionId();
6393 if (ids.indexOfKey(sessionId) < 0) {
6394 ids.add(sessionId, true);
6395 }
6396 }
6397 return ids;
6398}
6399
6400AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6401{
6402 Mutex::Autolock _l(mLock);
6403 AudioStreamIn *input = mInput;
6404 mInput = NULL;
6405 return input;
6406}
6407
6408// this method must always be called either with ThreadBase mLock held or inside the thread loop
6409audio_stream_t* AudioFlinger::RecordThread::stream() const
6410{
6411 if (mInput == NULL) {
6412 return NULL;
6413 }
6414 return &mInput->stream->common;
6415}
6416
6417status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6418{
6419 // only one chain per input thread
6420 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006421 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006422 return INVALID_OPERATION;
6423 }
6424 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006425 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006426 chain->setInBuffer(NULL);
6427 chain->setOutBuffer(NULL);
6428
6429 checkSuspendOnAddEffectChain_l(chain);
6430
Eric Laurent1b928682014-10-02 19:41:47 -07006431 // make sure enabled pre processing effects state is communicated to the HAL as we
6432 // just moved them to a new input stream.
6433 chain->syncHalEffectsState();
6434
Eric Laurent81784c32012-11-19 14:55:58 -08006435 mEffectChains.add(chain);
6436
6437 return NO_ERROR;
6438}
6439
6440size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6441{
6442 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6443 ALOGW_IF(mEffectChains.size() != 1,
6444 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6445 chain.get(), mEffectChains.size(), this);
6446 if (mEffectChains.size() == 1) {
6447 mEffectChains.removeAt(0);
6448 }
6449 return 0;
6450}
6451
Eric Laurent1c333e22014-05-20 10:48:17 -07006452status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6453 audio_patch_handle_t *handle)
6454{
6455 status_t status = NO_ERROR;
6456 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6457 // store new device and send to effects
6458 mInDevice = patch->sources[0].ext.device.type;
6459 for (size_t i = 0; i < mEffectChains.size(); i++) {
6460 mEffectChains[i]->setDevice_l(mInDevice);
6461 }
6462
6463 // disable AEC and NS if the device is a BT SCO headset supporting those
6464 // pre processings
6465 if (mTracks.size() > 0) {
6466 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6467 mAudioFlinger->btNrecIsOff();
6468 for (size_t i = 0; i < mTracks.size(); i++) {
6469 sp<RecordTrack> track = mTracks[i];
6470 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6471 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6472 }
6473 }
6474
6475 // store new source and send to effects
6476 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6477 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6478 for (size_t i = 0; i < mEffectChains.size(); i++) {
6479 mEffectChains[i]->setAudioSource_l(mAudioSource);
6480 }
6481 }
6482
6483 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6484 status = hwDevice->create_audio_patch(hwDevice,
6485 patch->num_sources,
6486 patch->sources,
6487 patch->num_sinks,
6488 patch->sinks,
6489 handle);
6490 } else {
6491 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6492 }
6493 return status;
6494}
6495
6496status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6497{
6498 status_t status = NO_ERROR;
6499 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6500 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6501 status = hwDevice->release_audio_patch(hwDevice, handle);
6502 } else {
6503 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6504 }
6505 return status;
6506}
6507
Eric Laurent83b88082014-06-20 18:31:16 -07006508void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6509{
6510 Mutex::Autolock _l(mLock);
6511 mTracks.add(record);
6512}
6513
6514void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6515{
6516 Mutex::Autolock _l(mLock);
6517 destroyTrack_l(record);
6518}
6519
6520void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6521{
6522 ThreadBase::getAudioPortConfig(config);
6523 config->role = AUDIO_PORT_ROLE_SINK;
6524 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6525 config->ext.mix.usecase.source = mAudioSource;
6526}
Eric Laurent1c333e22014-05-20 10:48:17 -07006527
Eric Laurent81784c32012-11-19 14:55:58 -08006528}; // namespace android