blob: 8fcc09c34d600aa74a37cea8f96e147e8fa26a68 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070029#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070042#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043#include <media/nbaio/AudioStreamOutSink.h>
44#include <media/nbaio/MonoPipe.h>
45#include <media/nbaio/MonoPipeReader.h>
46#include <media/nbaio/Pipe.h>
47#include <media/nbaio/PipeReader.h>
48#include <media/nbaio/SourceAudioBufferProvider.h>
49
50#include <powermanager/PowerManager.h>
51
52#include <common_time/cc_helper.h>
53#include <common_time/local_clock.h>
54
55#include "AudioFlinger.h"
56#include "AudioMixer.h"
57#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "ServiceUtilities.h"
60#include "SchedulingPolicyService.h"
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef ADD_BATTERY_DATA
63#include <media/IMediaPlayerService.h>
64#include <media/IMediaDeathNotifier.h>
65#endif
66
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
71
72// ----------------------------------------------------------------------------
73
74// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
86
Glenn Kasten49d00ad2014-07-21 11:22:03 -070087#define max(a, b) ((a) > (b) ? (a) : (b))
88
Eric Laurent81784c32012-11-19 14:55:58 -080089namespace android {
90
91// retry counts for buffer fill timeout
92// 50 * ~20msecs = 1 second
93static const int8_t kMaxTrackRetries = 50;
94static const int8_t kMaxTrackStartupRetries = 50;
95// allow less retry attempts on direct output thread.
96// direct outputs can be a scarce resource in audio hardware and should
97// be released as quickly as possible.
98static const int8_t kMaxTrackRetriesDirect = 2;
99
100// don't warn about blocked writes or record buffer overflows more often than this
101static const nsecs_t kWarningThrottleNs = seconds(5);
102
103// RecordThread loop sleep time upon application overrun or audio HAL read error
104static const int kRecordThreadSleepUs = 5000;
105
Eric Laurent10351942014-05-08 18:49:52 -0700106// maximum time to wait in sendConfigEvent_l() for a status to be received
107static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109// minimum sleep time for the mixer thread loop when tracks are active but in underrun
110static const uint32_t kMinThreadSleepTimeUs = 5000;
111// maximum divider applied to the active sleep time in the mixer thread loop
112static const uint32_t kMaxThreadSleepTimeShift = 2;
113
Andy Hung09a50072014-02-27 14:30:47 -0800114// minimum normal sink buffer size, expressed in milliseconds rather than frames
115static const uint32_t kMinNormalSinkBufferSizeMs = 20;
116// maximum normal sink buffer size
117static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800118
Eric Laurent972a1732013-09-04 09:42:59 -0700119// Offloaded output thread standby delay: allows track transition without going to standby
120static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122// Whether to use fast mixer
123static const enum {
124 FastMixer_Never, // never initialize or use: for debugging only
125 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
126 // normal mixer multiplier is 1
127 FastMixer_Static, // initialize if needed, then use all the time if initialized,
128 // multiplier is calculated based on min & max normal mixer buffer size
129 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 // FIXME for FastMixer_Dynamic:
132 // Supporting this option will require fixing HALs that can't handle large writes.
133 // For example, one HAL implementation returns an error from a large write,
134 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
135 // We could either fix the HAL implementations, or provide a wrapper that breaks
136 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
137} kUseFastMixer = FastMixer_Static;
138
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139// Whether to use fast capture
140static const enum {
141 FastCapture_Never, // never initialize or use: for debugging only
142 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
143 FastCapture_Static, // initialize if needed, then use all the time if initialized
144} kUseFastCapture = FastCapture_Static;
145
Eric Laurent81784c32012-11-19 14:55:58 -0800146// Priorities for requestPriority
147static const int kPriorityAudioApp = 2;
148static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700149static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
152// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800153// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
154// So for now we just assume that client is double-buffered for fast tracks.
155// FIXME It would be better for client to tell AudioFlinger the value of N,
156// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800157// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700158
159// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800160static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
Glenn Kasten03490092014-05-27 12:30:54 -0700162// The minimum and maximum allowed values
163static const int kFastTrackMultiplierMin = 1;
164static const int kFastTrackMultiplierMax = 2;
165
166// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
167static int sFastTrackMultiplier = kFastTrackMultiplier;
168
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700169// See Thread::readOnlyHeap().
170// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
171// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
172// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700173static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700174
Eric Laurent81784c32012-11-19 14:55:58 -0800175// ----------------------------------------------------------------------------
176
Glenn Kasten03490092014-05-27 12:30:54 -0700177static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
178
179static void sFastTrackMultiplierInit()
180{
181 char value[PROPERTY_VALUE_MAX];
182 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
183 char *endptr;
184 unsigned long ul = strtoul(value, &endptr, 0);
185 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
186 sFastTrackMultiplier = (int) ul;
187 }
188 }
189}
190
191// ----------------------------------------------------------------------------
192
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef ADD_BATTERY_DATA
194// To collect the amplifier usage
195static void addBatteryData(uint32_t params) {
196 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
197 if (service == NULL) {
198 // it already logged
199 return;
200 }
201
202 service->addBatteryData(params);
203}
204#endif
205
206
207// ----------------------------------------------------------------------------
208// CPU Stats
209// ----------------------------------------------------------------------------
210
211class CpuStats {
212public:
213 CpuStats();
214 void sample(const String8 &title);
215#ifdef DEBUG_CPU_USAGE
216private:
217 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
218 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
219
220 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
221
222 int mCpuNum; // thread's current CPU number
223 int mCpukHz; // frequency of thread's current CPU in kHz
224#endif
225};
226
227CpuStats::CpuStats()
228#ifdef DEBUG_CPU_USAGE
229 : mCpuNum(-1), mCpukHz(-1)
230#endif
231{
232}
233
Glenn Kasten0f11b512014-01-31 16:18:54 -0800234void CpuStats::sample(const String8 &title
235#ifndef DEBUG_CPU_USAGE
236 __unused
237#endif
238 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800239#ifdef DEBUG_CPU_USAGE
240 // get current thread's delta CPU time in wall clock ns
241 double wcNs;
242 bool valid = mCpuUsage.sampleAndEnable(wcNs);
243
244 // record sample for wall clock statistics
245 if (valid) {
246 mWcStats.sample(wcNs);
247 }
248
249 // get the current CPU number
250 int cpuNum = sched_getcpu();
251
252 // get the current CPU frequency in kHz
253 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
254
255 // check if either CPU number or frequency changed
256 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
257 mCpuNum = cpuNum;
258 mCpukHz = cpukHz;
259 // ignore sample for purposes of cycles
260 valid = false;
261 }
262
263 // if no change in CPU number or frequency, then record sample for cycle statistics
264 if (valid && mCpukHz > 0) {
265 double cycles = wcNs * cpukHz * 0.000001;
266 mHzStats.sample(cycles);
267 }
268
269 unsigned n = mWcStats.n();
270 // mCpuUsage.elapsed() is expensive, so don't call it every loop
271 if ((n & 127) == 1) {
272 long long elapsed = mCpuUsage.elapsed();
273 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
274 double perLoop = elapsed / (double) n;
275 double perLoop100 = perLoop * 0.01;
276 double perLoop1k = perLoop * 0.001;
277 double mean = mWcStats.mean();
278 double stddev = mWcStats.stddev();
279 double minimum = mWcStats.minimum();
280 double maximum = mWcStats.maximum();
281 double meanCycles = mHzStats.mean();
282 double stddevCycles = mHzStats.stddev();
283 double minCycles = mHzStats.minimum();
284 double maxCycles = mHzStats.maximum();
285 mCpuUsage.resetElapsed();
286 mWcStats.reset();
287 mHzStats.reset();
288 ALOGD("CPU usage for %s over past %.1f secs\n"
289 " (%u mixer loops at %.1f mean ms per loop):\n"
290 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
291 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
292 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
293 title.string(),
294 elapsed * .000000001, n, perLoop * .000001,
295 mean * .001,
296 stddev * .001,
297 minimum * .001,
298 maximum * .001,
299 mean / perLoop100,
300 stddev / perLoop100,
301 minimum / perLoop100,
302 maximum / perLoop100,
303 meanCycles / perLoop1k,
304 stddevCycles / perLoop1k,
305 minCycles / perLoop1k,
306 maxCycles / perLoop1k);
307
308 }
309 }
310#endif
311};
312
313// ----------------------------------------------------------------------------
314// ThreadBase
315// ----------------------------------------------------------------------------
316
Glenn Kasten97b7b752014-09-28 13:04:24 -0700317// static
318const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
319{
320 switch (type) {
321 case MIXER:
322 return "MIXER";
323 case DIRECT:
324 return "DIRECT";
325 case DUPLICATING:
326 return "DUPLICATING";
327 case RECORD:
328 return "RECORD";
329 case OFFLOAD:
330 return "OFFLOAD";
331 default:
332 return "unknown";
333 }
334}
335
336static String8 outputFlagsToString(audio_output_flags_t flags)
337{
338 static const struct mapping {
339 audio_output_flags_t mFlag;
340 const char * mString;
341 } mappings[] = {
342 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
343 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
344 AUDIO_OUTPUT_FLAG_FAST, "FAST",
345 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
346 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAAD",
347 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
348 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
349 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
350 };
351 String8 result;
352 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
353 const mapping *entry;
354 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
355 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
356 if (flags & entry->mFlag) {
357 if (!result.isEmpty()) {
358 result.append("|");
359 }
360 result.append(entry->mString);
361 }
362 }
363 if (flags & ~allFlags) {
364 if (!result.isEmpty()) {
365 result.append("|");
366 }
367 result.appendFormat("0x%X", flags & ~allFlags);
368 }
369 if (result.isEmpty()) {
370 result.append(entry->mString);
371 }
372 return result;
373}
374
Eric Laurent81784c32012-11-19 14:55:58 -0800375AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
376 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
377 : Thread(false /*canCallJava*/),
378 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700379 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700380 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800381 // are set by PlaybackThread::readOutputParameters_l() or
382 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700383 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800384 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
385 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
386 // mName will be set by concrete (non-virtual) subclass
387 mDeathRecipient(new PMDeathRecipient(this))
388{
389}
390
391AudioFlinger::ThreadBase::~ThreadBase()
392{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700393 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700394 mConfigEvents.clear();
395
Eric Laurent81784c32012-11-19 14:55:58 -0800396 // do not lock the mutex in destructor
397 releaseWakeLock_l();
398 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800399 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800400 binder->unlinkToDeath(mDeathRecipient);
401 }
402}
403
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700404status_t AudioFlinger::ThreadBase::readyToRun()
405{
406 status_t status = initCheck();
407 if (status == NO_ERROR) {
408 ALOGI("AudioFlinger's thread %p ready to run", this);
409 } else {
410 ALOGE("No working audio driver found.");
411 }
412 return status;
413}
414
Eric Laurent81784c32012-11-19 14:55:58 -0800415void AudioFlinger::ThreadBase::exit()
416{
417 ALOGV("ThreadBase::exit");
418 // do any cleanup required for exit to succeed
419 preExit();
420 {
421 // This lock prevents the following race in thread (uniprocessor for illustration):
422 // if (!exitPending()) {
423 // // context switch from here to exit()
424 // // exit() calls requestExit(), what exitPending() observes
425 // // exit() calls signal(), which is dropped since no waiters
426 // // context switch back from exit() to here
427 // mWaitWorkCV.wait(...);
428 // // now thread is hung
429 // }
430 AutoMutex lock(mLock);
431 requestExit();
432 mWaitWorkCV.broadcast();
433 }
434 // When Thread::requestExitAndWait is made virtual and this method is renamed to
435 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
436 requestExitAndWait();
437}
438
439status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
440{
441 status_t status;
442
443 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
444 Mutex::Autolock _l(mLock);
445
Eric Laurent10351942014-05-08 18:49:52 -0700446 return sendSetParameterConfigEvent_l(keyValuePairs);
447}
448
449// sendConfigEvent_l() must be called with ThreadBase::mLock held
450// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
451status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
452{
453 status_t status = NO_ERROR;
454
455 mConfigEvents.add(event);
456 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800457 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700458 mLock.unlock();
459 {
460 Mutex::Autolock _l(event->mLock);
461 while (event->mWaitStatus) {
462 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
463 event->mStatus = TIMED_OUT;
464 event->mWaitStatus = false;
465 }
466 }
467 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800468 }
Eric Laurent10351942014-05-08 18:49:52 -0700469 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800470 return status;
471}
472
473void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
474{
475 Mutex::Autolock _l(mLock);
476 sendIoConfigEvent_l(event, param);
477}
478
479// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
480void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
481{
Eric Laurent10351942014-05-08 18:49:52 -0700482 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
483 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800484}
485
486// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
487void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
488{
Eric Laurent10351942014-05-08 18:49:52 -0700489 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
490 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800491}
492
Eric Laurent10351942014-05-08 18:49:52 -0700493// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
494status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800495{
Eric Laurent10351942014-05-08 18:49:52 -0700496 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
497 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700498}
499
Eric Laurent1c333e22014-05-20 10:48:17 -0700500status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
501 const struct audio_patch *patch,
502 audio_patch_handle_t *handle)
503{
504 Mutex::Autolock _l(mLock);
505 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
506 status_t status = sendConfigEvent_l(configEvent);
507 if (status == NO_ERROR) {
508 CreateAudioPatchConfigEventData *data =
509 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
510 *handle = data->mHandle;
511 }
512 return status;
513}
514
515status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
516 const audio_patch_handle_t handle)
517{
518 Mutex::Autolock _l(mLock);
519 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
520 return sendConfigEvent_l(configEvent);
521}
522
523
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700524// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700525void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700526{
Eric Laurent10351942014-05-08 18:49:52 -0700527 bool configChanged = false;
528
Eric Laurent81784c32012-11-19 14:55:58 -0800529 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700530 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
531 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800532 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700533 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700534 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700535 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
536 // FIXME Need to understand why this has to be done asynchronously
537 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700538 true /*asynchronous*/);
539 if (err != 0) {
540 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700541 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700542 }
543 } break;
544 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700545 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700546 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700547 } break;
548 case CFG_EVENT_SET_PARAMETER: {
549 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
550 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
551 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700552 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700553 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700554 case CFG_EVENT_CREATE_AUDIO_PATCH: {
555 CreateAudioPatchConfigEventData *data =
556 (CreateAudioPatchConfigEventData *)event->mData.get();
557 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
558 } break;
559 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
560 ReleaseAudioPatchConfigEventData *data =
561 (ReleaseAudioPatchConfigEventData *)event->mData.get();
562 event->mStatus = releaseAudioPatch_l(data->mHandle);
563 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700564 default:
Eric Laurent10351942014-05-08 18:49:52 -0700565 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700566 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800567 }
Eric Laurent10351942014-05-08 18:49:52 -0700568 {
569 Mutex::Autolock _l(event->mLock);
570 if (event->mWaitStatus) {
571 event->mWaitStatus = false;
572 event->mCond.signal();
573 }
574 }
575 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
576 }
577
578 if (configChanged) {
579 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800580 }
Eric Laurent81784c32012-11-19 14:55:58 -0800581}
582
Marco Nelissenb2208842014-02-07 14:00:50 -0800583String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
584 String8 s;
585 if (output) {
586 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
587 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
588 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
589 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
590 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
591 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
592 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
593 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
594 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
595 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
596 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
597 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
598 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
599 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
600 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
601 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
602 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
603 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
604 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
605 } else {
606 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
607 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
608 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
609 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
610 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
611 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
612 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
613 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
614 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
615 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
616 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
617 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
618 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
619 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
620 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
621 }
622 int len = s.length();
623 if (s.length() > 2) {
624 char *str = s.lockBuffer(len);
625 s.unlockBuffer(len - 2);
626 }
627 return s;
628}
629
Glenn Kasten0f11b512014-01-31 16:18:54 -0800630void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 const size_t SIZE = 256;
633 char buffer[SIZE];
634 String8 result;
635
636 bool locked = AudioFlinger::dumpTryLock(mLock);
637 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700638 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800639 }
640
Elliott Hughes87cebad2014-05-22 10:14:43 -0700641 dprintf(fd, " I/O handle: %d\n", mId);
642 dprintf(fd, " TID: %d\n", getTid());
643 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700644 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700645 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700646 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700647 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700648 dprintf(fd, " Channel count: %u\n", mChannelCount);
649 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800650 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700651 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
652 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700653 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800654 size_t numConfig = mConfigEvents.size();
655 if (numConfig) {
656 for (size_t i = 0; i < numConfig; i++) {
657 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700658 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800659 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700660 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800661 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700662 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800663 }
Eric Laurent81784c32012-11-19 14:55:58 -0800664
665 if (locked) {
666 mLock.unlock();
667 }
668}
669
670void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
671{
672 const size_t SIZE = 256;
673 char buffer[SIZE];
674 String8 result;
675
Marco Nelissenb2208842014-02-07 14:00:50 -0800676 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000677 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800678 write(fd, buffer, strlen(buffer));
679
Marco Nelissenb2208842014-02-07 14:00:50 -0800680 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800681 sp<EffectChain> chain = mEffectChains[i];
682 if (chain != 0) {
683 chain->dump(fd, args);
684 }
685 }
686}
687
Marco Nelissene14a5d62013-10-03 08:51:24 -0700688void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800689{
690 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700691 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800692}
693
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100694String16 AudioFlinger::ThreadBase::getWakeLockTag()
695{
696 switch (mType) {
697 case MIXER:
698 return String16("AudioMix");
699 case DIRECT:
700 return String16("AudioDirectOut");
701 case DUPLICATING:
702 return String16("AudioDup");
703 case RECORD:
704 return String16("AudioIn");
705 case OFFLOAD:
706 return String16("AudioOffload");
707 default:
708 ALOG_ASSERT(false);
709 return String16("AudioUnknown");
710 }
711}
712
Marco Nelissene14a5d62013-10-03 08:51:24 -0700713void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800714{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800715 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800716 if (mPowerManager != 0) {
717 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700718 status_t status;
719 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700720 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700721 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100722 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700723 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700724 uid,
725 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700726 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700727 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700728 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100729 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700730 String16("media"),
731 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700732 }
Eric Laurent81784c32012-11-19 14:55:58 -0800733 if (status == NO_ERROR) {
734 mWakeLockToken = binder;
735 }
736 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
737 }
738}
739
740void AudioFlinger::ThreadBase::releaseWakeLock()
741{
742 Mutex::Autolock _l(mLock);
743 releaseWakeLock_l();
744}
745
746void AudioFlinger::ThreadBase::releaseWakeLock_l()
747{
748 if (mWakeLockToken != 0) {
749 ALOGV("releaseWakeLock_l() %s", mName);
750 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700751 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
752 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800753 }
754 mWakeLockToken.clear();
755 }
756}
757
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800758void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
759 Mutex::Autolock _l(mLock);
760 updateWakeLockUids_l(uids);
761}
762
763void AudioFlinger::ThreadBase::getPowerManager_l() {
764
765 if (mPowerManager == 0) {
766 // use checkService() to avoid blocking if power service is not up yet
767 sp<IBinder> binder =
768 defaultServiceManager()->checkService(String16("power"));
769 if (binder == 0) {
770 ALOGW("Thread %s cannot connect to the power manager service", mName);
771 } else {
772 mPowerManager = interface_cast<IPowerManager>(binder);
773 binder->linkToDeath(mDeathRecipient);
774 }
775 }
776}
777
778void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
779
780 getPowerManager_l();
781 if (mWakeLockToken == NULL) {
782 ALOGE("no wake lock to update!");
783 return;
784 }
785 if (mPowerManager != 0) {
786 sp<IBinder> binder = new BBinder();
787 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700788 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
789 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800790 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
791 }
792}
793
Eric Laurent81784c32012-11-19 14:55:58 -0800794void AudioFlinger::ThreadBase::clearPowerManager()
795{
796 Mutex::Autolock _l(mLock);
797 releaseWakeLock_l();
798 mPowerManager.clear();
799}
800
Glenn Kasten0f11b512014-01-31 16:18:54 -0800801void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800802{
803 sp<ThreadBase> thread = mThread.promote();
804 if (thread != 0) {
805 thread->clearPowerManager();
806 }
807 ALOGW("power manager service died !!!");
808}
809
810void AudioFlinger::ThreadBase::setEffectSuspended(
811 const effect_uuid_t *type, bool suspend, int sessionId)
812{
813 Mutex::Autolock _l(mLock);
814 setEffectSuspended_l(type, suspend, sessionId);
815}
816
817void AudioFlinger::ThreadBase::setEffectSuspended_l(
818 const effect_uuid_t *type, bool suspend, int sessionId)
819{
820 sp<EffectChain> chain = getEffectChain_l(sessionId);
821 if (chain != 0) {
822 if (type != NULL) {
823 chain->setEffectSuspended_l(type, suspend);
824 } else {
825 chain->setEffectSuspendedAll_l(suspend);
826 }
827 }
828
829 updateSuspendedSessions_l(type, suspend, sessionId);
830}
831
832void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
833{
834 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
835 if (index < 0) {
836 return;
837 }
838
839 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
840 mSuspendedSessions.valueAt(index);
841
842 for (size_t i = 0; i < sessionEffects.size(); i++) {
843 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
844 for (int j = 0; j < desc->mRefCount; j++) {
845 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
846 chain->setEffectSuspendedAll_l(true);
847 } else {
848 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
849 desc->mType.timeLow);
850 chain->setEffectSuspended_l(&desc->mType, true);
851 }
852 }
853 }
854}
855
856void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
857 bool suspend,
858 int sessionId)
859{
860 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
861
862 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
863
864 if (suspend) {
865 if (index >= 0) {
866 sessionEffects = mSuspendedSessions.valueAt(index);
867 } else {
868 mSuspendedSessions.add(sessionId, sessionEffects);
869 }
870 } else {
871 if (index < 0) {
872 return;
873 }
874 sessionEffects = mSuspendedSessions.valueAt(index);
875 }
876
877
878 int key = EffectChain::kKeyForSuspendAll;
879 if (type != NULL) {
880 key = type->timeLow;
881 }
882 index = sessionEffects.indexOfKey(key);
883
884 sp<SuspendedSessionDesc> desc;
885 if (suspend) {
886 if (index >= 0) {
887 desc = sessionEffects.valueAt(index);
888 } else {
889 desc = new SuspendedSessionDesc();
890 if (type != NULL) {
891 desc->mType = *type;
892 }
893 sessionEffects.add(key, desc);
894 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
895 }
896 desc->mRefCount++;
897 } else {
898 if (index < 0) {
899 return;
900 }
901 desc = sessionEffects.valueAt(index);
902 if (--desc->mRefCount == 0) {
903 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
904 sessionEffects.removeItemsAt(index);
905 if (sessionEffects.isEmpty()) {
906 ALOGV("updateSuspendedSessions_l() restore removing session %d",
907 sessionId);
908 mSuspendedSessions.removeItem(sessionId);
909 }
910 }
911 }
912 if (!sessionEffects.isEmpty()) {
913 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
914 }
915}
916
917void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
918 bool enabled,
919 int sessionId)
920{
921 Mutex::Autolock _l(mLock);
922 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
923}
924
925void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
926 bool enabled,
927 int sessionId)
928{
929 if (mType != RECORD) {
930 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
931 // another session. This gives the priority to well behaved effect control panels
932 // and applications not using global effects.
933 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
934 // global effects
935 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
936 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
937 }
938 }
939
940 sp<EffectChain> chain = getEffectChain_l(sessionId);
941 if (chain != 0) {
942 chain->checkSuspendOnEffectEnabled(effect, enabled);
943 }
944}
945
946// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
947sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
948 const sp<AudioFlinger::Client>& client,
949 const sp<IEffectClient>& effectClient,
950 int32_t priority,
951 int sessionId,
952 effect_descriptor_t *desc,
953 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700954 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800955{
956 sp<EffectModule> effect;
957 sp<EffectHandle> handle;
958 status_t lStatus;
959 sp<EffectChain> chain;
960 bool chainCreated = false;
961 bool effectCreated = false;
962 bool effectRegistered = false;
963
964 lStatus = initCheck();
965 if (lStatus != NO_ERROR) {
966 ALOGW("createEffect_l() Audio driver not initialized.");
967 goto Exit;
968 }
969
Andy Hung98ef9782014-03-04 14:46:50 -0800970 // Reject any effect on Direct output threads for now, since the format of
971 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
972 if (mType == DIRECT) {
973 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
974 desc->name, mName);
975 lStatus = BAD_VALUE;
976 goto Exit;
977 }
978
Andy Hung389cfdb2014-08-07 17:49:53 -0700979 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700980 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700981 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
982 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
983 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700984 lStatus = BAD_VALUE;
985 goto Exit;
986 }
987
Eric Laurent5baf2af2013-09-12 17:37:00 -0700988 // Allow global effects only on offloaded and mixer threads
989 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
990 switch (mType) {
991 case MIXER:
992 case OFFLOAD:
993 break;
994 case DIRECT:
995 case DUPLICATING:
996 case RECORD:
997 default:
998 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
999 lStatus = BAD_VALUE;
1000 goto Exit;
1001 }
Eric Laurent81784c32012-11-19 14:55:58 -08001002 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001003
Eric Laurent81784c32012-11-19 14:55:58 -08001004 // Only Pre processor effects are allowed on input threads and only on input threads
1005 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1006 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1007 desc->name, desc->flags, mType);
1008 lStatus = BAD_VALUE;
1009 goto Exit;
1010 }
1011
1012 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1013
1014 { // scope for mLock
1015 Mutex::Autolock _l(mLock);
1016
1017 // check for existing effect chain with the requested audio session
1018 chain = getEffectChain_l(sessionId);
1019 if (chain == 0) {
1020 // create a new chain for this session
1021 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1022 chain = new EffectChain(this, sessionId);
1023 addEffectChain_l(chain);
1024 chain->setStrategy(getStrategyForSession_l(sessionId));
1025 chainCreated = true;
1026 } else {
1027 effect = chain->getEffectFromDesc_l(desc);
1028 }
1029
1030 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1031
1032 if (effect == 0) {
1033 int id = mAudioFlinger->nextUniqueId();
1034 // Check CPU and memory usage
1035 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1036 if (lStatus != NO_ERROR) {
1037 goto Exit;
1038 }
1039 effectRegistered = true;
1040 // create a new effect module if none present in the chain
1041 effect = new EffectModule(this, chain, desc, id, sessionId);
1042 lStatus = effect->status();
1043 if (lStatus != NO_ERROR) {
1044 goto Exit;
1045 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001046 effect->setOffloaded(mType == OFFLOAD, mId);
1047
Eric Laurent81784c32012-11-19 14:55:58 -08001048 lStatus = chain->addEffect_l(effect);
1049 if (lStatus != NO_ERROR) {
1050 goto Exit;
1051 }
1052 effectCreated = true;
1053
1054 effect->setDevice(mOutDevice);
1055 effect->setDevice(mInDevice);
1056 effect->setMode(mAudioFlinger->getMode());
1057 effect->setAudioSource(mAudioSource);
1058 }
1059 // create effect handle and connect it to effect module
1060 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001061 lStatus = handle->initCheck();
1062 if (lStatus == OK) {
1063 lStatus = effect->addHandle(handle.get());
1064 }
Eric Laurent81784c32012-11-19 14:55:58 -08001065 if (enabled != NULL) {
1066 *enabled = (int)effect->isEnabled();
1067 }
1068 }
1069
1070Exit:
1071 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1072 Mutex::Autolock _l(mLock);
1073 if (effectCreated) {
1074 chain->removeEffect_l(effect);
1075 }
1076 if (effectRegistered) {
1077 AudioSystem::unregisterEffect(effect->id());
1078 }
1079 if (chainCreated) {
1080 removeEffectChain_l(chain);
1081 }
1082 handle.clear();
1083 }
1084
Glenn Kasten9156ef32013-08-06 15:39:08 -07001085 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001086 return handle;
1087}
1088
1089sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1090{
1091 Mutex::Autolock _l(mLock);
1092 return getEffect_l(sessionId, effectId);
1093}
1094
1095sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1096{
1097 sp<EffectChain> chain = getEffectChain_l(sessionId);
1098 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1099}
1100
1101// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1102// PlaybackThread::mLock held
1103status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1104{
1105 // check for existing effect chain with the requested audio session
1106 int sessionId = effect->sessionId();
1107 sp<EffectChain> chain = getEffectChain_l(sessionId);
1108 bool chainCreated = false;
1109
Eric Laurent5baf2af2013-09-12 17:37:00 -07001110 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1111 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1112 this, effect->desc().name, effect->desc().flags);
1113
Eric Laurent81784c32012-11-19 14:55:58 -08001114 if (chain == 0) {
1115 // create a new chain for this session
1116 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1117 chain = new EffectChain(this, sessionId);
1118 addEffectChain_l(chain);
1119 chain->setStrategy(getStrategyForSession_l(sessionId));
1120 chainCreated = true;
1121 }
1122 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1123
1124 if (chain->getEffectFromId_l(effect->id()) != 0) {
1125 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1126 this, effect->desc().name, chain.get());
1127 return BAD_VALUE;
1128 }
1129
Eric Laurent5baf2af2013-09-12 17:37:00 -07001130 effect->setOffloaded(mType == OFFLOAD, mId);
1131
Eric Laurent81784c32012-11-19 14:55:58 -08001132 status_t status = chain->addEffect_l(effect);
1133 if (status != NO_ERROR) {
1134 if (chainCreated) {
1135 removeEffectChain_l(chain);
1136 }
1137 return status;
1138 }
1139
1140 effect->setDevice(mOutDevice);
1141 effect->setDevice(mInDevice);
1142 effect->setMode(mAudioFlinger->getMode());
1143 effect->setAudioSource(mAudioSource);
1144 return NO_ERROR;
1145}
1146
1147void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1148
1149 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1150 effect_descriptor_t desc = effect->desc();
1151 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1152 detachAuxEffect_l(effect->id());
1153 }
1154
1155 sp<EffectChain> chain = effect->chain().promote();
1156 if (chain != 0) {
1157 // remove effect chain if removing last effect
1158 if (chain->removeEffect_l(effect) == 0) {
1159 removeEffectChain_l(chain);
1160 }
1161 } else {
1162 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1163 }
1164}
1165
1166void AudioFlinger::ThreadBase::lockEffectChains_l(
1167 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1168{
1169 effectChains = mEffectChains;
1170 for (size_t i = 0; i < mEffectChains.size(); i++) {
1171 mEffectChains[i]->lock();
1172 }
1173}
1174
1175void AudioFlinger::ThreadBase::unlockEffectChains(
1176 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1177{
1178 for (size_t i = 0; i < effectChains.size(); i++) {
1179 effectChains[i]->unlock();
1180 }
1181}
1182
1183sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1184{
1185 Mutex::Autolock _l(mLock);
1186 return getEffectChain_l(sessionId);
1187}
1188
1189sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1190{
1191 size_t size = mEffectChains.size();
1192 for (size_t i = 0; i < size; i++) {
1193 if (mEffectChains[i]->sessionId() == sessionId) {
1194 return mEffectChains[i];
1195 }
1196 }
1197 return 0;
1198}
1199
1200void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1201{
1202 Mutex::Autolock _l(mLock);
1203 size_t size = mEffectChains.size();
1204 for (size_t i = 0; i < size; i++) {
1205 mEffectChains[i]->setMode_l(mode);
1206 }
1207}
1208
Eric Laurent83b88082014-06-20 18:31:16 -07001209void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1210{
1211 config->type = AUDIO_PORT_TYPE_MIX;
1212 config->ext.mix.handle = mId;
1213 config->sample_rate = mSampleRate;
1214 config->format = mFormat;
1215 config->channel_mask = mChannelMask;
1216 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1217 AUDIO_PORT_CONFIG_FORMAT;
1218}
1219
1220
Eric Laurent81784c32012-11-19 14:55:58 -08001221// ----------------------------------------------------------------------------
1222// Playback
1223// ----------------------------------------------------------------------------
1224
1225AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1226 AudioStreamOut* output,
1227 audio_io_handle_t id,
1228 audio_devices_t device,
1229 type_t type)
1230 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001231 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001232 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001233 mMixerBuffer(NULL),
1234 mMixerBufferSize(0),
1235 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1236 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001237 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001238 mEffectBuffer(NULL),
1239 mEffectBufferSize(0),
1240 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1241 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001242 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001244 // mStreamTypes[] initialized in constructor body
1245 mOutput(output),
1246 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1247 mMixerStatus(MIXER_IDLE),
1248 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1249 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001250 mBytesRemaining(0),
1251 mCurrentWriteLength(0),
1252 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001253 mWriteAckSequence(0),
1254 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001255 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001256 mScreenState(AudioFlinger::mScreenState),
1257 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001258 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001259 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001260 // mLatchD, mLatchQ,
1261 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001262{
1263 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001264 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001265
1266 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1267 // it would be safer to explicitly pass initial masterVolume/masterMute as
1268 // parameter.
1269 //
1270 // If the HAL we are using has support for master volume or master mute,
1271 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1272 // and the mute set to false).
1273 mMasterVolume = audioFlinger->masterVolume_l();
1274 mMasterMute = audioFlinger->masterMute_l();
1275 if (mOutput && mOutput->audioHwDev) {
1276 if (mOutput->audioHwDev->canSetMasterVolume()) {
1277 mMasterVolume = 1.0;
1278 }
1279
1280 if (mOutput->audioHwDev->canSetMasterMute()) {
1281 mMasterMute = false;
1282 }
1283 }
1284
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001285 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001286
Eric Laurent223fd5c2014-11-11 13:43:36 -08001287 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001288 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001289 stream = (audio_stream_type_t) (stream + 1)) {
1290 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1291 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1292 }
Eric Laurent81784c32012-11-19 14:55:58 -08001293}
1294
1295AudioFlinger::PlaybackThread::~PlaybackThread()
1296{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001297 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001298 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001299 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001300 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001301}
1302
1303void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1304{
1305 dumpInternals(fd, args);
1306 dumpTracks(fd, args);
1307 dumpEffectChains(fd, args);
1308}
1309
Glenn Kasten0f11b512014-01-31 16:18:54 -08001310void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001311{
1312 const size_t SIZE = 256;
1313 char buffer[SIZE];
1314 String8 result;
1315
Marco Nelissenb2208842014-02-07 14:00:50 -08001316 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001317 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1318 const stream_type_t *st = &mStreamTypes[i];
1319 if (i > 0) {
1320 result.appendFormat(", ");
1321 }
1322 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1323 if (st->mute) {
1324 result.append("M");
1325 }
1326 }
1327 result.append("\n");
1328 write(fd, result.string(), result.length());
1329 result.clear();
1330
Eric Laurent81784c32012-11-19 14:55:58 -08001331 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1332 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001333 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001334 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001335
1336 size_t numtracks = mTracks.size();
1337 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001338 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001339 size_t numactiveseen = 0;
1340 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001341 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001342 Track::appendDumpHeader(result);
1343 for (size_t i = 0; i < numtracks; ++i) {
1344 sp<Track> track = mTracks[i];
1345 if (track != 0) {
1346 bool active = mActiveTracks.indexOf(track) >= 0;
1347 if (active) {
1348 numactiveseen++;
1349 }
1350 track->dump(buffer, SIZE, active);
1351 result.append(buffer);
1352 }
1353 }
1354 } else {
1355 result.append("\n");
1356 }
1357 if (numactiveseen != numactive) {
1358 // some tracks in the active list were not in the tracks list
1359 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1360 " not in the track list\n");
1361 result.append(buffer);
1362 Track::appendDumpHeader(result);
1363 for (size_t i = 0; i < numactive; ++i) {
1364 sp<Track> track = mActiveTracks[i].promote();
1365 if (track != 0 && mTracks.indexOf(track) < 0) {
1366 track->dump(buffer, SIZE, true);
1367 result.append(buffer);
1368 }
1369 }
1370 }
1371
1372 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001373}
1374
1375void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1376{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001377 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001378 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1379 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1380 dprintf(fd, " Total writes: %d\n", mNumWrites);
1381 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1382 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1383 dprintf(fd, " Suspend count: %d\n", mSuspended);
1384 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1385 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1386 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1387 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001388 AudioStreamOut *output = mOutput;
1389 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1390 String8 flagsAsString = outputFlagsToString(flags);
1391 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001392
1393 dumpBase(fd, args);
1394}
1395
1396// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001397
1398void AudioFlinger::PlaybackThread::onFirstRef()
1399{
1400 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1401}
1402
1403// ThreadBase virtuals
1404void AudioFlinger::PlaybackThread::preExit()
1405{
1406 ALOGV(" preExit()");
1407 // FIXME this is using hard-coded strings but in the future, this functionality will be
1408 // converted to use audio HAL extensions required to support tunneling
1409 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1410}
1411
1412// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1413sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1414 const sp<AudioFlinger::Client>& client,
1415 audio_stream_type_t streamType,
1416 uint32_t sampleRate,
1417 audio_format_t format,
1418 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001419 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001420 const sp<IMemory>& sharedBuffer,
1421 int sessionId,
1422 IAudioFlinger::track_flags_t *flags,
1423 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001424 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001425 status_t *status)
1426{
Glenn Kasten74935e42013-12-19 08:56:45 -08001427 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001428 sp<Track> track;
1429 status_t lStatus;
1430
1431 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1432
1433 // client expresses a preference for FAST, but we get the final say
1434 if (*flags & IAudioFlinger::TRACK_FAST) {
1435 if (
1436 // not timed
1437 (!isTimed) &&
1438 // either of these use cases:
1439 (
1440 // use case 1: shared buffer with any frame count
1441 (
1442 (sharedBuffer != 0)
1443 ) ||
1444 // use case 2: callback handler and frame count is default or at least as large as HAL
1445 (
1446 (tid != -1) &&
1447 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001448 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001449 )
1450 ) &&
1451 // PCM data
1452 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001453 // identical channel mask to sink, or mono in and stereo sink
1454 (channelMask == mChannelMask ||
1455 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1456 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001457 // hardware sample rate
1458 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001459 // normal mixer has an associated fast mixer
1460 hasFastMixer() &&
1461 // there are sufficient fast track slots available
1462 (mFastTrackAvailMask != 0)
1463 // FIXME test that MixerThread for this fast track has a capable output HAL
1464 // FIXME add a permission test also?
1465 ) {
1466 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1467 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001468 // read the fast track multiplier property the first time it is needed
1469 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1470 if (ok != 0) {
1471 ALOGE("%s pthread_once failed: %d", __func__, ok);
1472 }
1473 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001474 }
1475 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1476 frameCount, mFrameCount);
1477 } else {
1478 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001479 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1480 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001481 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001482 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001483 audio_is_linear_pcm(format),
1484 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1485 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001486 }
1487 }
1488 // For normal PCM streaming tracks, update minimum frame count.
1489 // For compatibility with AudioTrack calculation, buffer depth is forced
1490 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1491 // This is probably too conservative, but legacy application code may depend on it.
1492 // If you change this calculation, also review the start threshold which is related.
1493 if (!(*flags & IAudioFlinger::TRACK_FAST)
1494 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001495 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1496 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1497 if (minBufCount < 2) {
1498 minBufCount = 2;
1499 }
Andy Hung0e48d252015-01-26 11:43:15 -08001500 size_t minFrameCount =
1501 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1502 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001503 frameCount = minFrameCount;
1504 }
Eric Laurent81784c32012-11-19 14:55:58 -08001505 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001506 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001507
Glenn Kastenc3df8382014-03-13 15:05:25 -07001508 switch (mType) {
1509
1510 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001511 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001512 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001513 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1514 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001515 sampleRate, format, channelMask, mOutput, mFormat);
1516 lStatus = BAD_VALUE;
1517 goto Exit;
1518 }
1519 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001520 break;
1521
1522 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001523 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001524 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1525 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001526 sampleRate, format, channelMask, mOutput, mFormat);
1527 lStatus = BAD_VALUE;
1528 goto Exit;
1529 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001530 break;
1531
1532 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001533 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001534 ALOGE("createTrack_l() Bad parameter: format %#x \""
1535 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001536 format, mOutput, mFormat);
1537 lStatus = BAD_VALUE;
1538 goto Exit;
1539 }
Andy Hungcd044842014-08-07 11:04:34 -07001540 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001541 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1542 lStatus = BAD_VALUE;
1543 goto Exit;
1544 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001545 break;
1546
Eric Laurent81784c32012-11-19 14:55:58 -08001547 }
1548
1549 lStatus = initCheck();
1550 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001551 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001552 goto Exit;
1553 }
1554
1555 { // scope for mLock
1556 Mutex::Autolock _l(mLock);
1557
1558 // all tracks in same audio session must share the same routing strategy otherwise
1559 // conflicts will happen when tracks are moved from one output to another by audio policy
1560 // manager
1561 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1562 for (size_t i = 0; i < mTracks.size(); ++i) {
1563 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001564 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001565 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1566 if (sessionId == t->sessionId() && strategy != actual) {
1567 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1568 strategy, actual);
1569 lStatus = BAD_VALUE;
1570 goto Exit;
1571 }
1572 }
1573 }
1574
1575 if (!isTimed) {
1576 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001577 channelMask, frameCount, NULL, sharedBuffer,
1578 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001579 } else {
1580 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001581 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001582 }
Glenn Kasten03003332013-08-06 15:40:54 -07001583
1584 // new Track always returns non-NULL,
1585 // but TimedTrack::create() is a factory that could fail by returning NULL
1586 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1587 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001588 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001589 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001590 goto Exit;
1591 }
1592 mTracks.add(track);
1593
1594 sp<EffectChain> chain = getEffectChain_l(sessionId);
1595 if (chain != 0) {
1596 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1597 track->setMainBuffer(chain->inBuffer());
1598 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1599 chain->incTrackCnt();
1600 }
1601
1602 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1603 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1604 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1605 // so ask activity manager to do this on our behalf
1606 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1607 }
1608 }
1609
1610 lStatus = NO_ERROR;
1611
1612Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001613 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001614 return track;
1615}
1616
1617uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1618{
1619 return latency;
1620}
1621
1622uint32_t AudioFlinger::PlaybackThread::latency() const
1623{
1624 Mutex::Autolock _l(mLock);
1625 return latency_l();
1626}
1627uint32_t AudioFlinger::PlaybackThread::latency_l() const
1628{
1629 if (initCheck() == NO_ERROR) {
1630 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1631 } else {
1632 return 0;
1633 }
1634}
1635
1636void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1637{
1638 Mutex::Autolock _l(mLock);
1639 // Don't apply master volume in SW if our HAL can do it for us.
1640 if (mOutput && mOutput->audioHwDev &&
1641 mOutput->audioHwDev->canSetMasterVolume()) {
1642 mMasterVolume = 1.0;
1643 } else {
1644 mMasterVolume = value;
1645 }
1646}
1647
1648void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1649{
1650 Mutex::Autolock _l(mLock);
1651 // Don't apply master mute in SW if our HAL can do it for us.
1652 if (mOutput && mOutput->audioHwDev &&
1653 mOutput->audioHwDev->canSetMasterMute()) {
1654 mMasterMute = false;
1655 } else {
1656 mMasterMute = muted;
1657 }
1658}
1659
1660void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1661{
1662 Mutex::Autolock _l(mLock);
1663 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001664 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001665}
1666
1667void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1668{
1669 Mutex::Autolock _l(mLock);
1670 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001671 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001672}
1673
1674float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1675{
1676 Mutex::Autolock _l(mLock);
1677 return mStreamTypes[stream].volume;
1678}
1679
1680// addTrack_l() must be called with ThreadBase::mLock held
1681status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1682{
1683 status_t status = ALREADY_EXISTS;
1684
1685 // set retry count for buffer fill
1686 track->mRetryCount = kMaxTrackStartupRetries;
1687 if (mActiveTracks.indexOf(track) < 0) {
1688 // the track is newly added, make sure it fills up all its
1689 // buffers before playing. This is to ensure the client will
1690 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001691 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692 TrackBase::track_state state = track->mState;
1693 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001694 status = AudioSystem::startOutput(mId, track->streamType(),
1695 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001696 mLock.lock();
1697 // abort track was stopped/paused while we released the lock
1698 if (state != track->mState) {
1699 if (status == NO_ERROR) {
1700 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001701 AudioSystem::stopOutput(mId, track->streamType(),
1702 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001703 mLock.lock();
1704 }
1705 return INVALID_OPERATION;
1706 }
1707 // abort if start is rejected by audio policy manager
1708 if (status != NO_ERROR) {
1709 return PERMISSION_DENIED;
1710 }
1711#ifdef ADD_BATTERY_DATA
1712 // to track the speaker usage
1713 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1714#endif
1715 }
1716
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001717 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001718 track->mResetDone = false;
1719 track->mPresentationCompleteFrames = 0;
1720 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001721 mWakeLockUids.add(track->uid());
1722 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001723 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001724 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1725 if (chain != 0) {
1726 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1727 track->sessionId());
1728 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001729 }
1730
1731 status = NO_ERROR;
1732 }
1733
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001734 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001735 return status;
1736}
1737
Eric Laurentbfb1b832013-01-07 09:53:42 -08001738bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001739{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001740 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001741 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1743 track->mState = TrackBase::STOPPED;
1744 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001745 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001746 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001748 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001749
1750 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001751}
1752
1753void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1754{
1755 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1756 mTracks.remove(track);
1757 deleteTrackName_l(track->name());
1758 // redundant as track is about to be destroyed, for dumpsys only
1759 track->mName = -1;
1760 if (track->isFastTrack()) {
1761 int index = track->mFastIndex;
1762 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1763 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1764 mFastTrackAvailMask |= 1 << index;
1765 // redundant as track is about to be destroyed, for dumpsys only
1766 track->mFastIndex = -1;
1767 }
1768 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1769 if (chain != 0) {
1770 chain->decTrackCnt();
1771 }
1772}
1773
Eric Laurentede6c3b2013-09-19 14:37:46 -07001774void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001775{
1776 // Thread could be blocked waiting for async
1777 // so signal it to handle state changes immediately
1778 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1779 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1780 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001781 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782}
1783
Eric Laurent81784c32012-11-19 14:55:58 -08001784String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1785{
Eric Laurent81784c32012-11-19 14:55:58 -08001786 Mutex::Autolock _l(mLock);
1787 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001788 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001789 }
1790
Glenn Kastend8ea6992013-07-16 14:17:15 -07001791 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1792 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001793 free(s);
1794 return out_s8;
1795}
1796
Eric Laurent021cf962014-05-13 10:18:14 -07001797void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001798 AudioSystem::OutputDescriptor desc;
1799 void *param2 = NULL;
1800
Eric Laurent021cf962014-05-13 10:18:14 -07001801 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001802 param);
1803
1804 switch (event) {
1805 case AudioSystem::OUTPUT_OPENED:
1806 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001807 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001808 desc.samplingRate = mSampleRate;
1809 desc.format = mFormat;
1810 desc.frameCount = mNormalFrameCount; // FIXME see
1811 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001812 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001813 param2 = &desc;
1814 break;
1815
1816 case AudioSystem::STREAM_CONFIG_CHANGED:
1817 param2 = &param;
1818 case AudioSystem::OUTPUT_CLOSED:
1819 default:
1820 break;
1821 }
Eric Laurent021cf962014-05-13 10:18:14 -07001822 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001823}
1824
Eric Laurentbfb1b832013-01-07 09:53:42 -08001825void AudioFlinger::PlaybackThread::writeCallback()
1826{
1827 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001828 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001829}
1830
1831void AudioFlinger::PlaybackThread::drainCallback()
1832{
1833 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001834 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001835}
1836
Eric Laurent3b4529e2013-09-05 18:09:19 -07001837void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001838{
1839 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001840 // reject out of sequence requests
1841 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1842 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843 mWaitWorkCV.signal();
1844 }
1845}
1846
Eric Laurent3b4529e2013-09-05 18:09:19 -07001847void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848{
1849 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001850 // reject out of sequence requests
1851 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1852 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001853 mWaitWorkCV.signal();
1854 }
1855}
1856
1857// static
1858int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001859 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001860 void *cookie)
1861{
1862 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1863 ALOGV("asyncCallback() event %d", event);
1864 switch (event) {
1865 case STREAM_CBK_EVENT_WRITE_READY:
1866 me->writeCallback();
1867 break;
1868 case STREAM_CBK_EVENT_DRAIN_READY:
1869 me->drainCallback();
1870 break;
1871 default:
1872 ALOGW("asyncCallback() unknown event %d", event);
1873 break;
1874 }
1875 return 0;
1876}
1877
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001878void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001879{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001880 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001881 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1882 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001883 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001884 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001885 }
Andy Hung9a592762014-07-21 21:56:01 -07001886 if ((mType == MIXER || mType == DUPLICATING)
1887 && !isValidPcmSinkChannelMask(mChannelMask)) {
1888 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1889 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001890 }
Andy Hunge5412692014-05-16 11:25:07 -07001891 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001892 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1893 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001894 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001895 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001896 }
Andy Hung6146c082014-03-18 11:56:15 -07001897 if ((mType == MIXER || mType == DUPLICATING)
1898 && !isValidPcmSinkFormat(mFormat)) {
1899 LOG_FATAL("HAL format %#x not supported for mixed output",
1900 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001901 }
Eric Laurent665470b2014-07-03 16:37:08 -07001902 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001903 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1904 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001905 if (mFrameCount & 15) {
1906 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1907 mFrameCount);
1908 }
1909
Eric Laurentbfb1b832013-01-07 09:53:42 -08001910 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1911 (mOutput->stream->set_callback != NULL)) {
1912 if (mOutput->stream->set_callback(mOutput->stream,
1913 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1914 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001915 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001916 }
1917 }
1918
Eric Laurentd1f69b02014-12-15 14:33:13 -08001919 mHwSupportsPause = false;
1920 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1921 if (mOutput->stream->pause != NULL) {
1922 if (mOutput->stream->resume != NULL) {
1923 mHwSupportsPause = true;
1924 } else {
1925 ALOGW("direct output implements pause but not resume");
1926 }
1927 } else if (mOutput->stream->resume != NULL) {
1928 ALOGW("direct output implements resume but not pause");
1929 }
1930 }
1931
Andy Hungfbfc3952015-01-15 13:33:51 -08001932 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
1933 // For best precision, we use float instead of the associated output
1934 // device format (typically PCM 16 bit).
1935
1936 mFormat = AUDIO_FORMAT_PCM_FLOAT;
1937 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
1938 mBufferSize = mFrameSize * mFrameCount;
1939
1940 // TODO: We currently use the associated output device channel mask and sample rate.
1941 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
1942 // (if a valid mask) to avoid premature downmix.
1943 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
1944 // instead of the output device sample rate to avoid loss of high frequency information.
1945 // This may need to be updated as MixerThread/OutputTracks are added and not here.
1946 }
1947
Andy Hung09a50072014-02-27 14:30:47 -08001948 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001949 double multiplier = 1.0;
1950 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1951 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001952 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1953 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001954 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1955 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1956 maxNormalFrameCount = maxNormalFrameCount & ~15;
1957 if (maxNormalFrameCount < minNormalFrameCount) {
1958 maxNormalFrameCount = minNormalFrameCount;
1959 }
1960 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1961 if (multiplier <= 1.0) {
1962 multiplier = 1.0;
1963 } else if (multiplier <= 2.0) {
1964 if (2 * mFrameCount <= maxNormalFrameCount) {
1965 multiplier = 2.0;
1966 } else {
1967 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1968 }
1969 } else {
1970 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001971 // 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 -08001972 // track, but we sometimes have to do this to satisfy the maximum frame count
1973 // constraint)
1974 // FIXME this rounding up should not be done if no HAL SRC
1975 uint32_t truncMult = (uint32_t) multiplier;
1976 if ((truncMult & 1)) {
1977 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1978 ++truncMult;
1979 }
1980 }
1981 multiplier = (double) truncMult;
1982 }
1983 }
1984 mNormalFrameCount = multiplier * mFrameCount;
1985 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001986 if (mType == MIXER || mType == DUPLICATING) {
1987 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1988 }
Andy Hung09a50072014-02-27 14:30:47 -08001989 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001990 mNormalFrameCount);
1991
Andy Hung010a1a12014-03-13 13:57:33 -07001992 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1993 // Originally this was int16_t[] array, need to remove legacy implications.
1994 free(mSinkBuffer);
1995 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001996 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1997 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1998 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001999 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002000
Andy Hung69aed5f2014-02-25 17:24:40 -08002001 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2002 // drives the output.
2003 free(mMixerBuffer);
2004 mMixerBuffer = NULL;
2005 if (mMixerBufferEnabled) {
2006 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2007 mMixerBufferSize = mNormalFrameCount * mChannelCount
2008 * audio_bytes_per_sample(mMixerBufferFormat);
2009 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2010 }
Andy Hung98ef9782014-03-04 14:46:50 -08002011 free(mEffectBuffer);
2012 mEffectBuffer = NULL;
2013 if (mEffectBufferEnabled) {
2014 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2015 mEffectBufferSize = mNormalFrameCount * mChannelCount
2016 * audio_bytes_per_sample(mEffectBufferFormat);
2017 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2018 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002019
Eric Laurent81784c32012-11-19 14:55:58 -08002020 // force reconfiguration of effect chains and engines to take new buffer size and audio
2021 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002022 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002023 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2024 // matter.
2025 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2026 Vector< sp<EffectChain> > effectChains = mEffectChains;
2027 for (size_t i = 0; i < effectChains.size(); i ++) {
2028 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2029 }
2030}
2031
2032
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002033status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002034{
2035 if (halFrames == NULL || dspFrames == NULL) {
2036 return BAD_VALUE;
2037 }
2038 Mutex::Autolock _l(mLock);
2039 if (initCheck() != NO_ERROR) {
2040 return INVALID_OPERATION;
2041 }
2042 size_t framesWritten = mBytesWritten / mFrameSize;
2043 *halFrames = framesWritten;
2044
2045 if (isSuspended()) {
2046 // return an estimation of rendered frames when the output is suspended
2047 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2048 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2049 return NO_ERROR;
2050 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002051 status_t status;
2052 uint32_t frames;
2053 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2054 *dspFrames = (size_t)frames;
2055 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
2057}
2058
2059uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2060{
2061 Mutex::Autolock _l(mLock);
2062 uint32_t result = 0;
2063 if (getEffectChain_l(sessionId) != 0) {
2064 result = EFFECT_SESSION;
2065 }
2066
2067 for (size_t i = 0; i < mTracks.size(); ++i) {
2068 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002069 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002070 result |= TRACK_SESSION;
2071 break;
2072 }
2073 }
2074
2075 return result;
2076}
2077
2078uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2079{
2080 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2081 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2082 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2083 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2084 }
2085 for (size_t i = 0; i < mTracks.size(); i++) {
2086 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002087 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002088 return AudioSystem::getStrategyForStream(track->streamType());
2089 }
2090 }
2091 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2092}
2093
2094
2095AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2096{
2097 Mutex::Autolock _l(mLock);
2098 return mOutput;
2099}
2100
2101AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2102{
2103 Mutex::Autolock _l(mLock);
2104 AudioStreamOut *output = mOutput;
2105 mOutput = NULL;
2106 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2107 // must push a NULL and wait for ack
2108 mOutputSink.clear();
2109 mPipeSink.clear();
2110 mNormalSink.clear();
2111 return output;
2112}
2113
2114// this method must always be called either with ThreadBase mLock held or inside the thread loop
2115audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2116{
2117 if (mOutput == NULL) {
2118 return NULL;
2119 }
2120 return &mOutput->stream->common;
2121}
2122
2123uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2124{
2125 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2126}
2127
2128status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2129{
2130 if (!isValidSyncEvent(event)) {
2131 return BAD_VALUE;
2132 }
2133
2134 Mutex::Autolock _l(mLock);
2135
2136 for (size_t i = 0; i < mTracks.size(); ++i) {
2137 sp<Track> track = mTracks[i];
2138 if (event->triggerSession() == track->sessionId()) {
2139 (void) track->setSyncEvent(event);
2140 return NO_ERROR;
2141 }
2142 }
2143
2144 return NAME_NOT_FOUND;
2145}
2146
2147bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2148{
2149 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2150}
2151
2152void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2153 const Vector< sp<Track> >& tracksToRemove)
2154{
2155 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002156 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002157 for (size_t i = 0 ; i < count ; i++) {
2158 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002159 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002160 AudioSystem::stopOutput(mId, track->streamType(),
2161 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162#ifdef ADD_BATTERY_DATA
2163 // to track the speaker usage
2164 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2165#endif
2166 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002167 AudioSystem::releaseOutput(mId, track->streamType(),
2168 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 }
Eric Laurent81784c32012-11-19 14:55:58 -08002170 }
2171 }
2172 }
Eric Laurent81784c32012-11-19 14:55:58 -08002173}
2174
2175void AudioFlinger::PlaybackThread::checkSilentMode_l()
2176{
2177 if (!mMasterMute) {
2178 char value[PROPERTY_VALUE_MAX];
2179 if (property_get("ro.audio.silent", value, "0") > 0) {
2180 char *endptr;
2181 unsigned long ul = strtoul(value, &endptr, 0);
2182 if (*endptr == '\0' && ul != 0) {
2183 ALOGD("Silence is golden");
2184 // The setprop command will not allow a property to be changed after
2185 // the first time it is set, so we don't have to worry about un-muting.
2186 setMasterMute_l(true);
2187 }
2188 }
2189 }
2190}
2191
2192// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002193ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002194{
2195 // FIXME rewrite to reduce number of system calls
2196 mLastWriteTime = systemTime();
2197 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002199 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002200
2201 // If an NBAIO sink is present, use it to write the normal mixer's submix
2202 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002203
Andy Hung010a1a12014-03-13 13:57:33 -07002204 const size_t count = mBytesRemaining / mFrameSize;
2205
Simon Wilson2d590962012-11-29 15:18:50 -08002206 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002207 // update the setpoint when AudioFlinger::mScreenState changes
2208 uint32_t screenState = AudioFlinger::mScreenState;
2209 if (screenState != mScreenState) {
2210 mScreenState = screenState;
2211 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2212 if (pipe != NULL) {
2213 pipe->setAvgFrames((mScreenState & 1) ?
2214 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2215 }
2216 }
Andy Hung010a1a12014-03-13 13:57:33 -07002217 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002218 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002219 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002220 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002221 } else {
2222 bytesWritten = framesWritten;
2223 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002224 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002225 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002226 if (status == NO_ERROR) {
2227 size_t totalFramesWritten = mNormalSink->framesWritten();
2228 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2229 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002230 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002231 mLatchDValid = true;
2232 }
2233 }
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // otherwise use the HAL / AudioStreamOut directly
2235 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002236 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002237
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002239 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2240 mWriteAckSequence += 2;
2241 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002243 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002245 // FIXME We should have an implementation of timestamps for direct output threads.
2246 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002248 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 if (mUseAsyncWrite &&
2250 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2251 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002252 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255 }
Eric Laurent81784c32012-11-19 14:55:58 -08002256 }
2257
Eric Laurent81784c32012-11-19 14:55:58 -08002258 mNumWrites++;
2259 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002260 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002261 return bytesWritten;
2262}
2263
2264void AudioFlinger::PlaybackThread::threadLoop_drain()
2265{
2266 if (mOutput->stream->drain) {
2267 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2268 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002269 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2270 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002272 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 }
2274 mOutput->stream->drain(mOutput->stream,
2275 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2276 : AUDIO_DRAIN_ALL);
2277 }
2278}
2279
2280void AudioFlinger::PlaybackThread::threadLoop_exit()
2281{
Eric Laurent275e8e92014-11-30 15:14:47 -08002282 {
2283 Mutex::Autolock _l(mLock);
2284 for (size_t i = 0; i < mTracks.size(); i++) {
2285 sp<Track> track = mTracks[i];
2286 track->invalidate();
2287 }
2288 }
Eric Laurent81784c32012-11-19 14:55:58 -08002289}
2290
2291/*
2292The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002293 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002294 - activeSleepTime from activeSleepTimeUs()
2295 - idleSleepTime from idleSleepTimeUs()
2296 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2297 - maxPeriod from frame count and sample rate (MIXER only)
2298
2299The parameters that affect these derived values are:
2300 - frame count
2301 - frame size
2302 - sample rate
2303 - device type: A2DP or not
2304 - device latency
2305 - format: PCM or not
2306 - active sleep time
2307 - idle sleep time
2308*/
2309
2310void AudioFlinger::PlaybackThread::cacheParameters_l()
2311{
Andy Hung25c2dac2014-02-27 14:56:00 -08002312 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002313 activeSleepTime = activeSleepTimeUs();
2314 idleSleepTime = idleSleepTimeUs();
2315}
2316
2317void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2318{
Glenn Kasten7c027242012-12-26 14:43:16 -08002319 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002320 this, streamType, mTracks.size());
2321 Mutex::Autolock _l(mLock);
2322
2323 size_t size = mTracks.size();
2324 for (size_t i = 0; i < size; i++) {
2325 sp<Track> t = mTracks[i];
2326 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002327 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002328 }
2329 }
2330}
2331
2332status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2333{
2334 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002335 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2336 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002337 bool ownsBuffer = false;
2338
2339 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2340 if (session > 0) {
2341 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002342 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002343 if (mType != DIRECT) {
2344 size_t numSamples = mNormalFrameCount * mChannelCount;
2345 buffer = new int16_t[numSamples];
2346 memset(buffer, 0, numSamples * sizeof(int16_t));
2347 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2348 ownsBuffer = true;
2349 }
2350
2351 // Attach all tracks with same session ID to this chain.
2352 for (size_t i = 0; i < mTracks.size(); ++i) {
2353 sp<Track> track = mTracks[i];
2354 if (session == track->sessionId()) {
2355 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2356 buffer);
2357 track->setMainBuffer(buffer);
2358 chain->incTrackCnt();
2359 }
2360 }
2361
2362 // indicate all active tracks in the chain
2363 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2364 sp<Track> track = mActiveTracks[i].promote();
2365 if (track == 0) {
2366 continue;
2367 }
2368 if (session == track->sessionId()) {
2369 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2370 chain->incActiveTrackCnt();
2371 }
2372 }
2373 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002374 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002375 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002376 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2377 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2379 // chains list in order to be processed last as it contains output stage effects
2380 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2381 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2382 // after track specific effects and before output stage
2383 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2384 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2385 // Effect chain for other sessions are inserted at beginning of effect
2386 // chains list to be processed before output mix effects. Relative order between other
2387 // sessions is not important
2388 size_t size = mEffectChains.size();
2389 size_t i = 0;
2390 for (i = 0; i < size; i++) {
2391 if (mEffectChains[i]->sessionId() < session) {
2392 break;
2393 }
2394 }
2395 mEffectChains.insertAt(chain, i);
2396 checkSuspendOnAddEffectChain_l(chain);
2397
2398 return NO_ERROR;
2399}
2400
2401size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2402{
2403 int session = chain->sessionId();
2404
2405 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2406
2407 for (size_t i = 0; i < mEffectChains.size(); i++) {
2408 if (chain == mEffectChains[i]) {
2409 mEffectChains.removeAt(i);
2410 // detach all active tracks from the chain
2411 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2412 sp<Track> track = mActiveTracks[i].promote();
2413 if (track == 0) {
2414 continue;
2415 }
2416 if (session == track->sessionId()) {
2417 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2418 chain.get(), session);
2419 chain->decActiveTrackCnt();
2420 }
2421 }
2422
2423 // detach all tracks with same session ID from this chain
2424 for (size_t i = 0; i < mTracks.size(); ++i) {
2425 sp<Track> track = mTracks[i];
2426 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002427 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002428 chain->decTrackCnt();
2429 }
2430 }
2431 break;
2432 }
2433 }
2434 return mEffectChains.size();
2435}
2436
2437status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2438 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2439{
2440 Mutex::Autolock _l(mLock);
2441 return attachAuxEffect_l(track, EffectId);
2442}
2443
2444status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2445 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2446{
2447 status_t status = NO_ERROR;
2448
2449 if (EffectId == 0) {
2450 track->setAuxBuffer(0, NULL);
2451 } else {
2452 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2453 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2454 if (effect != 0) {
2455 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2456 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2457 } else {
2458 status = INVALID_OPERATION;
2459 }
2460 } else {
2461 status = BAD_VALUE;
2462 }
2463 }
2464 return status;
2465}
2466
2467void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2468{
2469 for (size_t i = 0; i < mTracks.size(); ++i) {
2470 sp<Track> track = mTracks[i];
2471 if (track->auxEffectId() == effectId) {
2472 attachAuxEffect_l(track, 0);
2473 }
2474 }
2475}
2476
2477bool AudioFlinger::PlaybackThread::threadLoop()
2478{
2479 Vector< sp<Track> > tracksToRemove;
2480
2481 standbyTime = systemTime();
2482
2483 // MIXER
2484 nsecs_t lastWarning = 0;
2485
2486 // DUPLICATING
2487 // FIXME could this be made local to while loop?
2488 writeFrames = 0;
2489
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002490 int lastGeneration = 0;
2491
Eric Laurent81784c32012-11-19 14:55:58 -08002492 cacheParameters_l();
2493 sleepTime = idleSleepTime;
2494
2495 if (mType == MIXER) {
2496 sleepTimeShift = 0;
2497 }
2498
2499 CpuStats cpuStats;
2500 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2501
2502 acquireWakeLock();
2503
Glenn Kasten9e58b552013-01-18 15:09:48 -08002504 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2505 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2506 // and then that string will be logged at the next convenient opportunity.
2507 const char *logString = NULL;
2508
Eric Laurent664539d2013-09-23 18:24:31 -07002509 checkSilentMode_l();
2510
Eric Laurent81784c32012-11-19 14:55:58 -08002511 while (!exitPending())
2512 {
2513 cpuStats.sample(myName);
2514
2515 Vector< sp<EffectChain> > effectChains;
2516
Eric Laurent81784c32012-11-19 14:55:58 -08002517 { // scope for mLock
2518
2519 Mutex::Autolock _l(mLock);
2520
Eric Laurent021cf962014-05-13 10:18:14 -07002521 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002522
Glenn Kasten9e58b552013-01-18 15:09:48 -08002523 if (logString != NULL) {
2524 mNBLogWriter->logTimestamp();
2525 mNBLogWriter->log(logString);
2526 logString = NULL;
2527 }
2528
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002529 // Gather the framesReleased counters for all active tracks,
2530 // and latch them atomically with the timestamp.
2531 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2532 mLatchD.mFramesReleased.clear();
2533 size_t size = mActiveTracks.size();
2534 for (size_t i = 0; i < size; i++) {
2535 sp<Track> t = mActiveTracks[i].promote();
2536 if (t != 0) {
2537 mLatchD.mFramesReleased.add(t.get(),
2538 t->mAudioTrackServerProxy->framesReleased());
2539 }
2540 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002541 if (mLatchDValid) {
2542 mLatchQ = mLatchD;
2543 mLatchDValid = false;
2544 mLatchQValid = true;
2545 }
2546
Eric Laurent81784c32012-11-19 14:55:58 -08002547 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002548 if (mSignalPending) {
2549 // A signal was raised while we were unlocked
2550 mSignalPending = false;
2551 } else if (waitingAsyncCallback_l()) {
2552 if (exitPending()) {
2553 break;
2554 }
2555 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002556 mWakeLockUids.clear();
2557 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558 ALOGV("wait async completion");
2559 mWaitWorkCV.wait(mLock);
2560 ALOGV("async completion/wake");
2561 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002562 standbyTime = systemTime() + standbyDelay;
2563 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002564
2565 continue;
2566 }
2567 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 isSuspended()) {
2569 // put audio hardware into standby after short delay
2570 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002571
2572 threadLoop_standby();
2573
2574 mStandby = true;
2575 }
2576
2577 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2578 // we're about to wait, flush the binder command buffer
2579 IPCThreadState::self()->flushCommands();
2580
2581 clearOutputTracks();
2582
2583 if (exitPending()) {
2584 break;
2585 }
2586
2587 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002588 mWakeLockUids.clear();
2589 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002590 // wait until we have something to do...
2591 ALOGV("%s going to sleep", myName.string());
2592 mWaitWorkCV.wait(mLock);
2593 ALOGV("%s waking up", myName.string());
2594 acquireWakeLock_l();
2595
2596 mMixerStatus = MIXER_IDLE;
2597 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2598 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002600 checkSilentMode_l();
2601
2602 standbyTime = systemTime() + standbyDelay;
2603 sleepTime = idleSleepTime;
2604 if (mType == MIXER) {
2605 sleepTimeShift = 0;
2606 }
2607
2608 continue;
2609 }
2610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611 // mMixerStatusIgnoringFastTracks is also updated internally
2612 mMixerStatus = prepareTracks_l(&tracksToRemove);
2613
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002614 // compare with previously applied list
2615 if (lastGeneration != mActiveTracksGeneration) {
2616 // update wakelock
2617 updateWakeLockUids_l(mWakeLockUids);
2618 lastGeneration = mActiveTracksGeneration;
2619 }
2620
Eric Laurent81784c32012-11-19 14:55:58 -08002621 // prevent any changes in effect chain list and in each effect chain
2622 // during mixing and effect process as the audio buffers could be deleted
2623 // or modified if an effect is created or deleted
2624 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002625 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002626
Eric Laurentbfb1b832013-01-07 09:53:42 -08002627 if (mBytesRemaining == 0) {
2628 mCurrentWriteLength = 0;
2629 if (mMixerStatus == MIXER_TRACKS_READY) {
2630 // threadLoop_mix() sets mCurrentWriteLength
2631 threadLoop_mix();
2632 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2633 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2634 // threadLoop_sleepTime sets sleepTime to 0 if data
2635 // must be written to HAL
2636 threadLoop_sleepTime();
2637 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002638 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 }
2640 }
Andy Hung98ef9782014-03-04 14:46:50 -08002641 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2642 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2643 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2644 // or mSinkBuffer (if there are no effects).
2645 //
2646 // This is done pre-effects computation; if effects change to
2647 // support higher precision, this needs to move.
2648 //
2649 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2650 // TODO use sleepTime == 0 as an additional condition.
2651 if (mMixerBufferValid) {
2652 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2653 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2654
2655 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2656 mNormalFrameCount * mChannelCount);
2657 }
2658
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 mBytesRemaining = mCurrentWriteLength;
2660 if (isSuspended()) {
2661 sleepTime = suspendSleepTimeUs();
2662 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002663 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 mBytesRemaining = 0;
2665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002668 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 for (size_t i = 0; i < effectChains.size(); i ++) {
2670 effectChains[i]->process_l();
2671 }
Eric Laurent81784c32012-11-19 14:55:58 -08002672 }
2673 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002674 // Process effect chains for offloaded thread even if no audio
2675 // was read from audio track: process only updates effect state
2676 // and thus does have to be synchronized with audio writes but may have
2677 // to be called while waiting for async write callback
2678 if (mType == OFFLOAD) {
2679 for (size_t i = 0; i < effectChains.size(); i ++) {
2680 effectChains[i]->process_l();
2681 }
2682 }
Eric Laurent81784c32012-11-19 14:55:58 -08002683
Andy Hung98ef9782014-03-04 14:46:50 -08002684 // Only if the Effects buffer is enabled and there is data in the
2685 // Effects buffer (buffer valid), we need to
2686 // copy into the sink buffer.
2687 // TODO use sleepTime == 0 as an additional condition.
2688 if (mEffectBufferValid) {
2689 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2690 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2691 mNormalFrameCount * mChannelCount);
2692 }
2693
Eric Laurent81784c32012-11-19 14:55:58 -08002694 // enable changes in effect chain
2695 unlockEffectChains(effectChains);
2696
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697 if (!waitingAsyncCallback()) {
2698 // sleepTime == 0 means we must write to audio hardware
2699 if (sleepTime == 0) {
2700 if (mBytesRemaining) {
2701 ssize_t ret = threadLoop_write();
2702 if (ret < 0) {
2703 mBytesRemaining = 0;
2704 } else {
2705 mBytesWritten += ret;
2706 mBytesRemaining -= ret;
2707 }
2708 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2709 (mMixerStatus == MIXER_DRAIN_ALL)) {
2710 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002711 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002712 if (mType == MIXER) {
2713 // write blocked detection
2714 nsecs_t now = systemTime();
2715 nsecs_t delta = now - mLastWriteTime;
2716 if (!mStandby && delta > maxPeriod) {
2717 mNumDelayedWrites++;
2718 if ((now - lastWarning) > kWarningThrottleNs) {
2719 ATRACE_NAME("underrun");
2720 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2721 ns2ms(delta), mNumDelayedWrites, this);
2722 lastWarning = now;
2723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724 }
2725 }
Eric Laurent81784c32012-11-19 14:55:58 -08002726
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002728 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002730 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 }
Eric Laurent81784c32012-11-19 14:55:58 -08002732 }
2733
2734 // Finally let go of removed track(s), without the lock held
2735 // since we can't guarantee the destructors won't acquire that
2736 // same lock. This will also mutate and push a new fast mixer state.
2737 threadLoop_removeTracks(tracksToRemove);
2738 tracksToRemove.clear();
2739
2740 // FIXME I don't understand the need for this here;
2741 // it was in the original code but maybe the
2742 // assignment in saveOutputTracks() makes this unnecessary?
2743 clearOutputTracks();
2744
2745 // Effect chains will be actually deleted here if they were removed from
2746 // mEffectChains list during mixing or effects processing
2747 effectChains.clear();
2748
2749 // FIXME Note that the above .clear() is no longer necessary since effectChains
2750 // is now local to this block, but will keep it for now (at least until merge done).
2751 }
2752
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 threadLoop_exit();
2754
Eric Laurentcf817a22014-08-04 20:36:31 -07002755 if (!mStandby) {
2756 threadLoop_standby();
2757 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 }
2759
2760 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002761 mWakeLockUids.clear();
2762 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002763
2764 ALOGV("Thread %p type %d exiting", this, mType);
2765 return false;
2766}
2767
Eric Laurentbfb1b832013-01-07 09:53:42 -08002768// removeTracks_l() must be called with ThreadBase::mLock held
2769void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2770{
2771 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002772 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002773 for (size_t i=0 ; i<count ; i++) {
2774 const sp<Track>& track = tracksToRemove.itemAt(i);
2775 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002776 mWakeLockUids.remove(track->uid());
2777 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2779 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2780 if (chain != 0) {
2781 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2782 track->sessionId());
2783 chain->decActiveTrackCnt();
2784 }
2785 if (track->isTerminated()) {
2786 removeTrack_l(track);
2787 }
2788 }
2789 }
2790
2791}
Eric Laurent81784c32012-11-19 14:55:58 -08002792
Eric Laurentaccc1472013-09-20 09:36:34 -07002793status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2794{
2795 if (mNormalSink != 0) {
2796 return mNormalSink->getTimestamp(timestamp);
2797 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002798 if ((mType == OFFLOAD || mType == DIRECT)
2799 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002800 uint64_t position64;
2801 int ret = mOutput->stream->get_presentation_position(
2802 mOutput->stream, &position64, &timestamp.mTime);
2803 if (ret == 0) {
2804 timestamp.mPosition = (uint32_t)position64;
2805 return NO_ERROR;
2806 }
2807 }
2808 return INVALID_OPERATION;
2809}
Eric Laurent1c333e22014-05-20 10:48:17 -07002810
2811status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2812 audio_patch_handle_t *handle)
2813{
2814 status_t status = NO_ERROR;
2815 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2816 // store new device and send to effects
2817 audio_devices_t type = AUDIO_DEVICE_NONE;
2818 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2819 type |= patch->sinks[i].ext.device.type;
2820 }
2821 mOutDevice = type;
2822 for (size_t i = 0; i < mEffectChains.size(); i++) {
2823 mEffectChains[i]->setDevice_l(mOutDevice);
2824 }
2825
2826 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2827 status = hwDevice->create_audio_patch(hwDevice,
2828 patch->num_sources,
2829 patch->sources,
2830 patch->num_sinks,
2831 patch->sinks,
2832 handle);
2833 } else {
2834 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2835 }
2836 return status;
2837}
2838
2839status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2840{
2841 status_t status = NO_ERROR;
2842 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2843 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2844 status = hwDevice->release_audio_patch(hwDevice, handle);
2845 } else {
2846 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2847 }
2848 return status;
2849}
2850
Eric Laurent83b88082014-06-20 18:31:16 -07002851void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2852{
2853 Mutex::Autolock _l(mLock);
2854 mTracks.add(track);
2855}
2856
2857void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2858{
2859 Mutex::Autolock _l(mLock);
2860 destroyTrack_l(track);
2861}
2862
2863void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2864{
2865 ThreadBase::getAudioPortConfig(config);
2866 config->role = AUDIO_PORT_ROLE_SOURCE;
2867 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2868 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2869}
2870
Eric Laurent81784c32012-11-19 14:55:58 -08002871// ----------------------------------------------------------------------------
2872
2873AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2874 audio_io_handle_t id, audio_devices_t device, type_t type)
2875 : PlaybackThread(audioFlinger, output, id, device, type),
2876 // mAudioMixer below
2877 // mFastMixer below
2878 mFastMixerFutex(0)
2879 // mOutputSink below
2880 // mPipeSink below
2881 // mNormalSink below
2882{
2883 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002884 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002885 "mFrameCount=%d, mNormalFrameCount=%d",
2886 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2887 mNormalFrameCount);
2888 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2889
Andy Hungfbfc3952015-01-15 13:33:51 -08002890 if (type == DUPLICATING) {
2891 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2892 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2893 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2894 return;
2895 }
Eric Laurent81784c32012-11-19 14:55:58 -08002896 // create an NBAIO sink for the HAL output stream, and negotiate
2897 mOutputSink = new AudioStreamOutSink(output->stream);
2898 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002899 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002900 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2901 ALOG_ASSERT(index == 0);
2902
2903 // initialize fast mixer depending on configuration
2904 bool initFastMixer;
2905 switch (kUseFastMixer) {
2906 case FastMixer_Never:
2907 initFastMixer = false;
2908 break;
2909 case FastMixer_Always:
2910 initFastMixer = true;
2911 break;
2912 case FastMixer_Static:
2913 case FastMixer_Dynamic:
2914 initFastMixer = mFrameCount < mNormalFrameCount;
2915 break;
2916 }
2917 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002918 audio_format_t fastMixerFormat;
2919 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2920 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2921 } else {
2922 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2923 }
2924 if (mFormat != fastMixerFormat) {
2925 // change our Sink format to accept our intermediate precision
2926 mFormat = fastMixerFormat;
2927 free(mSinkBuffer);
2928 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2929 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2930 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2931 }
Eric Laurent81784c32012-11-19 14:55:58 -08002932
2933 // create a MonoPipe to connect our submix to FastMixer
2934 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002935 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002936 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002937 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002938 format.mFormat = fastMixerFormat;
2939 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2940
Eric Laurent81784c32012-11-19 14:55:58 -08002941 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2942 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2943 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2944 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2945 const NBAIO_Format offers[1] = {format};
2946 size_t numCounterOffers = 0;
2947 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2948 ALOG_ASSERT(index == 0);
2949 monoPipe->setAvgFrames((mScreenState & 1) ?
2950 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2951 mPipeSink = monoPipe;
2952
Glenn Kasten46909e72013-02-26 09:20:22 -08002953#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002954 if (mTeeSinkOutputEnabled) {
2955 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002956 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2957 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002958 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002959 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002960 ALOG_ASSERT(index == 0);
2961 mTeeSink = teeSink;
2962 PipeReader *teeSource = new PipeReader(*teeSink);
2963 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002964 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002965 ALOG_ASSERT(index == 0);
2966 mTeeSource = teeSource;
2967 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002968#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002969
2970 // create fast mixer and configure it initially with just one fast track for our submix
2971 mFastMixer = new FastMixer();
2972 FastMixerStateQueue *sq = mFastMixer->sq();
2973#ifdef STATE_QUEUE_DUMP
2974 sq->setObserverDump(&mStateQueueObserverDump);
2975 sq->setMutatorDump(&mStateQueueMutatorDump);
2976#endif
2977 FastMixerState *state = sq->begin();
2978 FastTrack *fastTrack = &state->mFastTracks[0];
2979 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2980 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2981 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002982 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2983 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002984 fastTrack->mGeneration++;
2985 state->mFastTracksGen++;
2986 state->mTrackMask = 1;
2987 // fast mixer will use the HAL output sink
2988 state->mOutputSink = mOutputSink.get();
2989 state->mOutputSinkGen++;
2990 state->mFrameCount = mFrameCount;
2991 state->mCommand = FastMixerState::COLD_IDLE;
2992 // already done in constructor initialization list
2993 //mFastMixerFutex = 0;
2994 state->mColdFutexAddr = &mFastMixerFutex;
2995 state->mColdGen++;
2996 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002997#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002998 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002999#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003000 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3001 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003002 sq->end();
3003 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3004
3005 // start the fast mixer
3006 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3007 pid_t tid = mFastMixer->getTid();
3008 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3009 if (err != 0) {
3010 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3011 kPriorityFastMixer, getpid_cached, tid, err);
3012 }
3013
3014#ifdef AUDIO_WATCHDOG
3015 // create and start the watchdog
3016 mAudioWatchdog = new AudioWatchdog();
3017 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3018 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3019 tid = mAudioWatchdog->getTid();
3020 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3021 if (err != 0) {
3022 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3023 kPriorityFastMixer, getpid_cached, tid, err);
3024 }
3025#endif
3026
Eric Laurent81784c32012-11-19 14:55:58 -08003027 }
3028
3029 switch (kUseFastMixer) {
3030 case FastMixer_Never:
3031 case FastMixer_Dynamic:
3032 mNormalSink = mOutputSink;
3033 break;
3034 case FastMixer_Always:
3035 mNormalSink = mPipeSink;
3036 break;
3037 case FastMixer_Static:
3038 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3039 break;
3040 }
3041}
3042
3043AudioFlinger::MixerThread::~MixerThread()
3044{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003045 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003046 FastMixerStateQueue *sq = mFastMixer->sq();
3047 FastMixerState *state = sq->begin();
3048 if (state->mCommand == FastMixerState::COLD_IDLE) {
3049 int32_t old = android_atomic_inc(&mFastMixerFutex);
3050 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003051 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003052 }
3053 }
3054 state->mCommand = FastMixerState::EXIT;
3055 sq->end();
3056 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3057 mFastMixer->join();
3058 // Though the fast mixer thread has exited, it's state queue is still valid.
3059 // We'll use that extract the final state which contains one remaining fast track
3060 // corresponding to our sub-mix.
3061 state = sq->begin();
3062 ALOG_ASSERT(state->mTrackMask == 1);
3063 FastTrack *fastTrack = &state->mFastTracks[0];
3064 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3065 delete fastTrack->mBufferProvider;
3066 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003067 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003068#ifdef AUDIO_WATCHDOG
3069 if (mAudioWatchdog != 0) {
3070 mAudioWatchdog->requestExit();
3071 mAudioWatchdog->requestExitAndWait();
3072 mAudioWatchdog.clear();
3073 }
3074#endif
3075 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003076 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003077 delete mAudioMixer;
3078}
3079
3080
3081uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3082{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003083 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003084 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3085 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3086 }
3087 return latency;
3088}
3089
3090
3091void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3092{
3093 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3094}
3095
Eric Laurentbfb1b832013-01-07 09:53:42 -08003096ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003097{
3098 // FIXME we should only do one push per cycle; confirm this is true
3099 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003100 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003101 FastMixerStateQueue *sq = mFastMixer->sq();
3102 FastMixerState *state = sq->begin();
3103 if (state->mCommand != FastMixerState::MIX_WRITE &&
3104 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3105 if (state->mCommand == FastMixerState::COLD_IDLE) {
3106 int32_t old = android_atomic_inc(&mFastMixerFutex);
3107 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003108 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003109 }
3110#ifdef AUDIO_WATCHDOG
3111 if (mAudioWatchdog != 0) {
3112 mAudioWatchdog->resume();
3113 }
3114#endif
3115 }
3116 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003117 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3118 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003119 sq->end();
3120 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3121 if (kUseFastMixer == FastMixer_Dynamic) {
3122 mNormalSink = mPipeSink;
3123 }
3124 } else {
3125 sq->end(false /*didModify*/);
3126 }
3127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003129}
3130
3131void AudioFlinger::MixerThread::threadLoop_standby()
3132{
3133 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003134 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003135 FastMixerStateQueue *sq = mFastMixer->sq();
3136 FastMixerState *state = sq->begin();
3137 if (!(state->mCommand & FastMixerState::IDLE)) {
3138 state->mCommand = FastMixerState::COLD_IDLE;
3139 state->mColdFutexAddr = &mFastMixerFutex;
3140 state->mColdGen++;
3141 mFastMixerFutex = 0;
3142 sq->end();
3143 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3144 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3145 if (kUseFastMixer == FastMixer_Dynamic) {
3146 mNormalSink = mOutputSink;
3147 }
3148#ifdef AUDIO_WATCHDOG
3149 if (mAudioWatchdog != 0) {
3150 mAudioWatchdog->pause();
3151 }
3152#endif
3153 } else {
3154 sq->end(false /*didModify*/);
3155 }
3156 }
3157 PlaybackThread::threadLoop_standby();
3158}
3159
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3161{
3162 return false;
3163}
3164
3165bool AudioFlinger::PlaybackThread::shouldStandby_l()
3166{
3167 return !mStandby;
3168}
3169
3170bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3171{
3172 Mutex::Autolock _l(mLock);
3173 return waitingAsyncCallback_l();
3174}
3175
Eric Laurent81784c32012-11-19 14:55:58 -08003176// shared by MIXER and DIRECT, overridden by DUPLICATING
3177void AudioFlinger::PlaybackThread::threadLoop_standby()
3178{
3179 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3180 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003182 // discard any pending drain or write ack by incrementing sequence
3183 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3184 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003186 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3187 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003189 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003190}
3191
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003192void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3193{
3194 ALOGV("signal playback thread");
3195 broadcast_l();
3196}
3197
Eric Laurent81784c32012-11-19 14:55:58 -08003198void AudioFlinger::MixerThread::threadLoop_mix()
3199{
3200 // obtain the presentation timestamp of the next output buffer
3201 int64_t pts;
3202 status_t status = INVALID_OPERATION;
3203
3204 if (mNormalSink != 0) {
3205 status = mNormalSink->getNextWriteTimestamp(&pts);
3206 } else {
3207 status = mOutputSink->getNextWriteTimestamp(&pts);
3208 }
3209
3210 if (status != NO_ERROR) {
3211 pts = AudioBufferProvider::kInvalidPTS;
3212 }
3213
3214 // mix buffers...
3215 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003216 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003217 // increase sleep time progressively when application underrun condition clears.
3218 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3219 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3220 // such that we would underrun the audio HAL.
3221 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3222 sleepTimeShift--;
3223 }
3224 sleepTime = 0;
3225 standbyTime = systemTime() + standbyDelay;
3226 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003227
Eric Laurent81784c32012-11-19 14:55:58 -08003228}
3229
3230void AudioFlinger::MixerThread::threadLoop_sleepTime()
3231{
3232 // If no tracks are ready, sleep once for the duration of an output
3233 // buffer size, then write 0s to the output
3234 if (sleepTime == 0) {
3235 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3236 sleepTime = activeSleepTime >> sleepTimeShift;
3237 if (sleepTime < kMinThreadSleepTimeUs) {
3238 sleepTime = kMinThreadSleepTimeUs;
3239 }
3240 // reduce sleep time in case of consecutive application underruns to avoid
3241 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3242 // duration we would end up writing less data than needed by the audio HAL if
3243 // the condition persists.
3244 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3245 sleepTimeShift++;
3246 }
3247 } else {
3248 sleepTime = idleSleepTime;
3249 }
3250 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003251 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3252 // before effects processing or output.
3253 if (mMixerBufferValid) {
3254 memset(mMixerBuffer, 0, mMixerBufferSize);
3255 } else {
3256 memset(mSinkBuffer, 0, mSinkBufferSize);
3257 }
Eric Laurent81784c32012-11-19 14:55:58 -08003258 sleepTime = 0;
3259 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3260 "anticipated start");
3261 }
3262 // TODO add standby time extension fct of effect tail
3263}
3264
3265// prepareTracks_l() must be called with ThreadBase::mLock held
3266AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3267 Vector< sp<Track> > *tracksToRemove)
3268{
3269
3270 mixer_state mixerStatus = MIXER_IDLE;
3271 // find out which tracks need to be processed
3272 size_t count = mActiveTracks.size();
3273 size_t mixedTracks = 0;
3274 size_t tracksWithEffect = 0;
3275 // counts only _active_ fast tracks
3276 size_t fastTracks = 0;
3277 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3278
3279 float masterVolume = mMasterVolume;
3280 bool masterMute = mMasterMute;
3281
3282 if (masterMute) {
3283 masterVolume = 0;
3284 }
3285 // Delegate master volume control to effect in output mix effect chain if needed
3286 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3287 if (chain != 0) {
3288 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3289 chain->setVolume_l(&v, &v);
3290 masterVolume = (float)((v + (1 << 23)) >> 24);
3291 chain.clear();
3292 }
3293
3294 // prepare a new state to push
3295 FastMixerStateQueue *sq = NULL;
3296 FastMixerState *state = NULL;
3297 bool didModify = false;
3298 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003299 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003300 sq = mFastMixer->sq();
3301 state = sq->begin();
3302 }
3303
Andy Hung69aed5f2014-02-25 17:24:40 -08003304 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003305 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003306
Eric Laurent81784c32012-11-19 14:55:58 -08003307 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003308 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003309 if (t == 0) {
3310 continue;
3311 }
3312
3313 // this const just means the local variable doesn't change
3314 Track* const track = t.get();
3315
3316 // process fast tracks
3317 if (track->isFastTrack()) {
3318
3319 // It's theoretically possible (though unlikely) for a fast track to be created
3320 // and then removed within the same normal mix cycle. This is not a problem, as
3321 // the track never becomes active so it's fast mixer slot is never touched.
3322 // The converse, of removing an (active) track and then creating a new track
3323 // at the identical fast mixer slot within the same normal mix cycle,
3324 // is impossible because the slot isn't marked available until the end of each cycle.
3325 int j = track->mFastIndex;
3326 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3327 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3328 FastTrack *fastTrack = &state->mFastTracks[j];
3329
3330 // Determine whether the track is currently in underrun condition,
3331 // and whether it had a recent underrun.
3332 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3333 FastTrackUnderruns underruns = ftDump->mUnderruns;
3334 uint32_t recentFull = (underruns.mBitFields.mFull -
3335 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3336 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3337 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3338 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3339 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3340 uint32_t recentUnderruns = recentPartial + recentEmpty;
3341 track->mObservedUnderruns = underruns;
3342 // don't count underruns that occur while stopping or pausing
3343 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003344 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3345 recentUnderruns > 0) {
3346 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3347 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003348 }
3349
3350 // This is similar to the state machine for normal tracks,
3351 // with a few modifications for fast tracks.
3352 bool isActive = true;
3353 switch (track->mState) {
3354 case TrackBase::STOPPING_1:
3355 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003357 track->mState = TrackBase::STOPPING_2;
3358 }
3359 break;
3360 case TrackBase::PAUSING:
3361 // ramp down is not yet implemented
3362 track->setPaused();
3363 break;
3364 case TrackBase::RESUMING:
3365 // ramp up is not yet implemented
3366 track->mState = TrackBase::ACTIVE;
3367 break;
3368 case TrackBase::ACTIVE:
3369 if (recentFull > 0 || recentPartial > 0) {
3370 // track has provided at least some frames recently: reset retry count
3371 track->mRetryCount = kMaxTrackRetries;
3372 }
3373 if (recentUnderruns == 0) {
3374 // no recent underruns: stay active
3375 break;
3376 }
3377 // there has recently been an underrun of some kind
3378 if (track->sharedBuffer() == 0) {
3379 // were any of the recent underruns "empty" (no frames available)?
3380 if (recentEmpty == 0) {
3381 // no, then ignore the partial underruns as they are allowed indefinitely
3382 break;
3383 }
3384 // there has recently been an "empty" underrun: decrement the retry counter
3385 if (--(track->mRetryCount) > 0) {
3386 break;
3387 }
3388 // indicate to client process that the track was disabled because of underrun;
3389 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003390 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003391 // remove from active list, but state remains ACTIVE [confusing but true]
3392 isActive = false;
3393 break;
3394 }
3395 // fall through
3396 case TrackBase::STOPPING_2:
3397 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003398 case TrackBase::STOPPED:
3399 case TrackBase::FLUSHED: // flush() while active
3400 // Check for presentation complete if track is inactive
3401 // We have consumed all the buffers of this track.
3402 // This would be incomplete if we auto-paused on underrun
3403 {
3404 size_t audioHALFrames =
3405 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3406 size_t framesWritten = mBytesWritten / mFrameSize;
3407 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3408 // track stays in active list until presentation is complete
3409 break;
3410 }
3411 }
3412 if (track->isStopping_2()) {
3413 track->mState = TrackBase::STOPPED;
3414 }
3415 if (track->isStopped()) {
3416 // Can't reset directly, as fast mixer is still polling this track
3417 // track->reset();
3418 // So instead mark this track as needing to be reset after push with ack
3419 resetMask |= 1 << i;
3420 }
3421 isActive = false;
3422 break;
3423 case TrackBase::IDLE:
3424 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003425 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003426 }
3427
3428 if (isActive) {
3429 // was it previously inactive?
3430 if (!(state->mTrackMask & (1 << j))) {
3431 ExtendedAudioBufferProvider *eabp = track;
3432 VolumeProvider *vp = track;
3433 fastTrack->mBufferProvider = eabp;
3434 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003435 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003436 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003437 fastTrack->mGeneration++;
3438 state->mTrackMask |= 1 << j;
3439 didModify = true;
3440 // no acknowledgement required for newly active tracks
3441 }
3442 // cache the combined master volume and stream type volume for fast mixer; this
3443 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003444 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003445 ++fastTracks;
3446 } else {
3447 // was it previously active?
3448 if (state->mTrackMask & (1 << j)) {
3449 fastTrack->mBufferProvider = NULL;
3450 fastTrack->mGeneration++;
3451 state->mTrackMask &= ~(1 << j);
3452 didModify = true;
3453 // If any fast tracks were removed, we must wait for acknowledgement
3454 // because we're about to decrement the last sp<> on those tracks.
3455 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3456 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003457 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 }
3459 tracksToRemove->add(track);
3460 // Avoids a misleading display in dumpsys
3461 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3462 }
3463 continue;
3464 }
3465
3466 { // local variable scope to avoid goto warning
3467
3468 audio_track_cblk_t* cblk = track->cblk();
3469
3470 // The first time a track is added we wait
3471 // for all its buffers to be filled before processing it
3472 int name = track->name();
3473 // make sure that we have enough frames to mix one full buffer.
3474 // enforce this condition only once to enable draining the buffer in case the client
3475 // app does not call stop() and relies on underrun to stop:
3476 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3477 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003478 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003479 uint32_t sr = track->sampleRate();
3480 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003481 desiredFrames = mNormalFrameCount;
3482 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003483 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003484 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003485 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003486 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003487#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003488 // the minimum track buffer size is normally twice the number of frames necessary
3489 // to fill one buffer and the resampler should not leave more than one buffer worth
3490 // of unreleased frames after each pass, but just in case...
3491 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003492#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003493 }
Eric Laurent81784c32012-11-19 14:55:58 -08003494 uint32_t minFrames = 1;
3495 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3496 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003497 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003498 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003499
3500 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003501 if (ATRACE_ENABLED()) {
3502 // I wish we had formatted trace names
3503 char traceName[16];
3504 strcpy(traceName, "nRdy");
3505 int name = track->name();
3506 if (AudioMixer::TRACK0 <= name &&
3507 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3508 name -= AudioMixer::TRACK0;
3509 traceName[4] = (name / 10) + '0';
3510 traceName[5] = (name % 10) + '0';
3511 } else {
3512 traceName[4] = '?';
3513 traceName[5] = '?';
3514 }
3515 traceName[6] = '\0';
3516 ATRACE_INT(traceName, framesReady);
3517 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003518 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003519 !track->isPaused() && !track->isTerminated())
3520 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003521 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003522
3523 mixedTracks++;
3524
Andy Hung69aed5f2014-02-25 17:24:40 -08003525 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3526 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003527 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003528 if (track->mainBuffer() != mSinkBuffer &&
3529 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003530 if (mEffectBufferEnabled) {
3531 mEffectBufferValid = true; // Later can set directly.
3532 }
Eric Laurent81784c32012-11-19 14:55:58 -08003533 chain = getEffectChain_l(track->sessionId());
3534 // Delegate volume control to effect in track effect chain if needed
3535 if (chain != 0) {
3536 tracksWithEffect++;
3537 } else {
3538 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3539 "session %d",
3540 name, track->sessionId());
3541 }
3542 }
3543
3544
3545 int param = AudioMixer::VOLUME;
3546 if (track->mFillingUpStatus == Track::FS_FILLED) {
3547 // no ramp for the first volume setting
3548 track->mFillingUpStatus = Track::FS_ACTIVE;
3549 if (track->mState == TrackBase::RESUMING) {
3550 track->mState = TrackBase::ACTIVE;
3551 param = AudioMixer::RAMP_VOLUME;
3552 }
3553 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003554 // FIXME should not make a decision based on mServer
3555 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003556 // If the track is stopped before the first frame was mixed,
3557 // do not apply ramp
3558 param = AudioMixer::RAMP_VOLUME;
3559 }
3560
3561 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003562 uint32_t vl, vr; // in U8.24 integer format
3563 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003564 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003565 vl = vr = 0;
3566 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003567 if (track->isPausing()) {
3568 track->setPaused();
3569 }
3570 } else {
3571
3572 // read original volumes with volume control
3573 float typeVolume = mStreamTypes[track->streamType()].volume;
3574 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003575 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003576 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003577 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3578 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003579 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003580 if (vlf > GAIN_FLOAT_UNITY) {
3581 ALOGV("Track left volume out of range: %.3g", vlf);
3582 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003583 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003584 if (vrf > GAIN_FLOAT_UNITY) {
3585 ALOGV("Track right volume out of range: %.3g", vrf);
3586 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003587 }
3588 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003589 vlf *= v;
3590 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003591 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003592 // then derive vl and vr as U8.24 versions for the effect chain
3593 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3594 vl = (uint32_t) (scaleto8_24 * vlf);
3595 vr = (uint32_t) (scaleto8_24 * vrf);
3596 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003597 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // send level comes from shared memory and so may be corrupt
3599 if (sendLevel > MAX_GAIN_INT) {
3600 ALOGV("Track send level out of range: %04X", sendLevel);
3601 sendLevel = MAX_GAIN_INT;
3602 }
Andy Hung6be49402014-05-30 10:42:03 -07003603 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3604 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606
Eric Laurent81784c32012-11-19 14:55:58 -08003607 // Delegate volume control to effect in track effect chain if needed
3608 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3609 // Do not ramp volume if volume is controlled by effect
3610 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003611 // Update remaining floating point volume levels
3612 vlf = (float)vl / (1 << 24);
3613 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003614 track->mHasVolumeController = true;
3615 } else {
3616 // force no volume ramp when volume controller was just disabled or removed
3617 // from effect chain to avoid volume spike
3618 if (track->mHasVolumeController) {
3619 param = AudioMixer::VOLUME;
3620 }
3621 track->mHasVolumeController = false;
3622 }
3623
Eric Laurent81784c32012-11-19 14:55:58 -08003624 // XXX: these things DON'T need to be done each time
3625 mAudioMixer->setBufferProvider(name, track);
3626 mAudioMixer->enable(name);
3627
Andy Hung6be49402014-05-30 10:42:03 -07003628 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3629 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3630 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003631 mAudioMixer->setParameter(
3632 name,
3633 AudioMixer::TRACK,
3634 AudioMixer::FORMAT, (void *)track->format());
3635 mAudioMixer->setParameter(
3636 name,
3637 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003638 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003639 mAudioMixer->setParameter(
3640 name,
3641 AudioMixer::TRACK,
3642 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003643 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003644 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003645 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003646 if (reqSampleRate == 0) {
3647 reqSampleRate = mSampleRate;
3648 } else if (reqSampleRate > maxSampleRate) {
3649 reqSampleRate = maxSampleRate;
3650 }
Eric Laurent81784c32012-11-19 14:55:58 -08003651 mAudioMixer->setParameter(
3652 name,
3653 AudioMixer::RESAMPLE,
3654 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003655 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003656 /*
3657 * Select the appropriate output buffer for the track.
3658 *
Andy Hung98ef9782014-03-04 14:46:50 -08003659 * Tracks with effects go into their own effects chain buffer
3660 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003661 *
3662 * Other tracks can use mMixerBuffer for higher precision
3663 * channel accumulation. If this buffer is enabled
3664 * (mMixerBufferEnabled true), then selected tracks will accumulate
3665 * into it.
3666 *
3667 */
3668 if (mMixerBufferEnabled
3669 && (track->mainBuffer() == mSinkBuffer
3670 || track->mainBuffer() == mMixerBuffer)) {
3671 mAudioMixer->setParameter(
3672 name,
3673 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003674 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003675 mAudioMixer->setParameter(
3676 name,
3677 AudioMixer::TRACK,
3678 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3679 // TODO: override track->mainBuffer()?
3680 mMixerBufferValid = true;
3681 } else {
3682 mAudioMixer->setParameter(
3683 name,
3684 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003685 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003686 mAudioMixer->setParameter(
3687 name,
3688 AudioMixer::TRACK,
3689 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3690 }
Eric Laurent81784c32012-11-19 14:55:58 -08003691 mAudioMixer->setParameter(
3692 name,
3693 AudioMixer::TRACK,
3694 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3695
3696 // reset retry count
3697 track->mRetryCount = kMaxTrackRetries;
3698
3699 // If one track is ready, set the mixer ready if:
3700 // - the mixer was not ready during previous round OR
3701 // - no other track is not ready
3702 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3703 mixerStatus != MIXER_TRACKS_ENABLED) {
3704 mixerStatus = MIXER_TRACKS_READY;
3705 }
3706 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003707 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003708 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003709 }
Eric Laurent81784c32012-11-19 14:55:58 -08003710 // clear effect chain input buffer if an active track underruns to avoid sending
3711 // previous audio buffer again to effects
3712 chain = getEffectChain_l(track->sessionId());
3713 if (chain != 0) {
3714 chain->clearInputBuffer();
3715 }
3716
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003717 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003718 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3719 track->isStopped() || track->isPaused()) {
3720 // We have consumed all the buffers of this track.
3721 // Remove it from the list of active tracks.
3722 // TODO: use actual buffer filling status instead of latency when available from
3723 // audio HAL
3724 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3725 size_t framesWritten = mBytesWritten / mFrameSize;
3726 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3727 if (track->isStopped()) {
3728 track->reset();
3729 }
3730 tracksToRemove->add(track);
3731 }
3732 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003733 // No buffers for this track. Give it a few chances to
3734 // fill a buffer, then remove it from active list.
3735 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003736 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003737 tracksToRemove->add(track);
3738 // indicate to client process that the track was disabled because of underrun;
3739 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003740 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003741 // If one track is not ready, mark the mixer also not ready if:
3742 // - the mixer was ready during previous round OR
3743 // - no other track is ready
3744 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3745 mixerStatus != MIXER_TRACKS_READY) {
3746 mixerStatus = MIXER_TRACKS_ENABLED;
3747 }
3748 }
3749 mAudioMixer->disable(name);
3750 }
3751
3752 } // local variable scope to avoid goto warning
3753track_is_ready: ;
3754
3755 }
3756
3757 // Push the new FastMixer state if necessary
3758 bool pauseAudioWatchdog = false;
3759 if (didModify) {
3760 state->mFastTracksGen++;
3761 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3762 if (kUseFastMixer == FastMixer_Dynamic &&
3763 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3764 state->mCommand = FastMixerState::COLD_IDLE;
3765 state->mColdFutexAddr = &mFastMixerFutex;
3766 state->mColdGen++;
3767 mFastMixerFutex = 0;
3768 if (kUseFastMixer == FastMixer_Dynamic) {
3769 mNormalSink = mOutputSink;
3770 }
3771 // If we go into cold idle, need to wait for acknowledgement
3772 // so that fast mixer stops doing I/O.
3773 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3774 pauseAudioWatchdog = true;
3775 }
Eric Laurent81784c32012-11-19 14:55:58 -08003776 }
3777 if (sq != NULL) {
3778 sq->end(didModify);
3779 sq->push(block);
3780 }
3781#ifdef AUDIO_WATCHDOG
3782 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3783 mAudioWatchdog->pause();
3784 }
3785#endif
3786
3787 // Now perform the deferred reset on fast tracks that have stopped
3788 while (resetMask != 0) {
3789 size_t i = __builtin_ctz(resetMask);
3790 ALOG_ASSERT(i < count);
3791 resetMask &= ~(1 << i);
3792 sp<Track> t = mActiveTracks[i].promote();
3793 if (t == 0) {
3794 continue;
3795 }
3796 Track* track = t.get();
3797 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3798 track->reset();
3799 }
3800
3801 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003803
Eric Laurent97d547d2014-09-02 14:45:53 -07003804 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3805 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003806 }
3807
3808 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003809 // as long as there are effects we should clear the effects buffer, to avoid
3810 // passing a non-clean buffer to the effect chain
3811 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003812 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003813 // sink or mix buffer must be cleared if all tracks are connected to an
3814 // effect chain as in this case the mixer will not write to the sink or mix buffer
3815 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003816 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3817 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003818 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003819 if (mMixerBufferValid) {
3820 memset(mMixerBuffer, 0, mMixerBufferSize);
3821 // TODO: In testing, mSinkBuffer below need not be cleared because
3822 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3823 // after mixing.
3824 //
3825 // To enforce this guarantee:
3826 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3827 // (mixedTracks == 0 && fastTracks > 0))
3828 // must imply MIXER_TRACKS_READY.
3829 // Later, we may clear buffers regardless, and skip much of this logic.
3830 }
Andy Hung98ef9782014-03-04 14:46:50 -08003831 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003832 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003833 }
3834
3835 // if any fast tracks, then status is ready
3836 mMixerStatusIgnoringFastTracks = mixerStatus;
3837 if (fastTracks > 0) {
3838 mixerStatus = MIXER_TRACKS_READY;
3839 }
3840 return mixerStatus;
3841}
3842
3843// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003844int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3845 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003846{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003847 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003848}
3849
3850// deleteTrackName_l() must be called with ThreadBase::mLock held
3851void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3852{
3853 ALOGV("remove track (%d) and delete from mixer", name);
3854 mAudioMixer->deleteTrackName(name);
3855}
3856
Eric Laurent10351942014-05-08 18:49:52 -07003857// checkForNewParameter_l() must be called with ThreadBase::mLock held
3858bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3859 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003860{
Eric Laurent81784c32012-11-19 14:55:58 -08003861 bool reconfig = false;
3862
Eric Laurent10351942014-05-08 18:49:52 -07003863 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003864
Eric Laurent10351942014-05-08 18:49:52 -07003865 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3866 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003867 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003868 FastMixerStateQueue *sq = mFastMixer->sq();
3869 FastMixerState *state = sq->begin();
3870 if (!(state->mCommand & FastMixerState::IDLE)) {
3871 previousCommand = state->mCommand;
3872 state->mCommand = FastMixerState::HOT_IDLE;
3873 sq->end();
3874 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3875 } else {
3876 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003877 }
Eric Laurent10351942014-05-08 18:49:52 -07003878 }
Eric Laurent81784c32012-11-19 14:55:58 -08003879
Eric Laurent10351942014-05-08 18:49:52 -07003880 AudioParameter param = AudioParameter(keyValuePair);
3881 int value;
3882 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3883 reconfig = true;
3884 }
3885 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003886 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003887 status = BAD_VALUE;
3888 } else {
3889 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003890 reconfig = true;
3891 }
Eric Laurent10351942014-05-08 18:49:52 -07003892 }
3893 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003894 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003895 status = BAD_VALUE;
3896 } else {
3897 // no need to save value, since it's constant
3898 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003899 }
Eric Laurent10351942014-05-08 18:49:52 -07003900 }
3901 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3902 // do not accept frame count changes if tracks are open as the track buffer
3903 // size depends on frame count and correct behavior would not be guaranteed
3904 // if frame count is changed after track creation
3905 if (!mTracks.isEmpty()) {
3906 status = INVALID_OPERATION;
3907 } else {
3908 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003909 }
Eric Laurent10351942014-05-08 18:49:52 -07003910 }
3911 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003912#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003913 // when changing the audio output device, call addBatteryData to notify
3914 // the change
3915 if (mOutDevice != value) {
3916 uint32_t params = 0;
3917 // check whether speaker is on
3918 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3919 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003920 }
Eric Laurent10351942014-05-08 18:49:52 -07003921
3922 audio_devices_t deviceWithoutSpeaker
3923 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3924 // check if any other device (except speaker) is on
3925 if (value & deviceWithoutSpeaker ) {
3926 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3927 }
3928
3929 if (params != 0) {
3930 addBatteryData(params);
3931 }
3932 }
Eric Laurent81784c32012-11-19 14:55:58 -08003933#endif
3934
Eric Laurent10351942014-05-08 18:49:52 -07003935 // forward device change to effects that have requested to be
3936 // aware of attached audio device.
3937 if (value != AUDIO_DEVICE_NONE) {
3938 mOutDevice = value;
3939 for (size_t i = 0; i < mEffectChains.size(); i++) {
3940 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003941 }
3942 }
Eric Laurent10351942014-05-08 18:49:52 -07003943 }
Eric Laurent81784c32012-11-19 14:55:58 -08003944
Eric Laurent10351942014-05-08 18:49:52 -07003945 if (status == NO_ERROR) {
3946 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3947 keyValuePair.string());
3948 if (!mStandby && status == INVALID_OPERATION) {
3949 mOutput->stream->common.standby(&mOutput->stream->common);
3950 mStandby = true;
3951 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003952 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003953 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003954 }
Eric Laurent10351942014-05-08 18:49:52 -07003955 if (status == NO_ERROR && reconfig) {
3956 readOutputParameters_l();
3957 delete mAudioMixer;
3958 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3959 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003960 int name = getTrackName_l(mTracks[i]->mChannelMask,
3961 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003962 if (name < 0) {
3963 break;
3964 }
3965 mTracks[i]->mName = name;
3966 }
3967 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3968 }
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
3970
3971 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003972 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003973 FastMixerStateQueue *sq = mFastMixer->sq();
3974 FastMixerState *state = sq->begin();
3975 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3976 state->mCommand = previousCommand;
3977 sq->end();
3978 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3979 }
3980
3981 return reconfig;
3982}
3983
3984
3985void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3986{
3987 const size_t SIZE = 256;
3988 char buffer[SIZE];
3989 String8 result;
3990
3991 PlaybackThread::dumpInternals(fd, args);
3992
Elliott Hughes87cebad2014-05-22 10:14:43 -07003993 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003994
3995 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003996 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003997 copy.dump(fd);
3998
3999#ifdef STATE_QUEUE_DUMP
4000 // Similar for state queue
4001 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4002 observerCopy.dump(fd);
4003 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4004 mutatorCopy.dump(fd);
4005#endif
4006
Glenn Kasten46909e72013-02-26 09:20:22 -08004007#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004008 // Write the tee output to a .wav file
4009 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004010#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004011
4012#ifdef AUDIO_WATCHDOG
4013 if (mAudioWatchdog != 0) {
4014 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4015 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4016 wdCopy.dump(fd);
4017 }
4018#endif
4019}
4020
4021uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4022{
4023 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4024}
4025
4026uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4027{
4028 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4029}
4030
4031void AudioFlinger::MixerThread::cacheParameters_l()
4032{
4033 PlaybackThread::cacheParameters_l();
4034
4035 // FIXME: Relaxed timing because of a certain device that can't meet latency
4036 // Should be reduced to 2x after the vendor fixes the driver issue
4037 // increase threshold again due to low power audio mode. The way this warning
4038 // threshold is calculated and its usefulness should be reconsidered anyway.
4039 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4040}
4041
4042// ----------------------------------------------------------------------------
4043
4044AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4045 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4046 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4047 // mLeftVolFloat, mRightVolFloat
4048{
4049}
4050
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4052 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4053 ThreadBase::type_t type)
4054 : PlaybackThread(audioFlinger, output, id, device, type)
4055 // mLeftVolFloat, mRightVolFloat
4056{
4057}
4058
Eric Laurent81784c32012-11-19 14:55:58 -08004059AudioFlinger::DirectOutputThread::~DirectOutputThread()
4060{
4061}
4062
Eric Laurentbfb1b832013-01-07 09:53:42 -08004063void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4064{
4065 audio_track_cblk_t* cblk = track->cblk();
4066 float left, right;
4067
4068 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4069 left = right = 0;
4070 } else {
4071 float typeVolume = mStreamTypes[track->streamType()].volume;
4072 float v = mMasterVolume * typeVolume;
4073 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004074 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4075 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4076 if (left > GAIN_FLOAT_UNITY) {
4077 left = GAIN_FLOAT_UNITY;
4078 }
4079 left *= v;
4080 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4081 if (right > GAIN_FLOAT_UNITY) {
4082 right = GAIN_FLOAT_UNITY;
4083 }
4084 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085 }
4086
4087 if (lastTrack) {
4088 if (left != mLeftVolFloat || right != mRightVolFloat) {
4089 mLeftVolFloat = left;
4090 mRightVolFloat = right;
4091
4092 // Convert volumes from float to 8.24
4093 uint32_t vl = (uint32_t)(left * (1 << 24));
4094 uint32_t vr = (uint32_t)(right * (1 << 24));
4095
4096 // Delegate volume control to effect in track effect chain if needed
4097 // only one effect chain can be present on DirectOutputThread, so if
4098 // there is one, the track is connected to it
4099 if (!mEffectChains.isEmpty()) {
4100 mEffectChains[0]->setVolume_l(&vl, &vr);
4101 left = (float)vl / (1 << 24);
4102 right = (float)vr / (1 << 24);
4103 }
4104 if (mOutput->stream->set_volume) {
4105 mOutput->stream->set_volume(mOutput->stream, left, right);
4106 }
4107 }
4108 }
4109}
4110
4111
Eric Laurent81784c32012-11-19 14:55:58 -08004112AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4113 Vector< sp<Track> > *tracksToRemove
4114)
4115{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004116 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004117 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004118 bool doHwPause = false;
4119 bool doHwResume = false;
4120 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004121
4122 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004123 for (size_t i = 0; i < count; i++) {
4124 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004125 // The track died recently
4126 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004127 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004128 }
4129
4130 Track* const track = t.get();
4131 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004132 // Only consider last track started for volume and mixer state control.
4133 // In theory an older track could underrun and restart after the new one starts
4134 // but as we only care about the transition phase between two tracks on a
4135 // direct output, it is not a problem to ignore the underrun case.
4136 sp<Track> l = mLatestActiveTrack.promote();
4137 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004138
Eric Laurentd1f69b02014-12-15 14:33:13 -08004139 if (mHwSupportsPause && track->isPausing()) {
4140 track->setPaused();
4141 if (last && !mHwPaused) {
4142 doHwPause = true;
4143 mHwPaused = true;
4144 }
4145 tracksToRemove->add(track);
4146 } else if (track->isFlushPending()) {
4147 track->flushAck();
4148 if (last) {
4149 flushPending = true;
4150 }
4151 } else if (mHwSupportsPause && track->isResumePending()){
4152 track->resumeAck();
4153 if (last) {
4154 if (mHwPaused) {
4155 doHwResume = true;
4156 mHwPaused = false;
4157 }
4158 }
4159 }
4160
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004162 // for all its buffers to be filled before processing it.
4163 // Allow draining the buffer in case the client
4164 // app does not call stop() and relies on underrun to stop:
4165 // hence the test on (track->mRetryCount > 1).
4166 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004167 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004168 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4169 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004170 minFrames = mNormalFrameCount;
4171 } else {
4172 minFrames = 1;
4173 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174
Eric Laurentab5cdba2014-06-09 17:22:27 -07004175 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4176 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004177 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004178 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004179
4180 if (track->mFillingUpStatus == Track::FS_FILLED) {
4181 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004182 // make sure processVolume_l() will apply new volume even if 0
4183 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004184 if (!mHwSupportsPause) {
4185 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004186 }
4187 }
4188
4189 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190 processVolume_l(track, last);
4191 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004192 // reset retry count
4193 track->mRetryCount = kMaxTrackRetriesDirect;
4194 mActiveTrack = t;
4195 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004196 if (usesHwAvSync() && mHwPaused) {
4197 doHwResume = true;
4198 mHwPaused = false;
4199 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004200 }
Eric Laurent81784c32012-11-19 14:55:58 -08004201 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004202 // clear effect chain input buffer if the last active track started underruns
4203 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004204 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004205 mEffectChains[0]->clearInputBuffer();
4206 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004207 if (track->isStopping_1()) {
4208 track->mState = TrackBase::STOPPING_2;
4209 }
4210 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4211 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004212 // We have consumed all the buffers of this track.
4213 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004214 size_t audioHALFrames;
4215 if (audio_is_linear_pcm(mFormat)) {
4216 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4217 } else {
4218 audioHALFrames = 0;
4219 }
4220
Eric Laurent81784c32012-11-19 14:55:58 -08004221 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004222 if (mStandby || !last ||
4223 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004224 if (track->isStopping_2()) {
4225 track->mState = TrackBase::STOPPED;
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227 if (track->isStopped()) {
4228 track->reset();
4229 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004230 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004231 }
4232 } else {
4233 // No buffers for this track. Give it a few chances to
4234 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004235 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004236 if (--(track->mRetryCount) <= 0) {
4237 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004238 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004239 // indicate to client process that the track was disabled because of underrun;
4240 // it will then automatically call start() when data is available
4241 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004242 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004243 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004244 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4245 doHwPause = true;
4246 mHwPaused = true;
4247 }
Eric Laurent81784c32012-11-19 14:55:58 -08004248 }
4249 }
4250 }
4251 }
4252
Eric Laurentd1f69b02014-12-15 14:33:13 -08004253 // if an active track did not command a flush, check for pending flush on stopped tracks
4254 if (!flushPending) {
4255 for (size_t i = 0; i < mTracks.size(); i++) {
4256 if (mTracks[i]->isFlushPending()) {
4257 mTracks[i]->flushAck();
4258 flushPending = true;
4259 }
4260 }
4261 }
4262
4263 // make sure the pause/flush/resume sequence is executed in the right order.
4264 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4265 // before flush and then resume HW. This can happen in case of pause/flush/resume
4266 // if resume is received before pause is executed.
4267 if (mHwSupportsPause && !mStandby &&
4268 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4269 mOutput->stream->pause(mOutput->stream);
4270 }
4271 if (flushPending) {
4272 flushHw_l();
4273 }
4274 if (mHwSupportsPause && !mStandby && doHwResume) {
4275 mOutput->stream->resume(mOutput->stream);
4276 }
Eric Laurent81784c32012-11-19 14:55:58 -08004277 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004279
4280 return mixerStatus;
4281}
4282
4283void AudioFlinger::DirectOutputThread::threadLoop_mix()
4284{
Eric Laurent81784c32012-11-19 14:55:58 -08004285 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004286 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004287 // output audio to hardware
4288 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004289 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004290 buffer.frameCount = frameCount;
4291 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004292 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004293 memset(curBuf, 0, frameCount * mFrameSize);
4294 break;
4295 }
4296 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4297 frameCount -= buffer.frameCount;
4298 curBuf += buffer.frameCount * mFrameSize;
4299 mActiveTrack->releaseBuffer(&buffer);
4300 }
Andy Hung2098f272014-02-27 14:00:06 -08004301 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004302 sleepTime = 0;
4303 standbyTime = systemTime() + standbyDelay;
4304 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004305}
4306
4307void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4308{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004309 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004310 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004311 sleepTime = idleSleepTime;
4312 return;
4313 }
Eric Laurent81784c32012-11-19 14:55:58 -08004314 if (sleepTime == 0) {
4315 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4316 sleepTime = activeSleepTime;
4317 } else {
4318 sleepTime = idleSleepTime;
4319 }
4320 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004321 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004322 sleepTime = 0;
4323 }
4324}
4325
Eric Laurentd1f69b02014-12-15 14:33:13 -08004326void AudioFlinger::DirectOutputThread::threadLoop_exit()
4327{
4328 {
4329 Mutex::Autolock _l(mLock);
4330 bool flushPending = false;
4331 for (size_t i = 0; i < mTracks.size(); i++) {
4332 if (mTracks[i]->isFlushPending()) {
4333 mTracks[i]->flushAck();
4334 flushPending = true;
4335 }
4336 }
4337 if (flushPending) {
4338 flushHw_l();
4339 }
4340 }
4341 PlaybackThread::threadLoop_exit();
4342}
4343
4344// must be called with thread mutex locked
4345bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4346{
4347 bool trackPaused = false;
4348
4349 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4350 // after a timeout and we will enter standby then.
4351 if (mTracks.size() > 0) {
4352 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4353 }
4354
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004355 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004356}
4357
Eric Laurent81784c32012-11-19 14:55:58 -08004358// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004359int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004360 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004361{
4362 return 0;
4363}
4364
4365// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004366void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004367{
4368}
4369
Eric Laurent10351942014-05-08 18:49:52 -07004370// checkForNewParameter_l() must be called with ThreadBase::mLock held
4371bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4372 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004373{
4374 bool reconfig = false;
4375
Eric Laurent10351942014-05-08 18:49:52 -07004376 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004377
Eric Laurent10351942014-05-08 18:49:52 -07004378 AudioParameter param = AudioParameter(keyValuePair);
4379 int value;
4380 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4381 // forward device change to effects that have requested to be
4382 // aware of attached audio device.
4383 if (value != AUDIO_DEVICE_NONE) {
4384 mOutDevice = value;
4385 for (size_t i = 0; i < mEffectChains.size(); i++) {
4386 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004387 }
4388 }
Eric Laurent81784c32012-11-19 14:55:58 -08004389 }
Eric Laurent10351942014-05-08 18:49:52 -07004390 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4391 // do not accept frame count changes if tracks are open as the track buffer
4392 // size depends on frame count and correct behavior would not be garantied
4393 // if frame count is changed after track creation
4394 if (!mTracks.isEmpty()) {
4395 status = INVALID_OPERATION;
4396 } else {
4397 reconfig = true;
4398 }
4399 }
4400 if (status == NO_ERROR) {
4401 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4402 keyValuePair.string());
4403 if (!mStandby && status == INVALID_OPERATION) {
4404 mOutput->stream->common.standby(&mOutput->stream->common);
4405 mStandby = true;
4406 mBytesWritten = 0;
4407 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4408 keyValuePair.string());
4409 }
4410 if (status == NO_ERROR && reconfig) {
4411 readOutputParameters_l();
4412 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4413 }
4414 }
4415
Eric Laurent81784c32012-11-19 14:55:58 -08004416 return reconfig;
4417}
4418
4419uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4420{
4421 uint32_t time;
4422 if (audio_is_linear_pcm(mFormat)) {
4423 time = PlaybackThread::activeSleepTimeUs();
4424 } else {
4425 time = 10000;
4426 }
4427 return time;
4428}
4429
4430uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4431{
4432 uint32_t time;
4433 if (audio_is_linear_pcm(mFormat)) {
4434 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4435 } else {
4436 time = 10000;
4437 }
4438 return time;
4439}
4440
4441uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4442{
4443 uint32_t time;
4444 if (audio_is_linear_pcm(mFormat)) {
4445 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4446 } else {
4447 time = 10000;
4448 }
4449 return time;
4450}
4451
4452void AudioFlinger::DirectOutputThread::cacheParameters_l()
4453{
4454 PlaybackThread::cacheParameters_l();
4455
4456 // use shorter standby delay as on normal output to release
4457 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004458 if (audio_is_linear_pcm(mFormat)) {
4459 standbyDelay = microseconds(activeSleepTime*2);
4460 } else {
4461 standbyDelay = kOffloadStandbyDelayNs;
4462 }
Eric Laurent81784c32012-11-19 14:55:58 -08004463}
4464
Eric Laurente659ef42014-09-29 13:06:46 -07004465void AudioFlinger::DirectOutputThread::flushHw_l()
4466{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004467 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004468 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004469 }
4470 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004471}
4472
Eric Laurent81784c32012-11-19 14:55:58 -08004473// ----------------------------------------------------------------------------
4474
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004476 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004477 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004478 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004479 mWriteAckSequence(0),
4480 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481{
4482}
4483
4484AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4485{
4486}
4487
4488void AudioFlinger::AsyncCallbackThread::onFirstRef()
4489{
4490 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4491}
4492
4493bool AudioFlinger::AsyncCallbackThread::threadLoop()
4494{
4495 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004496 uint32_t writeAckSequence;
4497 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498
4499 {
4500 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004501 while (!((mWriteAckSequence & 1) ||
4502 (mDrainSequence & 1) ||
4503 exitPending())) {
4504 mWaitWorkCV.wait(mLock);
4505 }
4506
Eric Laurentbfb1b832013-01-07 09:53:42 -08004507 if (exitPending()) {
4508 break;
4509 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004510 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4511 mWriteAckSequence, mDrainSequence);
4512 writeAckSequence = mWriteAckSequence;
4513 mWriteAckSequence &= ~1;
4514 drainSequence = mDrainSequence;
4515 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 }
4517 {
Eric Laurent4de95592013-09-26 15:28:21 -07004518 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4519 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004520 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004521 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004523 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004524 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 }
4526 }
4527 }
4528 }
4529 return false;
4530}
4531
4532void AudioFlinger::AsyncCallbackThread::exit()
4533{
4534 ALOGV("AsyncCallbackThread::exit");
4535 Mutex::Autolock _l(mLock);
4536 requestExit();
4537 mWaitWorkCV.broadcast();
4538}
4539
Eric Laurent3b4529e2013-09-05 18:09:19 -07004540void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004541{
4542 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004543 // bit 0 is cleared
4544 mWriteAckSequence = sequence << 1;
4545}
4546
4547void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4548{
4549 Mutex::Autolock _l(mLock);
4550 // ignore unexpected callbacks
4551 if (mWriteAckSequence & 2) {
4552 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004553 mWaitWorkCV.signal();
4554 }
4555}
4556
Eric Laurent3b4529e2013-09-05 18:09:19 -07004557void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004558{
4559 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004560 // bit 0 is cleared
4561 mDrainSequence = sequence << 1;
4562}
4563
4564void AudioFlinger::AsyncCallbackThread::resetDraining()
4565{
4566 Mutex::Autolock _l(mLock);
4567 // ignore unexpected callbacks
4568 if (mDrainSequence & 2) {
4569 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004570 mWaitWorkCV.signal();
4571 }
4572}
4573
4574
4575// ----------------------------------------------------------------------------
4576AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4577 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4578 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004579 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580{
Eric Laurentfd477972013-10-25 18:10:40 -07004581 //FIXME: mStandby should be set to true by ThreadBase constructor
4582 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004583}
4584
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585void AudioFlinger::OffloadThread::threadLoop_exit()
4586{
4587 if (mFlushPending || mHwPaused) {
4588 // If a flush is pending or track was paused, just discard buffered data
4589 flushHw_l();
4590 } else {
4591 mMixerStatus = MIXER_DRAIN_ALL;
4592 threadLoop_drain();
4593 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004594 if (mUseAsyncWrite) {
4595 ALOG_ASSERT(mCallbackThread != 0);
4596 mCallbackThread->exit();
4597 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598 PlaybackThread::threadLoop_exit();
4599}
4600
4601AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4602 Vector< sp<Track> > *tracksToRemove
4603)
4604{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605 size_t count = mActiveTracks.size();
4606
4607 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004608 bool doHwPause = false;
4609 bool doHwResume = false;
4610
Eric Laurentede6c3b2013-09-19 14:37:46 -07004611 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4612
Eric Laurentbfb1b832013-01-07 09:53:42 -08004613 // find out which tracks need to be processed
4614 for (size_t i = 0; i < count; i++) {
4615 sp<Track> t = mActiveTracks[i].promote();
4616 // The track died recently
4617 if (t == 0) {
4618 continue;
4619 }
4620 Track* const track = t.get();
4621 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004622 // Only consider last track started for volume and mixer state control.
4623 // In theory an older track could underrun and restart after the new one starts
4624 // but as we only care about the transition phase between two tracks on a
4625 // direct output, it is not a problem to ignore the underrun case.
4626 sp<Track> l = mLatestActiveTrack.promote();
4627 bool last = l.get() == track;
4628
Haynes Mathew George7844f672014-01-15 12:32:55 -08004629 if (track->isInvalid()) {
4630 ALOGW("An invalidated track shouldn't be in active list");
4631 tracksToRemove->add(track);
4632 continue;
4633 }
4634
4635 if (track->mState == TrackBase::IDLE) {
4636 ALOGW("An idle track shouldn't be in active list");
4637 continue;
4638 }
4639
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 if (track->isPausing()) {
4641 track->setPaused();
4642 if (last) {
4643 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004644 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 mHwPaused = true;
4646 }
4647 // If we were part way through writing the mixbuffer to
4648 // the HAL we must save this until we resume
4649 // BUG - this will be wrong if a different track is made active,
4650 // in that case we want to discard the pending data in the
4651 // mixbuffer and tell the client to present it again when the
4652 // track is resumed
4653 mPausedWriteLength = mCurrentWriteLength;
4654 mPausedBytesRemaining = mBytesRemaining;
4655 mBytesRemaining = 0; // stop writing
4656 }
4657 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004658 } else if (track->isFlushPending()) {
4659 track->flushAck();
4660 if (last) {
4661 mFlushPending = true;
4662 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004663 } else if (track->isResumePending()){
4664 track->resumeAck();
4665 if (last) {
4666 if (mPausedBytesRemaining) {
4667 // Need to continue write that was interrupted
4668 mCurrentWriteLength = mPausedWriteLength;
4669 mBytesRemaining = mPausedBytesRemaining;
4670 mPausedBytesRemaining = 0;
4671 }
4672 if (mHwPaused) {
4673 doHwResume = true;
4674 mHwPaused = false;
4675 // threadLoop_mix() will handle the case that we need to
4676 // resume an interrupted write
4677 }
4678 // enable write to audio HAL
4679 sleepTime = 0;
4680
4681 // Do not handle new data in this iteration even if track->framesReady()
4682 mixerStatus = MIXER_TRACKS_ENABLED;
4683 }
4684 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004685 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004686 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004687 if (track->mFillingUpStatus == Track::FS_FILLED) {
4688 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004689 // make sure processVolume_l() will apply new volume even if 0
4690 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004691 }
4692
4693 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004694 sp<Track> previousTrack = mPreviousTrack.promote();
4695 if (previousTrack != 0) {
4696 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004697 // Flush any data still being written from last track
4698 mBytesRemaining = 0;
4699 if (mPausedBytesRemaining) {
4700 // Last track was paused so we also need to flush saved
4701 // mixbuffer state and invalidate track so that it will
4702 // re-submit that unwritten data when it is next resumed
4703 mPausedBytesRemaining = 0;
4704 // Invalidate is a bit drastic - would be more efficient
4705 // to have a flag to tell client that some of the
4706 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004707 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004708 }
4709 // flush data already sent to the DSP if changing audio session as audio
4710 // comes from a different source. Also invalidate previous track to force a
4711 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004712 if (previousTrack->sessionId() != track->sessionId()) {
4713 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004714 }
4715 }
4716 }
4717 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718 // reset retry count
4719 track->mRetryCount = kMaxTrackRetriesOffload;
4720 mActiveTrack = t;
4721 mixerStatus = MIXER_TRACKS_READY;
4722 }
4723 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004724 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004725 if (track->isStopping_1()) {
4726 // Hardware buffer can hold a large amount of audio so we must
4727 // wait for all current track's data to drain before we say
4728 // that the track is stopped.
4729 if (mBytesRemaining == 0) {
4730 // Only start draining when all data in mixbuffer
4731 // has been written
4732 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4733 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004734 // do not drain if no data was ever sent to HAL (mStandby == true)
4735 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004736 // do not modify drain sequence if we are already draining. This happens
4737 // when resuming from pause after drain.
4738 if ((mDrainSequence & 1) == 0) {
4739 sleepTime = 0;
4740 standbyTime = systemTime() + standbyDelay;
4741 mixerStatus = MIXER_DRAIN_TRACK;
4742 mDrainSequence += 2;
4743 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004744 if (mHwPaused) {
4745 // It is possible to move from PAUSED to STOPPING_1 without
4746 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004747 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748 mHwPaused = false;
4749 }
4750 }
4751 }
4752 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004753 // Drain has completed or we are in standby, signal presentation complete
4754 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755 track->mState = TrackBase::STOPPED;
4756 size_t audioHALFrames =
4757 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4758 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004759 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004760 track->presentationComplete(framesWritten, audioHALFrames);
4761 track->reset();
4762 tracksToRemove->add(track);
4763 }
4764 } else {
4765 // No buffers for this track. Give it a few chances to
4766 // fill a buffer, then remove it from active list.
4767 if (--(track->mRetryCount) <= 0) {
4768 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4769 track->name());
4770 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004771 // indicate to client process that the track was disabled because of underrun;
4772 // it will then automatically call start() when data is available
4773 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774 } else if (last){
4775 mixerStatus = MIXER_TRACKS_ENABLED;
4776 }
4777 }
4778 }
4779 // compute volume for this track
4780 processVolume_l(track, last);
4781 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004782
Eric Laurentea0fade2013-10-04 16:23:48 -07004783 // make sure the pause/flush/resume sequence is executed in the right order.
4784 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4785 // before flush and then resume HW. This can happen in case of pause/flush/resume
4786 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004787 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004788 mOutput->stream->pause(mOutput->stream);
4789 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004790 if (mFlushPending) {
4791 flushHw_l();
4792 mFlushPending = false;
4793 }
Eric Laurentfd477972013-10-25 18:10:40 -07004794 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004795 mOutput->stream->resume(mOutput->stream);
4796 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004797
Eric Laurentbfb1b832013-01-07 09:53:42 -08004798 // remove all the tracks that need to be...
4799 removeTracks_l(*tracksToRemove);
4800
4801 return mixerStatus;
4802}
4803
Eric Laurentbfb1b832013-01-07 09:53:42 -08004804// must be called with thread mutex locked
4805bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4806{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004807 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4808 mWriteAckSequence, mDrainSequence);
4809 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004810 return true;
4811 }
4812 return false;
4813}
4814
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4816{
4817 Mutex::Autolock _l(mLock);
4818 return waitingAsyncCallback_l();
4819}
4820
4821void AudioFlinger::OffloadThread::flushHw_l()
4822{
Eric Laurente659ef42014-09-29 13:06:46 -07004823 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824 // Flush anything still waiting in the mixbuffer
4825 mCurrentWriteLength = 0;
4826 mBytesRemaining = 0;
4827 mPausedWriteLength = 0;
4828 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004829
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004831 // discard any pending drain or write ack by incrementing sequence
4832 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4833 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004834 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004835 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4836 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837 }
4838}
4839
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004840void AudioFlinger::OffloadThread::onAddNewTrack_l()
4841{
4842 sp<Track> previousTrack = mPreviousTrack.promote();
4843 sp<Track> latestTrack = mLatestActiveTrack.promote();
4844
4845 if (previousTrack != 0 && latestTrack != 0 &&
4846 (previousTrack->sessionId() != latestTrack->sessionId())) {
4847 mFlushPending = true;
4848 }
4849 PlaybackThread::onAddNewTrack_l();
4850}
4851
Eric Laurentbfb1b832013-01-07 09:53:42 -08004852// ----------------------------------------------------------------------------
4853
Eric Laurent81784c32012-11-19 14:55:58 -08004854AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4855 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4856 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4857 DUPLICATING),
4858 mWaitTimeMs(UINT_MAX)
4859{
4860 addOutputTrack(mainThread);
4861}
4862
4863AudioFlinger::DuplicatingThread::~DuplicatingThread()
4864{
4865 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4866 mOutputTracks[i]->destroy();
4867 }
4868}
4869
4870void AudioFlinger::DuplicatingThread::threadLoop_mix()
4871{
4872 // mix buffers...
4873 if (outputsReady(outputTracks)) {
4874 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4875 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004876 if (mMixerBufferValid) {
4877 memset(mMixerBuffer, 0, mMixerBufferSize);
4878 } else {
4879 memset(mSinkBuffer, 0, mSinkBufferSize);
4880 }
Eric Laurent81784c32012-11-19 14:55:58 -08004881 }
4882 sleepTime = 0;
4883 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004884 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004885 standbyTime = systemTime() + standbyDelay;
4886}
4887
4888void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4889{
4890 if (sleepTime == 0) {
4891 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4892 sleepTime = activeSleepTime;
4893 } else {
4894 sleepTime = idleSleepTime;
4895 }
4896 } else if (mBytesWritten != 0) {
4897 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4898 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004899 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004900 } else {
4901 // flush remaining overflow buffers in output tracks
4902 writeFrames = 0;
4903 }
4904 sleepTime = 0;
4905 }
4906}
4907
Eric Laurentbfb1b832013-01-07 09:53:42 -08004908ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004909{
4910 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004911 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004912 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004913 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004914 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004915}
4916
4917void AudioFlinger::DuplicatingThread::threadLoop_standby()
4918{
4919 // DuplicatingThread implements standby by stopping all tracks
4920 for (size_t i = 0; i < outputTracks.size(); i++) {
4921 outputTracks[i]->stop();
4922 }
4923}
4924
4925void AudioFlinger::DuplicatingThread::saveOutputTracks()
4926{
4927 outputTracks = mOutputTracks;
4928}
4929
4930void AudioFlinger::DuplicatingThread::clearOutputTracks()
4931{
4932 outputTracks.clear();
4933}
4934
4935void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4936{
4937 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004938 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4939 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4940 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4941 const size_t frameCount =
4942 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4943 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4944 // from different OutputTracks and their associated MixerThreads (e.g. one may
4945 // nearly empty and the other may be dropping data).
4946
4947 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004948 this,
4949 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004950 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004951 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004952 frameCount,
4953 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004954 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004955 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004956 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004957 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004958 updateWaitTime_l();
4959 }
4960}
4961
4962void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4963{
4964 Mutex::Autolock _l(mLock);
4965 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4966 if (mOutputTracks[i]->thread() == thread) {
4967 mOutputTracks[i]->destroy();
4968 mOutputTracks.removeAt(i);
4969 updateWaitTime_l();
4970 return;
4971 }
4972 }
4973 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4974}
4975
4976// caller must hold mLock
4977void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4978{
4979 mWaitTimeMs = UINT_MAX;
4980 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4981 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4982 if (strong != 0) {
4983 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4984 if (waitTimeMs < mWaitTimeMs) {
4985 mWaitTimeMs = waitTimeMs;
4986 }
4987 }
4988 }
4989}
4990
4991
4992bool AudioFlinger::DuplicatingThread::outputsReady(
4993 const SortedVector< sp<OutputTrack> > &outputTracks)
4994{
4995 for (size_t i = 0; i < outputTracks.size(); i++) {
4996 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4997 if (thread == 0) {
4998 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4999 outputTracks[i].get());
5000 return false;
5001 }
5002 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5003 // see note at standby() declaration
5004 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5005 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5006 thread.get());
5007 return false;
5008 }
5009 }
5010 return true;
5011}
5012
5013uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5014{
5015 return (mWaitTimeMs * 1000) / 2;
5016}
5017
5018void AudioFlinger::DuplicatingThread::cacheParameters_l()
5019{
5020 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5021 updateWaitTime_l();
5022
5023 MixerThread::cacheParameters_l();
5024}
5025
5026// ----------------------------------------------------------------------------
5027// Record
5028// ----------------------------------------------------------------------------
5029
5030AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5031 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005032 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005033 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005034 audio_devices_t inDevice
5035#ifdef TEE_SINK
5036 , const sp<NBAIO_Sink>& teeSink
5037#endif
5038 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005039 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005040 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005041 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005042 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005043#ifdef TEE_SINK
5044 , mTeeSink(teeSink)
5045#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005046 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5047 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005048 // mFastCapture below
5049 , mFastCaptureFutex(0)
5050 // mInputSource
5051 // mPipeSink
5052 // mPipeSource
5053 , mPipeFramesP2(0)
5054 // mPipeMemory
5055 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005056 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005057{
5058 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005059 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005060
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005061 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005062
5063 // create an NBAIO source for the HAL input stream, and negotiate
5064 mInputSource = new AudioStreamInSource(input->stream);
5065 size_t numCounterOffers = 0;
5066 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5067 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5068 ALOG_ASSERT(index == 0);
5069
5070 // initialize fast capture depending on configuration
5071 bool initFastCapture;
5072 switch (kUseFastCapture) {
5073 case FastCapture_Never:
5074 initFastCapture = false;
5075 break;
5076 case FastCapture_Always:
5077 initFastCapture = true;
5078 break;
5079 case FastCapture_Static:
5080 uint32_t primaryOutputSampleRate;
5081 {
5082 AutoMutex _l(audioFlinger->mHardwareLock);
5083 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5084 }
5085 initFastCapture =
5086 // either capture sample rate is same as (a reasonable) primary output sample rate
5087 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5088 (mSampleRate == primaryOutputSampleRate)) ||
5089 // or primary output sample rate is unknown, and capture sample rate is reasonable
5090 ((primaryOutputSampleRate == 0) &&
5091 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005092 // and the buffer size is < 12 ms
5093 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005094 break;
5095 // case FastCapture_Dynamic:
5096 }
5097
5098 if (initFastCapture) {
5099 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5100 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005101 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005102 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5103 void *pipeBuffer;
5104 const sp<MemoryDealer> roHeap(readOnlyHeap());
5105 sp<IMemory> pipeMemory;
5106 if ((roHeap == 0) ||
5107 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5108 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5109 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5110 goto failed;
5111 }
5112 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5113 memset(pipeBuffer, 0, pipeSize);
5114 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5115 const NBAIO_Format offers[1] = {format};
5116 size_t numCounterOffers = 0;
5117 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5118 ALOG_ASSERT(index == 0);
5119 mPipeSink = pipe;
5120 PipeReader *pipeReader = new PipeReader(*pipe);
5121 numCounterOffers = 0;
5122 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5123 ALOG_ASSERT(index == 0);
5124 mPipeSource = pipeReader;
5125 mPipeFramesP2 = pipeFramesP2;
5126 mPipeMemory = pipeMemory;
5127
5128 // create fast capture
5129 mFastCapture = new FastCapture();
5130 FastCaptureStateQueue *sq = mFastCapture->sq();
5131#ifdef STATE_QUEUE_DUMP
5132 // FIXME
5133#endif
5134 FastCaptureState *state = sq->begin();
5135 state->mCblk = NULL;
5136 state->mInputSource = mInputSource.get();
5137 state->mInputSourceGen++;
5138 state->mPipeSink = pipe;
5139 state->mPipeSinkGen++;
5140 state->mFrameCount = mFrameCount;
5141 state->mCommand = FastCaptureState::COLD_IDLE;
5142 // already done in constructor initialization list
5143 //mFastCaptureFutex = 0;
5144 state->mColdFutexAddr = &mFastCaptureFutex;
5145 state->mColdGen++;
5146 state->mDumpState = &mFastCaptureDumpState;
5147#ifdef TEE_SINK
5148 // FIXME
5149#endif
5150 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5151 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5152 sq->end();
5153 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5154
5155 // start the fast capture
5156 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5157 pid_t tid = mFastCapture->getTid();
5158 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5159 if (err != 0) {
5160 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5161 kPriorityFastCapture, getpid_cached, tid, err);
5162 }
5163
5164#ifdef AUDIO_WATCHDOG
5165 // FIXME
5166#endif
5167
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005168 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005169 }
5170failed: ;
5171
5172 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005173}
5174
5175
5176AudioFlinger::RecordThread::~RecordThread()
5177{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005178 if (mFastCapture != 0) {
5179 FastCaptureStateQueue *sq = mFastCapture->sq();
5180 FastCaptureState *state = sq->begin();
5181 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5182 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5183 if (old == -1) {
5184 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5185 }
5186 }
5187 state->mCommand = FastCaptureState::EXIT;
5188 sq->end();
5189 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5190 mFastCapture->join();
5191 mFastCapture.clear();
5192 }
5193 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005194 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005195 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005196}
5197
5198void AudioFlinger::RecordThread::onFirstRef()
5199{
5200 run(mName, PRIORITY_URGENT_AUDIO);
5201}
5202
Eric Laurent81784c32012-11-19 14:55:58 -08005203bool AudioFlinger::RecordThread::threadLoop()
5204{
Eric Laurent81784c32012-11-19 14:55:58 -08005205 nsecs_t lastWarning = 0;
5206
5207 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005208
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005209reacquire_wakelock:
5210 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005211 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005212 {
5213 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005214 size_t size = mActiveTracks.size();
5215 activeTracksGen = mActiveTracksGen;
5216 if (size > 0) {
5217 // FIXME an arbitrary choice
5218 activeTrack = mActiveTracks[0];
5219 acquireWakeLock_l(activeTrack->uid());
5220 if (size > 1) {
5221 SortedVector<int> tmp;
5222 for (size_t i = 0; i < size; i++) {
5223 tmp.add(mActiveTracks[i]->uid());
5224 }
5225 updateWakeLockUids_l(tmp);
5226 }
5227 } else {
5228 acquireWakeLock_l(-1);
5229 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005230 }
5231
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005232 // used to request a deferred sleep, to be executed later while mutex is unlocked
5233 uint32_t sleepUs = 0;
5234
5235 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005236 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005237 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005238
Glenn Kasten5edadd42013-08-14 16:30:49 -07005239 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005240 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005241 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005242 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005243 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005245 }
5246
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005247 // activeTracks accumulates a copy of a subset of mActiveTracks
5248 Vector< sp<RecordTrack> > activeTracks;
5249
Glenn Kasten735f45f2014-08-18 15:51:59 -07005250 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005251 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005252
Glenn Kasten735f45f2014-08-18 15:51:59 -07005253 // reference to a fast track which is about to be removed
5254 sp<RecordTrack> fastTrackToRemove;
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256 { // scope for mLock
5257 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005258
Eric Laurent021cf962014-05-13 10:18:14 -07005259 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005260
Eric Laurent000a4192014-01-29 15:17:32 -08005261 // check exitPending here because checkForNewParameters_l() and
5262 // checkForNewParameters_l() can temporarily release mLock
5263 if (exitPending()) {
5264 break;
5265 }
5266
Glenn Kasten2b806402013-11-20 16:37:38 -08005267 // if no active track(s), then standby and release wakelock
5268 size_t size = mActiveTracks.size();
5269 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005270 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005271 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005272 releaseWakeLock_l();
5273 ALOGV("RecordThread: loop stopping");
5274 // go to sleep
5275 mWaitWorkCV.wait(mLock);
5276 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005277 goto reacquire_wakelock;
5278 }
5279
Glenn Kasten2b806402013-11-20 16:37:38 -08005280 if (mActiveTracksGen != activeTracksGen) {
5281 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005282 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005283 for (size_t i = 0; i < size; i++) {
5284 tmp.add(mActiveTracks[i]->uid());
5285 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005286 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005287 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005288
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005289 bool doBroadcast = false;
5290 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005291
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005292 activeTrack = mActiveTracks[i];
5293 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005294 if (activeTrack->isFastTrack()) {
5295 ALOG_ASSERT(fastTrackToRemove == 0);
5296 fastTrackToRemove = activeTrack;
5297 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005299 mActiveTracks.remove(activeTrack);
5300 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005301 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005302 continue;
5303 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005304
5305 TrackBase::track_state activeTrackState = activeTrack->mState;
5306 switch (activeTrackState) {
5307
5308 case TrackBase::PAUSING:
5309 mActiveTracks.remove(activeTrack);
5310 mActiveTracksGen++;
5311 doBroadcast = true;
5312 size--;
5313 continue;
5314
5315 case TrackBase::STARTING_1:
5316 sleepUs = 10000;
5317 i++;
5318 continue;
5319
5320 case TrackBase::STARTING_2:
5321 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005322 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005323 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005324 break;
5325
5326 case TrackBase::ACTIVE:
5327 break;
5328
5329 case TrackBase::IDLE:
5330 i++;
5331 continue;
5332
5333 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005334 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005335 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005336
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005337 activeTracks.add(activeTrack);
5338 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005339
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005340 if (activeTrack->isFastTrack()) {
5341 ALOG_ASSERT(!mFastTrackAvail);
5342 ALOG_ASSERT(fastTrack == 0);
5343 fastTrack = activeTrack;
5344 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005345 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005346 if (doBroadcast) {
5347 mStartStopCond.broadcast();
5348 }
5349
5350 // sleep if there are no active tracks to process
5351 if (activeTracks.size() == 0) {
5352 if (sleepUs == 0) {
5353 sleepUs = kRecordThreadSleepUs;
5354 }
5355 continue;
5356 }
5357 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005358
Eric Laurent81784c32012-11-19 14:55:58 -08005359 lockEffectChains_l(effectChains);
5360 }
5361
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005362 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005364 size_t size = effectChains.size();
5365 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005366 // thread mutex is not locked, but effect chain is locked
5367 effectChains[i]->process_l();
5368 }
5369
Glenn Kasten735f45f2014-08-18 15:51:59 -07005370 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005371 if (mFastCapture != 0) {
5372 FastCaptureStateQueue *sq = mFastCapture->sq();
5373 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005374 bool didModify = false;
5375 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005376 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5377 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5378 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5379 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5380 if (old == -1) {
5381 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5382 }
5383 }
5384 state->mCommand = FastCaptureState::READ_WRITE;
5385#if 0 // FIXME
5386 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005387 FastCaptureDumpState::kSamplingNforLowRamDevice :
5388 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005389#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005390 didModify = true;
5391 }
5392 audio_track_cblk_t *cblkOld = state->mCblk;
5393 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5394 if (cblkNew != cblkOld) {
5395 state->mCblk = cblkNew;
5396 // block until acked if removing a fast track
5397 if (cblkOld != NULL) {
5398 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5399 }
5400 didModify = true;
5401 }
5402 sq->end(didModify);
5403 if (didModify) {
5404 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005405#if 0
5406 if (kUseFastCapture == FastCapture_Dynamic) {
5407 mNormalSource = mPipeSource;
5408 }
5409#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005410 }
5411 }
5412
Glenn Kasten735f45f2014-08-18 15:51:59 -07005413 // now run the fast track destructor with thread mutex unlocked
5414 fastTrackToRemove.clear();
5415
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005416 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5417 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5418 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5419 // If destination is non-contiguous, first read past the nominal end of buffer, then
5420 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005421
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005422 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005423 ssize_t framesRead;
5424
5425 // If an NBAIO source is present, use it to read the normal capture's data
5426 if (mPipeSource != 0) {
5427 size_t framesToRead = mBufferSize / mFrameSize;
5428 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5429 framesToRead, AudioBufferProvider::kInvalidPTS);
5430 if (framesRead == 0) {
5431 // since pipe is non-blocking, simulate blocking input
5432 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5433 }
5434 // otherwise use the HAL / AudioStreamIn directly
5435 } else {
5436 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5437 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5438 if (bytesRead < 0) {
5439 framesRead = bytesRead;
5440 } else {
5441 framesRead = bytesRead / mFrameSize;
5442 }
5443 }
5444
5445 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5446 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005447 // Force input into standby so that it tries to recover at next read attempt
5448 inputStandBy();
5449 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005450 }
5451 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005452 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005453 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005455
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005456 if (mTeeSink != 0) {
5457 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5458 }
5459 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005460 {
5461 size_t part1 = mRsmpInFramesP2 - rear;
5462 if ((size_t) framesRead > part1) {
5463 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5464 (framesRead - part1) * mFrameSize);
5465 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005466 }
5467 rear = mRsmpInRear += framesRead;
5468
5469 size = activeTracks.size();
5470 // loop over each active track
5471 for (size_t i = 0; i < size; i++) {
5472 activeTrack = activeTracks[i];
5473
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005474 // skip fast tracks, as those are handled directly by FastCapture
5475 if (activeTrack->isFastTrack()) {
5476 continue;
5477 }
5478
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005479 enum {
5480 OVERRUN_UNKNOWN,
5481 OVERRUN_TRUE,
5482 OVERRUN_FALSE
5483 } overrun = OVERRUN_UNKNOWN;
5484
5485 // loop over getNextBuffer to handle circular sink
5486 for (;;) {
5487
5488 activeTrack->mSink.frameCount = ~0;
5489 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5490 size_t framesOut = activeTrack->mSink.frameCount;
5491 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5492
5493 int32_t front = activeTrack->mRsmpInFront;
5494 ssize_t filled = rear - front;
5495 size_t framesIn;
5496
5497 if (filled < 0) {
5498 // should not happen, but treat like a massive overrun and re-sync
5499 framesIn = 0;
5500 activeTrack->mRsmpInFront = rear;
5501 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005502 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005503 framesIn = (size_t) filled;
5504 } else {
5505 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005506 framesIn = mRsmpInFrames;
5507 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005508 overrun = OVERRUN_TRUE;
5509 }
5510
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005511 if (framesOut == 0 || framesIn == 0) {
5512 break;
5513 }
5514
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005515 if (activeTrack->mResampler == NULL) {
5516 // no resampling
5517 if (framesIn > framesOut) {
5518 framesIn = framesOut;
5519 } else {
5520 framesOut = framesIn;
5521 }
5522 int8_t *dst = activeTrack->mSink.i8;
5523 while (framesIn > 0) {
5524 front &= mRsmpInFramesP2 - 1;
5525 size_t part1 = mRsmpInFramesP2 - front;
5526 if (part1 > framesIn) {
5527 part1 = framesIn;
5528 }
5529 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005530 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005531 memcpy(dst, src, part1 * mFrameSize);
5532 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005533 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005534 part1);
5535 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005536 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5537 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005538 }
5539 dst += part1 * activeTrack->mFrameSize;
5540 front += part1;
5541 framesIn -= part1;
5542 }
5543 activeTrack->mRsmpInFront += framesOut;
5544
5545 } else {
5546 // resampling
5547 // FIXME framesInNeeded should really be part of resampler API, and should
5548 // depend on the SRC ratio
5549 // to keep mRsmpInBuffer full so resampler always has sufficient input
5550 size_t framesInNeeded;
5551 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005552 // Do not precompute in/out because floating point is not associative
5553 // e.g. a*b/c != a*(b/c).
5554 const double in(mSampleRate);
5555 const double out(activeTrack->mSampleRate);
5556 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005557 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005558 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005559 // Although we theoretically have framesIn in circular buffer, some of those are
5560 // unreleased frames, and thus must be discounted for purpose of budgeting.
5561 size_t unreleased = activeTrack->mRsmpInUnrel;
5562 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005563 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005564 ALOGV("not enough to resample: have %u frames in but need %u in to "
5565 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005566 framesIn, framesInNeeded, framesOut, in / out);
5567 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005568 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5569 if (newFramesOut == 0) {
5570 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005571 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005572 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005573 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005574 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005575 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5576 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5577 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005578 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005579 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005580 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005581 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005582 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005583 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005584 }
5585
5586 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5587 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005588 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005589 delete[] activeTrack->mRsmpOutBuffer;
5590 // resampler always outputs stereo
5591 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5592 activeTrack->mRsmpOutFrameCount = framesOut;
5593 }
5594
5595 // resampler accumulates, but we only have one source track
5596 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5597 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005598 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005599 activeTrack->mResamplerBufferProvider
5600 /*this*/ /* AudioBufferProvider* */);
5601 // ditherAndClamp() works as long as all buffers returned by
5602 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005603 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005604 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005605 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5606 framesOut);
5607 // the resampler always outputs stereo samples:
5608 // do post stereo to mono conversion
5609 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005610 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005611 } else {
5612 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5613 activeTrack->mRsmpOutBuffer, framesOut);
5614 }
5615 // now done with mRsmpOutBuffer
5616
5617 }
5618
5619 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5620 overrun = OVERRUN_FALSE;
5621 }
5622
5623 if (activeTrack->mFramesToDrop == 0) {
5624 if (framesOut > 0) {
5625 activeTrack->mSink.frameCount = framesOut;
5626 activeTrack->releaseBuffer(&activeTrack->mSink);
5627 }
5628 } else {
5629 // FIXME could do a partial drop of framesOut
5630 if (activeTrack->mFramesToDrop > 0) {
5631 activeTrack->mFramesToDrop -= framesOut;
5632 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005633 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 }
5635 } else {
5636 activeTrack->mFramesToDrop += framesOut;
5637 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5638 activeTrack->mSyncStartEvent->isCancelled()) {
5639 ALOGW("Synced record %s, session %d, trigger session %d",
5640 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5641 activeTrack->sessionId(),
5642 (activeTrack->mSyncStartEvent != 0) ?
5643 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005644 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005645 }
5646 }
5647 }
5648
5649 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005651 }
5652 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005653
5654 switch (overrun) {
5655 case OVERRUN_TRUE:
5656 // client isn't retrieving buffers fast enough
5657 if (!activeTrack->setOverflow()) {
5658 nsecs_t now = systemTime();
5659 // FIXME should lastWarning per track?
5660 if ((now - lastWarning) > kWarningThrottleNs) {
5661 ALOGW("RecordThread: buffer overflow");
5662 lastWarning = now;
5663 }
5664 }
5665 break;
5666 case OVERRUN_FALSE:
5667 activeTrack->clearOverflow();
5668 break;
5669 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 break;
5671 }
5672
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005673 }
5674
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005675unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005676 // enable changes in effect chain
5677 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005678 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005679 }
5680
Glenn Kasten93e471f2013-08-19 08:40:07 -07005681 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005682
5683 {
5684 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005685 for (size_t i = 0; i < mTracks.size(); i++) {
5686 sp<RecordTrack> track = mTracks[i];
5687 track->invalidate();
5688 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005689 mActiveTracks.clear();
5690 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005691 mStartStopCond.broadcast();
5692 }
5693
5694 releaseWakeLock();
5695
5696 ALOGV("RecordThread %p exiting", this);
5697 return false;
5698}
5699
Glenn Kasten93e471f2013-08-19 08:40:07 -07005700void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005701{
5702 if (!mStandby) {
5703 inputStandBy();
5704 mStandby = true;
5705 }
5706}
5707
5708void AudioFlinger::RecordThread::inputStandBy()
5709{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005710 // Idle the fast capture if it's currently running
5711 if (mFastCapture != 0) {
5712 FastCaptureStateQueue *sq = mFastCapture->sq();
5713 FastCaptureState *state = sq->begin();
5714 if (!(state->mCommand & FastCaptureState::IDLE)) {
5715 state->mCommand = FastCaptureState::COLD_IDLE;
5716 state->mColdFutexAddr = &mFastCaptureFutex;
5717 state->mColdGen++;
5718 mFastCaptureFutex = 0;
5719 sq->end();
5720 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5721 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5722#if 0
5723 if (kUseFastCapture == FastCapture_Dynamic) {
5724 // FIXME
5725 }
5726#endif
5727#ifdef AUDIO_WATCHDOG
5728 // FIXME
5729#endif
5730 } else {
5731 sq->end(false /*didModify*/);
5732 }
5733 }
Eric Laurent81784c32012-11-19 14:55:58 -08005734 mInput->stream->common.standby(&mInput->stream->common);
5735}
5736
Glenn Kasten05997e22014-03-13 15:08:33 -07005737// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005738sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005739 const sp<AudioFlinger::Client>& client,
5740 uint32_t sampleRate,
5741 audio_format_t format,
5742 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005743 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005744 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005745 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005746 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005747 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005748 pid_t tid,
5749 status_t *status)
5750{
Glenn Kasten74935e42013-12-19 08:56:45 -08005751 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005752 sp<RecordTrack> track;
5753 status_t lStatus;
5754
Glenn Kasten90e58b12013-07-31 16:16:02 -07005755 // client expresses a preference for FAST, but we get the final say
5756 if (*flags & IAudioFlinger::TRACK_FAST) {
5757 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005758 // use case: callback handler
5759 (tid != -1) &&
5760 // frame count is not specified, or is exactly the pipe depth
5761 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005762 // PCM data
5763 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005764 // native format
5765 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005766 // native channel mask
5767 (channelMask == mChannelMask) &&
5768 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005769 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005770 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005771 hasFastCapture() &&
5772 // there are sufficient fast track slots available
5773 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005774 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005775 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005776 frameCount, mFrameCount);
5777 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005778 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5779 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005780 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005781 frameCount, mFrameCount, mPipeFramesP2,
5782 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5783 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005784 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005785 }
5786 }
5787
5788 // compute track buffer size in frames, and suggest the notification frame count
5789 if (*flags & IAudioFlinger::TRACK_FAST) {
5790 // fast track: frame count is exactly the pipe depth
5791 frameCount = mPipeFramesP2;
5792 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5793 *notificationFrames = mFrameCount;
5794 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005795 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5796 // or 20 ms if there is a fast capture
5797 // TODO This could be a roundupRatio inline, and const
5798 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5799 * sampleRate + mSampleRate - 1) / mSampleRate;
5800 // minimum number of notification periods is at least kMinNotifications,
5801 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5802 static const size_t kMinNotifications = 3;
5803 static const uint32_t kMinMs = 30;
5804 // TODO This could be a roundupRatio inline
5805 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5806 // TODO This could be a roundupRatio inline
5807 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5808 maxNotificationFrames;
5809 const size_t minFrameCount = maxNotificationFrames *
5810 max(kMinNotifications, minNotificationsByMs);
5811 frameCount = max(frameCount, minFrameCount);
5812 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5813 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005814 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005815 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005816 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005817
Glenn Kasten15e57982013-09-24 11:52:37 -07005818 lStatus = initCheck();
5819 if (lStatus != NO_ERROR) {
5820 ALOGE("createRecordTrack_l() audio driver not initialized");
5821 goto Exit;
5822 }
Eric Laurent81784c32012-11-19 14:55:58 -08005823
5824 { // scope for mLock
5825 Mutex::Autolock _l(mLock);
5826
5827 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005828 format, channelMask, frameCount, NULL, sessionId, uid,
5829 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005830
Glenn Kasten03003332013-08-06 15:40:54 -07005831 lStatus = track->initCheck();
5832 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005833 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005834 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005835 goto Exit;
5836 }
5837 mTracks.add(track);
5838
5839 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5840 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5841 mAudioFlinger->btNrecIsOff();
5842 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5843 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005844
5845 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5846 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5847 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5848 // so ask activity manager to do this on our behalf
5849 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5850 }
Eric Laurent81784c32012-11-19 14:55:58 -08005851 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005852
Eric Laurent81784c32012-11-19 14:55:58 -08005853 lStatus = NO_ERROR;
5854
5855Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005856 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005857 return track;
5858}
5859
5860status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5861 AudioSystem::sync_event_t event,
5862 int triggerSession)
5863{
5864 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5865 sp<ThreadBase> strongMe = this;
5866 status_t status = NO_ERROR;
5867
5868 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005869 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005870 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005871 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005872 triggerSession,
5873 recordTrack->sessionId(),
5874 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005875 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005876 // Sync event can be cancelled by the trigger session if the track is not in a
5877 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005878 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005879 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005880 } else {
5881 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005883 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005884 }
5885 }
5886
5887 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005888 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005889 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5891 if (recordTrack->mState == TrackBase::PAUSING) {
5892 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005893 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005894 } else {
5895 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005896 }
5897 return status;
5898 }
5899
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005900 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5901 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5902 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005904 mActiveTracks.add(recordTrack);
5905 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005906 status_t status = NO_ERROR;
5907 if (recordTrack->isExternalTrack()) {
5908 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005909 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005910 mLock.lock();
5911 // FIXME should verify that recordTrack is still in mActiveTracks
5912 if (status != NO_ERROR) {
5913 mActiveTracks.remove(recordTrack);
5914 mActiveTracksGen++;
5915 recordTrack->clearSyncStartEvent();
5916 ALOGV("RecordThread::start error %d", status);
5917 return status;
5918 }
Eric Laurent81784c32012-11-19 14:55:58 -08005919 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920 // Catch up with current buffer indices if thread is already running.
5921 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5922 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5923 // see previously buffered data before it called start(), but with greater risk of overrun.
5924
5925 recordTrack->mRsmpInFront = mRsmpInRear;
5926 recordTrack->mRsmpInUnrel = 0;
5927 // FIXME why reset?
5928 if (recordTrack->mResampler != NULL) {
5929 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005930 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005932 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005933 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005934 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005935 ALOGV("Record failed to start");
5936 status = BAD_VALUE;
5937 goto startError;
5938 }
Eric Laurent81784c32012-11-19 14:55:58 -08005939 return status;
5940 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005941
Eric Laurent81784c32012-11-19 14:55:58 -08005942startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005943 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005944 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005945 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005946 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005947 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005948 return status;
5949}
5950
Eric Laurent81784c32012-11-19 14:55:58 -08005951void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5952{
5953 sp<SyncEvent> strongEvent = event.promote();
5954
5955 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005956 sp<RefBase> ptr = strongEvent->cookie().promote();
5957 if (ptr != 0) {
5958 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5959 recordTrack->handleSyncStartEvent(strongEvent);
5960 }
Eric Laurent81784c32012-11-19 14:55:58 -08005961 }
5962}
5963
Glenn Kastena8356f62013-07-25 14:37:52 -07005964bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005965 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005966 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005967 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005968 return false;
5969 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005970 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005971 recordTrack->mState = TrackBase::PAUSING;
5972 // do not wait for mStartStopCond if exiting
5973 if (exitPending()) {
5974 return true;
5975 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005976 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005977 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005978 // if we have been restarted, recordTrack is in mActiveTracks here
5979 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005980 ALOGV("Record stopped OK");
5981 return true;
5982 }
5983 return false;
5984}
5985
Glenn Kasten0f11b512014-01-31 16:18:54 -08005986bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005987{
5988 return false;
5989}
5990
Glenn Kasten0f11b512014-01-31 16:18:54 -08005991status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005992{
5993#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5994 if (!isValidSyncEvent(event)) {
5995 return BAD_VALUE;
5996 }
5997
5998 int eventSession = event->triggerSession();
5999 status_t ret = NAME_NOT_FOUND;
6000
6001 Mutex::Autolock _l(mLock);
6002
6003 for (size_t i = 0; i < mTracks.size(); i++) {
6004 sp<RecordTrack> track = mTracks[i];
6005 if (eventSession == track->sessionId()) {
6006 (void) track->setSyncEvent(event);
6007 ret = NO_ERROR;
6008 }
6009 }
6010 return ret;
6011#else
6012 return BAD_VALUE;
6013#endif
6014}
6015
6016// destroyTrack_l() must be called with ThreadBase::mLock held
6017void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6018{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006019 track->terminate();
6020 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006021 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006022 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006023 removeTrack_l(track);
6024 }
6025}
6026
6027void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6028{
6029 mTracks.remove(track);
6030 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006031 if (track->isFastTrack()) {
6032 ALOG_ASSERT(!mFastTrackAvail);
6033 mFastTrackAvail = true;
6034 }
Eric Laurent81784c32012-11-19 14:55:58 -08006035}
6036
6037void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6038{
6039 dumpInternals(fd, args);
6040 dumpTracks(fd, args);
6041 dumpEffectChains(fd, args);
6042}
6043
6044void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6045{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006046 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006047
Glenn Kasten2b806402013-11-20 16:37:38 -08006048 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006049 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006051 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006052 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006053 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006055
Eric Laurent81784c32012-11-19 14:55:58 -08006056 dumpBase(fd, args);
6057}
6058
Glenn Kasten0f11b512014-01-31 16:18:54 -08006059void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006060{
6061 const size_t SIZE = 256;
6062 char buffer[SIZE];
6063 String8 result;
6064
Marco Nelissenb2208842014-02-07 14:00:50 -08006065 size_t numtracks = mTracks.size();
6066 size_t numactive = mActiveTracks.size();
6067 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006068 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006069 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006070 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006071 RecordTrack::appendDumpHeader(result);
6072 for (size_t i = 0; i < numtracks ; ++i) {
6073 sp<RecordTrack> track = mTracks[i];
6074 if (track != 0) {
6075 bool active = mActiveTracks.indexOf(track) >= 0;
6076 if (active) {
6077 numactiveseen++;
6078 }
6079 track->dump(buffer, SIZE, active);
6080 result.append(buffer);
6081 }
Eric Laurent81784c32012-11-19 14:55:58 -08006082 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006083 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006084 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006085 }
6086
Marco Nelissenb2208842014-02-07 14:00:50 -08006087 if (numactiveseen != numactive) {
6088 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6089 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006090 result.append(buffer);
6091 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006092 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006093 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006094 if (mTracks.indexOf(track) < 0) {
6095 track->dump(buffer, SIZE, true);
6096 result.append(buffer);
6097 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006098 }
Eric Laurent81784c32012-11-19 14:55:58 -08006099
6100 }
6101 write(fd, result.string(), result.size());
6102}
6103
6104// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6106 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006107{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006108 RecordTrack *activeTrack = mRecordTrack;
6109 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6110 if (threadBase == 0) {
6111 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006112 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 return NOT_ENOUGH_DATA;
6114 }
6115 RecordThread *recordThread = (RecordThread *) threadBase.get();
6116 int32_t rear = recordThread->mRsmpInRear;
6117 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006118 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006119 // FIXME should not be P2 (don't want to increase latency)
6120 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006121 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006122 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 front &= recordThread->mRsmpInFramesP2 - 1;
6124 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006125 if (part1 > (size_t) filled) {
6126 part1 = filled;
6127 }
6128 size_t ask = buffer->frameCount;
6129 ALOG_ASSERT(ask > 0);
6130 if (part1 > ask) {
6131 part1 = ask;
6132 }
6133 if (part1 == 0) {
6134 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006135 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006136 buffer->raw = NULL;
6137 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006139 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006140 }
6141
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006142 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006143 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006144 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006145 return NO_ERROR;
6146}
6147
6148// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6150 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006151{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006153 size_t stepCount = buffer->frameCount;
6154 if (stepCount == 0) {
6155 return;
6156 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006157 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6158 activeTrack->mRsmpInUnrel -= stepCount;
6159 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006160 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006161 buffer->frameCount = 0;
6162}
6163
Eric Laurent10351942014-05-08 18:49:52 -07006164bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6165 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006166{
6167 bool reconfig = false;
6168
Eric Laurent10351942014-05-08 18:49:52 -07006169 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006170
Eric Laurent10351942014-05-08 18:49:52 -07006171 audio_format_t reqFormat = mFormat;
6172 uint32_t samplingRate = mSampleRate;
6173 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6174
6175 AudioParameter param = AudioParameter(keyValuePair);
6176 int value;
6177 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6178 // channel count change can be requested. Do we mandate the first client defines the
6179 // HAL sampling rate and channel count or do we allow changes on the fly?
6180 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6181 samplingRate = value;
6182 reconfig = true;
6183 }
6184 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6185 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6186 status = BAD_VALUE;
6187 } else {
6188 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006189 reconfig = true;
6190 }
Eric Laurent10351942014-05-08 18:49:52 -07006191 }
6192 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6193 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6194 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6195 status = BAD_VALUE;
6196 } else {
6197 channelMask = mask;
6198 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006199 }
Eric Laurent10351942014-05-08 18:49:52 -07006200 }
6201 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6202 // do not accept frame count changes if tracks are open as the track buffer
6203 // size depends on frame count and correct behavior would not be guaranteed
6204 // if frame count is changed after track creation
6205 if (mActiveTracks.size() > 0) {
6206 status = INVALID_OPERATION;
6207 } else {
6208 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006209 }
Eric Laurent10351942014-05-08 18:49:52 -07006210 }
6211 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6212 // forward device change to effects that have requested to be
6213 // aware of attached audio device.
6214 for (size_t i = 0; i < mEffectChains.size(); i++) {
6215 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006216 }
Eric Laurent81784c32012-11-19 14:55:58 -08006217
Eric Laurent10351942014-05-08 18:49:52 -07006218 // store input device and output device but do not forward output device to audio HAL.
6219 // Note that status is ignored by the caller for output device
6220 // (see AudioFlinger::setParameters()
6221 if (audio_is_output_devices(value)) {
6222 mOutDevice = value;
6223 status = BAD_VALUE;
6224 } else {
6225 mInDevice = value;
6226 // disable AEC and NS if the device is a BT SCO headset supporting those
6227 // pre processings
6228 if (mTracks.size() > 0) {
6229 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6230 mAudioFlinger->btNrecIsOff();
6231 for (size_t i = 0; i < mTracks.size(); i++) {
6232 sp<RecordTrack> track = mTracks[i];
6233 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6234 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006235 }
6236 }
6237 }
Eric Laurent10351942014-05-08 18:49:52 -07006238 }
6239 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6240 mAudioSource != (audio_source_t)value) {
6241 // forward device change to effects that have requested to be
6242 // aware of attached audio device.
6243 for (size_t i = 0; i < mEffectChains.size(); i++) {
6244 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
Eric Laurent10351942014-05-08 18:49:52 -07006246 mAudioSource = (audio_source_t)value;
6247 }
Glenn Kastene198c362013-08-13 09:13:36 -07006248
Eric Laurent10351942014-05-08 18:49:52 -07006249 if (status == NO_ERROR) {
6250 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6251 keyValuePair.string());
6252 if (status == INVALID_OPERATION) {
6253 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006254 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6255 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006256 }
6257 if (reconfig) {
6258 if (status == BAD_VALUE &&
6259 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6260 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6261 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6262 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006263 audio_channel_count_from_in_mask(
6264 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006265 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6266 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6267 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006268 }
Eric Laurent10351942014-05-08 18:49:52 -07006269 if (status == NO_ERROR) {
6270 readInputParameters_l();
6271 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
6273 }
Eric Laurent81784c32012-11-19 14:55:58 -08006274 }
Eric Laurent10351942014-05-08 18:49:52 -07006275
Eric Laurent81784c32012-11-19 14:55:58 -08006276 return reconfig;
6277}
6278
6279String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6280{
Eric Laurent81784c32012-11-19 14:55:58 -08006281 Mutex::Autolock _l(mLock);
6282 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006283 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006284 }
6285
Glenn Kastend8ea6992013-07-16 14:17:15 -07006286 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6287 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006288 free(s);
6289 return out_s8;
6290}
6291
Eric Laurent021cf962014-05-13 10:18:14 -07006292void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006293 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006294 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006295
6296 switch (event) {
6297 case AudioSystem::INPUT_OPENED:
6298 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006299 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006300 desc.samplingRate = mSampleRate;
6301 desc.format = mFormat;
6302 desc.frameCount = mFrameCount;
6303 desc.latency = 0;
6304 param2 = &desc;
6305 break;
6306
6307 case AudioSystem::INPUT_CLOSED:
6308 default:
6309 break;
6310 }
Eric Laurent021cf962014-05-13 10:18:14 -07006311 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006312}
6313
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006314void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006315{
Eric Laurent81784c32012-11-19 14:55:58 -08006316 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6317 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006318 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006319 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6320 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006321 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006322 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006323 }
Eric Laurent665470b2014-07-03 16:37:08 -07006324 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006325 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6326 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006327 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006328 // 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 -07006329 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006330 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 // A larger value should allow more old data to be read after a track calls start(),
6332 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006333 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006334 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006336
6337 // TODO optimize audio capture buffer sizes ...
6338 // Here we calculate the size of the sliding buffer used as a source
6339 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6340 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6341 // be better to have it derived from the pipe depth in the long term.
6342 // The current value is higher than necessary. However it should not add to latency.
6343
Glenn Kasten85948432013-08-19 12:09:05 -07006344 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6345 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006346
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006347 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6348 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006349}
6350
Glenn Kasten5f972c02014-01-13 09:59:31 -08006351uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006352{
6353 Mutex::Autolock _l(mLock);
6354 if (initCheck() != NO_ERROR) {
6355 return 0;
6356 }
6357
6358 return mInput->stream->get_input_frames_lost(mInput->stream);
6359}
6360
6361uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6362{
6363 Mutex::Autolock _l(mLock);
6364 uint32_t result = 0;
6365 if (getEffectChain_l(sessionId) != 0) {
6366 result = EFFECT_SESSION;
6367 }
6368
6369 for (size_t i = 0; i < mTracks.size(); ++i) {
6370 if (sessionId == mTracks[i]->sessionId()) {
6371 result |= TRACK_SESSION;
6372 break;
6373 }
6374 }
6375
6376 return result;
6377}
6378
6379KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6380{
6381 KeyedVector<int, bool> ids;
6382 Mutex::Autolock _l(mLock);
6383 for (size_t j = 0; j < mTracks.size(); ++j) {
6384 sp<RecordThread::RecordTrack> track = mTracks[j];
6385 int sessionId = track->sessionId();
6386 if (ids.indexOfKey(sessionId) < 0) {
6387 ids.add(sessionId, true);
6388 }
6389 }
6390 return ids;
6391}
6392
6393AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6394{
6395 Mutex::Autolock _l(mLock);
6396 AudioStreamIn *input = mInput;
6397 mInput = NULL;
6398 return input;
6399}
6400
6401// this method must always be called either with ThreadBase mLock held or inside the thread loop
6402audio_stream_t* AudioFlinger::RecordThread::stream() const
6403{
6404 if (mInput == NULL) {
6405 return NULL;
6406 }
6407 return &mInput->stream->common;
6408}
6409
6410status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6411{
6412 // only one chain per input thread
6413 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006414 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006415 return INVALID_OPERATION;
6416 }
6417 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006418 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006419 chain->setInBuffer(NULL);
6420 chain->setOutBuffer(NULL);
6421
6422 checkSuspendOnAddEffectChain_l(chain);
6423
Eric Laurent1b928682014-10-02 19:41:47 -07006424 // make sure enabled pre processing effects state is communicated to the HAL as we
6425 // just moved them to a new input stream.
6426 chain->syncHalEffectsState();
6427
Eric Laurent81784c32012-11-19 14:55:58 -08006428 mEffectChains.add(chain);
6429
6430 return NO_ERROR;
6431}
6432
6433size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6434{
6435 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6436 ALOGW_IF(mEffectChains.size() != 1,
6437 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6438 chain.get(), mEffectChains.size(), this);
6439 if (mEffectChains.size() == 1) {
6440 mEffectChains.removeAt(0);
6441 }
6442 return 0;
6443}
6444
Eric Laurent1c333e22014-05-20 10:48:17 -07006445status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6446 audio_patch_handle_t *handle)
6447{
6448 status_t status = NO_ERROR;
6449 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6450 // store new device and send to effects
6451 mInDevice = patch->sources[0].ext.device.type;
6452 for (size_t i = 0; i < mEffectChains.size(); i++) {
6453 mEffectChains[i]->setDevice_l(mInDevice);
6454 }
6455
6456 // disable AEC and NS if the device is a BT SCO headset supporting those
6457 // pre processings
6458 if (mTracks.size() > 0) {
6459 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6460 mAudioFlinger->btNrecIsOff();
6461 for (size_t i = 0; i < mTracks.size(); i++) {
6462 sp<RecordTrack> track = mTracks[i];
6463 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6464 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6465 }
6466 }
6467
6468 // store new source and send to effects
6469 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6470 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6471 for (size_t i = 0; i < mEffectChains.size(); i++) {
6472 mEffectChains[i]->setAudioSource_l(mAudioSource);
6473 }
6474 }
6475
6476 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6477 status = hwDevice->create_audio_patch(hwDevice,
6478 patch->num_sources,
6479 patch->sources,
6480 patch->num_sinks,
6481 patch->sinks,
6482 handle);
6483 } else {
6484 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6485 }
6486 return status;
6487}
6488
6489status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6490{
6491 status_t status = NO_ERROR;
6492 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6493 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6494 status = hwDevice->release_audio_patch(hwDevice, handle);
6495 } else {
6496 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6497 }
6498 return status;
6499}
6500
Eric Laurent83b88082014-06-20 18:31:16 -07006501void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6502{
6503 Mutex::Autolock _l(mLock);
6504 mTracks.add(record);
6505}
6506
6507void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6508{
6509 Mutex::Autolock _l(mLock);
6510 destroyTrack_l(record);
6511}
6512
6513void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6514{
6515 ThreadBase::getAudioPortConfig(config);
6516 config->role = AUDIO_PORT_ROLE_SINK;
6517 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6518 config->ext.mix.usecase.source = mAudioSource;
6519}
Eric Laurent1c333e22014-05-20 10:48:17 -07006520
Eric Laurent81784c32012-11-19 14:55:58 -08006521}; // namespace android