blob: 7451245a020c38fa972f72eb2c247a0477cf4e94 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// ----------------------------------------------------------------------------
178
Glenn Kasten03490092014-05-27 12:30:54 -0700179static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
180
181static void sFastTrackMultiplierInit()
182{
183 char value[PROPERTY_VALUE_MAX];
184 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
185 char *endptr;
186 unsigned long ul = strtoul(value, &endptr, 0);
187 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
188 sFastTrackMultiplier = (int) ul;
189 }
190 }
191}
192
193// ----------------------------------------------------------------------------
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195#ifdef ADD_BATTERY_DATA
196// To collect the amplifier usage
197static void addBatteryData(uint32_t params) {
198 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
199 if (service == NULL) {
200 // it already logged
201 return;
202 }
203
204 service->addBatteryData(params);
205}
206#endif
207
208
209// ----------------------------------------------------------------------------
210// CPU Stats
211// ----------------------------------------------------------------------------
212
213class CpuStats {
214public:
215 CpuStats();
216 void sample(const String8 &title);
217#ifdef DEBUG_CPU_USAGE
218private:
219 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
220 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
221
222 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
223
224 int mCpuNum; // thread's current CPU number
225 int mCpukHz; // frequency of thread's current CPU in kHz
226#endif
227};
228
229CpuStats::CpuStats()
230#ifdef DEBUG_CPU_USAGE
231 : mCpuNum(-1), mCpukHz(-1)
232#endif
233{
234}
235
Glenn Kasten0f11b512014-01-31 16:18:54 -0800236void CpuStats::sample(const String8 &title
237#ifndef DEBUG_CPU_USAGE
238 __unused
239#endif
240 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800241#ifdef DEBUG_CPU_USAGE
242 // get current thread's delta CPU time in wall clock ns
243 double wcNs;
244 bool valid = mCpuUsage.sampleAndEnable(wcNs);
245
246 // record sample for wall clock statistics
247 if (valid) {
248 mWcStats.sample(wcNs);
249 }
250
251 // get the current CPU number
252 int cpuNum = sched_getcpu();
253
254 // get the current CPU frequency in kHz
255 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
256
257 // check if either CPU number or frequency changed
258 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
259 mCpuNum = cpuNum;
260 mCpukHz = cpukHz;
261 // ignore sample for purposes of cycles
262 valid = false;
263 }
264
265 // if no change in CPU number or frequency, then record sample for cycle statistics
266 if (valid && mCpukHz > 0) {
267 double cycles = wcNs * cpukHz * 0.000001;
268 mHzStats.sample(cycles);
269 }
270
271 unsigned n = mWcStats.n();
272 // mCpuUsage.elapsed() is expensive, so don't call it every loop
273 if ((n & 127) == 1) {
274 long long elapsed = mCpuUsage.elapsed();
275 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
276 double perLoop = elapsed / (double) n;
277 double perLoop100 = perLoop * 0.01;
278 double perLoop1k = perLoop * 0.001;
279 double mean = mWcStats.mean();
280 double stddev = mWcStats.stddev();
281 double minimum = mWcStats.minimum();
282 double maximum = mWcStats.maximum();
283 double meanCycles = mHzStats.mean();
284 double stddevCycles = mHzStats.stddev();
285 double minCycles = mHzStats.minimum();
286 double maxCycles = mHzStats.maximum();
287 mCpuUsage.resetElapsed();
288 mWcStats.reset();
289 mHzStats.reset();
290 ALOGD("CPU usage for %s over past %.1f secs\n"
291 " (%u mixer loops at %.1f mean ms per loop):\n"
292 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
293 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
294 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
295 title.string(),
296 elapsed * .000000001, n, perLoop * .000001,
297 mean * .001,
298 stddev * .001,
299 minimum * .001,
300 maximum * .001,
301 mean / perLoop100,
302 stddev / perLoop100,
303 minimum / perLoop100,
304 maximum / perLoop100,
305 meanCycles / perLoop1k,
306 stddevCycles / perLoop1k,
307 minCycles / perLoop1k,
308 maxCycles / perLoop1k);
309
310 }
311 }
312#endif
313};
314
315// ----------------------------------------------------------------------------
316// ThreadBase
317// ----------------------------------------------------------------------------
318
Glenn Kasten97b7b752014-09-28 13:04:24 -0700319// static
320const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
321{
322 switch (type) {
323 case MIXER:
324 return "MIXER";
325 case DIRECT:
326 return "DIRECT";
327 case DUPLICATING:
328 return "DUPLICATING";
329 case RECORD:
330 return "RECORD";
331 case OFFLOAD:
332 return "OFFLOAD";
333 default:
334 return "unknown";
335 }
336}
337
338static String8 outputFlagsToString(audio_output_flags_t flags)
339{
340 static const struct mapping {
341 audio_output_flags_t mFlag;
342 const char * mString;
343 } mappings[] = {
344 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
345 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
346 AUDIO_OUTPUT_FLAG_FAST, "FAST",
347 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
348 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAAD",
349 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
350 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
351 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
352 };
353 String8 result;
354 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
355 const mapping *entry;
356 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
357 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
358 if (flags & entry->mFlag) {
359 if (!result.isEmpty()) {
360 result.append("|");
361 }
362 result.append(entry->mString);
363 }
364 }
365 if (flags & ~allFlags) {
366 if (!result.isEmpty()) {
367 result.append("|");
368 }
369 result.appendFormat("0x%X", flags & ~allFlags);
370 }
371 if (result.isEmpty()) {
372 result.append(entry->mString);
373 }
374 return result;
375}
376
Eric Laurent81784c32012-11-19 14:55:58 -0800377AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
378 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
379 : Thread(false /*canCallJava*/),
380 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700381 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700382 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800383 // are set by PlaybackThread::readOutputParameters_l() or
384 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700385 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800386 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
387 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
388 // mName will be set by concrete (non-virtual) subclass
389 mDeathRecipient(new PMDeathRecipient(this))
390{
391}
392
393AudioFlinger::ThreadBase::~ThreadBase()
394{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700395 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700396 mConfigEvents.clear();
397
Eric Laurent81784c32012-11-19 14:55:58 -0800398 // do not lock the mutex in destructor
399 releaseWakeLock_l();
400 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800401 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800402 binder->unlinkToDeath(mDeathRecipient);
403 }
404}
405
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700406status_t AudioFlinger::ThreadBase::readyToRun()
407{
408 status_t status = initCheck();
409 if (status == NO_ERROR) {
410 ALOGI("AudioFlinger's thread %p ready to run", this);
411 } else {
412 ALOGE("No working audio driver found.");
413 }
414 return status;
415}
416
Eric Laurent81784c32012-11-19 14:55:58 -0800417void AudioFlinger::ThreadBase::exit()
418{
419 ALOGV("ThreadBase::exit");
420 // do any cleanup required for exit to succeed
421 preExit();
422 {
423 // This lock prevents the following race in thread (uniprocessor for illustration):
424 // if (!exitPending()) {
425 // // context switch from here to exit()
426 // // exit() calls requestExit(), what exitPending() observes
427 // // exit() calls signal(), which is dropped since no waiters
428 // // context switch back from exit() to here
429 // mWaitWorkCV.wait(...);
430 // // now thread is hung
431 // }
432 AutoMutex lock(mLock);
433 requestExit();
434 mWaitWorkCV.broadcast();
435 }
436 // When Thread::requestExitAndWait is made virtual and this method is renamed to
437 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
438 requestExitAndWait();
439}
440
441status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
442{
443 status_t status;
444
445 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
446 Mutex::Autolock _l(mLock);
447
Eric Laurent10351942014-05-08 18:49:52 -0700448 return sendSetParameterConfigEvent_l(keyValuePairs);
449}
450
451// sendConfigEvent_l() must be called with ThreadBase::mLock held
452// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
453status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
454{
455 status_t status = NO_ERROR;
456
457 mConfigEvents.add(event);
458 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800459 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700460 mLock.unlock();
461 {
462 Mutex::Autolock _l(event->mLock);
463 while (event->mWaitStatus) {
464 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
465 event->mStatus = TIMED_OUT;
466 event->mWaitStatus = false;
467 }
468 }
469 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800470 }
Eric Laurent10351942014-05-08 18:49:52 -0700471 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800472 return status;
473}
474
475void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
476{
477 Mutex::Autolock _l(mLock);
478 sendIoConfigEvent_l(event, param);
479}
480
481// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
482void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
483{
Eric Laurent10351942014-05-08 18:49:52 -0700484 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
485 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800486}
487
488// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
489void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
490{
Eric Laurent10351942014-05-08 18:49:52 -0700491 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
492 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800493}
494
Eric Laurent10351942014-05-08 18:49:52 -0700495// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
496status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800497{
Eric Laurent10351942014-05-08 18:49:52 -0700498 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
499 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700500}
501
Eric Laurent1c333e22014-05-20 10:48:17 -0700502status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
503 const struct audio_patch *patch,
504 audio_patch_handle_t *handle)
505{
506 Mutex::Autolock _l(mLock);
507 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
508 status_t status = sendConfigEvent_l(configEvent);
509 if (status == NO_ERROR) {
510 CreateAudioPatchConfigEventData *data =
511 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
512 *handle = data->mHandle;
513 }
514 return status;
515}
516
517status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
518 const audio_patch_handle_t handle)
519{
520 Mutex::Autolock _l(mLock);
521 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
522 return sendConfigEvent_l(configEvent);
523}
524
525
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700526// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700527void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700528{
Eric Laurent10351942014-05-08 18:49:52 -0700529 bool configChanged = false;
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700532 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
533 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700535 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700536 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700537 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
538 // FIXME Need to understand why this has to be done asynchronously
539 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700540 true /*asynchronous*/);
541 if (err != 0) {
542 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700543 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700544 }
545 } break;
546 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700547 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700548 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700549 } break;
550 case CFG_EVENT_SET_PARAMETER: {
551 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
552 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
553 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700554 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700555 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700556 case CFG_EVENT_CREATE_AUDIO_PATCH: {
557 CreateAudioPatchConfigEventData *data =
558 (CreateAudioPatchConfigEventData *)event->mData.get();
559 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
560 } break;
561 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
562 ReleaseAudioPatchConfigEventData *data =
563 (ReleaseAudioPatchConfigEventData *)event->mData.get();
564 event->mStatus = releaseAudioPatch_l(data->mHandle);
565 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700566 default:
Eric Laurent10351942014-05-08 18:49:52 -0700567 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700568 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800569 }
Eric Laurent10351942014-05-08 18:49:52 -0700570 {
571 Mutex::Autolock _l(event->mLock);
572 if (event->mWaitStatus) {
573 event->mWaitStatus = false;
574 event->mCond.signal();
575 }
576 }
577 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
578 }
579
580 if (configChanged) {
581 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800582 }
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Marco Nelissenb2208842014-02-07 14:00:50 -0800585String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
586 String8 s;
587 if (output) {
588 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
589 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
590 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
591 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
592 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
593 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
594 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
595 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
596 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
597 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
598 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
599 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
600 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
601 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
602 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
603 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
604 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
605 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
606 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
607 } else {
608 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
609 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
610 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
611 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
612 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
613 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
614 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
615 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
616 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
617 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
618 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
619 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
620 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
621 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
622 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
623 }
624 int len = s.length();
625 if (s.length() > 2) {
626 char *str = s.lockBuffer(len);
627 s.unlockBuffer(len - 2);
628 }
629 return s;
630}
631
Glenn Kasten0f11b512014-01-31 16:18:54 -0800632void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
634 const size_t SIZE = 256;
635 char buffer[SIZE];
636 String8 result;
637
638 bool locked = AudioFlinger::dumpTryLock(mLock);
639 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700640 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800641 }
642
Elliott Hughes87cebad2014-05-22 10:14:43 -0700643 dprintf(fd, " I/O handle: %d\n", mId);
644 dprintf(fd, " TID: %d\n", getTid());
645 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700646 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700647 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700648 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700649 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700650 dprintf(fd, " Channel count: %u\n", mChannelCount);
651 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800652 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700653 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
654 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700655 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800656 size_t numConfig = mConfigEvents.size();
657 if (numConfig) {
658 for (size_t i = 0; i < numConfig; i++) {
659 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700660 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800661 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700662 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800663 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700664 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800665 }
Eric Laurent81784c32012-11-19 14:55:58 -0800666
667 if (locked) {
668 mLock.unlock();
669 }
670}
671
672void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
673{
674 const size_t SIZE = 256;
675 char buffer[SIZE];
676 String8 result;
677
Marco Nelissenb2208842014-02-07 14:00:50 -0800678 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000679 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800680 write(fd, buffer, strlen(buffer));
681
Marco Nelissenb2208842014-02-07 14:00:50 -0800682 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800683 sp<EffectChain> chain = mEffectChains[i];
684 if (chain != 0) {
685 chain->dump(fd, args);
686 }
687 }
688}
689
Marco Nelissene14a5d62013-10-03 08:51:24 -0700690void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800691{
692 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700693 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800694}
695
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100696String16 AudioFlinger::ThreadBase::getWakeLockTag()
697{
698 switch (mType) {
699 case MIXER:
700 return String16("AudioMix");
701 case DIRECT:
702 return String16("AudioDirectOut");
703 case DUPLICATING:
704 return String16("AudioDup");
705 case RECORD:
706 return String16("AudioIn");
707 case OFFLOAD:
708 return String16("AudioOffload");
709 default:
710 ALOG_ASSERT(false);
711 return String16("AudioUnknown");
712 }
713}
714
Marco Nelissene14a5d62013-10-03 08:51:24 -0700715void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800716{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800717 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800718 if (mPowerManager != 0) {
719 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700720 status_t status;
721 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700722 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700723 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100724 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700725 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700726 uid,
727 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700728 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700729 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700730 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100731 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700732 String16("media"),
733 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700734 }
Eric Laurent81784c32012-11-19 14:55:58 -0800735 if (status == NO_ERROR) {
736 mWakeLockToken = binder;
737 }
738 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
739 }
740}
741
742void AudioFlinger::ThreadBase::releaseWakeLock()
743{
744 Mutex::Autolock _l(mLock);
745 releaseWakeLock_l();
746}
747
748void AudioFlinger::ThreadBase::releaseWakeLock_l()
749{
750 if (mWakeLockToken != 0) {
751 ALOGV("releaseWakeLock_l() %s", mName);
752 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700753 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
754 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800755 }
756 mWakeLockToken.clear();
757 }
758}
759
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800760void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
761 Mutex::Autolock _l(mLock);
762 updateWakeLockUids_l(uids);
763}
764
765void AudioFlinger::ThreadBase::getPowerManager_l() {
766
767 if (mPowerManager == 0) {
768 // use checkService() to avoid blocking if power service is not up yet
769 sp<IBinder> binder =
770 defaultServiceManager()->checkService(String16("power"));
771 if (binder == 0) {
772 ALOGW("Thread %s cannot connect to the power manager service", mName);
773 } else {
774 mPowerManager = interface_cast<IPowerManager>(binder);
775 binder->linkToDeath(mDeathRecipient);
776 }
777 }
778}
779
780void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
781
782 getPowerManager_l();
783 if (mWakeLockToken == NULL) {
784 ALOGE("no wake lock to update!");
785 return;
786 }
787 if (mPowerManager != 0) {
788 sp<IBinder> binder = new BBinder();
789 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700790 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
791 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800792 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
793 }
794}
795
Eric Laurent81784c32012-11-19 14:55:58 -0800796void AudioFlinger::ThreadBase::clearPowerManager()
797{
798 Mutex::Autolock _l(mLock);
799 releaseWakeLock_l();
800 mPowerManager.clear();
801}
802
Glenn Kasten0f11b512014-01-31 16:18:54 -0800803void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800804{
805 sp<ThreadBase> thread = mThread.promote();
806 if (thread != 0) {
807 thread->clearPowerManager();
808 }
809 ALOGW("power manager service died !!!");
810}
811
812void AudioFlinger::ThreadBase::setEffectSuspended(
813 const effect_uuid_t *type, bool suspend, int sessionId)
814{
815 Mutex::Autolock _l(mLock);
816 setEffectSuspended_l(type, suspend, sessionId);
817}
818
819void AudioFlinger::ThreadBase::setEffectSuspended_l(
820 const effect_uuid_t *type, bool suspend, int sessionId)
821{
822 sp<EffectChain> chain = getEffectChain_l(sessionId);
823 if (chain != 0) {
824 if (type != NULL) {
825 chain->setEffectSuspended_l(type, suspend);
826 } else {
827 chain->setEffectSuspendedAll_l(suspend);
828 }
829 }
830
831 updateSuspendedSessions_l(type, suspend, sessionId);
832}
833
834void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
835{
836 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
837 if (index < 0) {
838 return;
839 }
840
841 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
842 mSuspendedSessions.valueAt(index);
843
844 for (size_t i = 0; i < sessionEffects.size(); i++) {
845 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
846 for (int j = 0; j < desc->mRefCount; j++) {
847 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
848 chain->setEffectSuspendedAll_l(true);
849 } else {
850 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
851 desc->mType.timeLow);
852 chain->setEffectSuspended_l(&desc->mType, true);
853 }
854 }
855 }
856}
857
858void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
859 bool suspend,
860 int sessionId)
861{
862 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
863
864 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
865
866 if (suspend) {
867 if (index >= 0) {
868 sessionEffects = mSuspendedSessions.valueAt(index);
869 } else {
870 mSuspendedSessions.add(sessionId, sessionEffects);
871 }
872 } else {
873 if (index < 0) {
874 return;
875 }
876 sessionEffects = mSuspendedSessions.valueAt(index);
877 }
878
879
880 int key = EffectChain::kKeyForSuspendAll;
881 if (type != NULL) {
882 key = type->timeLow;
883 }
884 index = sessionEffects.indexOfKey(key);
885
886 sp<SuspendedSessionDesc> desc;
887 if (suspend) {
888 if (index >= 0) {
889 desc = sessionEffects.valueAt(index);
890 } else {
891 desc = new SuspendedSessionDesc();
892 if (type != NULL) {
893 desc->mType = *type;
894 }
895 sessionEffects.add(key, desc);
896 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
897 }
898 desc->mRefCount++;
899 } else {
900 if (index < 0) {
901 return;
902 }
903 desc = sessionEffects.valueAt(index);
904 if (--desc->mRefCount == 0) {
905 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
906 sessionEffects.removeItemsAt(index);
907 if (sessionEffects.isEmpty()) {
908 ALOGV("updateSuspendedSessions_l() restore removing session %d",
909 sessionId);
910 mSuspendedSessions.removeItem(sessionId);
911 }
912 }
913 }
914 if (!sessionEffects.isEmpty()) {
915 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
916 }
917}
918
919void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
920 bool enabled,
921 int sessionId)
922{
923 Mutex::Autolock _l(mLock);
924 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
925}
926
927void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
928 bool enabled,
929 int sessionId)
930{
931 if (mType != RECORD) {
932 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
933 // another session. This gives the priority to well behaved effect control panels
934 // and applications not using global effects.
935 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
936 // global effects
937 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
938 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
939 }
940 }
941
942 sp<EffectChain> chain = getEffectChain_l(sessionId);
943 if (chain != 0) {
944 chain->checkSuspendOnEffectEnabled(effect, enabled);
945 }
946}
947
948// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
949sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
950 const sp<AudioFlinger::Client>& client,
951 const sp<IEffectClient>& effectClient,
952 int32_t priority,
953 int sessionId,
954 effect_descriptor_t *desc,
955 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700956 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800957{
958 sp<EffectModule> effect;
959 sp<EffectHandle> handle;
960 status_t lStatus;
961 sp<EffectChain> chain;
962 bool chainCreated = false;
963 bool effectCreated = false;
964 bool effectRegistered = false;
965
966 lStatus = initCheck();
967 if (lStatus != NO_ERROR) {
968 ALOGW("createEffect_l() Audio driver not initialized.");
969 goto Exit;
970 }
971
Andy Hung98ef9782014-03-04 14:46:50 -0800972 // Reject any effect on Direct output threads for now, since the format of
973 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
974 if (mType == DIRECT) {
975 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
976 desc->name, mName);
977 lStatus = BAD_VALUE;
978 goto Exit;
979 }
980
Andy Hung389cfdb2014-08-07 17:49:53 -0700981 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700982 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700983 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
984 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
985 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700986 lStatus = BAD_VALUE;
987 goto Exit;
988 }
989
Eric Laurent5baf2af2013-09-12 17:37:00 -0700990 // Allow global effects only on offloaded and mixer threads
991 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
992 switch (mType) {
993 case MIXER:
994 case OFFLOAD:
995 break;
996 case DIRECT:
997 case DUPLICATING:
998 case RECORD:
999 default:
1000 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
1001 lStatus = BAD_VALUE;
1002 goto Exit;
1003 }
Eric Laurent81784c32012-11-19 14:55:58 -08001004 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001005
Eric Laurent81784c32012-11-19 14:55:58 -08001006 // Only Pre processor effects are allowed on input threads and only on input threads
1007 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1008 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1009 desc->name, desc->flags, mType);
1010 lStatus = BAD_VALUE;
1011 goto Exit;
1012 }
1013
1014 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1015
1016 { // scope for mLock
1017 Mutex::Autolock _l(mLock);
1018
1019 // check for existing effect chain with the requested audio session
1020 chain = getEffectChain_l(sessionId);
1021 if (chain == 0) {
1022 // create a new chain for this session
1023 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1024 chain = new EffectChain(this, sessionId);
1025 addEffectChain_l(chain);
1026 chain->setStrategy(getStrategyForSession_l(sessionId));
1027 chainCreated = true;
1028 } else {
1029 effect = chain->getEffectFromDesc_l(desc);
1030 }
1031
1032 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1033
1034 if (effect == 0) {
1035 int id = mAudioFlinger->nextUniqueId();
1036 // Check CPU and memory usage
1037 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1038 if (lStatus != NO_ERROR) {
1039 goto Exit;
1040 }
1041 effectRegistered = true;
1042 // create a new effect module if none present in the chain
1043 effect = new EffectModule(this, chain, desc, id, sessionId);
1044 lStatus = effect->status();
1045 if (lStatus != NO_ERROR) {
1046 goto Exit;
1047 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001048 effect->setOffloaded(mType == OFFLOAD, mId);
1049
Eric Laurent81784c32012-11-19 14:55:58 -08001050 lStatus = chain->addEffect_l(effect);
1051 if (lStatus != NO_ERROR) {
1052 goto Exit;
1053 }
1054 effectCreated = true;
1055
1056 effect->setDevice(mOutDevice);
1057 effect->setDevice(mInDevice);
1058 effect->setMode(mAudioFlinger->getMode());
1059 effect->setAudioSource(mAudioSource);
1060 }
1061 // create effect handle and connect it to effect module
1062 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001063 lStatus = handle->initCheck();
1064 if (lStatus == OK) {
1065 lStatus = effect->addHandle(handle.get());
1066 }
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (enabled != NULL) {
1068 *enabled = (int)effect->isEnabled();
1069 }
1070 }
1071
1072Exit:
1073 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1074 Mutex::Autolock _l(mLock);
1075 if (effectCreated) {
1076 chain->removeEffect_l(effect);
1077 }
1078 if (effectRegistered) {
1079 AudioSystem::unregisterEffect(effect->id());
1080 }
1081 if (chainCreated) {
1082 removeEffectChain_l(chain);
1083 }
1084 handle.clear();
1085 }
1086
Glenn Kasten9156ef32013-08-06 15:39:08 -07001087 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001088 return handle;
1089}
1090
1091sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1092{
1093 Mutex::Autolock _l(mLock);
1094 return getEffect_l(sessionId, effectId);
1095}
1096
1097sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1098{
1099 sp<EffectChain> chain = getEffectChain_l(sessionId);
1100 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1101}
1102
1103// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1104// PlaybackThread::mLock held
1105status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1106{
1107 // check for existing effect chain with the requested audio session
1108 int sessionId = effect->sessionId();
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 bool chainCreated = false;
1111
Eric Laurent5baf2af2013-09-12 17:37:00 -07001112 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1113 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1114 this, effect->desc().name, effect->desc().flags);
1115
Eric Laurent81784c32012-11-19 14:55:58 -08001116 if (chain == 0) {
1117 // create a new chain for this session
1118 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1119 chain = new EffectChain(this, sessionId);
1120 addEffectChain_l(chain);
1121 chain->setStrategy(getStrategyForSession_l(sessionId));
1122 chainCreated = true;
1123 }
1124 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1125
1126 if (chain->getEffectFromId_l(effect->id()) != 0) {
1127 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1128 this, effect->desc().name, chain.get());
1129 return BAD_VALUE;
1130 }
1131
Eric Laurent5baf2af2013-09-12 17:37:00 -07001132 effect->setOffloaded(mType == OFFLOAD, mId);
1133
Eric Laurent81784c32012-11-19 14:55:58 -08001134 status_t status = chain->addEffect_l(effect);
1135 if (status != NO_ERROR) {
1136 if (chainCreated) {
1137 removeEffectChain_l(chain);
1138 }
1139 return status;
1140 }
1141
1142 effect->setDevice(mOutDevice);
1143 effect->setDevice(mInDevice);
1144 effect->setMode(mAudioFlinger->getMode());
1145 effect->setAudioSource(mAudioSource);
1146 return NO_ERROR;
1147}
1148
1149void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1150
1151 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1152 effect_descriptor_t desc = effect->desc();
1153 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1154 detachAuxEffect_l(effect->id());
1155 }
1156
1157 sp<EffectChain> chain = effect->chain().promote();
1158 if (chain != 0) {
1159 // remove effect chain if removing last effect
1160 if (chain->removeEffect_l(effect) == 0) {
1161 removeEffectChain_l(chain);
1162 }
1163 } else {
1164 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1165 }
1166}
1167
1168void AudioFlinger::ThreadBase::lockEffectChains_l(
1169 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1170{
1171 effectChains = mEffectChains;
1172 for (size_t i = 0; i < mEffectChains.size(); i++) {
1173 mEffectChains[i]->lock();
1174 }
1175}
1176
1177void AudioFlinger::ThreadBase::unlockEffectChains(
1178 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1179{
1180 for (size_t i = 0; i < effectChains.size(); i++) {
1181 effectChains[i]->unlock();
1182 }
1183}
1184
1185sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1186{
1187 Mutex::Autolock _l(mLock);
1188 return getEffectChain_l(sessionId);
1189}
1190
1191sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1192{
1193 size_t size = mEffectChains.size();
1194 for (size_t i = 0; i < size; i++) {
1195 if (mEffectChains[i]->sessionId() == sessionId) {
1196 return mEffectChains[i];
1197 }
1198 }
1199 return 0;
1200}
1201
1202void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1203{
1204 Mutex::Autolock _l(mLock);
1205 size_t size = mEffectChains.size();
1206 for (size_t i = 0; i < size; i++) {
1207 mEffectChains[i]->setMode_l(mode);
1208 }
1209}
1210
Eric Laurent83b88082014-06-20 18:31:16 -07001211void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1212{
1213 config->type = AUDIO_PORT_TYPE_MIX;
1214 config->ext.mix.handle = mId;
1215 config->sample_rate = mSampleRate;
1216 config->format = mFormat;
1217 config->channel_mask = mChannelMask;
1218 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1219 AUDIO_PORT_CONFIG_FORMAT;
1220}
1221
1222
Eric Laurent81784c32012-11-19 14:55:58 -08001223// ----------------------------------------------------------------------------
1224// Playback
1225// ----------------------------------------------------------------------------
1226
1227AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1228 AudioStreamOut* output,
1229 audio_io_handle_t id,
1230 audio_devices_t device,
1231 type_t type)
1232 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001233 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001234 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001235 mMixerBuffer(NULL),
1236 mMixerBufferSize(0),
1237 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1238 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001239 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001240 mEffectBuffer(NULL),
1241 mEffectBufferSize(0),
1242 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1243 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001244 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001245 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001246 // mStreamTypes[] initialized in constructor body
1247 mOutput(output),
1248 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1249 mMixerStatus(MIXER_IDLE),
1250 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1251 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001252 mBytesRemaining(0),
1253 mCurrentWriteLength(0),
1254 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001255 mWriteAckSequence(0),
1256 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001257 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001258 mScreenState(AudioFlinger::mScreenState),
1259 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001260 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001261 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001262 // mLatchD, mLatchQ,
1263 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001264{
1265 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001266 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001267
1268 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1269 // it would be safer to explicitly pass initial masterVolume/masterMute as
1270 // parameter.
1271 //
1272 // If the HAL we are using has support for master volume or master mute,
1273 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1274 // and the mute set to false).
1275 mMasterVolume = audioFlinger->masterVolume_l();
1276 mMasterMute = audioFlinger->masterMute_l();
1277 if (mOutput && mOutput->audioHwDev) {
1278 if (mOutput->audioHwDev->canSetMasterVolume()) {
1279 mMasterVolume = 1.0;
1280 }
1281
1282 if (mOutput->audioHwDev->canSetMasterMute()) {
1283 mMasterMute = false;
1284 }
1285 }
1286
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001287 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001288
Eric Laurent223fd5c2014-11-11 13:43:36 -08001289 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001290 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001291 stream = (audio_stream_type_t) (stream + 1)) {
1292 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1293 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1294 }
Eric Laurent81784c32012-11-19 14:55:58 -08001295}
1296
1297AudioFlinger::PlaybackThread::~PlaybackThread()
1298{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001299 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001300 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001301 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001302 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001303}
1304
1305void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1306{
1307 dumpInternals(fd, args);
1308 dumpTracks(fd, args);
1309 dumpEffectChains(fd, args);
1310}
1311
Glenn Kasten0f11b512014-01-31 16:18:54 -08001312void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001313{
1314 const size_t SIZE = 256;
1315 char buffer[SIZE];
1316 String8 result;
1317
Marco Nelissenb2208842014-02-07 14:00:50 -08001318 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001319 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1320 const stream_type_t *st = &mStreamTypes[i];
1321 if (i > 0) {
1322 result.appendFormat(", ");
1323 }
1324 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1325 if (st->mute) {
1326 result.append("M");
1327 }
1328 }
1329 result.append("\n");
1330 write(fd, result.string(), result.length());
1331 result.clear();
1332
Eric Laurent81784c32012-11-19 14:55:58 -08001333 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1334 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001335 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001336 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001337
1338 size_t numtracks = mTracks.size();
1339 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001340 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001341 size_t numactiveseen = 0;
1342 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001343 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001344 Track::appendDumpHeader(result);
1345 for (size_t i = 0; i < numtracks; ++i) {
1346 sp<Track> track = mTracks[i];
1347 if (track != 0) {
1348 bool active = mActiveTracks.indexOf(track) >= 0;
1349 if (active) {
1350 numactiveseen++;
1351 }
1352 track->dump(buffer, SIZE, active);
1353 result.append(buffer);
1354 }
1355 }
1356 } else {
1357 result.append("\n");
1358 }
1359 if (numactiveseen != numactive) {
1360 // some tracks in the active list were not in the tracks list
1361 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1362 " not in the track list\n");
1363 result.append(buffer);
1364 Track::appendDumpHeader(result);
1365 for (size_t i = 0; i < numactive; ++i) {
1366 sp<Track> track = mActiveTracks[i].promote();
1367 if (track != 0 && mTracks.indexOf(track) < 0) {
1368 track->dump(buffer, SIZE, true);
1369 result.append(buffer);
1370 }
1371 }
1372 }
1373
1374 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001375}
1376
1377void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1378{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001379 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001380 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1381 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1382 dprintf(fd, " Total writes: %d\n", mNumWrites);
1383 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1384 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1385 dprintf(fd, " Suspend count: %d\n", mSuspended);
1386 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1387 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1388 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1389 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001390 AudioStreamOut *output = mOutput;
1391 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1392 String8 flagsAsString = outputFlagsToString(flags);
1393 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001394
1395 dumpBase(fd, args);
1396}
1397
1398// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001399
1400void AudioFlinger::PlaybackThread::onFirstRef()
1401{
1402 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1403}
1404
1405// ThreadBase virtuals
1406void AudioFlinger::PlaybackThread::preExit()
1407{
1408 ALOGV(" preExit()");
1409 // FIXME this is using hard-coded strings but in the future, this functionality will be
1410 // converted to use audio HAL extensions required to support tunneling
1411 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1412}
1413
1414// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1415sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1416 const sp<AudioFlinger::Client>& client,
1417 audio_stream_type_t streamType,
1418 uint32_t sampleRate,
1419 audio_format_t format,
1420 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001421 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001422 const sp<IMemory>& sharedBuffer,
1423 int sessionId,
1424 IAudioFlinger::track_flags_t *flags,
1425 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001426 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001427 status_t *status)
1428{
Glenn Kasten74935e42013-12-19 08:56:45 -08001429 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001430 sp<Track> track;
1431 status_t lStatus;
1432
1433 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1434
1435 // client expresses a preference for FAST, but we get the final say
1436 if (*flags & IAudioFlinger::TRACK_FAST) {
1437 if (
1438 // not timed
1439 (!isTimed) &&
1440 // either of these use cases:
1441 (
1442 // use case 1: shared buffer with any frame count
1443 (
1444 (sharedBuffer != 0)
1445 ) ||
1446 // use case 2: callback handler and frame count is default or at least as large as HAL
1447 (
1448 (tid != -1) &&
1449 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001450 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001451 )
1452 ) &&
1453 // PCM data
1454 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001455 // identical channel mask to sink, or mono in and stereo sink
1456 (channelMask == mChannelMask ||
1457 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1458 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001459 // hardware sample rate
1460 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001461 // normal mixer has an associated fast mixer
1462 hasFastMixer() &&
1463 // there are sufficient fast track slots available
1464 (mFastTrackAvailMask != 0)
1465 // FIXME test that MixerThread for this fast track has a capable output HAL
1466 // FIXME add a permission test also?
1467 ) {
1468 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1469 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001470 // read the fast track multiplier property the first time it is needed
1471 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1472 if (ok != 0) {
1473 ALOGE("%s pthread_once failed: %d", __func__, ok);
1474 }
1475 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001476 }
1477 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1478 frameCount, mFrameCount);
1479 } else {
1480 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001481 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1482 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001483 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001484 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001485 audio_is_linear_pcm(format),
1486 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1487 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001488 }
1489 }
1490 // For normal PCM streaming tracks, update minimum frame count.
1491 // For compatibility with AudioTrack calculation, buffer depth is forced
1492 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1493 // This is probably too conservative, but legacy application code may depend on it.
1494 // If you change this calculation, also review the start threshold which is related.
1495 if (!(*flags & IAudioFlinger::TRACK_FAST)
1496 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001497 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1498 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1499 if (minBufCount < 2) {
1500 minBufCount = 2;
1501 }
Andy Hung0e48d252015-01-26 11:43:15 -08001502 size_t minFrameCount =
1503 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1504 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001505 frameCount = minFrameCount;
1506 }
Eric Laurent81784c32012-11-19 14:55:58 -08001507 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001508 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001509
Glenn Kastenc3df8382014-03-13 15:05:25 -07001510 switch (mType) {
1511
1512 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001513 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001514 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001515 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1516 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001517 sampleRate, format, channelMask, mOutput, mFormat);
1518 lStatus = BAD_VALUE;
1519 goto Exit;
1520 }
1521 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001522 break;
1523
1524 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001525 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001526 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1527 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001528 sampleRate, format, channelMask, mOutput, mFormat);
1529 lStatus = BAD_VALUE;
1530 goto Exit;
1531 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001532 break;
1533
1534 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001535 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001536 ALOGE("createTrack_l() Bad parameter: format %#x \""
1537 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001538 format, mOutput, mFormat);
1539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
Andy Hungcd044842014-08-07 11:04:34 -07001542 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001543 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1544 lStatus = BAD_VALUE;
1545 goto Exit;
1546 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001547 break;
1548
Eric Laurent81784c32012-11-19 14:55:58 -08001549 }
1550
1551 lStatus = initCheck();
1552 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001553 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001554 goto Exit;
1555 }
1556
1557 { // scope for mLock
1558 Mutex::Autolock _l(mLock);
1559
1560 // all tracks in same audio session must share the same routing strategy otherwise
1561 // conflicts will happen when tracks are moved from one output to another by audio policy
1562 // manager
1563 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1564 for (size_t i = 0; i < mTracks.size(); ++i) {
1565 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001566 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001567 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1568 if (sessionId == t->sessionId() && strategy != actual) {
1569 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1570 strategy, actual);
1571 lStatus = BAD_VALUE;
1572 goto Exit;
1573 }
1574 }
1575 }
1576
1577 if (!isTimed) {
1578 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001579 channelMask, frameCount, NULL, sharedBuffer,
1580 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001581 } else {
1582 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001583 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 }
Glenn Kasten03003332013-08-06 15:40:54 -07001585
1586 // new Track always returns non-NULL,
1587 // but TimedTrack::create() is a factory that could fail by returning NULL
1588 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1589 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001590 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001591 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001592 goto Exit;
1593 }
1594 mTracks.add(track);
1595
1596 sp<EffectChain> chain = getEffectChain_l(sessionId);
1597 if (chain != 0) {
1598 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1599 track->setMainBuffer(chain->inBuffer());
1600 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1601 chain->incTrackCnt();
1602 }
1603
1604 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1605 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1606 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1607 // so ask activity manager to do this on our behalf
1608 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1609 }
1610 }
1611
1612 lStatus = NO_ERROR;
1613
1614Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001615 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001616 return track;
1617}
1618
1619uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1620{
1621 return latency;
1622}
1623
1624uint32_t AudioFlinger::PlaybackThread::latency() const
1625{
1626 Mutex::Autolock _l(mLock);
1627 return latency_l();
1628}
1629uint32_t AudioFlinger::PlaybackThread::latency_l() const
1630{
1631 if (initCheck() == NO_ERROR) {
1632 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1633 } else {
1634 return 0;
1635 }
1636}
1637
1638void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1639{
1640 Mutex::Autolock _l(mLock);
1641 // Don't apply master volume in SW if our HAL can do it for us.
1642 if (mOutput && mOutput->audioHwDev &&
1643 mOutput->audioHwDev->canSetMasterVolume()) {
1644 mMasterVolume = 1.0;
1645 } else {
1646 mMasterVolume = value;
1647 }
1648}
1649
1650void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1651{
1652 Mutex::Autolock _l(mLock);
1653 // Don't apply master mute in SW if our HAL can do it for us.
1654 if (mOutput && mOutput->audioHwDev &&
1655 mOutput->audioHwDev->canSetMasterMute()) {
1656 mMasterMute = false;
1657 } else {
1658 mMasterMute = muted;
1659 }
1660}
1661
1662void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1663{
1664 Mutex::Autolock _l(mLock);
1665 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001666 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001667}
1668
1669void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1670{
1671 Mutex::Autolock _l(mLock);
1672 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001673 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
1676float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1677{
1678 Mutex::Autolock _l(mLock);
1679 return mStreamTypes[stream].volume;
1680}
1681
1682// addTrack_l() must be called with ThreadBase::mLock held
1683status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1684{
1685 status_t status = ALREADY_EXISTS;
1686
1687 // set retry count for buffer fill
1688 track->mRetryCount = kMaxTrackStartupRetries;
1689 if (mActiveTracks.indexOf(track) < 0) {
1690 // the track is newly added, make sure it fills up all its
1691 // buffers before playing. This is to ensure the client will
1692 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001693 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001694 TrackBase::track_state state = track->mState;
1695 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001696 status = AudioSystem::startOutput(mId, track->streamType(),
1697 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001698 mLock.lock();
1699 // abort track was stopped/paused while we released the lock
1700 if (state != track->mState) {
1701 if (status == NO_ERROR) {
1702 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001703 AudioSystem::stopOutput(mId, track->streamType(),
1704 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mLock.lock();
1706 }
1707 return INVALID_OPERATION;
1708 }
1709 // abort if start is rejected by audio policy manager
1710 if (status != NO_ERROR) {
1711 return PERMISSION_DENIED;
1712 }
1713#ifdef ADD_BATTERY_DATA
1714 // to track the speaker usage
1715 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1716#endif
1717 }
1718
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001720 track->mResetDone = false;
1721 track->mPresentationCompleteFrames = 0;
1722 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001723 mWakeLockUids.add(track->uid());
1724 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001725 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001726 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1727 if (chain != 0) {
1728 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1729 track->sessionId());
1730 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001731 }
1732
1733 status = NO_ERROR;
1734 }
1735
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001736 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001737 return status;
1738}
1739
Eric Laurentbfb1b832013-01-07 09:53:42 -08001740bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001741{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001744 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1745 track->mState = TrackBase::STOPPED;
1746 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001747 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001748 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001749 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751
1752 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001753}
1754
1755void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1756{
1757 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1758 mTracks.remove(track);
1759 deleteTrackName_l(track->name());
1760 // redundant as track is about to be destroyed, for dumpsys only
1761 track->mName = -1;
1762 if (track->isFastTrack()) {
1763 int index = track->mFastIndex;
1764 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1765 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1766 mFastTrackAvailMask |= 1 << index;
1767 // redundant as track is about to be destroyed, for dumpsys only
1768 track->mFastIndex = -1;
1769 }
1770 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1771 if (chain != 0) {
1772 chain->decTrackCnt();
1773 }
1774}
1775
Eric Laurentede6c3b2013-09-19 14:37:46 -07001776void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777{
1778 // Thread could be blocked waiting for async
1779 // so signal it to handle state changes immediately
1780 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1781 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1782 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001783 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784}
1785
Eric Laurent81784c32012-11-19 14:55:58 -08001786String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1787{
Eric Laurent81784c32012-11-19 14:55:58 -08001788 Mutex::Autolock _l(mLock);
1789 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001790 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001791 }
1792
Glenn Kastend8ea6992013-07-16 14:17:15 -07001793 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1794 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001795 free(s);
1796 return out_s8;
1797}
1798
Eric Laurent021cf962014-05-13 10:18:14 -07001799void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001800 AudioSystem::OutputDescriptor desc;
1801 void *param2 = NULL;
1802
Eric Laurent021cf962014-05-13 10:18:14 -07001803 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001804 param);
1805
1806 switch (event) {
1807 case AudioSystem::OUTPUT_OPENED:
1808 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001809 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001810 desc.samplingRate = mSampleRate;
1811 desc.format = mFormat;
1812 desc.frameCount = mNormalFrameCount; // FIXME see
1813 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001814 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001815 param2 = &desc;
1816 break;
1817
1818 case AudioSystem::STREAM_CONFIG_CHANGED:
1819 param2 = &param;
1820 case AudioSystem::OUTPUT_CLOSED:
1821 default:
1822 break;
1823 }
Eric Laurent021cf962014-05-13 10:18:14 -07001824 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001825}
1826
Eric Laurentbfb1b832013-01-07 09:53:42 -08001827void AudioFlinger::PlaybackThread::writeCallback()
1828{
1829 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001830 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001831}
1832
1833void AudioFlinger::PlaybackThread::drainCallback()
1834{
1835 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001836 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001837}
1838
Eric Laurent3b4529e2013-09-05 18:09:19 -07001839void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001840{
1841 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001842 // reject out of sequence requests
1843 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1844 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 mWaitWorkCV.signal();
1846 }
1847}
1848
Eric Laurent3b4529e2013-09-05 18:09:19 -07001849void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850{
1851 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001852 // reject out of sequence requests
1853 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1854 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855 mWaitWorkCV.signal();
1856 }
1857}
1858
1859// static
1860int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001861 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 void *cookie)
1863{
1864 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1865 ALOGV("asyncCallback() event %d", event);
1866 switch (event) {
1867 case STREAM_CBK_EVENT_WRITE_READY:
1868 me->writeCallback();
1869 break;
1870 case STREAM_CBK_EVENT_DRAIN_READY:
1871 me->drainCallback();
1872 break;
1873 default:
1874 ALOGW("asyncCallback() unknown event %d", event);
1875 break;
1876 }
1877 return 0;
1878}
1879
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001880void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001881{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001882 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001883 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1884 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001885 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001886 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001887 }
Andy Hung9a592762014-07-21 21:56:01 -07001888 if ((mType == MIXER || mType == DUPLICATING)
1889 && !isValidPcmSinkChannelMask(mChannelMask)) {
1890 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1891 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001892 }
Andy Hunge5412692014-05-16 11:25:07 -07001893 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001894 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1895 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001896 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001897 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001898 }
Andy Hung6146c082014-03-18 11:56:15 -07001899 if ((mType == MIXER || mType == DUPLICATING)
1900 && !isValidPcmSinkFormat(mFormat)) {
1901 LOG_FATAL("HAL format %#x not supported for mixed output",
1902 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001903 }
Eric Laurent665470b2014-07-03 16:37:08 -07001904 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001905 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1906 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001907 if (mFrameCount & 15) {
1908 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1909 mFrameCount);
1910 }
1911
Eric Laurentbfb1b832013-01-07 09:53:42 -08001912 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1913 (mOutput->stream->set_callback != NULL)) {
1914 if (mOutput->stream->set_callback(mOutput->stream,
1915 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1916 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001917 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001918 }
1919 }
1920
Eric Laurentd1f69b02014-12-15 14:33:13 -08001921 mHwSupportsPause = false;
1922 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1923 if (mOutput->stream->pause != NULL) {
1924 if (mOutput->stream->resume != NULL) {
1925 mHwSupportsPause = true;
1926 } else {
1927 ALOGW("direct output implements pause but not resume");
1928 }
1929 } else if (mOutput->stream->resume != NULL) {
1930 ALOGW("direct output implements resume but not pause");
1931 }
1932 }
1933
Andy Hungfbfc3952015-01-15 13:33:51 -08001934 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
1935 // For best precision, we use float instead of the associated output
1936 // device format (typically PCM 16 bit).
1937
1938 mFormat = AUDIO_FORMAT_PCM_FLOAT;
1939 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
1940 mBufferSize = mFrameSize * mFrameCount;
1941
1942 // TODO: We currently use the associated output device channel mask and sample rate.
1943 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
1944 // (if a valid mask) to avoid premature downmix.
1945 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
1946 // instead of the output device sample rate to avoid loss of high frequency information.
1947 // This may need to be updated as MixerThread/OutputTracks are added and not here.
1948 }
1949
Andy Hung09a50072014-02-27 14:30:47 -08001950 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001951 double multiplier = 1.0;
1952 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1953 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001954 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1955 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001956 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1957 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1958 maxNormalFrameCount = maxNormalFrameCount & ~15;
1959 if (maxNormalFrameCount < minNormalFrameCount) {
1960 maxNormalFrameCount = minNormalFrameCount;
1961 }
1962 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1963 if (multiplier <= 1.0) {
1964 multiplier = 1.0;
1965 } else if (multiplier <= 2.0) {
1966 if (2 * mFrameCount <= maxNormalFrameCount) {
1967 multiplier = 2.0;
1968 } else {
1969 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1970 }
1971 } else {
1972 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001973 // 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 -08001974 // track, but we sometimes have to do this to satisfy the maximum frame count
1975 // constraint)
1976 // FIXME this rounding up should not be done if no HAL SRC
1977 uint32_t truncMult = (uint32_t) multiplier;
1978 if ((truncMult & 1)) {
1979 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1980 ++truncMult;
1981 }
1982 }
1983 multiplier = (double) truncMult;
1984 }
1985 }
1986 mNormalFrameCount = multiplier * mFrameCount;
1987 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001988 if (mType == MIXER || mType == DUPLICATING) {
1989 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1990 }
Andy Hung09a50072014-02-27 14:30:47 -08001991 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001992 mNormalFrameCount);
1993
Andy Hung010a1a12014-03-13 13:57:33 -07001994 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1995 // Originally this was int16_t[] array, need to remove legacy implications.
1996 free(mSinkBuffer);
1997 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001998 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1999 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2000 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002001 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002002
Andy Hung69aed5f2014-02-25 17:24:40 -08002003 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2004 // drives the output.
2005 free(mMixerBuffer);
2006 mMixerBuffer = NULL;
2007 if (mMixerBufferEnabled) {
2008 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2009 mMixerBufferSize = mNormalFrameCount * mChannelCount
2010 * audio_bytes_per_sample(mMixerBufferFormat);
2011 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2012 }
Andy Hung98ef9782014-03-04 14:46:50 -08002013 free(mEffectBuffer);
2014 mEffectBuffer = NULL;
2015 if (mEffectBufferEnabled) {
2016 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2017 mEffectBufferSize = mNormalFrameCount * mChannelCount
2018 * audio_bytes_per_sample(mEffectBufferFormat);
2019 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2020 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002021
Eric Laurent81784c32012-11-19 14:55:58 -08002022 // force reconfiguration of effect chains and engines to take new buffer size and audio
2023 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002024 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002025 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2026 // matter.
2027 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2028 Vector< sp<EffectChain> > effectChains = mEffectChains;
2029 for (size_t i = 0; i < effectChains.size(); i ++) {
2030 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2031 }
2032}
2033
2034
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002035status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002036{
2037 if (halFrames == NULL || dspFrames == NULL) {
2038 return BAD_VALUE;
2039 }
2040 Mutex::Autolock _l(mLock);
2041 if (initCheck() != NO_ERROR) {
2042 return INVALID_OPERATION;
2043 }
2044 size_t framesWritten = mBytesWritten / mFrameSize;
2045 *halFrames = framesWritten;
2046
2047 if (isSuspended()) {
2048 // return an estimation of rendered frames when the output is suspended
2049 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2050 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2051 return NO_ERROR;
2052 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002053 status_t status;
2054 uint32_t frames;
2055 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2056 *dspFrames = (size_t)frames;
2057 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002058 }
2059}
2060
2061uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2062{
2063 Mutex::Autolock _l(mLock);
2064 uint32_t result = 0;
2065 if (getEffectChain_l(sessionId) != 0) {
2066 result = EFFECT_SESSION;
2067 }
2068
2069 for (size_t i = 0; i < mTracks.size(); ++i) {
2070 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002071 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002072 result |= TRACK_SESSION;
2073 break;
2074 }
2075 }
2076
2077 return result;
2078}
2079
2080uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2081{
2082 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2083 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2084 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2085 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2086 }
2087 for (size_t i = 0; i < mTracks.size(); i++) {
2088 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002089 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002090 return AudioSystem::getStrategyForStream(track->streamType());
2091 }
2092 }
2093 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2094}
2095
2096
2097AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2098{
2099 Mutex::Autolock _l(mLock);
2100 return mOutput;
2101}
2102
2103AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2104{
2105 Mutex::Autolock _l(mLock);
2106 AudioStreamOut *output = mOutput;
2107 mOutput = NULL;
2108 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2109 // must push a NULL and wait for ack
2110 mOutputSink.clear();
2111 mPipeSink.clear();
2112 mNormalSink.clear();
2113 return output;
2114}
2115
2116// this method must always be called either with ThreadBase mLock held or inside the thread loop
2117audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2118{
2119 if (mOutput == NULL) {
2120 return NULL;
2121 }
2122 return &mOutput->stream->common;
2123}
2124
2125uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2126{
2127 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2128}
2129
2130status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2131{
2132 if (!isValidSyncEvent(event)) {
2133 return BAD_VALUE;
2134 }
2135
2136 Mutex::Autolock _l(mLock);
2137
2138 for (size_t i = 0; i < mTracks.size(); ++i) {
2139 sp<Track> track = mTracks[i];
2140 if (event->triggerSession() == track->sessionId()) {
2141 (void) track->setSyncEvent(event);
2142 return NO_ERROR;
2143 }
2144 }
2145
2146 return NAME_NOT_FOUND;
2147}
2148
2149bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2150{
2151 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2152}
2153
2154void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2155 const Vector< sp<Track> >& tracksToRemove)
2156{
2157 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002158 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002159 for (size_t i = 0 ; i < count ; i++) {
2160 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002161 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002162 AudioSystem::stopOutput(mId, track->streamType(),
2163 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164#ifdef ADD_BATTERY_DATA
2165 // to track the speaker usage
2166 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2167#endif
2168 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002169 AudioSystem::releaseOutput(mId, track->streamType(),
2170 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171 }
Eric Laurent81784c32012-11-19 14:55:58 -08002172 }
2173 }
2174 }
Eric Laurent81784c32012-11-19 14:55:58 -08002175}
2176
2177void AudioFlinger::PlaybackThread::checkSilentMode_l()
2178{
2179 if (!mMasterMute) {
2180 char value[PROPERTY_VALUE_MAX];
2181 if (property_get("ro.audio.silent", value, "0") > 0) {
2182 char *endptr;
2183 unsigned long ul = strtoul(value, &endptr, 0);
2184 if (*endptr == '\0' && ul != 0) {
2185 ALOGD("Silence is golden");
2186 // The setprop command will not allow a property to be changed after
2187 // the first time it is set, so we don't have to worry about un-muting.
2188 setMasterMute_l(true);
2189 }
2190 }
2191 }
2192}
2193
2194// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002196{
2197 // FIXME rewrite to reduce number of system calls
2198 mLastWriteTime = systemTime();
2199 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002201 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002202
2203 // If an NBAIO sink is present, use it to write the normal mixer's submix
2204 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002205
Andy Hung010a1a12014-03-13 13:57:33 -07002206 const size_t count = mBytesRemaining / mFrameSize;
2207
Simon Wilson2d590962012-11-29 15:18:50 -08002208 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002209 // update the setpoint when AudioFlinger::mScreenState changes
2210 uint32_t screenState = AudioFlinger::mScreenState;
2211 if (screenState != mScreenState) {
2212 mScreenState = screenState;
2213 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2214 if (pipe != NULL) {
2215 pipe->setAvgFrames((mScreenState & 1) ?
2216 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2217 }
2218 }
Andy Hung010a1a12014-03-13 13:57:33 -07002219 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002220 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002221 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002222 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002223 } else {
2224 bytesWritten = framesWritten;
2225 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002226 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002227 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002228 if (status == NO_ERROR) {
2229 size_t totalFramesWritten = mNormalSink->framesWritten();
2230 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2231 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002232 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002233 mLatchDValid = true;
2234 }
2235 }
Eric Laurent81784c32012-11-19 14:55:58 -08002236 // otherwise use the HAL / AudioStreamOut directly
2237 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002239
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002241 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2242 mWriteAckSequence += 2;
2243 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002245 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002247 // FIXME We should have an implementation of timestamps for direct output threads.
2248 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002250 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251 if (mUseAsyncWrite &&
2252 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2253 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002256 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002257 }
Eric Laurent81784c32012-11-19 14:55:58 -08002258 }
2259
Eric Laurent81784c32012-11-19 14:55:58 -08002260 mNumWrites++;
2261 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002262 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263 return bytesWritten;
2264}
2265
2266void AudioFlinger::PlaybackThread::threadLoop_drain()
2267{
2268 if (mOutput->stream->drain) {
2269 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2270 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002271 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2272 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002274 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275 }
2276 mOutput->stream->drain(mOutput->stream,
2277 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2278 : AUDIO_DRAIN_ALL);
2279 }
2280}
2281
2282void AudioFlinger::PlaybackThread::threadLoop_exit()
2283{
Eric Laurent275e8e92014-11-30 15:14:47 -08002284 {
2285 Mutex::Autolock _l(mLock);
2286 for (size_t i = 0; i < mTracks.size(); i++) {
2287 sp<Track> track = mTracks[i];
2288 track->invalidate();
2289 }
2290 }
Eric Laurent81784c32012-11-19 14:55:58 -08002291}
2292
2293/*
2294The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002295 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002296 - activeSleepTime from activeSleepTimeUs()
2297 - idleSleepTime from idleSleepTimeUs()
2298 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2299 - maxPeriod from frame count and sample rate (MIXER only)
2300
2301The parameters that affect these derived values are:
2302 - frame count
2303 - frame size
2304 - sample rate
2305 - device type: A2DP or not
2306 - device latency
2307 - format: PCM or not
2308 - active sleep time
2309 - idle sleep time
2310*/
2311
2312void AudioFlinger::PlaybackThread::cacheParameters_l()
2313{
Andy Hung25c2dac2014-02-27 14:56:00 -08002314 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002315 activeSleepTime = activeSleepTimeUs();
2316 idleSleepTime = idleSleepTimeUs();
2317}
2318
2319void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2320{
Glenn Kasten7c027242012-12-26 14:43:16 -08002321 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002322 this, streamType, mTracks.size());
2323 Mutex::Autolock _l(mLock);
2324
2325 size_t size = mTracks.size();
2326 for (size_t i = 0; i < size; i++) {
2327 sp<Track> t = mTracks[i];
2328 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002329 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002330 }
2331 }
2332}
2333
2334status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2335{
2336 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002337 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2338 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002339 bool ownsBuffer = false;
2340
2341 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2342 if (session > 0) {
2343 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002344 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002345 if (mType != DIRECT) {
2346 size_t numSamples = mNormalFrameCount * mChannelCount;
2347 buffer = new int16_t[numSamples];
2348 memset(buffer, 0, numSamples * sizeof(int16_t));
2349 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2350 ownsBuffer = true;
2351 }
2352
2353 // Attach all tracks with same session ID to this chain.
2354 for (size_t i = 0; i < mTracks.size(); ++i) {
2355 sp<Track> track = mTracks[i];
2356 if (session == track->sessionId()) {
2357 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2358 buffer);
2359 track->setMainBuffer(buffer);
2360 chain->incTrackCnt();
2361 }
2362 }
2363
2364 // indicate all active tracks in the chain
2365 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2366 sp<Track> track = mActiveTracks[i].promote();
2367 if (track == 0) {
2368 continue;
2369 }
2370 if (session == track->sessionId()) {
2371 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2372 chain->incActiveTrackCnt();
2373 }
2374 }
2375 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002376 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002377 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002378 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2379 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002380 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2381 // chains list in order to be processed last as it contains output stage effects
2382 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2383 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2384 // after track specific effects and before output stage
2385 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2386 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2387 // Effect chain for other sessions are inserted at beginning of effect
2388 // chains list to be processed before output mix effects. Relative order between other
2389 // sessions is not important
2390 size_t size = mEffectChains.size();
2391 size_t i = 0;
2392 for (i = 0; i < size; i++) {
2393 if (mEffectChains[i]->sessionId() < session) {
2394 break;
2395 }
2396 }
2397 mEffectChains.insertAt(chain, i);
2398 checkSuspendOnAddEffectChain_l(chain);
2399
2400 return NO_ERROR;
2401}
2402
2403size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2404{
2405 int session = chain->sessionId();
2406
2407 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2408
2409 for (size_t i = 0; i < mEffectChains.size(); i++) {
2410 if (chain == mEffectChains[i]) {
2411 mEffectChains.removeAt(i);
2412 // detach all active tracks from the chain
2413 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2414 sp<Track> track = mActiveTracks[i].promote();
2415 if (track == 0) {
2416 continue;
2417 }
2418 if (session == track->sessionId()) {
2419 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2420 chain.get(), session);
2421 chain->decActiveTrackCnt();
2422 }
2423 }
2424
2425 // detach all tracks with same session ID from this chain
2426 for (size_t i = 0; i < mTracks.size(); ++i) {
2427 sp<Track> track = mTracks[i];
2428 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002429 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002430 chain->decTrackCnt();
2431 }
2432 }
2433 break;
2434 }
2435 }
2436 return mEffectChains.size();
2437}
2438
2439status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2440 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2441{
2442 Mutex::Autolock _l(mLock);
2443 return attachAuxEffect_l(track, EffectId);
2444}
2445
2446status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2447 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2448{
2449 status_t status = NO_ERROR;
2450
2451 if (EffectId == 0) {
2452 track->setAuxBuffer(0, NULL);
2453 } else {
2454 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2455 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2456 if (effect != 0) {
2457 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2458 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2459 } else {
2460 status = INVALID_OPERATION;
2461 }
2462 } else {
2463 status = BAD_VALUE;
2464 }
2465 }
2466 return status;
2467}
2468
2469void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2470{
2471 for (size_t i = 0; i < mTracks.size(); ++i) {
2472 sp<Track> track = mTracks[i];
2473 if (track->auxEffectId() == effectId) {
2474 attachAuxEffect_l(track, 0);
2475 }
2476 }
2477}
2478
2479bool AudioFlinger::PlaybackThread::threadLoop()
2480{
2481 Vector< sp<Track> > tracksToRemove;
2482
2483 standbyTime = systemTime();
2484
2485 // MIXER
2486 nsecs_t lastWarning = 0;
2487
2488 // DUPLICATING
2489 // FIXME could this be made local to while loop?
2490 writeFrames = 0;
2491
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002492 int lastGeneration = 0;
2493
Eric Laurent81784c32012-11-19 14:55:58 -08002494 cacheParameters_l();
2495 sleepTime = idleSleepTime;
2496
2497 if (mType == MIXER) {
2498 sleepTimeShift = 0;
2499 }
2500
2501 CpuStats cpuStats;
2502 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2503
2504 acquireWakeLock();
2505
Glenn Kasten9e58b552013-01-18 15:09:48 -08002506 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2507 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2508 // and then that string will be logged at the next convenient opportunity.
2509 const char *logString = NULL;
2510
Eric Laurent664539d2013-09-23 18:24:31 -07002511 checkSilentMode_l();
2512
Eric Laurent81784c32012-11-19 14:55:58 -08002513 while (!exitPending())
2514 {
2515 cpuStats.sample(myName);
2516
2517 Vector< sp<EffectChain> > effectChains;
2518
Eric Laurent81784c32012-11-19 14:55:58 -08002519 { // scope for mLock
2520
2521 Mutex::Autolock _l(mLock);
2522
Eric Laurent021cf962014-05-13 10:18:14 -07002523 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002524
Glenn Kasten9e58b552013-01-18 15:09:48 -08002525 if (logString != NULL) {
2526 mNBLogWriter->logTimestamp();
2527 mNBLogWriter->log(logString);
2528 logString = NULL;
2529 }
2530
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002531 // Gather the framesReleased counters for all active tracks,
2532 // and latch them atomically with the timestamp.
2533 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2534 mLatchD.mFramesReleased.clear();
2535 size_t size = mActiveTracks.size();
2536 for (size_t i = 0; i < size; i++) {
2537 sp<Track> t = mActiveTracks[i].promote();
2538 if (t != 0) {
2539 mLatchD.mFramesReleased.add(t.get(),
2540 t->mAudioTrackServerProxy->framesReleased());
2541 }
2542 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002543 if (mLatchDValid) {
2544 mLatchQ = mLatchD;
2545 mLatchDValid = false;
2546 mLatchQValid = true;
2547 }
2548
Eric Laurent81784c32012-11-19 14:55:58 -08002549 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550 if (mSignalPending) {
2551 // A signal was raised while we were unlocked
2552 mSignalPending = false;
2553 } else if (waitingAsyncCallback_l()) {
2554 if (exitPending()) {
2555 break;
2556 }
2557 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002558 mWakeLockUids.clear();
2559 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 ALOGV("wait async completion");
2561 mWaitWorkCV.wait(mLock);
2562 ALOGV("async completion/wake");
2563 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002564 standbyTime = systemTime() + standbyDelay;
2565 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002566
2567 continue;
2568 }
2569 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 isSuspended()) {
2571 // put audio hardware into standby after short delay
2572 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002573
2574 threadLoop_standby();
2575
2576 mStandby = true;
2577 }
2578
2579 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2580 // we're about to wait, flush the binder command buffer
2581 IPCThreadState::self()->flushCommands();
2582
2583 clearOutputTracks();
2584
2585 if (exitPending()) {
2586 break;
2587 }
2588
2589 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002590 mWakeLockUids.clear();
2591 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002592 // wait until we have something to do...
2593 ALOGV("%s going to sleep", myName.string());
2594 mWaitWorkCV.wait(mLock);
2595 ALOGV("%s waking up", myName.string());
2596 acquireWakeLock_l();
2597
2598 mMixerStatus = MIXER_IDLE;
2599 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2600 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002602 checkSilentMode_l();
2603
2604 standbyTime = systemTime() + standbyDelay;
2605 sleepTime = idleSleepTime;
2606 if (mType == MIXER) {
2607 sleepTimeShift = 0;
2608 }
2609
2610 continue;
2611 }
2612 }
Eric Laurent81784c32012-11-19 14:55:58 -08002613 // mMixerStatusIgnoringFastTracks is also updated internally
2614 mMixerStatus = prepareTracks_l(&tracksToRemove);
2615
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002616 // compare with previously applied list
2617 if (lastGeneration != mActiveTracksGeneration) {
2618 // update wakelock
2619 updateWakeLockUids_l(mWakeLockUids);
2620 lastGeneration = mActiveTracksGeneration;
2621 }
2622
Eric Laurent81784c32012-11-19 14:55:58 -08002623 // prevent any changes in effect chain list and in each effect chain
2624 // during mixing and effect process as the audio buffers could be deleted
2625 // or modified if an effect is created or deleted
2626 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002627 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 if (mBytesRemaining == 0) {
2630 mCurrentWriteLength = 0;
2631 if (mMixerStatus == MIXER_TRACKS_READY) {
2632 // threadLoop_mix() sets mCurrentWriteLength
2633 threadLoop_mix();
2634 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2635 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2636 // threadLoop_sleepTime sets sleepTime to 0 if data
2637 // must be written to HAL
2638 threadLoop_sleepTime();
2639 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002640 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 }
2642 }
Andy Hung98ef9782014-03-04 14:46:50 -08002643 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2644 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2645 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2646 // or mSinkBuffer (if there are no effects).
2647 //
2648 // This is done pre-effects computation; if effects change to
2649 // support higher precision, this needs to move.
2650 //
2651 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2652 // TODO use sleepTime == 0 as an additional condition.
2653 if (mMixerBufferValid) {
2654 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2655 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2656
2657 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2658 mNormalFrameCount * mChannelCount);
2659 }
2660
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 mBytesRemaining = mCurrentWriteLength;
2662 if (isSuspended()) {
2663 sleepTime = suspendSleepTimeUs();
2664 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002665 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 mBytesRemaining = 0;
2667 }
Eric Laurent81784c32012-11-19 14:55:58 -08002668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002670 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 for (size_t i = 0; i < effectChains.size(); i ++) {
2672 effectChains[i]->process_l();
2673 }
Eric Laurent81784c32012-11-19 14:55:58 -08002674 }
2675 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002676 // Process effect chains for offloaded thread even if no audio
2677 // was read from audio track: process only updates effect state
2678 // and thus does have to be synchronized with audio writes but may have
2679 // to be called while waiting for async write callback
2680 if (mType == OFFLOAD) {
2681 for (size_t i = 0; i < effectChains.size(); i ++) {
2682 effectChains[i]->process_l();
2683 }
2684 }
Eric Laurent81784c32012-11-19 14:55:58 -08002685
Andy Hung98ef9782014-03-04 14:46:50 -08002686 // Only if the Effects buffer is enabled and there is data in the
2687 // Effects buffer (buffer valid), we need to
2688 // copy into the sink buffer.
2689 // TODO use sleepTime == 0 as an additional condition.
2690 if (mEffectBufferValid) {
2691 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2692 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2693 mNormalFrameCount * mChannelCount);
2694 }
2695
Eric Laurent81784c32012-11-19 14:55:58 -08002696 // enable changes in effect chain
2697 unlockEffectChains(effectChains);
2698
Eric Laurentbfb1b832013-01-07 09:53:42 -08002699 if (!waitingAsyncCallback()) {
2700 // sleepTime == 0 means we must write to audio hardware
2701 if (sleepTime == 0) {
2702 if (mBytesRemaining) {
2703 ssize_t ret = threadLoop_write();
2704 if (ret < 0) {
2705 mBytesRemaining = 0;
2706 } else {
2707 mBytesWritten += ret;
2708 mBytesRemaining -= ret;
2709 }
2710 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2711 (mMixerStatus == MIXER_DRAIN_ALL)) {
2712 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002713 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002714 if (mType == MIXER) {
2715 // write blocked detection
2716 nsecs_t now = systemTime();
2717 nsecs_t delta = now - mLastWriteTime;
2718 if (!mStandby && delta > maxPeriod) {
2719 mNumDelayedWrites++;
2720 if ((now - lastWarning) > kWarningThrottleNs) {
2721 ATRACE_NAME("underrun");
2722 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2723 ns2ms(delta), mNumDelayedWrites, this);
2724 lastWarning = now;
2725 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 }
2727 }
Eric Laurent81784c32012-11-19 14:55:58 -08002728
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002730 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002732 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 }
Eric Laurent81784c32012-11-19 14:55:58 -08002734 }
2735
2736 // Finally let go of removed track(s), without the lock held
2737 // since we can't guarantee the destructors won't acquire that
2738 // same lock. This will also mutate and push a new fast mixer state.
2739 threadLoop_removeTracks(tracksToRemove);
2740 tracksToRemove.clear();
2741
2742 // FIXME I don't understand the need for this here;
2743 // it was in the original code but maybe the
2744 // assignment in saveOutputTracks() makes this unnecessary?
2745 clearOutputTracks();
2746
2747 // Effect chains will be actually deleted here if they were removed from
2748 // mEffectChains list during mixing or effects processing
2749 effectChains.clear();
2750
2751 // FIXME Note that the above .clear() is no longer necessary since effectChains
2752 // is now local to this block, but will keep it for now (at least until merge done).
2753 }
2754
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 threadLoop_exit();
2756
Eric Laurentcf817a22014-08-04 20:36:31 -07002757 if (!mStandby) {
2758 threadLoop_standby();
2759 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002760 }
2761
2762 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002763 mWakeLockUids.clear();
2764 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002765
2766 ALOGV("Thread %p type %d exiting", this, mType);
2767 return false;
2768}
2769
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770// removeTracks_l() must be called with ThreadBase::mLock held
2771void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2772{
2773 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002774 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002775 for (size_t i=0 ; i<count ; i++) {
2776 const sp<Track>& track = tracksToRemove.itemAt(i);
2777 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002778 mWakeLockUids.remove(track->uid());
2779 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2781 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2782 if (chain != 0) {
2783 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2784 track->sessionId());
2785 chain->decActiveTrackCnt();
2786 }
2787 if (track->isTerminated()) {
2788 removeTrack_l(track);
2789 }
2790 }
2791 }
2792
2793}
Eric Laurent81784c32012-11-19 14:55:58 -08002794
Eric Laurentaccc1472013-09-20 09:36:34 -07002795status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2796{
2797 if (mNormalSink != 0) {
2798 return mNormalSink->getTimestamp(timestamp);
2799 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002800 if ((mType == OFFLOAD || mType == DIRECT)
2801 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002802 uint64_t position64;
2803 int ret = mOutput->stream->get_presentation_position(
2804 mOutput->stream, &position64, &timestamp.mTime);
2805 if (ret == 0) {
2806 timestamp.mPosition = (uint32_t)position64;
2807 return NO_ERROR;
2808 }
2809 }
2810 return INVALID_OPERATION;
2811}
Eric Laurent1c333e22014-05-20 10:48:17 -07002812
2813status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2814 audio_patch_handle_t *handle)
2815{
2816 status_t status = NO_ERROR;
2817 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2818 // store new device and send to effects
2819 audio_devices_t type = AUDIO_DEVICE_NONE;
2820 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2821 type |= patch->sinks[i].ext.device.type;
2822 }
2823 mOutDevice = type;
2824 for (size_t i = 0; i < mEffectChains.size(); i++) {
2825 mEffectChains[i]->setDevice_l(mOutDevice);
2826 }
2827
2828 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2829 status = hwDevice->create_audio_patch(hwDevice,
2830 patch->num_sources,
2831 patch->sources,
2832 patch->num_sinks,
2833 patch->sinks,
2834 handle);
2835 } else {
2836 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2837 }
2838 return status;
2839}
2840
2841status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2842{
2843 status_t status = NO_ERROR;
2844 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2845 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2846 status = hwDevice->release_audio_patch(hwDevice, handle);
2847 } else {
2848 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2849 }
2850 return status;
2851}
2852
Eric Laurent83b88082014-06-20 18:31:16 -07002853void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2854{
2855 Mutex::Autolock _l(mLock);
2856 mTracks.add(track);
2857}
2858
2859void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2860{
2861 Mutex::Autolock _l(mLock);
2862 destroyTrack_l(track);
2863}
2864
2865void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2866{
2867 ThreadBase::getAudioPortConfig(config);
2868 config->role = AUDIO_PORT_ROLE_SOURCE;
2869 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2870 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2871}
2872
Eric Laurent81784c32012-11-19 14:55:58 -08002873// ----------------------------------------------------------------------------
2874
2875AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2876 audio_io_handle_t id, audio_devices_t device, type_t type)
2877 : PlaybackThread(audioFlinger, output, id, device, type),
2878 // mAudioMixer below
2879 // mFastMixer below
2880 mFastMixerFutex(0)
2881 // mOutputSink below
2882 // mPipeSink below
2883 // mNormalSink below
2884{
2885 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002886 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002887 "mFrameCount=%d, mNormalFrameCount=%d",
2888 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2889 mNormalFrameCount);
2890 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2891
Andy Hungfbfc3952015-01-15 13:33:51 -08002892 if (type == DUPLICATING) {
2893 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2894 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2895 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2896 return;
2897 }
Eric Laurent81784c32012-11-19 14:55:58 -08002898 // create an NBAIO sink for the HAL output stream, and negotiate
2899 mOutputSink = new AudioStreamOutSink(output->stream);
2900 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002901 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002902 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2903 ALOG_ASSERT(index == 0);
2904
2905 // initialize fast mixer depending on configuration
2906 bool initFastMixer;
2907 switch (kUseFastMixer) {
2908 case FastMixer_Never:
2909 initFastMixer = false;
2910 break;
2911 case FastMixer_Always:
2912 initFastMixer = true;
2913 break;
2914 case FastMixer_Static:
2915 case FastMixer_Dynamic:
2916 initFastMixer = mFrameCount < mNormalFrameCount;
2917 break;
2918 }
2919 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002920 audio_format_t fastMixerFormat;
2921 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2922 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2923 } else {
2924 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2925 }
2926 if (mFormat != fastMixerFormat) {
2927 // change our Sink format to accept our intermediate precision
2928 mFormat = fastMixerFormat;
2929 free(mSinkBuffer);
2930 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2931 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2932 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934
2935 // create a MonoPipe to connect our submix to FastMixer
2936 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002937 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002938 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002939 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002940 format.mFormat = fastMixerFormat;
2941 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2942
Eric Laurent81784c32012-11-19 14:55:58 -08002943 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2944 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2945 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2946 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2947 const NBAIO_Format offers[1] = {format};
2948 size_t numCounterOffers = 0;
2949 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2950 ALOG_ASSERT(index == 0);
2951 monoPipe->setAvgFrames((mScreenState & 1) ?
2952 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2953 mPipeSink = monoPipe;
2954
Glenn Kasten46909e72013-02-26 09:20:22 -08002955#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002956 if (mTeeSinkOutputEnabled) {
2957 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002958 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2959 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002960 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002961 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002962 ALOG_ASSERT(index == 0);
2963 mTeeSink = teeSink;
2964 PipeReader *teeSource = new PipeReader(*teeSink);
2965 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002966 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002967 ALOG_ASSERT(index == 0);
2968 mTeeSource = teeSource;
2969 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002970#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002971
2972 // create fast mixer and configure it initially with just one fast track for our submix
2973 mFastMixer = new FastMixer();
2974 FastMixerStateQueue *sq = mFastMixer->sq();
2975#ifdef STATE_QUEUE_DUMP
2976 sq->setObserverDump(&mStateQueueObserverDump);
2977 sq->setMutatorDump(&mStateQueueMutatorDump);
2978#endif
2979 FastMixerState *state = sq->begin();
2980 FastTrack *fastTrack = &state->mFastTracks[0];
2981 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2982 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2983 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002984 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2985 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002986 fastTrack->mGeneration++;
2987 state->mFastTracksGen++;
2988 state->mTrackMask = 1;
2989 // fast mixer will use the HAL output sink
2990 state->mOutputSink = mOutputSink.get();
2991 state->mOutputSinkGen++;
2992 state->mFrameCount = mFrameCount;
2993 state->mCommand = FastMixerState::COLD_IDLE;
2994 // already done in constructor initialization list
2995 //mFastMixerFutex = 0;
2996 state->mColdFutexAddr = &mFastMixerFutex;
2997 state->mColdGen++;
2998 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002999#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003000 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003001#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003002 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3003 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003004 sq->end();
3005 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3006
3007 // start the fast mixer
3008 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3009 pid_t tid = mFastMixer->getTid();
3010 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3011 if (err != 0) {
3012 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3013 kPriorityFastMixer, getpid_cached, tid, err);
3014 }
3015
3016#ifdef AUDIO_WATCHDOG
3017 // create and start the watchdog
3018 mAudioWatchdog = new AudioWatchdog();
3019 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3020 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3021 tid = mAudioWatchdog->getTid();
3022 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3023 if (err != 0) {
3024 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3025 kPriorityFastMixer, getpid_cached, tid, err);
3026 }
3027#endif
3028
Eric Laurent81784c32012-11-19 14:55:58 -08003029 }
3030
3031 switch (kUseFastMixer) {
3032 case FastMixer_Never:
3033 case FastMixer_Dynamic:
3034 mNormalSink = mOutputSink;
3035 break;
3036 case FastMixer_Always:
3037 mNormalSink = mPipeSink;
3038 break;
3039 case FastMixer_Static:
3040 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3041 break;
3042 }
3043}
3044
3045AudioFlinger::MixerThread::~MixerThread()
3046{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003047 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003048 FastMixerStateQueue *sq = mFastMixer->sq();
3049 FastMixerState *state = sq->begin();
3050 if (state->mCommand == FastMixerState::COLD_IDLE) {
3051 int32_t old = android_atomic_inc(&mFastMixerFutex);
3052 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003053 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003054 }
3055 }
3056 state->mCommand = FastMixerState::EXIT;
3057 sq->end();
3058 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3059 mFastMixer->join();
3060 // Though the fast mixer thread has exited, it's state queue is still valid.
3061 // We'll use that extract the final state which contains one remaining fast track
3062 // corresponding to our sub-mix.
3063 state = sq->begin();
3064 ALOG_ASSERT(state->mTrackMask == 1);
3065 FastTrack *fastTrack = &state->mFastTracks[0];
3066 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3067 delete fastTrack->mBufferProvider;
3068 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003069 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003070#ifdef AUDIO_WATCHDOG
3071 if (mAudioWatchdog != 0) {
3072 mAudioWatchdog->requestExit();
3073 mAudioWatchdog->requestExitAndWait();
3074 mAudioWatchdog.clear();
3075 }
3076#endif
3077 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003078 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003079 delete mAudioMixer;
3080}
3081
3082
3083uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3084{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003085 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003086 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3087 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3088 }
3089 return latency;
3090}
3091
3092
3093void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3094{
3095 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3096}
3097
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003099{
3100 // FIXME we should only do one push per cycle; confirm this is true
3101 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003102 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003103 FastMixerStateQueue *sq = mFastMixer->sq();
3104 FastMixerState *state = sq->begin();
3105 if (state->mCommand != FastMixerState::MIX_WRITE &&
3106 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3107 if (state->mCommand == FastMixerState::COLD_IDLE) {
3108 int32_t old = android_atomic_inc(&mFastMixerFutex);
3109 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003110 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003111 }
3112#ifdef AUDIO_WATCHDOG
3113 if (mAudioWatchdog != 0) {
3114 mAudioWatchdog->resume();
3115 }
3116#endif
3117 }
3118 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003119#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003120 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003121 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003122#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003123 sq->end();
3124 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3125 if (kUseFastMixer == FastMixer_Dynamic) {
3126 mNormalSink = mPipeSink;
3127 }
3128 } else {
3129 sq->end(false /*didModify*/);
3130 }
3131 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003133}
3134
3135void AudioFlinger::MixerThread::threadLoop_standby()
3136{
3137 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003138 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003139 FastMixerStateQueue *sq = mFastMixer->sq();
3140 FastMixerState *state = sq->begin();
3141 if (!(state->mCommand & FastMixerState::IDLE)) {
3142 state->mCommand = FastMixerState::COLD_IDLE;
3143 state->mColdFutexAddr = &mFastMixerFutex;
3144 state->mColdGen++;
3145 mFastMixerFutex = 0;
3146 sq->end();
3147 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3149 if (kUseFastMixer == FastMixer_Dynamic) {
3150 mNormalSink = mOutputSink;
3151 }
3152#ifdef AUDIO_WATCHDOG
3153 if (mAudioWatchdog != 0) {
3154 mAudioWatchdog->pause();
3155 }
3156#endif
3157 } else {
3158 sq->end(false /*didModify*/);
3159 }
3160 }
3161 PlaybackThread::threadLoop_standby();
3162}
3163
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3165{
3166 return false;
3167}
3168
3169bool AudioFlinger::PlaybackThread::shouldStandby_l()
3170{
3171 return !mStandby;
3172}
3173
3174bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3175{
3176 Mutex::Autolock _l(mLock);
3177 return waitingAsyncCallback_l();
3178}
3179
Eric Laurent81784c32012-11-19 14:55:58 -08003180// shared by MIXER and DIRECT, overridden by DUPLICATING
3181void AudioFlinger::PlaybackThread::threadLoop_standby()
3182{
3183 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3184 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003186 // discard any pending drain or write ack by incrementing sequence
3187 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3188 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003189 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003190 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3191 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003193 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003194}
3195
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003196void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3197{
3198 ALOGV("signal playback thread");
3199 broadcast_l();
3200}
3201
Eric Laurent81784c32012-11-19 14:55:58 -08003202void AudioFlinger::MixerThread::threadLoop_mix()
3203{
3204 // obtain the presentation timestamp of the next output buffer
3205 int64_t pts;
3206 status_t status = INVALID_OPERATION;
3207
3208 if (mNormalSink != 0) {
3209 status = mNormalSink->getNextWriteTimestamp(&pts);
3210 } else {
3211 status = mOutputSink->getNextWriteTimestamp(&pts);
3212 }
3213
3214 if (status != NO_ERROR) {
3215 pts = AudioBufferProvider::kInvalidPTS;
3216 }
3217
3218 // mix buffers...
3219 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003220 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003221 // increase sleep time progressively when application underrun condition clears.
3222 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3223 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3224 // such that we would underrun the audio HAL.
3225 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3226 sleepTimeShift--;
3227 }
3228 sleepTime = 0;
3229 standbyTime = systemTime() + standbyDelay;
3230 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003231
Eric Laurent81784c32012-11-19 14:55:58 -08003232}
3233
3234void AudioFlinger::MixerThread::threadLoop_sleepTime()
3235{
3236 // If no tracks are ready, sleep once for the duration of an output
3237 // buffer size, then write 0s to the output
3238 if (sleepTime == 0) {
3239 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3240 sleepTime = activeSleepTime >> sleepTimeShift;
3241 if (sleepTime < kMinThreadSleepTimeUs) {
3242 sleepTime = kMinThreadSleepTimeUs;
3243 }
3244 // reduce sleep time in case of consecutive application underruns to avoid
3245 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3246 // duration we would end up writing less data than needed by the audio HAL if
3247 // the condition persists.
3248 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3249 sleepTimeShift++;
3250 }
3251 } else {
3252 sleepTime = idleSleepTime;
3253 }
3254 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003255 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3256 // before effects processing or output.
3257 if (mMixerBufferValid) {
3258 memset(mMixerBuffer, 0, mMixerBufferSize);
3259 } else {
3260 memset(mSinkBuffer, 0, mSinkBufferSize);
3261 }
Eric Laurent81784c32012-11-19 14:55:58 -08003262 sleepTime = 0;
3263 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3264 "anticipated start");
3265 }
3266 // TODO add standby time extension fct of effect tail
3267}
3268
3269// prepareTracks_l() must be called with ThreadBase::mLock held
3270AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3271 Vector< sp<Track> > *tracksToRemove)
3272{
3273
3274 mixer_state mixerStatus = MIXER_IDLE;
3275 // find out which tracks need to be processed
3276 size_t count = mActiveTracks.size();
3277 size_t mixedTracks = 0;
3278 size_t tracksWithEffect = 0;
3279 // counts only _active_ fast tracks
3280 size_t fastTracks = 0;
3281 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3282
3283 float masterVolume = mMasterVolume;
3284 bool masterMute = mMasterMute;
3285
3286 if (masterMute) {
3287 masterVolume = 0;
3288 }
3289 // Delegate master volume control to effect in output mix effect chain if needed
3290 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3291 if (chain != 0) {
3292 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3293 chain->setVolume_l(&v, &v);
3294 masterVolume = (float)((v + (1 << 23)) >> 24);
3295 chain.clear();
3296 }
3297
3298 // prepare a new state to push
3299 FastMixerStateQueue *sq = NULL;
3300 FastMixerState *state = NULL;
3301 bool didModify = false;
3302 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003303 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003304 sq = mFastMixer->sq();
3305 state = sq->begin();
3306 }
3307
Andy Hung69aed5f2014-02-25 17:24:40 -08003308 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003309 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003310
Eric Laurent81784c32012-11-19 14:55:58 -08003311 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003312 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003313 if (t == 0) {
3314 continue;
3315 }
3316
3317 // this const just means the local variable doesn't change
3318 Track* const track = t.get();
3319
3320 // process fast tracks
3321 if (track->isFastTrack()) {
3322
3323 // It's theoretically possible (though unlikely) for a fast track to be created
3324 // and then removed within the same normal mix cycle. This is not a problem, as
3325 // the track never becomes active so it's fast mixer slot is never touched.
3326 // The converse, of removing an (active) track and then creating a new track
3327 // at the identical fast mixer slot within the same normal mix cycle,
3328 // is impossible because the slot isn't marked available until the end of each cycle.
3329 int j = track->mFastIndex;
3330 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3331 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3332 FastTrack *fastTrack = &state->mFastTracks[j];
3333
3334 // Determine whether the track is currently in underrun condition,
3335 // and whether it had a recent underrun.
3336 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3337 FastTrackUnderruns underruns = ftDump->mUnderruns;
3338 uint32_t recentFull = (underruns.mBitFields.mFull -
3339 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3340 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3341 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3342 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3343 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3344 uint32_t recentUnderruns = recentPartial + recentEmpty;
3345 track->mObservedUnderruns = underruns;
3346 // don't count underruns that occur while stopping or pausing
3347 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003348 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3349 recentUnderruns > 0) {
3350 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3351 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003352 }
3353
3354 // This is similar to the state machine for normal tracks,
3355 // with a few modifications for fast tracks.
3356 bool isActive = true;
3357 switch (track->mState) {
3358 case TrackBase::STOPPING_1:
3359 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003361 track->mState = TrackBase::STOPPING_2;
3362 }
3363 break;
3364 case TrackBase::PAUSING:
3365 // ramp down is not yet implemented
3366 track->setPaused();
3367 break;
3368 case TrackBase::RESUMING:
3369 // ramp up is not yet implemented
3370 track->mState = TrackBase::ACTIVE;
3371 break;
3372 case TrackBase::ACTIVE:
3373 if (recentFull > 0 || recentPartial > 0) {
3374 // track has provided at least some frames recently: reset retry count
3375 track->mRetryCount = kMaxTrackRetries;
3376 }
3377 if (recentUnderruns == 0) {
3378 // no recent underruns: stay active
3379 break;
3380 }
3381 // there has recently been an underrun of some kind
3382 if (track->sharedBuffer() == 0) {
3383 // were any of the recent underruns "empty" (no frames available)?
3384 if (recentEmpty == 0) {
3385 // no, then ignore the partial underruns as they are allowed indefinitely
3386 break;
3387 }
3388 // there has recently been an "empty" underrun: decrement the retry counter
3389 if (--(track->mRetryCount) > 0) {
3390 break;
3391 }
3392 // indicate to client process that the track was disabled because of underrun;
3393 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003394 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003395 // remove from active list, but state remains ACTIVE [confusing but true]
3396 isActive = false;
3397 break;
3398 }
3399 // fall through
3400 case TrackBase::STOPPING_2:
3401 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003402 case TrackBase::STOPPED:
3403 case TrackBase::FLUSHED: // flush() while active
3404 // Check for presentation complete if track is inactive
3405 // We have consumed all the buffers of this track.
3406 // This would be incomplete if we auto-paused on underrun
3407 {
3408 size_t audioHALFrames =
3409 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3410 size_t framesWritten = mBytesWritten / mFrameSize;
3411 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3412 // track stays in active list until presentation is complete
3413 break;
3414 }
3415 }
3416 if (track->isStopping_2()) {
3417 track->mState = TrackBase::STOPPED;
3418 }
3419 if (track->isStopped()) {
3420 // Can't reset directly, as fast mixer is still polling this track
3421 // track->reset();
3422 // So instead mark this track as needing to be reset after push with ack
3423 resetMask |= 1 << i;
3424 }
3425 isActive = false;
3426 break;
3427 case TrackBase::IDLE:
3428 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003429 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003430 }
3431
3432 if (isActive) {
3433 // was it previously inactive?
3434 if (!(state->mTrackMask & (1 << j))) {
3435 ExtendedAudioBufferProvider *eabp = track;
3436 VolumeProvider *vp = track;
3437 fastTrack->mBufferProvider = eabp;
3438 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003439 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003440 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003441 fastTrack->mGeneration++;
3442 state->mTrackMask |= 1 << j;
3443 didModify = true;
3444 // no acknowledgement required for newly active tracks
3445 }
3446 // cache the combined master volume and stream type volume for fast mixer; this
3447 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003448 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003449 ++fastTracks;
3450 } else {
3451 // was it previously active?
3452 if (state->mTrackMask & (1 << j)) {
3453 fastTrack->mBufferProvider = NULL;
3454 fastTrack->mGeneration++;
3455 state->mTrackMask &= ~(1 << j);
3456 didModify = true;
3457 // If any fast tracks were removed, we must wait for acknowledgement
3458 // because we're about to decrement the last sp<> on those tracks.
3459 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3460 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003461 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
3463 tracksToRemove->add(track);
3464 // Avoids a misleading display in dumpsys
3465 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3466 }
3467 continue;
3468 }
3469
3470 { // local variable scope to avoid goto warning
3471
3472 audio_track_cblk_t* cblk = track->cblk();
3473
3474 // The first time a track is added we wait
3475 // for all its buffers to be filled before processing it
3476 int name = track->name();
3477 // make sure that we have enough frames to mix one full buffer.
3478 // enforce this condition only once to enable draining the buffer in case the client
3479 // app does not call stop() and relies on underrun to stop:
3480 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3481 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003482 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003483 uint32_t sr = track->sampleRate();
3484 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003485 desiredFrames = mNormalFrameCount;
3486 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003487 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003488 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003489 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003490 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003491#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003492 // the minimum track buffer size is normally twice the number of frames necessary
3493 // to fill one buffer and the resampler should not leave more than one buffer worth
3494 // of unreleased frames after each pass, but just in case...
3495 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003496#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003497 }
Eric Laurent81784c32012-11-19 14:55:58 -08003498 uint32_t minFrames = 1;
3499 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3500 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003501 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003502 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003503
3504 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003505 if (ATRACE_ENABLED()) {
3506 // I wish we had formatted trace names
3507 char traceName[16];
3508 strcpy(traceName, "nRdy");
3509 int name = track->name();
3510 if (AudioMixer::TRACK0 <= name &&
3511 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3512 name -= AudioMixer::TRACK0;
3513 traceName[4] = (name / 10) + '0';
3514 traceName[5] = (name % 10) + '0';
3515 } else {
3516 traceName[4] = '?';
3517 traceName[5] = '?';
3518 }
3519 traceName[6] = '\0';
3520 ATRACE_INT(traceName, framesReady);
3521 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003522 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003523 !track->isPaused() && !track->isTerminated())
3524 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003525 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003526
3527 mixedTracks++;
3528
Andy Hung69aed5f2014-02-25 17:24:40 -08003529 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3530 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003531 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003532 if (track->mainBuffer() != mSinkBuffer &&
3533 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003534 if (mEffectBufferEnabled) {
3535 mEffectBufferValid = true; // Later can set directly.
3536 }
Eric Laurent81784c32012-11-19 14:55:58 -08003537 chain = getEffectChain_l(track->sessionId());
3538 // Delegate volume control to effect in track effect chain if needed
3539 if (chain != 0) {
3540 tracksWithEffect++;
3541 } else {
3542 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3543 "session %d",
3544 name, track->sessionId());
3545 }
3546 }
3547
3548
3549 int param = AudioMixer::VOLUME;
3550 if (track->mFillingUpStatus == Track::FS_FILLED) {
3551 // no ramp for the first volume setting
3552 track->mFillingUpStatus = Track::FS_ACTIVE;
3553 if (track->mState == TrackBase::RESUMING) {
3554 track->mState = TrackBase::ACTIVE;
3555 param = AudioMixer::RAMP_VOLUME;
3556 }
3557 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003558 // FIXME should not make a decision based on mServer
3559 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003560 // If the track is stopped before the first frame was mixed,
3561 // do not apply ramp
3562 param = AudioMixer::RAMP_VOLUME;
3563 }
3564
3565 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003566 uint32_t vl, vr; // in U8.24 integer format
3567 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003568 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003569 vl = vr = 0;
3570 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003571 if (track->isPausing()) {
3572 track->setPaused();
3573 }
3574 } else {
3575
3576 // read original volumes with volume control
3577 float typeVolume = mStreamTypes[track->streamType()].volume;
3578 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003579 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003580 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003581 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3582 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003583 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003584 if (vlf > GAIN_FLOAT_UNITY) {
3585 ALOGV("Track left volume out of range: %.3g", vlf);
3586 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003587 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003588 if (vrf > GAIN_FLOAT_UNITY) {
3589 ALOGV("Track right volume out of range: %.3g", vrf);
3590 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003591 }
3592 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003593 vlf *= v;
3594 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003595 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003596 // then derive vl and vr as U8.24 versions for the effect chain
3597 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3598 vl = (uint32_t) (scaleto8_24 * vlf);
3599 vr = (uint32_t) (scaleto8_24 * vrf);
3600 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003601 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // send level comes from shared memory and so may be corrupt
3603 if (sendLevel > MAX_GAIN_INT) {
3604 ALOGV("Track send level out of range: %04X", sendLevel);
3605 sendLevel = MAX_GAIN_INT;
3606 }
Andy Hung6be49402014-05-30 10:42:03 -07003607 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3608 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003609 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // Delegate volume control to effect in track effect chain if needed
3612 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3613 // Do not ramp volume if volume is controlled by effect
3614 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003615 // Update remaining floating point volume levels
3616 vlf = (float)vl / (1 << 24);
3617 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003618 track->mHasVolumeController = true;
3619 } else {
3620 // force no volume ramp when volume controller was just disabled or removed
3621 // from effect chain to avoid volume spike
3622 if (track->mHasVolumeController) {
3623 param = AudioMixer::VOLUME;
3624 }
3625 track->mHasVolumeController = false;
3626 }
3627
Eric Laurent81784c32012-11-19 14:55:58 -08003628 // XXX: these things DON'T need to be done each time
3629 mAudioMixer->setBufferProvider(name, track);
3630 mAudioMixer->enable(name);
3631
Andy Hung6be49402014-05-30 10:42:03 -07003632 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3633 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3634 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003635 mAudioMixer->setParameter(
3636 name,
3637 AudioMixer::TRACK,
3638 AudioMixer::FORMAT, (void *)track->format());
3639 mAudioMixer->setParameter(
3640 name,
3641 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003642 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003643 mAudioMixer->setParameter(
3644 name,
3645 AudioMixer::TRACK,
3646 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003647 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003648 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003649 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003650 if (reqSampleRate == 0) {
3651 reqSampleRate = mSampleRate;
3652 } else if (reqSampleRate > maxSampleRate) {
3653 reqSampleRate = maxSampleRate;
3654 }
Eric Laurent81784c32012-11-19 14:55:58 -08003655 mAudioMixer->setParameter(
3656 name,
3657 AudioMixer::RESAMPLE,
3658 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003659 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003660 /*
3661 * Select the appropriate output buffer for the track.
3662 *
Andy Hung98ef9782014-03-04 14:46:50 -08003663 * Tracks with effects go into their own effects chain buffer
3664 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003665 *
3666 * Other tracks can use mMixerBuffer for higher precision
3667 * channel accumulation. If this buffer is enabled
3668 * (mMixerBufferEnabled true), then selected tracks will accumulate
3669 * into it.
3670 *
3671 */
3672 if (mMixerBufferEnabled
3673 && (track->mainBuffer() == mSinkBuffer
3674 || track->mainBuffer() == mMixerBuffer)) {
3675 mAudioMixer->setParameter(
3676 name,
3677 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003678 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003679 mAudioMixer->setParameter(
3680 name,
3681 AudioMixer::TRACK,
3682 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3683 // TODO: override track->mainBuffer()?
3684 mMixerBufferValid = true;
3685 } else {
3686 mAudioMixer->setParameter(
3687 name,
3688 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003689 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003690 mAudioMixer->setParameter(
3691 name,
3692 AudioMixer::TRACK,
3693 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3694 }
Eric Laurent81784c32012-11-19 14:55:58 -08003695 mAudioMixer->setParameter(
3696 name,
3697 AudioMixer::TRACK,
3698 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3699
3700 // reset retry count
3701 track->mRetryCount = kMaxTrackRetries;
3702
3703 // If one track is ready, set the mixer ready if:
3704 // - the mixer was not ready during previous round OR
3705 // - no other track is not ready
3706 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3707 mixerStatus != MIXER_TRACKS_ENABLED) {
3708 mixerStatus = MIXER_TRACKS_READY;
3709 }
3710 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003711 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003712 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003713 }
Eric Laurent81784c32012-11-19 14:55:58 -08003714 // clear effect chain input buffer if an active track underruns to avoid sending
3715 // previous audio buffer again to effects
3716 chain = getEffectChain_l(track->sessionId());
3717 if (chain != 0) {
3718 chain->clearInputBuffer();
3719 }
3720
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003721 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003722 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3723 track->isStopped() || track->isPaused()) {
3724 // We have consumed all the buffers of this track.
3725 // Remove it from the list of active tracks.
3726 // TODO: use actual buffer filling status instead of latency when available from
3727 // audio HAL
3728 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3729 size_t framesWritten = mBytesWritten / mFrameSize;
3730 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3731 if (track->isStopped()) {
3732 track->reset();
3733 }
3734 tracksToRemove->add(track);
3735 }
3736 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003737 // No buffers for this track. Give it a few chances to
3738 // fill a buffer, then remove it from active list.
3739 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003740 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003741 tracksToRemove->add(track);
3742 // indicate to client process that the track was disabled because of underrun;
3743 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003744 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003745 // If one track is not ready, mark the mixer also not ready if:
3746 // - the mixer was ready during previous round OR
3747 // - no other track is ready
3748 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3749 mixerStatus != MIXER_TRACKS_READY) {
3750 mixerStatus = MIXER_TRACKS_ENABLED;
3751 }
3752 }
3753 mAudioMixer->disable(name);
3754 }
3755
3756 } // local variable scope to avoid goto warning
3757track_is_ready: ;
3758
3759 }
3760
3761 // Push the new FastMixer state if necessary
3762 bool pauseAudioWatchdog = false;
3763 if (didModify) {
3764 state->mFastTracksGen++;
3765 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3766 if (kUseFastMixer == FastMixer_Dynamic &&
3767 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3768 state->mCommand = FastMixerState::COLD_IDLE;
3769 state->mColdFutexAddr = &mFastMixerFutex;
3770 state->mColdGen++;
3771 mFastMixerFutex = 0;
3772 if (kUseFastMixer == FastMixer_Dynamic) {
3773 mNormalSink = mOutputSink;
3774 }
3775 // If we go into cold idle, need to wait for acknowledgement
3776 // so that fast mixer stops doing I/O.
3777 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3778 pauseAudioWatchdog = true;
3779 }
Eric Laurent81784c32012-11-19 14:55:58 -08003780 }
3781 if (sq != NULL) {
3782 sq->end(didModify);
3783 sq->push(block);
3784 }
3785#ifdef AUDIO_WATCHDOG
3786 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3787 mAudioWatchdog->pause();
3788 }
3789#endif
3790
3791 // Now perform the deferred reset on fast tracks that have stopped
3792 while (resetMask != 0) {
3793 size_t i = __builtin_ctz(resetMask);
3794 ALOG_ASSERT(i < count);
3795 resetMask &= ~(1 << i);
3796 sp<Track> t = mActiveTracks[i].promote();
3797 if (t == 0) {
3798 continue;
3799 }
3800 Track* track = t.get();
3801 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3802 track->reset();
3803 }
3804
3805 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003806 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003807
Eric Laurent97d547d2014-09-02 14:45:53 -07003808 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3809 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003810 }
3811
3812 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003813 // as long as there are effects we should clear the effects buffer, to avoid
3814 // passing a non-clean buffer to the effect chain
3815 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003816 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003817 // sink or mix buffer must be cleared if all tracks are connected to an
3818 // effect chain as in this case the mixer will not write to the sink or mix buffer
3819 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003820 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3821 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003822 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003823 if (mMixerBufferValid) {
3824 memset(mMixerBuffer, 0, mMixerBufferSize);
3825 // TODO: In testing, mSinkBuffer below need not be cleared because
3826 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3827 // after mixing.
3828 //
3829 // To enforce this guarantee:
3830 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3831 // (mixedTracks == 0 && fastTracks > 0))
3832 // must imply MIXER_TRACKS_READY.
3833 // Later, we may clear buffers regardless, and skip much of this logic.
3834 }
Andy Hung98ef9782014-03-04 14:46:50 -08003835 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003836 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003837 }
3838
3839 // if any fast tracks, then status is ready
3840 mMixerStatusIgnoringFastTracks = mixerStatus;
3841 if (fastTracks > 0) {
3842 mixerStatus = MIXER_TRACKS_READY;
3843 }
3844 return mixerStatus;
3845}
3846
3847// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003848int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3849 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003850{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003851 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003852}
3853
3854// deleteTrackName_l() must be called with ThreadBase::mLock held
3855void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3856{
3857 ALOGV("remove track (%d) and delete from mixer", name);
3858 mAudioMixer->deleteTrackName(name);
3859}
3860
Eric Laurent10351942014-05-08 18:49:52 -07003861// checkForNewParameter_l() must be called with ThreadBase::mLock held
3862bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3863 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003864{
Eric Laurent81784c32012-11-19 14:55:58 -08003865 bool reconfig = false;
3866
Eric Laurent10351942014-05-08 18:49:52 -07003867 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003868
Eric Laurent10351942014-05-08 18:49:52 -07003869 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3870 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003871 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003872 FastMixerStateQueue *sq = mFastMixer->sq();
3873 FastMixerState *state = sq->begin();
3874 if (!(state->mCommand & FastMixerState::IDLE)) {
3875 previousCommand = state->mCommand;
3876 state->mCommand = FastMixerState::HOT_IDLE;
3877 sq->end();
3878 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3879 } else {
3880 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 }
Eric Laurent10351942014-05-08 18:49:52 -07003882 }
Eric Laurent81784c32012-11-19 14:55:58 -08003883
Eric Laurent10351942014-05-08 18:49:52 -07003884 AudioParameter param = AudioParameter(keyValuePair);
3885 int value;
3886 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3887 reconfig = true;
3888 }
3889 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003890 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003891 status = BAD_VALUE;
3892 } else {
3893 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003894 reconfig = true;
3895 }
Eric Laurent10351942014-05-08 18:49:52 -07003896 }
3897 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003898 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003899 status = BAD_VALUE;
3900 } else {
3901 // no need to save value, since it's constant
3902 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 }
Eric Laurent10351942014-05-08 18:49:52 -07003904 }
3905 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3906 // do not accept frame count changes if tracks are open as the track buffer
3907 // size depends on frame count and correct behavior would not be guaranteed
3908 // if frame count is changed after track creation
3909 if (!mTracks.isEmpty()) {
3910 status = INVALID_OPERATION;
3911 } else {
3912 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003913 }
Eric Laurent10351942014-05-08 18:49:52 -07003914 }
3915 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003916#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003917 // when changing the audio output device, call addBatteryData to notify
3918 // the change
3919 if (mOutDevice != value) {
3920 uint32_t params = 0;
3921 // check whether speaker is on
3922 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3923 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
Eric Laurent10351942014-05-08 18:49:52 -07003925
3926 audio_devices_t deviceWithoutSpeaker
3927 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3928 // check if any other device (except speaker) is on
3929 if (value & deviceWithoutSpeaker ) {
3930 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3931 }
3932
3933 if (params != 0) {
3934 addBatteryData(params);
3935 }
3936 }
Eric Laurent81784c32012-11-19 14:55:58 -08003937#endif
3938
Eric Laurent10351942014-05-08 18:49:52 -07003939 // forward device change to effects that have requested to be
3940 // aware of attached audio device.
3941 if (value != AUDIO_DEVICE_NONE) {
3942 mOutDevice = value;
3943 for (size_t i = 0; i < mEffectChains.size(); i++) {
3944 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003945 }
3946 }
Eric Laurent10351942014-05-08 18:49:52 -07003947 }
Eric Laurent81784c32012-11-19 14:55:58 -08003948
Eric Laurent10351942014-05-08 18:49:52 -07003949 if (status == NO_ERROR) {
3950 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3951 keyValuePair.string());
3952 if (!mStandby && status == INVALID_OPERATION) {
3953 mOutput->stream->common.standby(&mOutput->stream->common);
3954 mStandby = true;
3955 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003956 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003957 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003958 }
Eric Laurent10351942014-05-08 18:49:52 -07003959 if (status == NO_ERROR && reconfig) {
3960 readOutputParameters_l();
3961 delete mAudioMixer;
3962 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3963 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003964 int name = getTrackName_l(mTracks[i]->mChannelMask,
3965 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003966 if (name < 0) {
3967 break;
3968 }
3969 mTracks[i]->mName = name;
3970 }
3971 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3972 }
Eric Laurent81784c32012-11-19 14:55:58 -08003973 }
3974
3975 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003976 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003977 FastMixerStateQueue *sq = mFastMixer->sq();
3978 FastMixerState *state = sq->begin();
3979 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3980 state->mCommand = previousCommand;
3981 sq->end();
3982 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3983 }
3984
3985 return reconfig;
3986}
3987
3988
3989void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3990{
3991 const size_t SIZE = 256;
3992 char buffer[SIZE];
3993 String8 result;
3994
3995 PlaybackThread::dumpInternals(fd, args);
3996
Elliott Hughes87cebad2014-05-22 10:14:43 -07003997 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003998
3999 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004000 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004001 copy.dump(fd);
4002
4003#ifdef STATE_QUEUE_DUMP
4004 // Similar for state queue
4005 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4006 observerCopy.dump(fd);
4007 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4008 mutatorCopy.dump(fd);
4009#endif
4010
Glenn Kasten46909e72013-02-26 09:20:22 -08004011#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004012 // Write the tee output to a .wav file
4013 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004014#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004015
4016#ifdef AUDIO_WATCHDOG
4017 if (mAudioWatchdog != 0) {
4018 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4019 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4020 wdCopy.dump(fd);
4021 }
4022#endif
4023}
4024
4025uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4026{
4027 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4028}
4029
4030uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4031{
4032 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4033}
4034
4035void AudioFlinger::MixerThread::cacheParameters_l()
4036{
4037 PlaybackThread::cacheParameters_l();
4038
4039 // FIXME: Relaxed timing because of a certain device that can't meet latency
4040 // Should be reduced to 2x after the vendor fixes the driver issue
4041 // increase threshold again due to low power audio mode. The way this warning
4042 // threshold is calculated and its usefulness should be reconsidered anyway.
4043 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4044}
4045
4046// ----------------------------------------------------------------------------
4047
4048AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4049 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4050 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4051 // mLeftVolFloat, mRightVolFloat
4052{
4053}
4054
Eric Laurentbfb1b832013-01-07 09:53:42 -08004055AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4056 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4057 ThreadBase::type_t type)
4058 : PlaybackThread(audioFlinger, output, id, device, type)
4059 // mLeftVolFloat, mRightVolFloat
4060{
4061}
4062
Eric Laurent81784c32012-11-19 14:55:58 -08004063AudioFlinger::DirectOutputThread::~DirectOutputThread()
4064{
4065}
4066
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4068{
4069 audio_track_cblk_t* cblk = track->cblk();
4070 float left, right;
4071
4072 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4073 left = right = 0;
4074 } else {
4075 float typeVolume = mStreamTypes[track->streamType()].volume;
4076 float v = mMasterVolume * typeVolume;
4077 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004078 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4079 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4080 if (left > GAIN_FLOAT_UNITY) {
4081 left = GAIN_FLOAT_UNITY;
4082 }
4083 left *= v;
4084 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4085 if (right > GAIN_FLOAT_UNITY) {
4086 right = GAIN_FLOAT_UNITY;
4087 }
4088 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004089 }
4090
4091 if (lastTrack) {
4092 if (left != mLeftVolFloat || right != mRightVolFloat) {
4093 mLeftVolFloat = left;
4094 mRightVolFloat = right;
4095
4096 // Convert volumes from float to 8.24
4097 uint32_t vl = (uint32_t)(left * (1 << 24));
4098 uint32_t vr = (uint32_t)(right * (1 << 24));
4099
4100 // Delegate volume control to effect in track effect chain if needed
4101 // only one effect chain can be present on DirectOutputThread, so if
4102 // there is one, the track is connected to it
4103 if (!mEffectChains.isEmpty()) {
4104 mEffectChains[0]->setVolume_l(&vl, &vr);
4105 left = (float)vl / (1 << 24);
4106 right = (float)vr / (1 << 24);
4107 }
4108 if (mOutput->stream->set_volume) {
4109 mOutput->stream->set_volume(mOutput->stream, left, right);
4110 }
4111 }
4112 }
4113}
4114
4115
Eric Laurent81784c32012-11-19 14:55:58 -08004116AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4117 Vector< sp<Track> > *tracksToRemove
4118)
4119{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004120 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004121 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004122 bool doHwPause = false;
4123 bool doHwResume = false;
4124 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004125
4126 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004127 for (size_t i = 0; i < count; i++) {
4128 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004129 // The track died recently
4130 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004131 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004132 }
4133
4134 Track* const track = t.get();
4135 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004136 // Only consider last track started for volume and mixer state control.
4137 // In theory an older track could underrun and restart after the new one starts
4138 // but as we only care about the transition phase between two tracks on a
4139 // direct output, it is not a problem to ignore the underrun case.
4140 sp<Track> l = mLatestActiveTrack.promote();
4141 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004142
Eric Laurentd1f69b02014-12-15 14:33:13 -08004143 if (mHwSupportsPause && track->isPausing()) {
4144 track->setPaused();
4145 if (last && !mHwPaused) {
4146 doHwPause = true;
4147 mHwPaused = true;
4148 }
4149 tracksToRemove->add(track);
4150 } else if (track->isFlushPending()) {
4151 track->flushAck();
4152 if (last) {
4153 flushPending = true;
4154 }
4155 } else if (mHwSupportsPause && track->isResumePending()){
4156 track->resumeAck();
4157 if (last) {
4158 if (mHwPaused) {
4159 doHwResume = true;
4160 mHwPaused = false;
4161 }
4162 }
4163 }
4164
Eric Laurent81784c32012-11-19 14:55:58 -08004165 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004166 // for all its buffers to be filled before processing it.
4167 // Allow draining the buffer in case the client
4168 // app does not call stop() and relies on underrun to stop:
4169 // hence the test on (track->mRetryCount > 1).
4170 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004171 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004172 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4173 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004174 minFrames = mNormalFrameCount;
4175 } else {
4176 minFrames = 1;
4177 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178
Eric Laurentab5cdba2014-06-09 17:22:27 -07004179 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4180 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004181 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004182 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004183
4184 if (track->mFillingUpStatus == Track::FS_FILLED) {
4185 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004186 // make sure processVolume_l() will apply new volume even if 0
4187 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004188 if (!mHwSupportsPause) {
4189 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004190 }
4191 }
4192
4193 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004194 processVolume_l(track, last);
4195 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004196 // reset retry count
4197 track->mRetryCount = kMaxTrackRetriesDirect;
4198 mActiveTrack = t;
4199 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004200 if (usesHwAvSync() && mHwPaused) {
4201 doHwResume = true;
4202 mHwPaused = false;
4203 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004206 // clear effect chain input buffer if the last active track started underruns
4207 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004208 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004209 mEffectChains[0]->clearInputBuffer();
4210 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004211 if (track->isStopping_1()) {
4212 track->mState = TrackBase::STOPPING_2;
4213 }
4214 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4215 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004216 // We have consumed all the buffers of this track.
4217 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004218 size_t audioHALFrames;
4219 if (audio_is_linear_pcm(mFormat)) {
4220 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4221 } else {
4222 audioHALFrames = 0;
4223 }
4224
Eric Laurent81784c32012-11-19 14:55:58 -08004225 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004226 if (mStandby || !last ||
4227 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004228 if (track->isStopping_2()) {
4229 track->mState = TrackBase::STOPPED;
4230 }
Eric Laurent81784c32012-11-19 14:55:58 -08004231 if (track->isStopped()) {
4232 track->reset();
4233 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004234 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004235 }
4236 } else {
4237 // No buffers for this track. Give it a few chances to
4238 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004239 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004240 if (--(track->mRetryCount) <= 0) {
4241 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004242 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004243 // indicate to client process that the track was disabled because of underrun;
4244 // it will then automatically call start() when data is available
4245 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004247 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004248 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4249 doHwPause = true;
4250 mHwPaused = true;
4251 }
Eric Laurent81784c32012-11-19 14:55:58 -08004252 }
4253 }
4254 }
4255 }
4256
Eric Laurentd1f69b02014-12-15 14:33:13 -08004257 // if an active track did not command a flush, check for pending flush on stopped tracks
4258 if (!flushPending) {
4259 for (size_t i = 0; i < mTracks.size(); i++) {
4260 if (mTracks[i]->isFlushPending()) {
4261 mTracks[i]->flushAck();
4262 flushPending = true;
4263 }
4264 }
4265 }
4266
4267 // make sure the pause/flush/resume sequence is executed in the right order.
4268 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4269 // before flush and then resume HW. This can happen in case of pause/flush/resume
4270 // if resume is received before pause is executed.
4271 if (mHwSupportsPause && !mStandby &&
4272 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4273 mOutput->stream->pause(mOutput->stream);
4274 }
4275 if (flushPending) {
4276 flushHw_l();
4277 }
4278 if (mHwSupportsPause && !mStandby && doHwResume) {
4279 mOutput->stream->resume(mOutput->stream);
4280 }
Eric Laurent81784c32012-11-19 14:55:58 -08004281 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004282 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004283
4284 return mixerStatus;
4285}
4286
4287void AudioFlinger::DirectOutputThread::threadLoop_mix()
4288{
Eric Laurent81784c32012-11-19 14:55:58 -08004289 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004290 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // output audio to hardware
4292 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004293 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004294 buffer.frameCount = frameCount;
4295 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004296 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004297 memset(curBuf, 0, frameCount * mFrameSize);
4298 break;
4299 }
4300 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4301 frameCount -= buffer.frameCount;
4302 curBuf += buffer.frameCount * mFrameSize;
4303 mActiveTrack->releaseBuffer(&buffer);
4304 }
Andy Hung2098f272014-02-27 14:00:06 -08004305 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004306 sleepTime = 0;
4307 standbyTime = systemTime() + standbyDelay;
4308 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004309}
4310
4311void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4312{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004313 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004314 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004315 sleepTime = idleSleepTime;
4316 return;
4317 }
Eric Laurent81784c32012-11-19 14:55:58 -08004318 if (sleepTime == 0) {
4319 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4320 sleepTime = activeSleepTime;
4321 } else {
4322 sleepTime = idleSleepTime;
4323 }
4324 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004325 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004326 sleepTime = 0;
4327 }
4328}
4329
Eric Laurentd1f69b02014-12-15 14:33:13 -08004330void AudioFlinger::DirectOutputThread::threadLoop_exit()
4331{
4332 {
4333 Mutex::Autolock _l(mLock);
4334 bool flushPending = false;
4335 for (size_t i = 0; i < mTracks.size(); i++) {
4336 if (mTracks[i]->isFlushPending()) {
4337 mTracks[i]->flushAck();
4338 flushPending = true;
4339 }
4340 }
4341 if (flushPending) {
4342 flushHw_l();
4343 }
4344 }
4345 PlaybackThread::threadLoop_exit();
4346}
4347
4348// must be called with thread mutex locked
4349bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4350{
4351 bool trackPaused = false;
4352
4353 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4354 // after a timeout and we will enter standby then.
4355 if (mTracks.size() > 0) {
4356 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4357 }
4358
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004359 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004360}
4361
Eric Laurent81784c32012-11-19 14:55:58 -08004362// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004363int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004364 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004365{
4366 return 0;
4367}
4368
4369// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004370void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004371{
4372}
4373
Eric Laurent10351942014-05-08 18:49:52 -07004374// checkForNewParameter_l() must be called with ThreadBase::mLock held
4375bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4376 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004377{
4378 bool reconfig = false;
4379
Eric Laurent10351942014-05-08 18:49:52 -07004380 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004381
Eric Laurent10351942014-05-08 18:49:52 -07004382 AudioParameter param = AudioParameter(keyValuePair);
4383 int value;
4384 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4385 // forward device change to effects that have requested to be
4386 // aware of attached audio device.
4387 if (value != AUDIO_DEVICE_NONE) {
4388 mOutDevice = value;
4389 for (size_t i = 0; i < mEffectChains.size(); i++) {
4390 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004391 }
4392 }
Eric Laurent81784c32012-11-19 14:55:58 -08004393 }
Eric Laurent10351942014-05-08 18:49:52 -07004394 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4395 // do not accept frame count changes if tracks are open as the track buffer
4396 // size depends on frame count and correct behavior would not be garantied
4397 // if frame count is changed after track creation
4398 if (!mTracks.isEmpty()) {
4399 status = INVALID_OPERATION;
4400 } else {
4401 reconfig = true;
4402 }
4403 }
4404 if (status == NO_ERROR) {
4405 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4406 keyValuePair.string());
4407 if (!mStandby && status == INVALID_OPERATION) {
4408 mOutput->stream->common.standby(&mOutput->stream->common);
4409 mStandby = true;
4410 mBytesWritten = 0;
4411 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4412 keyValuePair.string());
4413 }
4414 if (status == NO_ERROR && reconfig) {
4415 readOutputParameters_l();
4416 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4417 }
4418 }
4419
Eric Laurent81784c32012-11-19 14:55:58 -08004420 return reconfig;
4421}
4422
4423uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4424{
4425 uint32_t time;
4426 if (audio_is_linear_pcm(mFormat)) {
4427 time = PlaybackThread::activeSleepTimeUs();
4428 } else {
4429 time = 10000;
4430 }
4431 return time;
4432}
4433
4434uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4435{
4436 uint32_t time;
4437 if (audio_is_linear_pcm(mFormat)) {
4438 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4439 } else {
4440 time = 10000;
4441 }
4442 return time;
4443}
4444
4445uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4446{
4447 uint32_t time;
4448 if (audio_is_linear_pcm(mFormat)) {
4449 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4450 } else {
4451 time = 10000;
4452 }
4453 return time;
4454}
4455
4456void AudioFlinger::DirectOutputThread::cacheParameters_l()
4457{
4458 PlaybackThread::cacheParameters_l();
4459
4460 // use shorter standby delay as on normal output to release
4461 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004462 if (audio_is_linear_pcm(mFormat)) {
4463 standbyDelay = microseconds(activeSleepTime*2);
4464 } else {
4465 standbyDelay = kOffloadStandbyDelayNs;
4466 }
Eric Laurent81784c32012-11-19 14:55:58 -08004467}
4468
Eric Laurente659ef42014-09-29 13:06:46 -07004469void AudioFlinger::DirectOutputThread::flushHw_l()
4470{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004471 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004472 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004473 }
4474 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004475}
4476
Eric Laurent81784c32012-11-19 14:55:58 -08004477// ----------------------------------------------------------------------------
4478
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004480 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004482 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004483 mWriteAckSequence(0),
4484 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485{
4486}
4487
4488AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4489{
4490}
4491
4492void AudioFlinger::AsyncCallbackThread::onFirstRef()
4493{
4494 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4495}
4496
4497bool AudioFlinger::AsyncCallbackThread::threadLoop()
4498{
4499 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004500 uint32_t writeAckSequence;
4501 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004502
4503 {
4504 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004505 while (!((mWriteAckSequence & 1) ||
4506 (mDrainSequence & 1) ||
4507 exitPending())) {
4508 mWaitWorkCV.wait(mLock);
4509 }
4510
Eric Laurentbfb1b832013-01-07 09:53:42 -08004511 if (exitPending()) {
4512 break;
4513 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004514 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4515 mWriteAckSequence, mDrainSequence);
4516 writeAckSequence = mWriteAckSequence;
4517 mWriteAckSequence &= ~1;
4518 drainSequence = mDrainSequence;
4519 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004520 }
4521 {
Eric Laurent4de95592013-09-26 15:28:21 -07004522 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4523 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004524 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004525 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004526 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004527 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004528 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
4530 }
4531 }
4532 }
4533 return false;
4534}
4535
4536void AudioFlinger::AsyncCallbackThread::exit()
4537{
4538 ALOGV("AsyncCallbackThread::exit");
4539 Mutex::Autolock _l(mLock);
4540 requestExit();
4541 mWaitWorkCV.broadcast();
4542}
4543
Eric Laurent3b4529e2013-09-05 18:09:19 -07004544void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004545{
4546 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004547 // bit 0 is cleared
4548 mWriteAckSequence = sequence << 1;
4549}
4550
4551void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4552{
4553 Mutex::Autolock _l(mLock);
4554 // ignore unexpected callbacks
4555 if (mWriteAckSequence & 2) {
4556 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004557 mWaitWorkCV.signal();
4558 }
4559}
4560
Eric Laurent3b4529e2013-09-05 18:09:19 -07004561void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004562{
4563 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004564 // bit 0 is cleared
4565 mDrainSequence = sequence << 1;
4566}
4567
4568void AudioFlinger::AsyncCallbackThread::resetDraining()
4569{
4570 Mutex::Autolock _l(mLock);
4571 // ignore unexpected callbacks
4572 if (mDrainSequence & 2) {
4573 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004574 mWaitWorkCV.signal();
4575 }
4576}
4577
4578
4579// ----------------------------------------------------------------------------
4580AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4581 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4582 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004583 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004584{
Eric Laurentfd477972013-10-25 18:10:40 -07004585 //FIXME: mStandby should be set to true by ThreadBase constructor
4586 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587}
4588
Eric Laurentbfb1b832013-01-07 09:53:42 -08004589void AudioFlinger::OffloadThread::threadLoop_exit()
4590{
4591 if (mFlushPending || mHwPaused) {
4592 // If a flush is pending or track was paused, just discard buffered data
4593 flushHw_l();
4594 } else {
4595 mMixerStatus = MIXER_DRAIN_ALL;
4596 threadLoop_drain();
4597 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004598 if (mUseAsyncWrite) {
4599 ALOG_ASSERT(mCallbackThread != 0);
4600 mCallbackThread->exit();
4601 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 PlaybackThread::threadLoop_exit();
4603}
4604
4605AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4606 Vector< sp<Track> > *tracksToRemove
4607)
4608{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004609 size_t count = mActiveTracks.size();
4610
4611 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004612 bool doHwPause = false;
4613 bool doHwResume = false;
4614
Eric Laurentede6c3b2013-09-19 14:37:46 -07004615 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4616
Eric Laurentbfb1b832013-01-07 09:53:42 -08004617 // find out which tracks need to be processed
4618 for (size_t i = 0; i < count; i++) {
4619 sp<Track> t = mActiveTracks[i].promote();
4620 // The track died recently
4621 if (t == 0) {
4622 continue;
4623 }
4624 Track* const track = t.get();
4625 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004626 // Only consider last track started for volume and mixer state control.
4627 // In theory an older track could underrun and restart after the new one starts
4628 // but as we only care about the transition phase between two tracks on a
4629 // direct output, it is not a problem to ignore the underrun case.
4630 sp<Track> l = mLatestActiveTrack.promote();
4631 bool last = l.get() == track;
4632
Haynes Mathew George7844f672014-01-15 12:32:55 -08004633 if (track->isInvalid()) {
4634 ALOGW("An invalidated track shouldn't be in active list");
4635 tracksToRemove->add(track);
4636 continue;
4637 }
4638
4639 if (track->mState == TrackBase::IDLE) {
4640 ALOGW("An idle track shouldn't be in active list");
4641 continue;
4642 }
4643
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 if (track->isPausing()) {
4645 track->setPaused();
4646 if (last) {
4647 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004648 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 mHwPaused = true;
4650 }
4651 // If we were part way through writing the mixbuffer to
4652 // the HAL we must save this until we resume
4653 // BUG - this will be wrong if a different track is made active,
4654 // in that case we want to discard the pending data in the
4655 // mixbuffer and tell the client to present it again when the
4656 // track is resumed
4657 mPausedWriteLength = mCurrentWriteLength;
4658 mPausedBytesRemaining = mBytesRemaining;
4659 mBytesRemaining = 0; // stop writing
4660 }
4661 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004662 } else if (track->isFlushPending()) {
4663 track->flushAck();
4664 if (last) {
4665 mFlushPending = true;
4666 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004667 } else if (track->isResumePending()){
4668 track->resumeAck();
4669 if (last) {
4670 if (mPausedBytesRemaining) {
4671 // Need to continue write that was interrupted
4672 mCurrentWriteLength = mPausedWriteLength;
4673 mBytesRemaining = mPausedBytesRemaining;
4674 mPausedBytesRemaining = 0;
4675 }
4676 if (mHwPaused) {
4677 doHwResume = true;
4678 mHwPaused = false;
4679 // threadLoop_mix() will handle the case that we need to
4680 // resume an interrupted write
4681 }
4682 // enable write to audio HAL
4683 sleepTime = 0;
4684
4685 // Do not handle new data in this iteration even if track->framesReady()
4686 mixerStatus = MIXER_TRACKS_ENABLED;
4687 }
4688 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004689 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004690 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004691 if (track->mFillingUpStatus == Track::FS_FILLED) {
4692 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004693 // make sure processVolume_l() will apply new volume even if 0
4694 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695 }
4696
4697 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004698 sp<Track> previousTrack = mPreviousTrack.promote();
4699 if (previousTrack != 0) {
4700 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004701 // Flush any data still being written from last track
4702 mBytesRemaining = 0;
4703 if (mPausedBytesRemaining) {
4704 // Last track was paused so we also need to flush saved
4705 // mixbuffer state and invalidate track so that it will
4706 // re-submit that unwritten data when it is next resumed
4707 mPausedBytesRemaining = 0;
4708 // Invalidate is a bit drastic - would be more efficient
4709 // to have a flag to tell client that some of the
4710 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004711 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004712 }
4713 // flush data already sent to the DSP if changing audio session as audio
4714 // comes from a different source. Also invalidate previous track to force a
4715 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004716 if (previousTrack->sessionId() != track->sessionId()) {
4717 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004718 }
4719 }
4720 }
4721 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004722 // reset retry count
4723 track->mRetryCount = kMaxTrackRetriesOffload;
4724 mActiveTrack = t;
4725 mixerStatus = MIXER_TRACKS_READY;
4726 }
4727 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004728 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729 if (track->isStopping_1()) {
4730 // Hardware buffer can hold a large amount of audio so we must
4731 // wait for all current track's data to drain before we say
4732 // that the track is stopped.
4733 if (mBytesRemaining == 0) {
4734 // Only start draining when all data in mixbuffer
4735 // has been written
4736 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4737 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004738 // do not drain if no data was ever sent to HAL (mStandby == true)
4739 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004740 // do not modify drain sequence if we are already draining. This happens
4741 // when resuming from pause after drain.
4742 if ((mDrainSequence & 1) == 0) {
4743 sleepTime = 0;
4744 standbyTime = systemTime() + standbyDelay;
4745 mixerStatus = MIXER_DRAIN_TRACK;
4746 mDrainSequence += 2;
4747 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748 if (mHwPaused) {
4749 // It is possible to move from PAUSED to STOPPING_1 without
4750 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004751 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752 mHwPaused = false;
4753 }
4754 }
4755 }
4756 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004757 // Drain has completed or we are in standby, signal presentation complete
4758 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004759 track->mState = TrackBase::STOPPED;
4760 size_t audioHALFrames =
4761 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4762 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004763 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004764 track->presentationComplete(framesWritten, audioHALFrames);
4765 track->reset();
4766 tracksToRemove->add(track);
4767 }
4768 } else {
4769 // No buffers for this track. Give it a few chances to
4770 // fill a buffer, then remove it from active list.
4771 if (--(track->mRetryCount) <= 0) {
4772 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4773 track->name());
4774 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004775 // indicate to client process that the track was disabled because of underrun;
4776 // it will then automatically call start() when data is available
4777 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 } else if (last){
4779 mixerStatus = MIXER_TRACKS_ENABLED;
4780 }
4781 }
4782 }
4783 // compute volume for this track
4784 processVolume_l(track, last);
4785 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004786
Eric Laurentea0fade2013-10-04 16:23:48 -07004787 // make sure the pause/flush/resume sequence is executed in the right order.
4788 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4789 // before flush and then resume HW. This can happen in case of pause/flush/resume
4790 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004791 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004792 mOutput->stream->pause(mOutput->stream);
4793 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004794 if (mFlushPending) {
4795 flushHw_l();
4796 mFlushPending = false;
4797 }
Eric Laurentfd477972013-10-25 18:10:40 -07004798 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004799 mOutput->stream->resume(mOutput->stream);
4800 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004801
Eric Laurentbfb1b832013-01-07 09:53:42 -08004802 // remove all the tracks that need to be...
4803 removeTracks_l(*tracksToRemove);
4804
4805 return mixerStatus;
4806}
4807
Eric Laurentbfb1b832013-01-07 09:53:42 -08004808// must be called with thread mutex locked
4809bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4810{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004811 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4812 mWriteAckSequence, mDrainSequence);
4813 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004814 return true;
4815 }
4816 return false;
4817}
4818
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4820{
4821 Mutex::Autolock _l(mLock);
4822 return waitingAsyncCallback_l();
4823}
4824
4825void AudioFlinger::OffloadThread::flushHw_l()
4826{
Eric Laurente659ef42014-09-29 13:06:46 -07004827 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 // Flush anything still waiting in the mixbuffer
4829 mCurrentWriteLength = 0;
4830 mBytesRemaining = 0;
4831 mPausedWriteLength = 0;
4832 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004833
Eric Laurentbfb1b832013-01-07 09:53:42 -08004834 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004835 // discard any pending drain or write ack by incrementing sequence
4836 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4837 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004838 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004839 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4840 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841 }
4842}
4843
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004844void AudioFlinger::OffloadThread::onAddNewTrack_l()
4845{
4846 sp<Track> previousTrack = mPreviousTrack.promote();
4847 sp<Track> latestTrack = mLatestActiveTrack.promote();
4848
4849 if (previousTrack != 0 && latestTrack != 0 &&
4850 (previousTrack->sessionId() != latestTrack->sessionId())) {
4851 mFlushPending = true;
4852 }
4853 PlaybackThread::onAddNewTrack_l();
4854}
4855
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856// ----------------------------------------------------------------------------
4857
Eric Laurent81784c32012-11-19 14:55:58 -08004858AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4859 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4860 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4861 DUPLICATING),
4862 mWaitTimeMs(UINT_MAX)
4863{
4864 addOutputTrack(mainThread);
4865}
4866
4867AudioFlinger::DuplicatingThread::~DuplicatingThread()
4868{
4869 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4870 mOutputTracks[i]->destroy();
4871 }
4872}
4873
4874void AudioFlinger::DuplicatingThread::threadLoop_mix()
4875{
4876 // mix buffers...
4877 if (outputsReady(outputTracks)) {
4878 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4879 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004880 if (mMixerBufferValid) {
4881 memset(mMixerBuffer, 0, mMixerBufferSize);
4882 } else {
4883 memset(mSinkBuffer, 0, mSinkBufferSize);
4884 }
Eric Laurent81784c32012-11-19 14:55:58 -08004885 }
4886 sleepTime = 0;
4887 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004888 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004889 standbyTime = systemTime() + standbyDelay;
4890}
4891
4892void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4893{
4894 if (sleepTime == 0) {
4895 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4896 sleepTime = activeSleepTime;
4897 } else {
4898 sleepTime = idleSleepTime;
4899 }
4900 } else if (mBytesWritten != 0) {
4901 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4902 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004903 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004904 } else {
4905 // flush remaining overflow buffers in output tracks
4906 writeFrames = 0;
4907 }
4908 sleepTime = 0;
4909 }
4910}
4911
Eric Laurentbfb1b832013-01-07 09:53:42 -08004912ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004913{
4914 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004915 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004916 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004917 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004918 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004919}
4920
4921void AudioFlinger::DuplicatingThread::threadLoop_standby()
4922{
4923 // DuplicatingThread implements standby by stopping all tracks
4924 for (size_t i = 0; i < outputTracks.size(); i++) {
4925 outputTracks[i]->stop();
4926 }
4927}
4928
4929void AudioFlinger::DuplicatingThread::saveOutputTracks()
4930{
4931 outputTracks = mOutputTracks;
4932}
4933
4934void AudioFlinger::DuplicatingThread::clearOutputTracks()
4935{
4936 outputTracks.clear();
4937}
4938
4939void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4940{
4941 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004942 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4943 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4944 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4945 const size_t frameCount =
4946 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4947 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4948 // from different OutputTracks and their associated MixerThreads (e.g. one may
4949 // nearly empty and the other may be dropping data).
4950
4951 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004952 this,
4953 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004954 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004955 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004956 frameCount,
4957 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004958 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004959 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004960 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004961 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004962 updateWaitTime_l();
4963 }
4964}
4965
4966void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4967{
4968 Mutex::Autolock _l(mLock);
4969 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4970 if (mOutputTracks[i]->thread() == thread) {
4971 mOutputTracks[i]->destroy();
4972 mOutputTracks.removeAt(i);
4973 updateWaitTime_l();
4974 return;
4975 }
4976 }
4977 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4978}
4979
4980// caller must hold mLock
4981void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4982{
4983 mWaitTimeMs = UINT_MAX;
4984 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4985 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4986 if (strong != 0) {
4987 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4988 if (waitTimeMs < mWaitTimeMs) {
4989 mWaitTimeMs = waitTimeMs;
4990 }
4991 }
4992 }
4993}
4994
4995
4996bool AudioFlinger::DuplicatingThread::outputsReady(
4997 const SortedVector< sp<OutputTrack> > &outputTracks)
4998{
4999 for (size_t i = 0; i < outputTracks.size(); i++) {
5000 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5001 if (thread == 0) {
5002 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5003 outputTracks[i].get());
5004 return false;
5005 }
5006 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5007 // see note at standby() declaration
5008 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5009 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5010 thread.get());
5011 return false;
5012 }
5013 }
5014 return true;
5015}
5016
5017uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5018{
5019 return (mWaitTimeMs * 1000) / 2;
5020}
5021
5022void AudioFlinger::DuplicatingThread::cacheParameters_l()
5023{
5024 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5025 updateWaitTime_l();
5026
5027 MixerThread::cacheParameters_l();
5028}
5029
5030// ----------------------------------------------------------------------------
5031// Record
5032// ----------------------------------------------------------------------------
5033
5034AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5035 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005036 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005037 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005038 audio_devices_t inDevice
5039#ifdef TEE_SINK
5040 , const sp<NBAIO_Sink>& teeSink
5041#endif
5042 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005043 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005044 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005045 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005046 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005047#ifdef TEE_SINK
5048 , mTeeSink(teeSink)
5049#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005050 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5051 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005052 // mFastCapture below
5053 , mFastCaptureFutex(0)
5054 // mInputSource
5055 // mPipeSink
5056 // mPipeSource
5057 , mPipeFramesP2(0)
5058 // mPipeMemory
5059 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005060 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005061{
5062 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005063 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005064
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005065 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005066
5067 // create an NBAIO source for the HAL input stream, and negotiate
5068 mInputSource = new AudioStreamInSource(input->stream);
5069 size_t numCounterOffers = 0;
5070 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5071 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5072 ALOG_ASSERT(index == 0);
5073
5074 // initialize fast capture depending on configuration
5075 bool initFastCapture;
5076 switch (kUseFastCapture) {
5077 case FastCapture_Never:
5078 initFastCapture = false;
5079 break;
5080 case FastCapture_Always:
5081 initFastCapture = true;
5082 break;
5083 case FastCapture_Static:
5084 uint32_t primaryOutputSampleRate;
5085 {
5086 AutoMutex _l(audioFlinger->mHardwareLock);
5087 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5088 }
5089 initFastCapture =
5090 // either capture sample rate is same as (a reasonable) primary output sample rate
5091 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5092 (mSampleRate == primaryOutputSampleRate)) ||
5093 // or primary output sample rate is unknown, and capture sample rate is reasonable
5094 ((primaryOutputSampleRate == 0) &&
5095 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005096 // and the buffer size is < 12 ms
5097 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005098 break;
5099 // case FastCapture_Dynamic:
5100 }
5101
5102 if (initFastCapture) {
5103 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5104 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005105 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005106 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5107 void *pipeBuffer;
5108 const sp<MemoryDealer> roHeap(readOnlyHeap());
5109 sp<IMemory> pipeMemory;
5110 if ((roHeap == 0) ||
5111 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5112 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5113 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5114 goto failed;
5115 }
5116 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5117 memset(pipeBuffer, 0, pipeSize);
5118 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5119 const NBAIO_Format offers[1] = {format};
5120 size_t numCounterOffers = 0;
5121 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5122 ALOG_ASSERT(index == 0);
5123 mPipeSink = pipe;
5124 PipeReader *pipeReader = new PipeReader(*pipe);
5125 numCounterOffers = 0;
5126 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5127 ALOG_ASSERT(index == 0);
5128 mPipeSource = pipeReader;
5129 mPipeFramesP2 = pipeFramesP2;
5130 mPipeMemory = pipeMemory;
5131
5132 // create fast capture
5133 mFastCapture = new FastCapture();
5134 FastCaptureStateQueue *sq = mFastCapture->sq();
5135#ifdef STATE_QUEUE_DUMP
5136 // FIXME
5137#endif
5138 FastCaptureState *state = sq->begin();
5139 state->mCblk = NULL;
5140 state->mInputSource = mInputSource.get();
5141 state->mInputSourceGen++;
5142 state->mPipeSink = pipe;
5143 state->mPipeSinkGen++;
5144 state->mFrameCount = mFrameCount;
5145 state->mCommand = FastCaptureState::COLD_IDLE;
5146 // already done in constructor initialization list
5147 //mFastCaptureFutex = 0;
5148 state->mColdFutexAddr = &mFastCaptureFutex;
5149 state->mColdGen++;
5150 state->mDumpState = &mFastCaptureDumpState;
5151#ifdef TEE_SINK
5152 // FIXME
5153#endif
5154 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5155 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5156 sq->end();
5157 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5158
5159 // start the fast capture
5160 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5161 pid_t tid = mFastCapture->getTid();
5162 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5163 if (err != 0) {
5164 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5165 kPriorityFastCapture, getpid_cached, tid, err);
5166 }
5167
5168#ifdef AUDIO_WATCHDOG
5169 // FIXME
5170#endif
5171
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005172 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005173 }
5174failed: ;
5175
5176 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005177}
5178
5179
5180AudioFlinger::RecordThread::~RecordThread()
5181{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005182 if (mFastCapture != 0) {
5183 FastCaptureStateQueue *sq = mFastCapture->sq();
5184 FastCaptureState *state = sq->begin();
5185 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5186 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5187 if (old == -1) {
5188 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5189 }
5190 }
5191 state->mCommand = FastCaptureState::EXIT;
5192 sq->end();
5193 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5194 mFastCapture->join();
5195 mFastCapture.clear();
5196 }
5197 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005198 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005199 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005200}
5201
5202void AudioFlinger::RecordThread::onFirstRef()
5203{
5204 run(mName, PRIORITY_URGENT_AUDIO);
5205}
5206
Eric Laurent81784c32012-11-19 14:55:58 -08005207bool AudioFlinger::RecordThread::threadLoop()
5208{
Eric Laurent81784c32012-11-19 14:55:58 -08005209 nsecs_t lastWarning = 0;
5210
5211 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005212
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005213reacquire_wakelock:
5214 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005215 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005216 {
5217 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005218 size_t size = mActiveTracks.size();
5219 activeTracksGen = mActiveTracksGen;
5220 if (size > 0) {
5221 // FIXME an arbitrary choice
5222 activeTrack = mActiveTracks[0];
5223 acquireWakeLock_l(activeTrack->uid());
5224 if (size > 1) {
5225 SortedVector<int> tmp;
5226 for (size_t i = 0; i < size; i++) {
5227 tmp.add(mActiveTracks[i]->uid());
5228 }
5229 updateWakeLockUids_l(tmp);
5230 }
5231 } else {
5232 acquireWakeLock_l(-1);
5233 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005234 }
5235
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005236 // used to request a deferred sleep, to be executed later while mutex is unlocked
5237 uint32_t sleepUs = 0;
5238
5239 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005240 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005241 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005242
Glenn Kasten5edadd42013-08-14 16:30:49 -07005243 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005245 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005246 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005247 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005248 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005249 }
5250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005251 // activeTracks accumulates a copy of a subset of mActiveTracks
5252 Vector< sp<RecordTrack> > activeTracks;
5253
Glenn Kasten735f45f2014-08-18 15:51:59 -07005254 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005255 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005256
Glenn Kasten735f45f2014-08-18 15:51:59 -07005257 // reference to a fast track which is about to be removed
5258 sp<RecordTrack> fastTrackToRemove;
5259
Eric Laurent81784c32012-11-19 14:55:58 -08005260 { // scope for mLock
5261 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005262
Eric Laurent021cf962014-05-13 10:18:14 -07005263 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005264
Eric Laurent000a4192014-01-29 15:17:32 -08005265 // check exitPending here because checkForNewParameters_l() and
5266 // checkForNewParameters_l() can temporarily release mLock
5267 if (exitPending()) {
5268 break;
5269 }
5270
Glenn Kasten2b806402013-11-20 16:37:38 -08005271 // if no active track(s), then standby and release wakelock
5272 size_t size = mActiveTracks.size();
5273 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005274 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005275 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005276 releaseWakeLock_l();
5277 ALOGV("RecordThread: loop stopping");
5278 // go to sleep
5279 mWaitWorkCV.wait(mLock);
5280 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005281 goto reacquire_wakelock;
5282 }
5283
Glenn Kasten2b806402013-11-20 16:37:38 -08005284 if (mActiveTracksGen != activeTracksGen) {
5285 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005286 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005287 for (size_t i = 0; i < size; i++) {
5288 tmp.add(mActiveTracks[i]->uid());
5289 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005290 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005292
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005293 bool doBroadcast = false;
5294 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005295
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005296 activeTrack = mActiveTracks[i];
5297 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005298 if (activeTrack->isFastTrack()) {
5299 ALOG_ASSERT(fastTrackToRemove == 0);
5300 fastTrackToRemove = activeTrack;
5301 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005302 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005303 mActiveTracks.remove(activeTrack);
5304 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005305 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005306 continue;
5307 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005308
5309 TrackBase::track_state activeTrackState = activeTrack->mState;
5310 switch (activeTrackState) {
5311
5312 case TrackBase::PAUSING:
5313 mActiveTracks.remove(activeTrack);
5314 mActiveTracksGen++;
5315 doBroadcast = true;
5316 size--;
5317 continue;
5318
5319 case TrackBase::STARTING_1:
5320 sleepUs = 10000;
5321 i++;
5322 continue;
5323
5324 case TrackBase::STARTING_2:
5325 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005326 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005327 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005328 break;
5329
5330 case TrackBase::ACTIVE:
5331 break;
5332
5333 case TrackBase::IDLE:
5334 i++;
5335 continue;
5336
5337 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005338 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005339 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005340
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005341 activeTracks.add(activeTrack);
5342 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005343
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005344 if (activeTrack->isFastTrack()) {
5345 ALOG_ASSERT(!mFastTrackAvail);
5346 ALOG_ASSERT(fastTrack == 0);
5347 fastTrack = activeTrack;
5348 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005349 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005350 if (doBroadcast) {
5351 mStartStopCond.broadcast();
5352 }
5353
5354 // sleep if there are no active tracks to process
5355 if (activeTracks.size() == 0) {
5356 if (sleepUs == 0) {
5357 sleepUs = kRecordThreadSleepUs;
5358 }
5359 continue;
5360 }
5361 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005362
Eric Laurent81784c32012-11-19 14:55:58 -08005363 lockEffectChains_l(effectChains);
5364 }
5365
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005366 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005367
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005368 size_t size = effectChains.size();
5369 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005370 // thread mutex is not locked, but effect chain is locked
5371 effectChains[i]->process_l();
5372 }
5373
Glenn Kasten735f45f2014-08-18 15:51:59 -07005374 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005375 if (mFastCapture != 0) {
5376 FastCaptureStateQueue *sq = mFastCapture->sq();
5377 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005378 bool didModify = false;
5379 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005380 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5381 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5382 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5383 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5384 if (old == -1) {
5385 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5386 }
5387 }
5388 state->mCommand = FastCaptureState::READ_WRITE;
5389#if 0 // FIXME
5390 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005391 FastThreadDumpState::kSamplingNforLowRamDevice :
5392 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005393#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005394 didModify = true;
5395 }
5396 audio_track_cblk_t *cblkOld = state->mCblk;
5397 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5398 if (cblkNew != cblkOld) {
5399 state->mCblk = cblkNew;
5400 // block until acked if removing a fast track
5401 if (cblkOld != NULL) {
5402 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5403 }
5404 didModify = true;
5405 }
5406 sq->end(didModify);
5407 if (didModify) {
5408 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005409#if 0
5410 if (kUseFastCapture == FastCapture_Dynamic) {
5411 mNormalSource = mPipeSource;
5412 }
5413#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005414 }
5415 }
5416
Glenn Kasten735f45f2014-08-18 15:51:59 -07005417 // now run the fast track destructor with thread mutex unlocked
5418 fastTrackToRemove.clear();
5419
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005420 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5421 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5422 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5423 // If destination is non-contiguous, first read past the nominal end of buffer, then
5424 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005425
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005426 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005427 ssize_t framesRead;
5428
5429 // If an NBAIO source is present, use it to read the normal capture's data
5430 if (mPipeSource != 0) {
5431 size_t framesToRead = mBufferSize / mFrameSize;
5432 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5433 framesToRead, AudioBufferProvider::kInvalidPTS);
5434 if (framesRead == 0) {
5435 // since pipe is non-blocking, simulate blocking input
5436 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5437 }
5438 // otherwise use the HAL / AudioStreamIn directly
5439 } else {
5440 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5441 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5442 if (bytesRead < 0) {
5443 framesRead = bytesRead;
5444 } else {
5445 framesRead = bytesRead / mFrameSize;
5446 }
5447 }
5448
5449 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5450 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005451 // Force input into standby so that it tries to recover at next read attempt
5452 inputStandBy();
5453 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005454 }
5455 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005456 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005457 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005459
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 if (mTeeSink != 0) {
5461 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5462 }
5463 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005464 {
5465 size_t part1 = mRsmpInFramesP2 - rear;
5466 if ((size_t) framesRead > part1) {
5467 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5468 (framesRead - part1) * mFrameSize);
5469 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005470 }
5471 rear = mRsmpInRear += framesRead;
5472
5473 size = activeTracks.size();
5474 // loop over each active track
5475 for (size_t i = 0; i < size; i++) {
5476 activeTrack = activeTracks[i];
5477
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005478 // skip fast tracks, as those are handled directly by FastCapture
5479 if (activeTrack->isFastTrack()) {
5480 continue;
5481 }
5482
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005483 enum {
5484 OVERRUN_UNKNOWN,
5485 OVERRUN_TRUE,
5486 OVERRUN_FALSE
5487 } overrun = OVERRUN_UNKNOWN;
5488
5489 // loop over getNextBuffer to handle circular sink
5490 for (;;) {
5491
5492 activeTrack->mSink.frameCount = ~0;
5493 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5494 size_t framesOut = activeTrack->mSink.frameCount;
5495 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5496
5497 int32_t front = activeTrack->mRsmpInFront;
5498 ssize_t filled = rear - front;
5499 size_t framesIn;
5500
5501 if (filled < 0) {
5502 // should not happen, but treat like a massive overrun and re-sync
5503 framesIn = 0;
5504 activeTrack->mRsmpInFront = rear;
5505 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005506 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005507 framesIn = (size_t) filled;
5508 } else {
5509 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005510 framesIn = mRsmpInFrames;
5511 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005512 overrun = OVERRUN_TRUE;
5513 }
5514
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005515 if (framesOut == 0 || framesIn == 0) {
5516 break;
5517 }
5518
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005519 if (activeTrack->mResampler == NULL) {
5520 // no resampling
5521 if (framesIn > framesOut) {
5522 framesIn = framesOut;
5523 } else {
5524 framesOut = framesIn;
5525 }
5526 int8_t *dst = activeTrack->mSink.i8;
5527 while (framesIn > 0) {
5528 front &= mRsmpInFramesP2 - 1;
5529 size_t part1 = mRsmpInFramesP2 - front;
5530 if (part1 > framesIn) {
5531 part1 = framesIn;
5532 }
5533 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005534 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005535 memcpy(dst, src, part1 * mFrameSize);
5536 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005537 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005538 part1);
5539 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005540 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5541 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005542 }
5543 dst += part1 * activeTrack->mFrameSize;
5544 front += part1;
5545 framesIn -= part1;
5546 }
5547 activeTrack->mRsmpInFront += framesOut;
5548
5549 } else {
5550 // resampling
5551 // FIXME framesInNeeded should really be part of resampler API, and should
5552 // depend on the SRC ratio
5553 // to keep mRsmpInBuffer full so resampler always has sufficient input
5554 size_t framesInNeeded;
5555 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005556 // Do not precompute in/out because floating point is not associative
5557 // e.g. a*b/c != a*(b/c).
5558 const double in(mSampleRate);
5559 const double out(activeTrack->mSampleRate);
5560 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005561 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005562 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005563 // Although we theoretically have framesIn in circular buffer, some of those are
5564 // unreleased frames, and thus must be discounted for purpose of budgeting.
5565 size_t unreleased = activeTrack->mRsmpInUnrel;
5566 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005567 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005568 ALOGV("not enough to resample: have %u frames in but need %u in to "
5569 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005570 framesIn, framesInNeeded, framesOut, in / out);
5571 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005572 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5573 if (newFramesOut == 0) {
5574 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005575 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005576 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005577 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005578 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005579 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5580 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5581 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005582 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005583 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005584 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005585 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005586 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005587 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005588 }
5589
5590 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5591 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005592 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005593 delete[] activeTrack->mRsmpOutBuffer;
5594 // resampler always outputs stereo
5595 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5596 activeTrack->mRsmpOutFrameCount = framesOut;
5597 }
5598
5599 // resampler accumulates, but we only have one source track
5600 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5601 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005602 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005603 activeTrack->mResamplerBufferProvider
5604 /*this*/ /* AudioBufferProvider* */);
5605 // ditherAndClamp() works as long as all buffers returned by
5606 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005607 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005608 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005609 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5610 framesOut);
5611 // the resampler always outputs stereo samples:
5612 // do post stereo to mono conversion
5613 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005614 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005615 } else {
5616 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5617 activeTrack->mRsmpOutBuffer, framesOut);
5618 }
5619 // now done with mRsmpOutBuffer
5620
5621 }
5622
5623 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5624 overrun = OVERRUN_FALSE;
5625 }
5626
5627 if (activeTrack->mFramesToDrop == 0) {
5628 if (framesOut > 0) {
5629 activeTrack->mSink.frameCount = framesOut;
5630 activeTrack->releaseBuffer(&activeTrack->mSink);
5631 }
5632 } else {
5633 // FIXME could do a partial drop of framesOut
5634 if (activeTrack->mFramesToDrop > 0) {
5635 activeTrack->mFramesToDrop -= framesOut;
5636 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005637 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 }
5639 } else {
5640 activeTrack->mFramesToDrop += framesOut;
5641 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5642 activeTrack->mSyncStartEvent->isCancelled()) {
5643 ALOGW("Synced record %s, session %d, trigger session %d",
5644 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5645 activeTrack->sessionId(),
5646 (activeTrack->mSyncStartEvent != 0) ?
5647 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005648 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005649 }
5650 }
5651 }
5652
5653 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005654 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005655 }
5656 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005657
5658 switch (overrun) {
5659 case OVERRUN_TRUE:
5660 // client isn't retrieving buffers fast enough
5661 if (!activeTrack->setOverflow()) {
5662 nsecs_t now = systemTime();
5663 // FIXME should lastWarning per track?
5664 if ((now - lastWarning) > kWarningThrottleNs) {
5665 ALOGW("RecordThread: buffer overflow");
5666 lastWarning = now;
5667 }
5668 }
5669 break;
5670 case OVERRUN_FALSE:
5671 activeTrack->clearOverflow();
5672 break;
5673 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005674 break;
5675 }
5676
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005677 }
5678
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005679unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005680 // enable changes in effect chain
5681 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005682 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005683 }
5684
Glenn Kasten93e471f2013-08-19 08:40:07 -07005685 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005686
5687 {
5688 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005689 for (size_t i = 0; i < mTracks.size(); i++) {
5690 sp<RecordTrack> track = mTracks[i];
5691 track->invalidate();
5692 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005693 mActiveTracks.clear();
5694 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005695 mStartStopCond.broadcast();
5696 }
5697
5698 releaseWakeLock();
5699
5700 ALOGV("RecordThread %p exiting", this);
5701 return false;
5702}
5703
Glenn Kasten93e471f2013-08-19 08:40:07 -07005704void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005705{
5706 if (!mStandby) {
5707 inputStandBy();
5708 mStandby = true;
5709 }
5710}
5711
5712void AudioFlinger::RecordThread::inputStandBy()
5713{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005714 // Idle the fast capture if it's currently running
5715 if (mFastCapture != 0) {
5716 FastCaptureStateQueue *sq = mFastCapture->sq();
5717 FastCaptureState *state = sq->begin();
5718 if (!(state->mCommand & FastCaptureState::IDLE)) {
5719 state->mCommand = FastCaptureState::COLD_IDLE;
5720 state->mColdFutexAddr = &mFastCaptureFutex;
5721 state->mColdGen++;
5722 mFastCaptureFutex = 0;
5723 sq->end();
5724 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5725 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5726#if 0
5727 if (kUseFastCapture == FastCapture_Dynamic) {
5728 // FIXME
5729 }
5730#endif
5731#ifdef AUDIO_WATCHDOG
5732 // FIXME
5733#endif
5734 } else {
5735 sq->end(false /*didModify*/);
5736 }
5737 }
Eric Laurent81784c32012-11-19 14:55:58 -08005738 mInput->stream->common.standby(&mInput->stream->common);
5739}
5740
Glenn Kasten05997e22014-03-13 15:08:33 -07005741// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005742sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005743 const sp<AudioFlinger::Client>& client,
5744 uint32_t sampleRate,
5745 audio_format_t format,
5746 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005747 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005748 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005749 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005750 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005751 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005752 pid_t tid,
5753 status_t *status)
5754{
Glenn Kasten74935e42013-12-19 08:56:45 -08005755 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005756 sp<RecordTrack> track;
5757 status_t lStatus;
5758
Glenn Kasten90e58b12013-07-31 16:16:02 -07005759 // client expresses a preference for FAST, but we get the final say
5760 if (*flags & IAudioFlinger::TRACK_FAST) {
5761 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005762 // use case: callback handler
5763 (tid != -1) &&
5764 // frame count is not specified, or is exactly the pipe depth
5765 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005766 // PCM data
5767 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005768 // native format
5769 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005770 // native channel mask
5771 (channelMask == mChannelMask) &&
5772 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005773 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005774 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 hasFastCapture() &&
5776 // there are sufficient fast track slots available
5777 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005778 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005779 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005780 frameCount, mFrameCount);
5781 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005782 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5783 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005784 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005785 frameCount, mFrameCount, mPipeFramesP2,
5786 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5787 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005788 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005789 }
5790 }
5791
5792 // compute track buffer size in frames, and suggest the notification frame count
5793 if (*flags & IAudioFlinger::TRACK_FAST) {
5794 // fast track: frame count is exactly the pipe depth
5795 frameCount = mPipeFramesP2;
5796 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5797 *notificationFrames = mFrameCount;
5798 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005799 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5800 // or 20 ms if there is a fast capture
5801 // TODO This could be a roundupRatio inline, and const
5802 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5803 * sampleRate + mSampleRate - 1) / mSampleRate;
5804 // minimum number of notification periods is at least kMinNotifications,
5805 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5806 static const size_t kMinNotifications = 3;
5807 static const uint32_t kMinMs = 30;
5808 // TODO This could be a roundupRatio inline
5809 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5810 // TODO This could be a roundupRatio inline
5811 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5812 maxNotificationFrames;
5813 const size_t minFrameCount = maxNotificationFrames *
5814 max(kMinNotifications, minNotificationsByMs);
5815 frameCount = max(frameCount, minFrameCount);
5816 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5817 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005818 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005819 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005820 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005821
Glenn Kasten15e57982013-09-24 11:52:37 -07005822 lStatus = initCheck();
5823 if (lStatus != NO_ERROR) {
5824 ALOGE("createRecordTrack_l() audio driver not initialized");
5825 goto Exit;
5826 }
Eric Laurent81784c32012-11-19 14:55:58 -08005827
5828 { // scope for mLock
5829 Mutex::Autolock _l(mLock);
5830
5831 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005832 format, channelMask, frameCount, NULL, sessionId, uid,
5833 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005834
Glenn Kasten03003332013-08-06 15:40:54 -07005835 lStatus = track->initCheck();
5836 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005837 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005838 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005839 goto Exit;
5840 }
5841 mTracks.add(track);
5842
5843 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5844 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5845 mAudioFlinger->btNrecIsOff();
5846 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5847 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005848
5849 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5850 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5851 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5852 // so ask activity manager to do this on our behalf
5853 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5854 }
Eric Laurent81784c32012-11-19 14:55:58 -08005855 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005856
Eric Laurent81784c32012-11-19 14:55:58 -08005857 lStatus = NO_ERROR;
5858
5859Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005860 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005861 return track;
5862}
5863
5864status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5865 AudioSystem::sync_event_t event,
5866 int triggerSession)
5867{
5868 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5869 sp<ThreadBase> strongMe = this;
5870 status_t status = NO_ERROR;
5871
5872 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005873 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005874 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005875 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005876 triggerSession,
5877 recordTrack->sessionId(),
5878 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005880 // Sync event can be cancelled by the trigger session if the track is not in a
5881 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005883 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005884 } else {
5885 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005886 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005887 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
5889 }
5890
5891 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005892 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005893 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005894 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5895 if (recordTrack->mState == TrackBase::PAUSING) {
5896 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005897 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005898 } else {
5899 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005900 }
5901 return status;
5902 }
5903
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005904 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5905 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5906 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005908 mActiveTracks.add(recordTrack);
5909 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005910 status_t status = NO_ERROR;
5911 if (recordTrack->isExternalTrack()) {
5912 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005913 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005914 mLock.lock();
5915 // FIXME should verify that recordTrack is still in mActiveTracks
5916 if (status != NO_ERROR) {
5917 mActiveTracks.remove(recordTrack);
5918 mActiveTracksGen++;
5919 recordTrack->clearSyncStartEvent();
5920 ALOGV("RecordThread::start error %d", status);
5921 return status;
5922 }
Eric Laurent81784c32012-11-19 14:55:58 -08005923 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005924 // Catch up with current buffer indices if thread is already running.
5925 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5926 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5927 // see previously buffered data before it called start(), but with greater risk of overrun.
5928
5929 recordTrack->mRsmpInFront = mRsmpInRear;
5930 recordTrack->mRsmpInUnrel = 0;
5931 // FIXME why reset?
5932 if (recordTrack->mResampler != NULL) {
5933 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005935 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005936 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005937 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005938 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005939 ALOGV("Record failed to start");
5940 status = BAD_VALUE;
5941 goto startError;
5942 }
Eric Laurent81784c32012-11-19 14:55:58 -08005943 return status;
5944 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005945
Eric Laurent81784c32012-11-19 14:55:58 -08005946startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005947 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005948 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005949 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005950 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005951 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005952 return status;
5953}
5954
Eric Laurent81784c32012-11-19 14:55:58 -08005955void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5956{
5957 sp<SyncEvent> strongEvent = event.promote();
5958
5959 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005960 sp<RefBase> ptr = strongEvent->cookie().promote();
5961 if (ptr != 0) {
5962 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5963 recordTrack->handleSyncStartEvent(strongEvent);
5964 }
Eric Laurent81784c32012-11-19 14:55:58 -08005965 }
5966}
5967
Glenn Kastena8356f62013-07-25 14:37:52 -07005968bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005969 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005970 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005971 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005972 return false;
5973 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005974 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005975 recordTrack->mState = TrackBase::PAUSING;
5976 // do not wait for mStartStopCond if exiting
5977 if (exitPending()) {
5978 return true;
5979 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005980 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005981 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005982 // if we have been restarted, recordTrack is in mActiveTracks here
5983 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005984 ALOGV("Record stopped OK");
5985 return true;
5986 }
5987 return false;
5988}
5989
Glenn Kasten0f11b512014-01-31 16:18:54 -08005990bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005991{
5992 return false;
5993}
5994
Glenn Kasten0f11b512014-01-31 16:18:54 -08005995status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005996{
5997#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5998 if (!isValidSyncEvent(event)) {
5999 return BAD_VALUE;
6000 }
6001
6002 int eventSession = event->triggerSession();
6003 status_t ret = NAME_NOT_FOUND;
6004
6005 Mutex::Autolock _l(mLock);
6006
6007 for (size_t i = 0; i < mTracks.size(); i++) {
6008 sp<RecordTrack> track = mTracks[i];
6009 if (eventSession == track->sessionId()) {
6010 (void) track->setSyncEvent(event);
6011 ret = NO_ERROR;
6012 }
6013 }
6014 return ret;
6015#else
6016 return BAD_VALUE;
6017#endif
6018}
6019
6020// destroyTrack_l() must be called with ThreadBase::mLock held
6021void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6022{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006023 track->terminate();
6024 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006025 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006026 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006027 removeTrack_l(track);
6028 }
6029}
6030
6031void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6032{
6033 mTracks.remove(track);
6034 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006035 if (track->isFastTrack()) {
6036 ALOG_ASSERT(!mFastTrackAvail);
6037 mFastTrackAvail = true;
6038 }
Eric Laurent81784c32012-11-19 14:55:58 -08006039}
6040
6041void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6042{
6043 dumpInternals(fd, args);
6044 dumpTracks(fd, args);
6045 dumpEffectChains(fd, args);
6046}
6047
6048void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6049{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006050 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006051
Glenn Kasten2b806402013-11-20 16:37:38 -08006052 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006053 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006054 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006055 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006056 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006057 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006058 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006059
Eric Laurent81784c32012-11-19 14:55:58 -08006060 dumpBase(fd, args);
6061}
6062
Glenn Kasten0f11b512014-01-31 16:18:54 -08006063void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006064{
6065 const size_t SIZE = 256;
6066 char buffer[SIZE];
6067 String8 result;
6068
Marco Nelissenb2208842014-02-07 14:00:50 -08006069 size_t numtracks = mTracks.size();
6070 size_t numactive = mActiveTracks.size();
6071 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006072 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006073 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006074 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006075 RecordTrack::appendDumpHeader(result);
6076 for (size_t i = 0; i < numtracks ; ++i) {
6077 sp<RecordTrack> track = mTracks[i];
6078 if (track != 0) {
6079 bool active = mActiveTracks.indexOf(track) >= 0;
6080 if (active) {
6081 numactiveseen++;
6082 }
6083 track->dump(buffer, SIZE, active);
6084 result.append(buffer);
6085 }
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006087 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006088 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
6090
Marco Nelissenb2208842014-02-07 14:00:50 -08006091 if (numactiveseen != numactive) {
6092 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6093 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006094 result.append(buffer);
6095 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006096 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006097 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006098 if (mTracks.indexOf(track) < 0) {
6099 track->dump(buffer, SIZE, true);
6100 result.append(buffer);
6101 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006102 }
Eric Laurent81784c32012-11-19 14:55:58 -08006103
6104 }
6105 write(fd, result.string(), result.size());
6106}
6107
6108// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006109status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6110 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006111{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006112 RecordTrack *activeTrack = mRecordTrack;
6113 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6114 if (threadBase == 0) {
6115 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006116 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 return NOT_ENOUGH_DATA;
6118 }
6119 RecordThread *recordThread = (RecordThread *) threadBase.get();
6120 int32_t rear = recordThread->mRsmpInRear;
6121 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006122 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 // FIXME should not be P2 (don't want to increase latency)
6124 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006125 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006126 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 front &= recordThread->mRsmpInFramesP2 - 1;
6128 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006129 if (part1 > (size_t) filled) {
6130 part1 = filled;
6131 }
6132 size_t ask = buffer->frameCount;
6133 ALOG_ASSERT(ask > 0);
6134 if (part1 > ask) {
6135 part1 = ask;
6136 }
6137 if (part1 == 0) {
6138 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006139 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006140 buffer->raw = NULL;
6141 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006142 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006143 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006144 }
6145
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006146 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006147 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006148 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006149 return NO_ERROR;
6150}
6151
6152// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006153void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6154 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006155{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006157 size_t stepCount = buffer->frameCount;
6158 if (stepCount == 0) {
6159 return;
6160 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6162 activeTrack->mRsmpInUnrel -= stepCount;
6163 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006164 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006165 buffer->frameCount = 0;
6166}
6167
Eric Laurent10351942014-05-08 18:49:52 -07006168bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6169 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006170{
6171 bool reconfig = false;
6172
Eric Laurent10351942014-05-08 18:49:52 -07006173 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006174
Eric Laurent10351942014-05-08 18:49:52 -07006175 audio_format_t reqFormat = mFormat;
6176 uint32_t samplingRate = mSampleRate;
6177 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6178
6179 AudioParameter param = AudioParameter(keyValuePair);
6180 int value;
6181 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6182 // channel count change can be requested. Do we mandate the first client defines the
6183 // HAL sampling rate and channel count or do we allow changes on the fly?
6184 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6185 samplingRate = value;
6186 reconfig = true;
6187 }
6188 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6189 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6190 status = BAD_VALUE;
6191 } else {
6192 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006193 reconfig = true;
6194 }
Eric Laurent10351942014-05-08 18:49:52 -07006195 }
6196 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6197 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6198 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6199 status = BAD_VALUE;
6200 } else {
6201 channelMask = mask;
6202 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006203 }
Eric Laurent10351942014-05-08 18:49:52 -07006204 }
6205 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6206 // do not accept frame count changes if tracks are open as the track buffer
6207 // size depends on frame count and correct behavior would not be guaranteed
6208 // if frame count is changed after track creation
6209 if (mActiveTracks.size() > 0) {
6210 status = INVALID_OPERATION;
6211 } else {
6212 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006213 }
Eric Laurent10351942014-05-08 18:49:52 -07006214 }
6215 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6216 // forward device change to effects that have requested to be
6217 // aware of attached audio device.
6218 for (size_t i = 0; i < mEffectChains.size(); i++) {
6219 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006220 }
Eric Laurent81784c32012-11-19 14:55:58 -08006221
Eric Laurent10351942014-05-08 18:49:52 -07006222 // store input device and output device but do not forward output device to audio HAL.
6223 // Note that status is ignored by the caller for output device
6224 // (see AudioFlinger::setParameters()
6225 if (audio_is_output_devices(value)) {
6226 mOutDevice = value;
6227 status = BAD_VALUE;
6228 } else {
6229 mInDevice = value;
6230 // disable AEC and NS if the device is a BT SCO headset supporting those
6231 // pre processings
6232 if (mTracks.size() > 0) {
6233 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6234 mAudioFlinger->btNrecIsOff();
6235 for (size_t i = 0; i < mTracks.size(); i++) {
6236 sp<RecordTrack> track = mTracks[i];
6237 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6238 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006239 }
6240 }
6241 }
Eric Laurent10351942014-05-08 18:49:52 -07006242 }
6243 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6244 mAudioSource != (audio_source_t)value) {
6245 // forward device change to effects that have requested to be
6246 // aware of attached audio device.
6247 for (size_t i = 0; i < mEffectChains.size(); i++) {
6248 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006249 }
Eric Laurent10351942014-05-08 18:49:52 -07006250 mAudioSource = (audio_source_t)value;
6251 }
Glenn Kastene198c362013-08-13 09:13:36 -07006252
Eric Laurent10351942014-05-08 18:49:52 -07006253 if (status == NO_ERROR) {
6254 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6255 keyValuePair.string());
6256 if (status == INVALID_OPERATION) {
6257 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006258 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6259 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006260 }
6261 if (reconfig) {
6262 if (status == BAD_VALUE &&
6263 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6264 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6265 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6266 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006267 audio_channel_count_from_in_mask(
6268 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006269 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6270 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6271 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
Eric Laurent10351942014-05-08 18:49:52 -07006273 if (status == NO_ERROR) {
6274 readInputParameters_l();
6275 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006276 }
6277 }
Eric Laurent81784c32012-11-19 14:55:58 -08006278 }
Eric Laurent10351942014-05-08 18:49:52 -07006279
Eric Laurent81784c32012-11-19 14:55:58 -08006280 return reconfig;
6281}
6282
6283String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6284{
Eric Laurent81784c32012-11-19 14:55:58 -08006285 Mutex::Autolock _l(mLock);
6286 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006287 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006288 }
6289
Glenn Kastend8ea6992013-07-16 14:17:15 -07006290 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6291 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006292 free(s);
6293 return out_s8;
6294}
6295
Eric Laurent021cf962014-05-13 10:18:14 -07006296void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006297 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006298 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006299
6300 switch (event) {
6301 case AudioSystem::INPUT_OPENED:
6302 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006303 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006304 desc.samplingRate = mSampleRate;
6305 desc.format = mFormat;
6306 desc.frameCount = mFrameCount;
6307 desc.latency = 0;
6308 param2 = &desc;
6309 break;
6310
6311 case AudioSystem::INPUT_CLOSED:
6312 default:
6313 break;
6314 }
Eric Laurent021cf962014-05-13 10:18:14 -07006315 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006316}
6317
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006318void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006319{
Eric Laurent81784c32012-11-19 14:55:58 -08006320 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6321 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006322 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006323 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6324 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006325 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006326 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006327 }
Eric Laurent665470b2014-07-03 16:37:08 -07006328 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006329 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6330 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006332 // 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 -07006333 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006334 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 // A larger value should allow more old data to be read after a track calls start(),
6336 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006337 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006338 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006340
6341 // TODO optimize audio capture buffer sizes ...
6342 // Here we calculate the size of the sliding buffer used as a source
6343 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6344 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6345 // be better to have it derived from the pipe depth in the long term.
6346 // The current value is higher than necessary. However it should not add to latency.
6347
Glenn Kasten85948432013-08-19 12:09:05 -07006348 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6349 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006350
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006351 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6352 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006353}
6354
Glenn Kasten5f972c02014-01-13 09:59:31 -08006355uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006356{
6357 Mutex::Autolock _l(mLock);
6358 if (initCheck() != NO_ERROR) {
6359 return 0;
6360 }
6361
6362 return mInput->stream->get_input_frames_lost(mInput->stream);
6363}
6364
6365uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6366{
6367 Mutex::Autolock _l(mLock);
6368 uint32_t result = 0;
6369 if (getEffectChain_l(sessionId) != 0) {
6370 result = EFFECT_SESSION;
6371 }
6372
6373 for (size_t i = 0; i < mTracks.size(); ++i) {
6374 if (sessionId == mTracks[i]->sessionId()) {
6375 result |= TRACK_SESSION;
6376 break;
6377 }
6378 }
6379
6380 return result;
6381}
6382
6383KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6384{
6385 KeyedVector<int, bool> ids;
6386 Mutex::Autolock _l(mLock);
6387 for (size_t j = 0; j < mTracks.size(); ++j) {
6388 sp<RecordThread::RecordTrack> track = mTracks[j];
6389 int sessionId = track->sessionId();
6390 if (ids.indexOfKey(sessionId) < 0) {
6391 ids.add(sessionId, true);
6392 }
6393 }
6394 return ids;
6395}
6396
6397AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6398{
6399 Mutex::Autolock _l(mLock);
6400 AudioStreamIn *input = mInput;
6401 mInput = NULL;
6402 return input;
6403}
6404
6405// this method must always be called either with ThreadBase mLock held or inside the thread loop
6406audio_stream_t* AudioFlinger::RecordThread::stream() const
6407{
6408 if (mInput == NULL) {
6409 return NULL;
6410 }
6411 return &mInput->stream->common;
6412}
6413
6414status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6415{
6416 // only one chain per input thread
6417 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006418 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006419 return INVALID_OPERATION;
6420 }
6421 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006422 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006423 chain->setInBuffer(NULL);
6424 chain->setOutBuffer(NULL);
6425
6426 checkSuspendOnAddEffectChain_l(chain);
6427
Eric Laurent1b928682014-10-02 19:41:47 -07006428 // make sure enabled pre processing effects state is communicated to the HAL as we
6429 // just moved them to a new input stream.
6430 chain->syncHalEffectsState();
6431
Eric Laurent81784c32012-11-19 14:55:58 -08006432 mEffectChains.add(chain);
6433
6434 return NO_ERROR;
6435}
6436
6437size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6438{
6439 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6440 ALOGW_IF(mEffectChains.size() != 1,
6441 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6442 chain.get(), mEffectChains.size(), this);
6443 if (mEffectChains.size() == 1) {
6444 mEffectChains.removeAt(0);
6445 }
6446 return 0;
6447}
6448
Eric Laurent1c333e22014-05-20 10:48:17 -07006449status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6450 audio_patch_handle_t *handle)
6451{
6452 status_t status = NO_ERROR;
6453 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6454 // store new device and send to effects
6455 mInDevice = patch->sources[0].ext.device.type;
6456 for (size_t i = 0; i < mEffectChains.size(); i++) {
6457 mEffectChains[i]->setDevice_l(mInDevice);
6458 }
6459
6460 // disable AEC and NS if the device is a BT SCO headset supporting those
6461 // pre processings
6462 if (mTracks.size() > 0) {
6463 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6464 mAudioFlinger->btNrecIsOff();
6465 for (size_t i = 0; i < mTracks.size(); i++) {
6466 sp<RecordTrack> track = mTracks[i];
6467 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6468 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6469 }
6470 }
6471
6472 // store new source and send to effects
6473 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6474 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6475 for (size_t i = 0; i < mEffectChains.size(); i++) {
6476 mEffectChains[i]->setAudioSource_l(mAudioSource);
6477 }
6478 }
6479
6480 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6481 status = hwDevice->create_audio_patch(hwDevice,
6482 patch->num_sources,
6483 patch->sources,
6484 patch->num_sinks,
6485 patch->sinks,
6486 handle);
6487 } else {
6488 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6489 }
6490 return status;
6491}
6492
6493status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6494{
6495 status_t status = NO_ERROR;
6496 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6497 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6498 status = hwDevice->release_audio_patch(hwDevice, handle);
6499 } else {
6500 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6501 }
6502 return status;
6503}
6504
Eric Laurent83b88082014-06-20 18:31:16 -07006505void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6506{
6507 Mutex::Autolock _l(mLock);
6508 mTracks.add(record);
6509}
6510
6511void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6512{
6513 Mutex::Autolock _l(mLock);
6514 destroyTrack_l(record);
6515}
6516
6517void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6518{
6519 ThreadBase::getAudioPortConfig(config);
6520 config->role = AUDIO_PORT_ROLE_SINK;
6521 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6522 config->ext.mix.usecase.source = mAudioSource;
6523}
Eric Laurent1c333e22014-05-20 10:48:17 -07006524
Glenn Kasten63238ef2015-03-02 15:50:29 -08006525} // namespace android