blob: a7ee38b6b7f8eb4ccc845d24851122f97028641e [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;
1486 // For compatibility with AudioTrack calculation, buffer depth is forced
1487 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1488 // This is probably too conservative, but legacy application code may depend on it.
1489 // If you change this calculation, also review the start threshold which is related.
1490 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1491 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1492 if (minBufCount < 2) {
1493 minBufCount = 2;
1494 }
1495 size_t minFrameCount = mNormalFrameCount * minBufCount;
1496 if (frameCount < minFrameCount) {
1497 frameCount = minFrameCount;
1498 }
1499 }
1500 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001501 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001502
Glenn Kastenc3df8382014-03-13 15:05:25 -07001503 switch (mType) {
1504
1505 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001506 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001507 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001508 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1509 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001510 sampleRate, format, channelMask, mOutput, mFormat);
1511 lStatus = BAD_VALUE;
1512 goto Exit;
1513 }
1514 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001515 break;
1516
1517 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001519 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1520 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001521 sampleRate, format, channelMask, mOutput, mFormat);
1522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001525 break;
1526
1527 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001528 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001529 ALOGE("createTrack_l() Bad parameter: format %#x \""
1530 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001531 format, mOutput, mFormat);
1532 lStatus = BAD_VALUE;
1533 goto Exit;
1534 }
Andy Hungcd044842014-08-07 11:04:34 -07001535 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001536 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1537 lStatus = BAD_VALUE;
1538 goto Exit;
1539 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001540 break;
1541
Eric Laurent81784c32012-11-19 14:55:58 -08001542 }
1543
1544 lStatus = initCheck();
1545 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001546 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001547 goto Exit;
1548 }
1549
1550 { // scope for mLock
1551 Mutex::Autolock _l(mLock);
1552
1553 // all tracks in same audio session must share the same routing strategy otherwise
1554 // conflicts will happen when tracks are moved from one output to another by audio policy
1555 // manager
1556 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1557 for (size_t i = 0; i < mTracks.size(); ++i) {
1558 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001559 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001560 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1561 if (sessionId == t->sessionId() && strategy != actual) {
1562 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1563 strategy, actual);
1564 lStatus = BAD_VALUE;
1565 goto Exit;
1566 }
1567 }
1568 }
1569
1570 if (!isTimed) {
1571 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001572 channelMask, frameCount, NULL, sharedBuffer,
1573 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001574 } else {
1575 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001576 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001577 }
Glenn Kasten03003332013-08-06 15:40:54 -07001578
1579 // new Track always returns non-NULL,
1580 // but TimedTrack::create() is a factory that could fail by returning NULL
1581 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1582 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001583 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001584 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001585 goto Exit;
1586 }
1587 mTracks.add(track);
1588
1589 sp<EffectChain> chain = getEffectChain_l(sessionId);
1590 if (chain != 0) {
1591 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1592 track->setMainBuffer(chain->inBuffer());
1593 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1594 chain->incTrackCnt();
1595 }
1596
1597 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1598 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1599 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1600 // so ask activity manager to do this on our behalf
1601 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1602 }
1603 }
1604
1605 lStatus = NO_ERROR;
1606
1607Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001608 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001609 return track;
1610}
1611
1612uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1613{
1614 return latency;
1615}
1616
1617uint32_t AudioFlinger::PlaybackThread::latency() const
1618{
1619 Mutex::Autolock _l(mLock);
1620 return latency_l();
1621}
1622uint32_t AudioFlinger::PlaybackThread::latency_l() const
1623{
1624 if (initCheck() == NO_ERROR) {
1625 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1626 } else {
1627 return 0;
1628 }
1629}
1630
1631void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1632{
1633 Mutex::Autolock _l(mLock);
1634 // Don't apply master volume in SW if our HAL can do it for us.
1635 if (mOutput && mOutput->audioHwDev &&
1636 mOutput->audioHwDev->canSetMasterVolume()) {
1637 mMasterVolume = 1.0;
1638 } else {
1639 mMasterVolume = value;
1640 }
1641}
1642
1643void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1644{
1645 Mutex::Autolock _l(mLock);
1646 // Don't apply master mute in SW if our HAL can do it for us.
1647 if (mOutput && mOutput->audioHwDev &&
1648 mOutput->audioHwDev->canSetMasterMute()) {
1649 mMasterMute = false;
1650 } else {
1651 mMasterMute = muted;
1652 }
1653}
1654
1655void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1656{
1657 Mutex::Autolock _l(mLock);
1658 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001659 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001660}
1661
1662void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1663{
1664 Mutex::Autolock _l(mLock);
1665 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001666 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001667}
1668
1669float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1670{
1671 Mutex::Autolock _l(mLock);
1672 return mStreamTypes[stream].volume;
1673}
1674
1675// addTrack_l() must be called with ThreadBase::mLock held
1676status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1677{
1678 status_t status = ALREADY_EXISTS;
1679
1680 // set retry count for buffer fill
1681 track->mRetryCount = kMaxTrackStartupRetries;
1682 if (mActiveTracks.indexOf(track) < 0) {
1683 // the track is newly added, make sure it fills up all its
1684 // buffers before playing. This is to ensure the client will
1685 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001686 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001687 TrackBase::track_state state = track->mState;
1688 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001689 status = AudioSystem::startOutput(mId, track->streamType(),
1690 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691 mLock.lock();
1692 // abort track was stopped/paused while we released the lock
1693 if (state != track->mState) {
1694 if (status == NO_ERROR) {
1695 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001696 AudioSystem::stopOutput(mId, track->streamType(),
1697 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001698 mLock.lock();
1699 }
1700 return INVALID_OPERATION;
1701 }
1702 // abort if start is rejected by audio policy manager
1703 if (status != NO_ERROR) {
1704 return PERMISSION_DENIED;
1705 }
1706#ifdef ADD_BATTERY_DATA
1707 // to track the speaker usage
1708 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1709#endif
1710 }
1711
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001713 track->mResetDone = false;
1714 track->mPresentationCompleteFrames = 0;
1715 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001716 mWakeLockUids.add(track->uid());
1717 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001718 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001719 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1720 if (chain != 0) {
1721 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1722 track->sessionId());
1723 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001724 }
1725
1726 status = NO_ERROR;
1727 }
1728
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001729 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001730 return status;
1731}
1732
Eric Laurentbfb1b832013-01-07 09:53:42 -08001733bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001734{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001735 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001736 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001737 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1738 track->mState = TrackBase::STOPPED;
1739 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001740 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001741 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001743 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001744
1745 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001746}
1747
1748void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1749{
1750 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1751 mTracks.remove(track);
1752 deleteTrackName_l(track->name());
1753 // redundant as track is about to be destroyed, for dumpsys only
1754 track->mName = -1;
1755 if (track->isFastTrack()) {
1756 int index = track->mFastIndex;
1757 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1758 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1759 mFastTrackAvailMask |= 1 << index;
1760 // redundant as track is about to be destroyed, for dumpsys only
1761 track->mFastIndex = -1;
1762 }
1763 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1764 if (chain != 0) {
1765 chain->decTrackCnt();
1766 }
1767}
1768
Eric Laurentede6c3b2013-09-19 14:37:46 -07001769void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001770{
1771 // Thread could be blocked waiting for async
1772 // so signal it to handle state changes immediately
1773 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1774 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1775 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001776 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777}
1778
Eric Laurent81784c32012-11-19 14:55:58 -08001779String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1780{
Eric Laurent81784c32012-11-19 14:55:58 -08001781 Mutex::Autolock _l(mLock);
1782 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001783 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001784 }
1785
Glenn Kastend8ea6992013-07-16 14:17:15 -07001786 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1787 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001788 free(s);
1789 return out_s8;
1790}
1791
Eric Laurent021cf962014-05-13 10:18:14 -07001792void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001793 AudioSystem::OutputDescriptor desc;
1794 void *param2 = NULL;
1795
Eric Laurent021cf962014-05-13 10:18:14 -07001796 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001797 param);
1798
1799 switch (event) {
1800 case AudioSystem::OUTPUT_OPENED:
1801 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001802 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001803 desc.samplingRate = mSampleRate;
1804 desc.format = mFormat;
1805 desc.frameCount = mNormalFrameCount; // FIXME see
1806 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001807 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001808 param2 = &desc;
1809 break;
1810
1811 case AudioSystem::STREAM_CONFIG_CHANGED:
1812 param2 = &param;
1813 case AudioSystem::OUTPUT_CLOSED:
1814 default:
1815 break;
1816 }
Eric Laurent021cf962014-05-13 10:18:14 -07001817 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
Eric Laurentbfb1b832013-01-07 09:53:42 -08001820void AudioFlinger::PlaybackThread::writeCallback()
1821{
1822 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001823 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001824}
1825
1826void AudioFlinger::PlaybackThread::drainCallback()
1827{
1828 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001829 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001830}
1831
Eric Laurent3b4529e2013-09-05 18:09:19 -07001832void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833{
1834 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001835 // reject out of sequence requests
1836 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1837 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001838 mWaitWorkCV.signal();
1839 }
1840}
1841
Eric Laurent3b4529e2013-09-05 18:09:19 -07001842void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843{
1844 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001845 // reject out of sequence requests
1846 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1847 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848 mWaitWorkCV.signal();
1849 }
1850}
1851
1852// static
1853int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001854 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855 void *cookie)
1856{
1857 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1858 ALOGV("asyncCallback() event %d", event);
1859 switch (event) {
1860 case STREAM_CBK_EVENT_WRITE_READY:
1861 me->writeCallback();
1862 break;
1863 case STREAM_CBK_EVENT_DRAIN_READY:
1864 me->drainCallback();
1865 break;
1866 default:
1867 ALOGW("asyncCallback() unknown event %d", event);
1868 break;
1869 }
1870 return 0;
1871}
1872
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001873void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001874{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001875 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001876 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1877 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001878 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001879 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001880 }
Andy Hung9a592762014-07-21 21:56:01 -07001881 if ((mType == MIXER || mType == DUPLICATING)
1882 && !isValidPcmSinkChannelMask(mChannelMask)) {
1883 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1884 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001885 }
Andy Hunge5412692014-05-16 11:25:07 -07001886 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001887 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1888 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001889 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001890 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001891 }
Andy Hung6146c082014-03-18 11:56:15 -07001892 if ((mType == MIXER || mType == DUPLICATING)
1893 && !isValidPcmSinkFormat(mFormat)) {
1894 LOG_FATAL("HAL format %#x not supported for mixed output",
1895 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001896 }
Eric Laurent665470b2014-07-03 16:37:08 -07001897 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001898 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1899 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001900 if (mFrameCount & 15) {
1901 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1902 mFrameCount);
1903 }
1904
Eric Laurentbfb1b832013-01-07 09:53:42 -08001905 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1906 (mOutput->stream->set_callback != NULL)) {
1907 if (mOutput->stream->set_callback(mOutput->stream,
1908 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1909 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001910 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001911 }
1912 }
1913
Eric Laurentd1f69b02014-12-15 14:33:13 -08001914 mHwSupportsPause = false;
1915 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1916 if (mOutput->stream->pause != NULL) {
1917 if (mOutput->stream->resume != NULL) {
1918 mHwSupportsPause = true;
1919 } else {
1920 ALOGW("direct output implements pause but not resume");
1921 }
1922 } else if (mOutput->stream->resume != NULL) {
1923 ALOGW("direct output implements resume but not pause");
1924 }
1925 }
1926
Andy Hung09a50072014-02-27 14:30:47 -08001927 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001928 double multiplier = 1.0;
1929 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1930 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001931 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1932 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001933 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1934 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1935 maxNormalFrameCount = maxNormalFrameCount & ~15;
1936 if (maxNormalFrameCount < minNormalFrameCount) {
1937 maxNormalFrameCount = minNormalFrameCount;
1938 }
1939 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1940 if (multiplier <= 1.0) {
1941 multiplier = 1.0;
1942 } else if (multiplier <= 2.0) {
1943 if (2 * mFrameCount <= maxNormalFrameCount) {
1944 multiplier = 2.0;
1945 } else {
1946 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1947 }
1948 } else {
1949 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001950 // 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 -08001951 // track, but we sometimes have to do this to satisfy the maximum frame count
1952 // constraint)
1953 // FIXME this rounding up should not be done if no HAL SRC
1954 uint32_t truncMult = (uint32_t) multiplier;
1955 if ((truncMult & 1)) {
1956 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1957 ++truncMult;
1958 }
1959 }
1960 multiplier = (double) truncMult;
1961 }
1962 }
1963 mNormalFrameCount = multiplier * mFrameCount;
1964 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001965 if (mType == MIXER || mType == DUPLICATING) {
1966 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1967 }
Andy Hung09a50072014-02-27 14:30:47 -08001968 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001969 mNormalFrameCount);
1970
Andy Hung010a1a12014-03-13 13:57:33 -07001971 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1972 // Originally this was int16_t[] array, need to remove legacy implications.
1973 free(mSinkBuffer);
1974 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001975 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1976 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1977 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001978 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001979
Andy Hung69aed5f2014-02-25 17:24:40 -08001980 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1981 // drives the output.
1982 free(mMixerBuffer);
1983 mMixerBuffer = NULL;
1984 if (mMixerBufferEnabled) {
1985 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1986 mMixerBufferSize = mNormalFrameCount * mChannelCount
1987 * audio_bytes_per_sample(mMixerBufferFormat);
1988 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1989 }
Andy Hung98ef9782014-03-04 14:46:50 -08001990 free(mEffectBuffer);
1991 mEffectBuffer = NULL;
1992 if (mEffectBufferEnabled) {
1993 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1994 mEffectBufferSize = mNormalFrameCount * mChannelCount
1995 * audio_bytes_per_sample(mEffectBufferFormat);
1996 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1997 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001998
Eric Laurent81784c32012-11-19 14:55:58 -08001999 // force reconfiguration of effect chains and engines to take new buffer size and audio
2000 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002001 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002002 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2003 // matter.
2004 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2005 Vector< sp<EffectChain> > effectChains = mEffectChains;
2006 for (size_t i = 0; i < effectChains.size(); i ++) {
2007 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2008 }
2009}
2010
2011
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002012status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002013{
2014 if (halFrames == NULL || dspFrames == NULL) {
2015 return BAD_VALUE;
2016 }
2017 Mutex::Autolock _l(mLock);
2018 if (initCheck() != NO_ERROR) {
2019 return INVALID_OPERATION;
2020 }
2021 size_t framesWritten = mBytesWritten / mFrameSize;
2022 *halFrames = framesWritten;
2023
2024 if (isSuspended()) {
2025 // return an estimation of rendered frames when the output is suspended
2026 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2027 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2028 return NO_ERROR;
2029 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002030 status_t status;
2031 uint32_t frames;
2032 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2033 *dspFrames = (size_t)frames;
2034 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002035 }
2036}
2037
2038uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2039{
2040 Mutex::Autolock _l(mLock);
2041 uint32_t result = 0;
2042 if (getEffectChain_l(sessionId) != 0) {
2043 result = EFFECT_SESSION;
2044 }
2045
2046 for (size_t i = 0; i < mTracks.size(); ++i) {
2047 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002048 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002049 result |= TRACK_SESSION;
2050 break;
2051 }
2052 }
2053
2054 return result;
2055}
2056
2057uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2058{
2059 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2060 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2061 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2062 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2063 }
2064 for (size_t i = 0; i < mTracks.size(); i++) {
2065 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002066 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002067 return AudioSystem::getStrategyForStream(track->streamType());
2068 }
2069 }
2070 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2071}
2072
2073
2074AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2075{
2076 Mutex::Autolock _l(mLock);
2077 return mOutput;
2078}
2079
2080AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2081{
2082 Mutex::Autolock _l(mLock);
2083 AudioStreamOut *output = mOutput;
2084 mOutput = NULL;
2085 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2086 // must push a NULL and wait for ack
2087 mOutputSink.clear();
2088 mPipeSink.clear();
2089 mNormalSink.clear();
2090 return output;
2091}
2092
2093// this method must always be called either with ThreadBase mLock held or inside the thread loop
2094audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2095{
2096 if (mOutput == NULL) {
2097 return NULL;
2098 }
2099 return &mOutput->stream->common;
2100}
2101
2102uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2103{
2104 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2105}
2106
2107status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2108{
2109 if (!isValidSyncEvent(event)) {
2110 return BAD_VALUE;
2111 }
2112
2113 Mutex::Autolock _l(mLock);
2114
2115 for (size_t i = 0; i < mTracks.size(); ++i) {
2116 sp<Track> track = mTracks[i];
2117 if (event->triggerSession() == track->sessionId()) {
2118 (void) track->setSyncEvent(event);
2119 return NO_ERROR;
2120 }
2121 }
2122
2123 return NAME_NOT_FOUND;
2124}
2125
2126bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2127{
2128 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2129}
2130
2131void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2132 const Vector< sp<Track> >& tracksToRemove)
2133{
2134 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002135 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002136 for (size_t i = 0 ; i < count ; i++) {
2137 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002138 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002139 AudioSystem::stopOutput(mId, track->streamType(),
2140 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141#ifdef ADD_BATTERY_DATA
2142 // to track the speaker usage
2143 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2144#endif
2145 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002146 AudioSystem::releaseOutput(mId, track->streamType(),
2147 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 }
Eric Laurent81784c32012-11-19 14:55:58 -08002149 }
2150 }
2151 }
Eric Laurent81784c32012-11-19 14:55:58 -08002152}
2153
2154void AudioFlinger::PlaybackThread::checkSilentMode_l()
2155{
2156 if (!mMasterMute) {
2157 char value[PROPERTY_VALUE_MAX];
2158 if (property_get("ro.audio.silent", value, "0") > 0) {
2159 char *endptr;
2160 unsigned long ul = strtoul(value, &endptr, 0);
2161 if (*endptr == '\0' && ul != 0) {
2162 ALOGD("Silence is golden");
2163 // The setprop command will not allow a property to be changed after
2164 // the first time it is set, so we don't have to worry about un-muting.
2165 setMasterMute_l(true);
2166 }
2167 }
2168 }
2169}
2170
2171// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002172ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002173{
2174 // FIXME rewrite to reduce number of system calls
2175 mLastWriteTime = systemTime();
2176 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002178 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002179
2180 // If an NBAIO sink is present, use it to write the normal mixer's submix
2181 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002182
Andy Hung010a1a12014-03-13 13:57:33 -07002183 const size_t count = mBytesRemaining / mFrameSize;
2184
Simon Wilson2d590962012-11-29 15:18:50 -08002185 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002186 // update the setpoint when AudioFlinger::mScreenState changes
2187 uint32_t screenState = AudioFlinger::mScreenState;
2188 if (screenState != mScreenState) {
2189 mScreenState = screenState;
2190 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2191 if (pipe != NULL) {
2192 pipe->setAvgFrames((mScreenState & 1) ?
2193 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2194 }
2195 }
Andy Hung010a1a12014-03-13 13:57:33 -07002196 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002197 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002198 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002199 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002200 } else {
2201 bytesWritten = framesWritten;
2202 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002203 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002204 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002205 if (status == NO_ERROR) {
2206 size_t totalFramesWritten = mNormalSink->framesWritten();
2207 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2208 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002209 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002210 mLatchDValid = true;
2211 }
2212 }
Eric Laurent81784c32012-11-19 14:55:58 -08002213 // otherwise use the HAL / AudioStreamOut directly
2214 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002215 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002216
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002218 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2219 mWriteAckSequence += 2;
2220 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002221 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002222 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002223 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002224 // FIXME We should have an implementation of timestamps for direct output threads.
2225 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002227 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002228 if (mUseAsyncWrite &&
2229 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2230 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002231 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002232 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002233 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 }
Eric Laurent81784c32012-11-19 14:55:58 -08002235 }
2236
Eric Laurent81784c32012-11-19 14:55:58 -08002237 mNumWrites++;
2238 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002239 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 return bytesWritten;
2241}
2242
2243void AudioFlinger::PlaybackThread::threadLoop_drain()
2244{
2245 if (mOutput->stream->drain) {
2246 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2247 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002248 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2249 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002251 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252 }
2253 mOutput->stream->drain(mOutput->stream,
2254 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2255 : AUDIO_DRAIN_ALL);
2256 }
2257}
2258
2259void AudioFlinger::PlaybackThread::threadLoop_exit()
2260{
Eric Laurent275e8e92014-11-30 15:14:47 -08002261 {
2262 Mutex::Autolock _l(mLock);
2263 for (size_t i = 0; i < mTracks.size(); i++) {
2264 sp<Track> track = mTracks[i];
2265 track->invalidate();
2266 }
2267 }
Eric Laurent81784c32012-11-19 14:55:58 -08002268}
2269
2270/*
2271The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002272 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002273 - activeSleepTime from activeSleepTimeUs()
2274 - idleSleepTime from idleSleepTimeUs()
2275 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2276 - maxPeriod from frame count and sample rate (MIXER only)
2277
2278The parameters that affect these derived values are:
2279 - frame count
2280 - frame size
2281 - sample rate
2282 - device type: A2DP or not
2283 - device latency
2284 - format: PCM or not
2285 - active sleep time
2286 - idle sleep time
2287*/
2288
2289void AudioFlinger::PlaybackThread::cacheParameters_l()
2290{
Andy Hung25c2dac2014-02-27 14:56:00 -08002291 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002292 activeSleepTime = activeSleepTimeUs();
2293 idleSleepTime = idleSleepTimeUs();
2294}
2295
2296void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2297{
Glenn Kasten7c027242012-12-26 14:43:16 -08002298 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002299 this, streamType, mTracks.size());
2300 Mutex::Autolock _l(mLock);
2301
2302 size_t size = mTracks.size();
2303 for (size_t i = 0; i < size; i++) {
2304 sp<Track> t = mTracks[i];
2305 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002306 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002307 }
2308 }
2309}
2310
2311status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2312{
2313 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002314 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2315 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002316 bool ownsBuffer = false;
2317
2318 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2319 if (session > 0) {
2320 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002321 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002322 if (mType != DIRECT) {
2323 size_t numSamples = mNormalFrameCount * mChannelCount;
2324 buffer = new int16_t[numSamples];
2325 memset(buffer, 0, numSamples * sizeof(int16_t));
2326 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2327 ownsBuffer = true;
2328 }
2329
2330 // Attach all tracks with same session ID to this chain.
2331 for (size_t i = 0; i < mTracks.size(); ++i) {
2332 sp<Track> track = mTracks[i];
2333 if (session == track->sessionId()) {
2334 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2335 buffer);
2336 track->setMainBuffer(buffer);
2337 chain->incTrackCnt();
2338 }
2339 }
2340
2341 // indicate all active tracks in the chain
2342 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2343 sp<Track> track = mActiveTracks[i].promote();
2344 if (track == 0) {
2345 continue;
2346 }
2347 if (session == track->sessionId()) {
2348 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2349 chain->incActiveTrackCnt();
2350 }
2351 }
2352 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002353 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002354 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002355 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2356 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002357 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2358 // chains list in order to be processed last as it contains output stage effects
2359 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2360 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2361 // after track specific effects and before output stage
2362 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2363 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2364 // Effect chain for other sessions are inserted at beginning of effect
2365 // chains list to be processed before output mix effects. Relative order between other
2366 // sessions is not important
2367 size_t size = mEffectChains.size();
2368 size_t i = 0;
2369 for (i = 0; i < size; i++) {
2370 if (mEffectChains[i]->sessionId() < session) {
2371 break;
2372 }
2373 }
2374 mEffectChains.insertAt(chain, i);
2375 checkSuspendOnAddEffectChain_l(chain);
2376
2377 return NO_ERROR;
2378}
2379
2380size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2381{
2382 int session = chain->sessionId();
2383
2384 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2385
2386 for (size_t i = 0; i < mEffectChains.size(); i++) {
2387 if (chain == mEffectChains[i]) {
2388 mEffectChains.removeAt(i);
2389 // detach all active tracks from the chain
2390 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2391 sp<Track> track = mActiveTracks[i].promote();
2392 if (track == 0) {
2393 continue;
2394 }
2395 if (session == track->sessionId()) {
2396 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2397 chain.get(), session);
2398 chain->decActiveTrackCnt();
2399 }
2400 }
2401
2402 // detach all tracks with same session ID from this chain
2403 for (size_t i = 0; i < mTracks.size(); ++i) {
2404 sp<Track> track = mTracks[i];
2405 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002406 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002407 chain->decTrackCnt();
2408 }
2409 }
2410 break;
2411 }
2412 }
2413 return mEffectChains.size();
2414}
2415
2416status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2417 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2418{
2419 Mutex::Autolock _l(mLock);
2420 return attachAuxEffect_l(track, EffectId);
2421}
2422
2423status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2424 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2425{
2426 status_t status = NO_ERROR;
2427
2428 if (EffectId == 0) {
2429 track->setAuxBuffer(0, NULL);
2430 } else {
2431 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2432 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2433 if (effect != 0) {
2434 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2435 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2436 } else {
2437 status = INVALID_OPERATION;
2438 }
2439 } else {
2440 status = BAD_VALUE;
2441 }
2442 }
2443 return status;
2444}
2445
2446void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2447{
2448 for (size_t i = 0; i < mTracks.size(); ++i) {
2449 sp<Track> track = mTracks[i];
2450 if (track->auxEffectId() == effectId) {
2451 attachAuxEffect_l(track, 0);
2452 }
2453 }
2454}
2455
2456bool AudioFlinger::PlaybackThread::threadLoop()
2457{
2458 Vector< sp<Track> > tracksToRemove;
2459
2460 standbyTime = systemTime();
2461
2462 // MIXER
2463 nsecs_t lastWarning = 0;
2464
2465 // DUPLICATING
2466 // FIXME could this be made local to while loop?
2467 writeFrames = 0;
2468
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002469 int lastGeneration = 0;
2470
Eric Laurent81784c32012-11-19 14:55:58 -08002471 cacheParameters_l();
2472 sleepTime = idleSleepTime;
2473
2474 if (mType == MIXER) {
2475 sleepTimeShift = 0;
2476 }
2477
2478 CpuStats cpuStats;
2479 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2480
2481 acquireWakeLock();
2482
Glenn Kasten9e58b552013-01-18 15:09:48 -08002483 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2484 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2485 // and then that string will be logged at the next convenient opportunity.
2486 const char *logString = NULL;
2487
Eric Laurent664539d2013-09-23 18:24:31 -07002488 checkSilentMode_l();
2489
Eric Laurent81784c32012-11-19 14:55:58 -08002490 while (!exitPending())
2491 {
2492 cpuStats.sample(myName);
2493
2494 Vector< sp<EffectChain> > effectChains;
2495
Eric Laurent81784c32012-11-19 14:55:58 -08002496 { // scope for mLock
2497
2498 Mutex::Autolock _l(mLock);
2499
Eric Laurent021cf962014-05-13 10:18:14 -07002500 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002501
Glenn Kasten9e58b552013-01-18 15:09:48 -08002502 if (logString != NULL) {
2503 mNBLogWriter->logTimestamp();
2504 mNBLogWriter->log(logString);
2505 logString = NULL;
2506 }
2507
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002508 // Gather the framesReleased counters for all active tracks,
2509 // and latch them atomically with the timestamp.
2510 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2511 mLatchD.mFramesReleased.clear();
2512 size_t size = mActiveTracks.size();
2513 for (size_t i = 0; i < size; i++) {
2514 sp<Track> t = mActiveTracks[i].promote();
2515 if (t != 0) {
2516 mLatchD.mFramesReleased.add(t.get(),
2517 t->mAudioTrackServerProxy->framesReleased());
2518 }
2519 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002520 if (mLatchDValid) {
2521 mLatchQ = mLatchD;
2522 mLatchDValid = false;
2523 mLatchQValid = true;
2524 }
2525
Eric Laurent81784c32012-11-19 14:55:58 -08002526 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527 if (mSignalPending) {
2528 // A signal was raised while we were unlocked
2529 mSignalPending = false;
2530 } else if (waitingAsyncCallback_l()) {
2531 if (exitPending()) {
2532 break;
2533 }
2534 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002535 mWakeLockUids.clear();
2536 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 ALOGV("wait async completion");
2538 mWaitWorkCV.wait(mLock);
2539 ALOGV("async completion/wake");
2540 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002541 standbyTime = systemTime() + standbyDelay;
2542 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002543
2544 continue;
2545 }
2546 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002547 isSuspended()) {
2548 // put audio hardware into standby after short delay
2549 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002550
2551 threadLoop_standby();
2552
2553 mStandby = true;
2554 }
2555
2556 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2557 // we're about to wait, flush the binder command buffer
2558 IPCThreadState::self()->flushCommands();
2559
2560 clearOutputTracks();
2561
2562 if (exitPending()) {
2563 break;
2564 }
2565
2566 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002567 mWakeLockUids.clear();
2568 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002569 // wait until we have something to do...
2570 ALOGV("%s going to sleep", myName.string());
2571 mWaitWorkCV.wait(mLock);
2572 ALOGV("%s waking up", myName.string());
2573 acquireWakeLock_l();
2574
2575 mMixerStatus = MIXER_IDLE;
2576 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2577 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002579 checkSilentMode_l();
2580
2581 standbyTime = systemTime() + standbyDelay;
2582 sleepTime = idleSleepTime;
2583 if (mType == MIXER) {
2584 sleepTimeShift = 0;
2585 }
2586
2587 continue;
2588 }
2589 }
Eric Laurent81784c32012-11-19 14:55:58 -08002590 // mMixerStatusIgnoringFastTracks is also updated internally
2591 mMixerStatus = prepareTracks_l(&tracksToRemove);
2592
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002593 // compare with previously applied list
2594 if (lastGeneration != mActiveTracksGeneration) {
2595 // update wakelock
2596 updateWakeLockUids_l(mWakeLockUids);
2597 lastGeneration = mActiveTracksGeneration;
2598 }
2599
Eric Laurent81784c32012-11-19 14:55:58 -08002600 // prevent any changes in effect chain list and in each effect chain
2601 // during mixing and effect process as the audio buffers could be deleted
2602 // or modified if an effect is created or deleted
2603 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002604 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002605
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 if (mBytesRemaining == 0) {
2607 mCurrentWriteLength = 0;
2608 if (mMixerStatus == MIXER_TRACKS_READY) {
2609 // threadLoop_mix() sets mCurrentWriteLength
2610 threadLoop_mix();
2611 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2612 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2613 // threadLoop_sleepTime sets sleepTime to 0 if data
2614 // must be written to HAL
2615 threadLoop_sleepTime();
2616 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002617 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 }
2619 }
Andy Hung98ef9782014-03-04 14:46:50 -08002620 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2621 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2622 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2623 // or mSinkBuffer (if there are no effects).
2624 //
2625 // This is done pre-effects computation; if effects change to
2626 // support higher precision, this needs to move.
2627 //
2628 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2629 // TODO use sleepTime == 0 as an additional condition.
2630 if (mMixerBufferValid) {
2631 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2632 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2633
2634 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2635 mNormalFrameCount * mChannelCount);
2636 }
2637
Eric Laurentbfb1b832013-01-07 09:53:42 -08002638 mBytesRemaining = mCurrentWriteLength;
2639 if (isSuspended()) {
2640 sleepTime = suspendSleepTimeUs();
2641 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002642 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 mBytesRemaining = 0;
2644 }
Eric Laurent81784c32012-11-19 14:55:58 -08002645
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002647 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 for (size_t i = 0; i < effectChains.size(); i ++) {
2649 effectChains[i]->process_l();
2650 }
Eric Laurent81784c32012-11-19 14:55:58 -08002651 }
2652 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002653 // Process effect chains for offloaded thread even if no audio
2654 // was read from audio track: process only updates effect state
2655 // and thus does have to be synchronized with audio writes but may have
2656 // to be called while waiting for async write callback
2657 if (mType == OFFLOAD) {
2658 for (size_t i = 0; i < effectChains.size(); i ++) {
2659 effectChains[i]->process_l();
2660 }
2661 }
Eric Laurent81784c32012-11-19 14:55:58 -08002662
Andy Hung98ef9782014-03-04 14:46:50 -08002663 // Only if the Effects buffer is enabled and there is data in the
2664 // Effects buffer (buffer valid), we need to
2665 // copy into the sink buffer.
2666 // TODO use sleepTime == 0 as an additional condition.
2667 if (mEffectBufferValid) {
2668 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2669 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2670 mNormalFrameCount * mChannelCount);
2671 }
2672
Eric Laurent81784c32012-11-19 14:55:58 -08002673 // enable changes in effect chain
2674 unlockEffectChains(effectChains);
2675
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 if (!waitingAsyncCallback()) {
2677 // sleepTime == 0 means we must write to audio hardware
2678 if (sleepTime == 0) {
2679 if (mBytesRemaining) {
2680 ssize_t ret = threadLoop_write();
2681 if (ret < 0) {
2682 mBytesRemaining = 0;
2683 } else {
2684 mBytesWritten += ret;
2685 mBytesRemaining -= ret;
2686 }
2687 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2688 (mMixerStatus == MIXER_DRAIN_ALL)) {
2689 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002690 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002691 if (mType == MIXER) {
2692 // write blocked detection
2693 nsecs_t now = systemTime();
2694 nsecs_t delta = now - mLastWriteTime;
2695 if (!mStandby && delta > maxPeriod) {
2696 mNumDelayedWrites++;
2697 if ((now - lastWarning) > kWarningThrottleNs) {
2698 ATRACE_NAME("underrun");
2699 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2700 ns2ms(delta), mNumDelayedWrites, this);
2701 lastWarning = now;
2702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 }
2704 }
Eric Laurent81784c32012-11-19 14:55:58 -08002705
Eric Laurentbfb1b832013-01-07 09:53:42 -08002706 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002707 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002709 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 }
Eric Laurent81784c32012-11-19 14:55:58 -08002711 }
2712
2713 // Finally let go of removed track(s), without the lock held
2714 // since we can't guarantee the destructors won't acquire that
2715 // same lock. This will also mutate and push a new fast mixer state.
2716 threadLoop_removeTracks(tracksToRemove);
2717 tracksToRemove.clear();
2718
2719 // FIXME I don't understand the need for this here;
2720 // it was in the original code but maybe the
2721 // assignment in saveOutputTracks() makes this unnecessary?
2722 clearOutputTracks();
2723
2724 // Effect chains will be actually deleted here if they were removed from
2725 // mEffectChains list during mixing or effects processing
2726 effectChains.clear();
2727
2728 // FIXME Note that the above .clear() is no longer necessary since effectChains
2729 // is now local to this block, but will keep it for now (at least until merge done).
2730 }
2731
Eric Laurentbfb1b832013-01-07 09:53:42 -08002732 threadLoop_exit();
2733
Eric Laurentcf817a22014-08-04 20:36:31 -07002734 if (!mStandby) {
2735 threadLoop_standby();
2736 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002737 }
2738
2739 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002740 mWakeLockUids.clear();
2741 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002742
2743 ALOGV("Thread %p type %d exiting", this, mType);
2744 return false;
2745}
2746
Eric Laurentbfb1b832013-01-07 09:53:42 -08002747// removeTracks_l() must be called with ThreadBase::mLock held
2748void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2749{
2750 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002751 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 for (size_t i=0 ; i<count ; i++) {
2753 const sp<Track>& track = tracksToRemove.itemAt(i);
2754 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002755 mWakeLockUids.remove(track->uid());
2756 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002757 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2758 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2759 if (chain != 0) {
2760 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2761 track->sessionId());
2762 chain->decActiveTrackCnt();
2763 }
2764 if (track->isTerminated()) {
2765 removeTrack_l(track);
2766 }
2767 }
2768 }
2769
2770}
Eric Laurent81784c32012-11-19 14:55:58 -08002771
Eric Laurentaccc1472013-09-20 09:36:34 -07002772status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2773{
2774 if (mNormalSink != 0) {
2775 return mNormalSink->getTimestamp(timestamp);
2776 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002777 if ((mType == OFFLOAD || mType == DIRECT)
2778 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002779 uint64_t position64;
2780 int ret = mOutput->stream->get_presentation_position(
2781 mOutput->stream, &position64, &timestamp.mTime);
2782 if (ret == 0) {
2783 timestamp.mPosition = (uint32_t)position64;
2784 return NO_ERROR;
2785 }
2786 }
2787 return INVALID_OPERATION;
2788}
Eric Laurent1c333e22014-05-20 10:48:17 -07002789
2790status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2791 audio_patch_handle_t *handle)
2792{
2793 status_t status = NO_ERROR;
2794 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2795 // store new device and send to effects
2796 audio_devices_t type = AUDIO_DEVICE_NONE;
2797 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2798 type |= patch->sinks[i].ext.device.type;
2799 }
2800 mOutDevice = type;
2801 for (size_t i = 0; i < mEffectChains.size(); i++) {
2802 mEffectChains[i]->setDevice_l(mOutDevice);
2803 }
2804
2805 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2806 status = hwDevice->create_audio_patch(hwDevice,
2807 patch->num_sources,
2808 patch->sources,
2809 patch->num_sinks,
2810 patch->sinks,
2811 handle);
2812 } else {
2813 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2814 }
2815 return status;
2816}
2817
2818status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2819{
2820 status_t status = NO_ERROR;
2821 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2822 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2823 status = hwDevice->release_audio_patch(hwDevice, handle);
2824 } else {
2825 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2826 }
2827 return status;
2828}
2829
Eric Laurent83b88082014-06-20 18:31:16 -07002830void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2831{
2832 Mutex::Autolock _l(mLock);
2833 mTracks.add(track);
2834}
2835
2836void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2837{
2838 Mutex::Autolock _l(mLock);
2839 destroyTrack_l(track);
2840}
2841
2842void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2843{
2844 ThreadBase::getAudioPortConfig(config);
2845 config->role = AUDIO_PORT_ROLE_SOURCE;
2846 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2847 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2848}
2849
Eric Laurent81784c32012-11-19 14:55:58 -08002850// ----------------------------------------------------------------------------
2851
2852AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2853 audio_io_handle_t id, audio_devices_t device, type_t type)
2854 : PlaybackThread(audioFlinger, output, id, device, type),
2855 // mAudioMixer below
2856 // mFastMixer below
2857 mFastMixerFutex(0)
2858 // mOutputSink below
2859 // mPipeSink below
2860 // mNormalSink below
2861{
2862 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002863 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002864 "mFrameCount=%d, mNormalFrameCount=%d",
2865 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2866 mNormalFrameCount);
2867 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2868
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // create an NBAIO sink for the HAL output stream, and negotiate
2870 mOutputSink = new AudioStreamOutSink(output->stream);
2871 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002872 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002873 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2874 ALOG_ASSERT(index == 0);
2875
2876 // initialize fast mixer depending on configuration
2877 bool initFastMixer;
2878 switch (kUseFastMixer) {
2879 case FastMixer_Never:
2880 initFastMixer = false;
2881 break;
2882 case FastMixer_Always:
2883 initFastMixer = true;
2884 break;
2885 case FastMixer_Static:
2886 case FastMixer_Dynamic:
2887 initFastMixer = mFrameCount < mNormalFrameCount;
2888 break;
2889 }
2890 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002891 audio_format_t fastMixerFormat;
2892 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2893 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2894 } else {
2895 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2896 }
2897 if (mFormat != fastMixerFormat) {
2898 // change our Sink format to accept our intermediate precision
2899 mFormat = fastMixerFormat;
2900 free(mSinkBuffer);
2901 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2902 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2903 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2904 }
Eric Laurent81784c32012-11-19 14:55:58 -08002905
2906 // create a MonoPipe to connect our submix to FastMixer
2907 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002908 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002909 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002910 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002911 format.mFormat = fastMixerFormat;
2912 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2915 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2916 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2917 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2918 const NBAIO_Format offers[1] = {format};
2919 size_t numCounterOffers = 0;
2920 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2921 ALOG_ASSERT(index == 0);
2922 monoPipe->setAvgFrames((mScreenState & 1) ?
2923 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2924 mPipeSink = monoPipe;
2925
Glenn Kasten46909e72013-02-26 09:20:22 -08002926#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002927 if (mTeeSinkOutputEnabled) {
2928 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002929 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2930 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002931 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002932 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002933 ALOG_ASSERT(index == 0);
2934 mTeeSink = teeSink;
2935 PipeReader *teeSource = new PipeReader(*teeSink);
2936 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002937 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002938 ALOG_ASSERT(index == 0);
2939 mTeeSource = teeSource;
2940 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002941#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002942
2943 // create fast mixer and configure it initially with just one fast track for our submix
2944 mFastMixer = new FastMixer();
2945 FastMixerStateQueue *sq = mFastMixer->sq();
2946#ifdef STATE_QUEUE_DUMP
2947 sq->setObserverDump(&mStateQueueObserverDump);
2948 sq->setMutatorDump(&mStateQueueMutatorDump);
2949#endif
2950 FastMixerState *state = sq->begin();
2951 FastTrack *fastTrack = &state->mFastTracks[0];
2952 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2953 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2954 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002955 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2956 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002957 fastTrack->mGeneration++;
2958 state->mFastTracksGen++;
2959 state->mTrackMask = 1;
2960 // fast mixer will use the HAL output sink
2961 state->mOutputSink = mOutputSink.get();
2962 state->mOutputSinkGen++;
2963 state->mFrameCount = mFrameCount;
2964 state->mCommand = FastMixerState::COLD_IDLE;
2965 // already done in constructor initialization list
2966 //mFastMixerFutex = 0;
2967 state->mColdFutexAddr = &mFastMixerFutex;
2968 state->mColdGen++;
2969 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002970#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002971 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002972#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002973 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2974 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002975 sq->end();
2976 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2977
2978 // start the fast mixer
2979 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2980 pid_t tid = mFastMixer->getTid();
2981 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2982 if (err != 0) {
2983 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2984 kPriorityFastMixer, getpid_cached, tid, err);
2985 }
2986
2987#ifdef AUDIO_WATCHDOG
2988 // create and start the watchdog
2989 mAudioWatchdog = new AudioWatchdog();
2990 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2991 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2992 tid = mAudioWatchdog->getTid();
2993 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2994 if (err != 0) {
2995 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2996 kPriorityFastMixer, getpid_cached, tid, err);
2997 }
2998#endif
2999
Eric Laurent81784c32012-11-19 14:55:58 -08003000 }
3001
3002 switch (kUseFastMixer) {
3003 case FastMixer_Never:
3004 case FastMixer_Dynamic:
3005 mNormalSink = mOutputSink;
3006 break;
3007 case FastMixer_Always:
3008 mNormalSink = mPipeSink;
3009 break;
3010 case FastMixer_Static:
3011 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3012 break;
3013 }
3014}
3015
3016AudioFlinger::MixerThread::~MixerThread()
3017{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003018 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003019 FastMixerStateQueue *sq = mFastMixer->sq();
3020 FastMixerState *state = sq->begin();
3021 if (state->mCommand == FastMixerState::COLD_IDLE) {
3022 int32_t old = android_atomic_inc(&mFastMixerFutex);
3023 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003024 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003025 }
3026 }
3027 state->mCommand = FastMixerState::EXIT;
3028 sq->end();
3029 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3030 mFastMixer->join();
3031 // Though the fast mixer thread has exited, it's state queue is still valid.
3032 // We'll use that extract the final state which contains one remaining fast track
3033 // corresponding to our sub-mix.
3034 state = sq->begin();
3035 ALOG_ASSERT(state->mTrackMask == 1);
3036 FastTrack *fastTrack = &state->mFastTracks[0];
3037 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3038 delete fastTrack->mBufferProvider;
3039 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003040 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003041#ifdef AUDIO_WATCHDOG
3042 if (mAudioWatchdog != 0) {
3043 mAudioWatchdog->requestExit();
3044 mAudioWatchdog->requestExitAndWait();
3045 mAudioWatchdog.clear();
3046 }
3047#endif
3048 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003049 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003050 delete mAudioMixer;
3051}
3052
3053
3054uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3055{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003056 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003057 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3058 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3059 }
3060 return latency;
3061}
3062
3063
3064void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3065{
3066 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3067}
3068
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003070{
3071 // FIXME we should only do one push per cycle; confirm this is true
3072 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003073 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003074 FastMixerStateQueue *sq = mFastMixer->sq();
3075 FastMixerState *state = sq->begin();
3076 if (state->mCommand != FastMixerState::MIX_WRITE &&
3077 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3078 if (state->mCommand == FastMixerState::COLD_IDLE) {
3079 int32_t old = android_atomic_inc(&mFastMixerFutex);
3080 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003081 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003082 }
3083#ifdef AUDIO_WATCHDOG
3084 if (mAudioWatchdog != 0) {
3085 mAudioWatchdog->resume();
3086 }
3087#endif
3088 }
3089 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003090 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3091 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003092 sq->end();
3093 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3094 if (kUseFastMixer == FastMixer_Dynamic) {
3095 mNormalSink = mPipeSink;
3096 }
3097 } else {
3098 sq->end(false /*didModify*/);
3099 }
3100 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003102}
3103
3104void AudioFlinger::MixerThread::threadLoop_standby()
3105{
3106 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003107 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003108 FastMixerStateQueue *sq = mFastMixer->sq();
3109 FastMixerState *state = sq->begin();
3110 if (!(state->mCommand & FastMixerState::IDLE)) {
3111 state->mCommand = FastMixerState::COLD_IDLE;
3112 state->mColdFutexAddr = &mFastMixerFutex;
3113 state->mColdGen++;
3114 mFastMixerFutex = 0;
3115 sq->end();
3116 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3117 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3118 if (kUseFastMixer == FastMixer_Dynamic) {
3119 mNormalSink = mOutputSink;
3120 }
3121#ifdef AUDIO_WATCHDOG
3122 if (mAudioWatchdog != 0) {
3123 mAudioWatchdog->pause();
3124 }
3125#endif
3126 } else {
3127 sq->end(false /*didModify*/);
3128 }
3129 }
3130 PlaybackThread::threadLoop_standby();
3131}
3132
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3134{
3135 return false;
3136}
3137
3138bool AudioFlinger::PlaybackThread::shouldStandby_l()
3139{
3140 return !mStandby;
3141}
3142
3143bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3144{
3145 Mutex::Autolock _l(mLock);
3146 return waitingAsyncCallback_l();
3147}
3148
Eric Laurent81784c32012-11-19 14:55:58 -08003149// shared by MIXER and DIRECT, overridden by DUPLICATING
3150void AudioFlinger::PlaybackThread::threadLoop_standby()
3151{
3152 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3153 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003154 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003155 // discard any pending drain or write ack by incrementing sequence
3156 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3157 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003159 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3160 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003162 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003163}
3164
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003165void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3166{
3167 ALOGV("signal playback thread");
3168 broadcast_l();
3169}
3170
Eric Laurent81784c32012-11-19 14:55:58 -08003171void AudioFlinger::MixerThread::threadLoop_mix()
3172{
3173 // obtain the presentation timestamp of the next output buffer
3174 int64_t pts;
3175 status_t status = INVALID_OPERATION;
3176
3177 if (mNormalSink != 0) {
3178 status = mNormalSink->getNextWriteTimestamp(&pts);
3179 } else {
3180 status = mOutputSink->getNextWriteTimestamp(&pts);
3181 }
3182
3183 if (status != NO_ERROR) {
3184 pts = AudioBufferProvider::kInvalidPTS;
3185 }
3186
3187 // mix buffers...
3188 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003189 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003190 // increase sleep time progressively when application underrun condition clears.
3191 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3192 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3193 // such that we would underrun the audio HAL.
3194 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3195 sleepTimeShift--;
3196 }
3197 sleepTime = 0;
3198 standbyTime = systemTime() + standbyDelay;
3199 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003200
Eric Laurent81784c32012-11-19 14:55:58 -08003201}
3202
3203void AudioFlinger::MixerThread::threadLoop_sleepTime()
3204{
3205 // If no tracks are ready, sleep once for the duration of an output
3206 // buffer size, then write 0s to the output
3207 if (sleepTime == 0) {
3208 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3209 sleepTime = activeSleepTime >> sleepTimeShift;
3210 if (sleepTime < kMinThreadSleepTimeUs) {
3211 sleepTime = kMinThreadSleepTimeUs;
3212 }
3213 // reduce sleep time in case of consecutive application underruns to avoid
3214 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3215 // duration we would end up writing less data than needed by the audio HAL if
3216 // the condition persists.
3217 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3218 sleepTimeShift++;
3219 }
3220 } else {
3221 sleepTime = idleSleepTime;
3222 }
3223 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003224 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3225 // before effects processing or output.
3226 if (mMixerBufferValid) {
3227 memset(mMixerBuffer, 0, mMixerBufferSize);
3228 } else {
3229 memset(mSinkBuffer, 0, mSinkBufferSize);
3230 }
Eric Laurent81784c32012-11-19 14:55:58 -08003231 sleepTime = 0;
3232 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3233 "anticipated start");
3234 }
3235 // TODO add standby time extension fct of effect tail
3236}
3237
3238// prepareTracks_l() must be called with ThreadBase::mLock held
3239AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3240 Vector< sp<Track> > *tracksToRemove)
3241{
3242
3243 mixer_state mixerStatus = MIXER_IDLE;
3244 // find out which tracks need to be processed
3245 size_t count = mActiveTracks.size();
3246 size_t mixedTracks = 0;
3247 size_t tracksWithEffect = 0;
3248 // counts only _active_ fast tracks
3249 size_t fastTracks = 0;
3250 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3251
3252 float masterVolume = mMasterVolume;
3253 bool masterMute = mMasterMute;
3254
3255 if (masterMute) {
3256 masterVolume = 0;
3257 }
3258 // Delegate master volume control to effect in output mix effect chain if needed
3259 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3260 if (chain != 0) {
3261 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3262 chain->setVolume_l(&v, &v);
3263 masterVolume = (float)((v + (1 << 23)) >> 24);
3264 chain.clear();
3265 }
3266
3267 // prepare a new state to push
3268 FastMixerStateQueue *sq = NULL;
3269 FastMixerState *state = NULL;
3270 bool didModify = false;
3271 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003272 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003273 sq = mFastMixer->sq();
3274 state = sq->begin();
3275 }
3276
Andy Hung69aed5f2014-02-25 17:24:40 -08003277 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003278 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003279
Eric Laurent81784c32012-11-19 14:55:58 -08003280 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003281 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003282 if (t == 0) {
3283 continue;
3284 }
3285
3286 // this const just means the local variable doesn't change
3287 Track* const track = t.get();
3288
3289 // process fast tracks
3290 if (track->isFastTrack()) {
3291
3292 // It's theoretically possible (though unlikely) for a fast track to be created
3293 // and then removed within the same normal mix cycle. This is not a problem, as
3294 // the track never becomes active so it's fast mixer slot is never touched.
3295 // The converse, of removing an (active) track and then creating a new track
3296 // at the identical fast mixer slot within the same normal mix cycle,
3297 // is impossible because the slot isn't marked available until the end of each cycle.
3298 int j = track->mFastIndex;
3299 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3300 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3301 FastTrack *fastTrack = &state->mFastTracks[j];
3302
3303 // Determine whether the track is currently in underrun condition,
3304 // and whether it had a recent underrun.
3305 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3306 FastTrackUnderruns underruns = ftDump->mUnderruns;
3307 uint32_t recentFull = (underruns.mBitFields.mFull -
3308 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3309 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3310 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3311 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3312 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3313 uint32_t recentUnderruns = recentPartial + recentEmpty;
3314 track->mObservedUnderruns = underruns;
3315 // don't count underruns that occur while stopping or pausing
3316 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003317 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3318 recentUnderruns > 0) {
3319 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3320 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003321 }
3322
3323 // This is similar to the state machine for normal tracks,
3324 // with a few modifications for fast tracks.
3325 bool isActive = true;
3326 switch (track->mState) {
3327 case TrackBase::STOPPING_1:
3328 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003330 track->mState = TrackBase::STOPPING_2;
3331 }
3332 break;
3333 case TrackBase::PAUSING:
3334 // ramp down is not yet implemented
3335 track->setPaused();
3336 break;
3337 case TrackBase::RESUMING:
3338 // ramp up is not yet implemented
3339 track->mState = TrackBase::ACTIVE;
3340 break;
3341 case TrackBase::ACTIVE:
3342 if (recentFull > 0 || recentPartial > 0) {
3343 // track has provided at least some frames recently: reset retry count
3344 track->mRetryCount = kMaxTrackRetries;
3345 }
3346 if (recentUnderruns == 0) {
3347 // no recent underruns: stay active
3348 break;
3349 }
3350 // there has recently been an underrun of some kind
3351 if (track->sharedBuffer() == 0) {
3352 // were any of the recent underruns "empty" (no frames available)?
3353 if (recentEmpty == 0) {
3354 // no, then ignore the partial underruns as they are allowed indefinitely
3355 break;
3356 }
3357 // there has recently been an "empty" underrun: decrement the retry counter
3358 if (--(track->mRetryCount) > 0) {
3359 break;
3360 }
3361 // indicate to client process that the track was disabled because of underrun;
3362 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003363 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003364 // remove from active list, but state remains ACTIVE [confusing but true]
3365 isActive = false;
3366 break;
3367 }
3368 // fall through
3369 case TrackBase::STOPPING_2:
3370 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003371 case TrackBase::STOPPED:
3372 case TrackBase::FLUSHED: // flush() while active
3373 // Check for presentation complete if track is inactive
3374 // We have consumed all the buffers of this track.
3375 // This would be incomplete if we auto-paused on underrun
3376 {
3377 size_t audioHALFrames =
3378 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3379 size_t framesWritten = mBytesWritten / mFrameSize;
3380 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3381 // track stays in active list until presentation is complete
3382 break;
3383 }
3384 }
3385 if (track->isStopping_2()) {
3386 track->mState = TrackBase::STOPPED;
3387 }
3388 if (track->isStopped()) {
3389 // Can't reset directly, as fast mixer is still polling this track
3390 // track->reset();
3391 // So instead mark this track as needing to be reset after push with ack
3392 resetMask |= 1 << i;
3393 }
3394 isActive = false;
3395 break;
3396 case TrackBase::IDLE:
3397 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003398 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003399 }
3400
3401 if (isActive) {
3402 // was it previously inactive?
3403 if (!(state->mTrackMask & (1 << j))) {
3404 ExtendedAudioBufferProvider *eabp = track;
3405 VolumeProvider *vp = track;
3406 fastTrack->mBufferProvider = eabp;
3407 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003408 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003409 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003410 fastTrack->mGeneration++;
3411 state->mTrackMask |= 1 << j;
3412 didModify = true;
3413 // no acknowledgement required for newly active tracks
3414 }
3415 // cache the combined master volume and stream type volume for fast mixer; this
3416 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003417 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003418 ++fastTracks;
3419 } else {
3420 // was it previously active?
3421 if (state->mTrackMask & (1 << j)) {
3422 fastTrack->mBufferProvider = NULL;
3423 fastTrack->mGeneration++;
3424 state->mTrackMask &= ~(1 << j);
3425 didModify = true;
3426 // If any fast tracks were removed, we must wait for acknowledgement
3427 // because we're about to decrement the last sp<> on those tracks.
3428 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3429 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003430 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003431 }
3432 tracksToRemove->add(track);
3433 // Avoids a misleading display in dumpsys
3434 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3435 }
3436 continue;
3437 }
3438
3439 { // local variable scope to avoid goto warning
3440
3441 audio_track_cblk_t* cblk = track->cblk();
3442
3443 // The first time a track is added we wait
3444 // for all its buffers to be filled before processing it
3445 int name = track->name();
3446 // make sure that we have enough frames to mix one full buffer.
3447 // enforce this condition only once to enable draining the buffer in case the client
3448 // app does not call stop() and relies on underrun to stop:
3449 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3450 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003451 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003452 uint32_t sr = track->sampleRate();
3453 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003454 desiredFrames = mNormalFrameCount;
3455 } else {
3456 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003457 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003458 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003459 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003460 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003461#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003462 // the minimum track buffer size is normally twice the number of frames necessary
3463 // to fill one buffer and the resampler should not leave more than one buffer worth
3464 // of unreleased frames after each pass, but just in case...
3465 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003466#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003467 }
Eric Laurent81784c32012-11-19 14:55:58 -08003468 uint32_t minFrames = 1;
3469 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3470 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003471 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003473
3474 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003475 if (ATRACE_ENABLED()) {
3476 // I wish we had formatted trace names
3477 char traceName[16];
3478 strcpy(traceName, "nRdy");
3479 int name = track->name();
3480 if (AudioMixer::TRACK0 <= name &&
3481 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3482 name -= AudioMixer::TRACK0;
3483 traceName[4] = (name / 10) + '0';
3484 traceName[5] = (name % 10) + '0';
3485 } else {
3486 traceName[4] = '?';
3487 traceName[5] = '?';
3488 }
3489 traceName[6] = '\0';
3490 ATRACE_INT(traceName, framesReady);
3491 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003492 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003493 !track->isPaused() && !track->isTerminated())
3494 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003495 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003496
3497 mixedTracks++;
3498
Andy Hung69aed5f2014-02-25 17:24:40 -08003499 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3500 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003501 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003502 if (track->mainBuffer() != mSinkBuffer &&
3503 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003504 if (mEffectBufferEnabled) {
3505 mEffectBufferValid = true; // Later can set directly.
3506 }
Eric Laurent81784c32012-11-19 14:55:58 -08003507 chain = getEffectChain_l(track->sessionId());
3508 // Delegate volume control to effect in track effect chain if needed
3509 if (chain != 0) {
3510 tracksWithEffect++;
3511 } else {
3512 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3513 "session %d",
3514 name, track->sessionId());
3515 }
3516 }
3517
3518
3519 int param = AudioMixer::VOLUME;
3520 if (track->mFillingUpStatus == Track::FS_FILLED) {
3521 // no ramp for the first volume setting
3522 track->mFillingUpStatus = Track::FS_ACTIVE;
3523 if (track->mState == TrackBase::RESUMING) {
3524 track->mState = TrackBase::ACTIVE;
3525 param = AudioMixer::RAMP_VOLUME;
3526 }
3527 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003528 // FIXME should not make a decision based on mServer
3529 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003530 // If the track is stopped before the first frame was mixed,
3531 // do not apply ramp
3532 param = AudioMixer::RAMP_VOLUME;
3533 }
3534
3535 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003536 uint32_t vl, vr; // in U8.24 integer format
3537 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003538 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003539 vl = vr = 0;
3540 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003541 if (track->isPausing()) {
3542 track->setPaused();
3543 }
3544 } else {
3545
3546 // read original volumes with volume control
3547 float typeVolume = mStreamTypes[track->streamType()].volume;
3548 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003549 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003550 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003551 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3552 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003553 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003554 if (vlf > GAIN_FLOAT_UNITY) {
3555 ALOGV("Track left volume out of range: %.3g", vlf);
3556 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003557 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003558 if (vrf > GAIN_FLOAT_UNITY) {
3559 ALOGV("Track right volume out of range: %.3g", vrf);
3560 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003561 }
3562 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003563 vlf *= v;
3564 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003565 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003566 // then derive vl and vr as U8.24 versions for the effect chain
3567 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3568 vl = (uint32_t) (scaleto8_24 * vlf);
3569 vr = (uint32_t) (scaleto8_24 * vrf);
3570 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003571 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003572 // send level comes from shared memory and so may be corrupt
3573 if (sendLevel > MAX_GAIN_INT) {
3574 ALOGV("Track send level out of range: %04X", sendLevel);
3575 sendLevel = MAX_GAIN_INT;
3576 }
Andy Hung6be49402014-05-30 10:42:03 -07003577 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3578 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // Delegate volume control to effect in track effect chain if needed
3582 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3583 // Do not ramp volume if volume is controlled by effect
3584 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003585 // Update remaining floating point volume levels
3586 vlf = (float)vl / (1 << 24);
3587 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003588 track->mHasVolumeController = true;
3589 } else {
3590 // force no volume ramp when volume controller was just disabled or removed
3591 // from effect chain to avoid volume spike
3592 if (track->mHasVolumeController) {
3593 param = AudioMixer::VOLUME;
3594 }
3595 track->mHasVolumeController = false;
3596 }
3597
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // XXX: these things DON'T need to be done each time
3599 mAudioMixer->setBufferProvider(name, track);
3600 mAudioMixer->enable(name);
3601
Andy Hung6be49402014-05-30 10:42:03 -07003602 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3603 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3604 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003605 mAudioMixer->setParameter(
3606 name,
3607 AudioMixer::TRACK,
3608 AudioMixer::FORMAT, (void *)track->format());
3609 mAudioMixer->setParameter(
3610 name,
3611 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003612 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003613 mAudioMixer->setParameter(
3614 name,
3615 AudioMixer::TRACK,
3616 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003617 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003618 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003619 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003620 if (reqSampleRate == 0) {
3621 reqSampleRate = mSampleRate;
3622 } else if (reqSampleRate > maxSampleRate) {
3623 reqSampleRate = maxSampleRate;
3624 }
Eric Laurent81784c32012-11-19 14:55:58 -08003625 mAudioMixer->setParameter(
3626 name,
3627 AudioMixer::RESAMPLE,
3628 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003629 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003630 /*
3631 * Select the appropriate output buffer for the track.
3632 *
Andy Hung98ef9782014-03-04 14:46:50 -08003633 * Tracks with effects go into their own effects chain buffer
3634 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003635 *
3636 * Other tracks can use mMixerBuffer for higher precision
3637 * channel accumulation. If this buffer is enabled
3638 * (mMixerBufferEnabled true), then selected tracks will accumulate
3639 * into it.
3640 *
3641 */
3642 if (mMixerBufferEnabled
3643 && (track->mainBuffer() == mSinkBuffer
3644 || track->mainBuffer() == mMixerBuffer)) {
3645 mAudioMixer->setParameter(
3646 name,
3647 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003648 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003649 mAudioMixer->setParameter(
3650 name,
3651 AudioMixer::TRACK,
3652 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3653 // TODO: override track->mainBuffer()?
3654 mMixerBufferValid = true;
3655 } else {
3656 mAudioMixer->setParameter(
3657 name,
3658 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003659 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003660 mAudioMixer->setParameter(
3661 name,
3662 AudioMixer::TRACK,
3663 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3664 }
Eric Laurent81784c32012-11-19 14:55:58 -08003665 mAudioMixer->setParameter(
3666 name,
3667 AudioMixer::TRACK,
3668 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3669
3670 // reset retry count
3671 track->mRetryCount = kMaxTrackRetries;
3672
3673 // If one track is ready, set the mixer ready if:
3674 // - the mixer was not ready during previous round OR
3675 // - no other track is not ready
3676 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3677 mixerStatus != MIXER_TRACKS_ENABLED) {
3678 mixerStatus = MIXER_TRACKS_READY;
3679 }
3680 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003681 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003682 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003683 }
Eric Laurent81784c32012-11-19 14:55:58 -08003684 // clear effect chain input buffer if an active track underruns to avoid sending
3685 // previous audio buffer again to effects
3686 chain = getEffectChain_l(track->sessionId());
3687 if (chain != 0) {
3688 chain->clearInputBuffer();
3689 }
3690
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003691 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003692 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3693 track->isStopped() || track->isPaused()) {
3694 // We have consumed all the buffers of this track.
3695 // Remove it from the list of active tracks.
3696 // TODO: use actual buffer filling status instead of latency when available from
3697 // audio HAL
3698 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3699 size_t framesWritten = mBytesWritten / mFrameSize;
3700 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3701 if (track->isStopped()) {
3702 track->reset();
3703 }
3704 tracksToRemove->add(track);
3705 }
3706 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 // No buffers for this track. Give it a few chances to
3708 // fill a buffer, then remove it from active list.
3709 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003710 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003711 tracksToRemove->add(track);
3712 // indicate to client process that the track was disabled because of underrun;
3713 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003714 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003715 // If one track is not ready, mark the mixer also not ready if:
3716 // - the mixer was ready during previous round OR
3717 // - no other track is ready
3718 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3719 mixerStatus != MIXER_TRACKS_READY) {
3720 mixerStatus = MIXER_TRACKS_ENABLED;
3721 }
3722 }
3723 mAudioMixer->disable(name);
3724 }
3725
3726 } // local variable scope to avoid goto warning
3727track_is_ready: ;
3728
3729 }
3730
3731 // Push the new FastMixer state if necessary
3732 bool pauseAudioWatchdog = false;
3733 if (didModify) {
3734 state->mFastTracksGen++;
3735 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3736 if (kUseFastMixer == FastMixer_Dynamic &&
3737 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3738 state->mCommand = FastMixerState::COLD_IDLE;
3739 state->mColdFutexAddr = &mFastMixerFutex;
3740 state->mColdGen++;
3741 mFastMixerFutex = 0;
3742 if (kUseFastMixer == FastMixer_Dynamic) {
3743 mNormalSink = mOutputSink;
3744 }
3745 // If we go into cold idle, need to wait for acknowledgement
3746 // so that fast mixer stops doing I/O.
3747 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3748 pauseAudioWatchdog = true;
3749 }
Eric Laurent81784c32012-11-19 14:55:58 -08003750 }
3751 if (sq != NULL) {
3752 sq->end(didModify);
3753 sq->push(block);
3754 }
3755#ifdef AUDIO_WATCHDOG
3756 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3757 mAudioWatchdog->pause();
3758 }
3759#endif
3760
3761 // Now perform the deferred reset on fast tracks that have stopped
3762 while (resetMask != 0) {
3763 size_t i = __builtin_ctz(resetMask);
3764 ALOG_ASSERT(i < count);
3765 resetMask &= ~(1 << i);
3766 sp<Track> t = mActiveTracks[i].promote();
3767 if (t == 0) {
3768 continue;
3769 }
3770 Track* track = t.get();
3771 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3772 track->reset();
3773 }
3774
3775 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003776 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003777
Eric Laurent97d547d2014-09-02 14:45:53 -07003778 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3779 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003780 }
3781
3782 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003783 // as long as there are effects we should clear the effects buffer, to avoid
3784 // passing a non-clean buffer to the effect chain
3785 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003786 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003787 // sink or mix buffer must be cleared if all tracks are connected to an
3788 // effect chain as in this case the mixer will not write to the sink or mix buffer
3789 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003790 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3791 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003792 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003793 if (mMixerBufferValid) {
3794 memset(mMixerBuffer, 0, mMixerBufferSize);
3795 // TODO: In testing, mSinkBuffer below need not be cleared because
3796 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3797 // after mixing.
3798 //
3799 // To enforce this guarantee:
3800 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3801 // (mixedTracks == 0 && fastTracks > 0))
3802 // must imply MIXER_TRACKS_READY.
3803 // Later, we may clear buffers regardless, and skip much of this logic.
3804 }
Andy Hung98ef9782014-03-04 14:46:50 -08003805 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003806 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003807 }
3808
3809 // if any fast tracks, then status is ready
3810 mMixerStatusIgnoringFastTracks = mixerStatus;
3811 if (fastTracks > 0) {
3812 mixerStatus = MIXER_TRACKS_READY;
3813 }
3814 return mixerStatus;
3815}
3816
3817// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003818int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3819 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003820{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003821 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003822}
3823
3824// deleteTrackName_l() must be called with ThreadBase::mLock held
3825void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3826{
3827 ALOGV("remove track (%d) and delete from mixer", name);
3828 mAudioMixer->deleteTrackName(name);
3829}
3830
Eric Laurent10351942014-05-08 18:49:52 -07003831// checkForNewParameter_l() must be called with ThreadBase::mLock held
3832bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3833 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003834{
Eric Laurent81784c32012-11-19 14:55:58 -08003835 bool reconfig = false;
3836
Eric Laurent10351942014-05-08 18:49:52 -07003837 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003838
Eric Laurent10351942014-05-08 18:49:52 -07003839 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3840 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003841 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003842 FastMixerStateQueue *sq = mFastMixer->sq();
3843 FastMixerState *state = sq->begin();
3844 if (!(state->mCommand & FastMixerState::IDLE)) {
3845 previousCommand = state->mCommand;
3846 state->mCommand = FastMixerState::HOT_IDLE;
3847 sq->end();
3848 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3849 } else {
3850 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003851 }
Eric Laurent10351942014-05-08 18:49:52 -07003852 }
Eric Laurent81784c32012-11-19 14:55:58 -08003853
Eric Laurent10351942014-05-08 18:49:52 -07003854 AudioParameter param = AudioParameter(keyValuePair);
3855 int value;
3856 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3857 reconfig = true;
3858 }
3859 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003860 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003861 status = BAD_VALUE;
3862 } else {
3863 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003864 reconfig = true;
3865 }
Eric Laurent10351942014-05-08 18:49:52 -07003866 }
3867 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003868 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003869 status = BAD_VALUE;
3870 } else {
3871 // no need to save value, since it's constant
3872 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003873 }
Eric Laurent10351942014-05-08 18:49:52 -07003874 }
3875 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3876 // do not accept frame count changes if tracks are open as the track buffer
3877 // size depends on frame count and correct behavior would not be guaranteed
3878 // if frame count is changed after track creation
3879 if (!mTracks.isEmpty()) {
3880 status = INVALID_OPERATION;
3881 } else {
3882 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003883 }
Eric Laurent10351942014-05-08 18:49:52 -07003884 }
3885 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003886#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003887 // when changing the audio output device, call addBatteryData to notify
3888 // the change
3889 if (mOutDevice != value) {
3890 uint32_t params = 0;
3891 // check whether speaker is on
3892 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3893 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003894 }
Eric Laurent10351942014-05-08 18:49:52 -07003895
3896 audio_devices_t deviceWithoutSpeaker
3897 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3898 // check if any other device (except speaker) is on
3899 if (value & deviceWithoutSpeaker ) {
3900 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3901 }
3902
3903 if (params != 0) {
3904 addBatteryData(params);
3905 }
3906 }
Eric Laurent81784c32012-11-19 14:55:58 -08003907#endif
3908
Eric Laurent10351942014-05-08 18:49:52 -07003909 // forward device change to effects that have requested to be
3910 // aware of attached audio device.
3911 if (value != AUDIO_DEVICE_NONE) {
3912 mOutDevice = value;
3913 for (size_t i = 0; i < mEffectChains.size(); i++) {
3914 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003915 }
3916 }
Eric Laurent10351942014-05-08 18:49:52 -07003917 }
Eric Laurent81784c32012-11-19 14:55:58 -08003918
Eric Laurent10351942014-05-08 18:49:52 -07003919 if (status == NO_ERROR) {
3920 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3921 keyValuePair.string());
3922 if (!mStandby && status == INVALID_OPERATION) {
3923 mOutput->stream->common.standby(&mOutput->stream->common);
3924 mStandby = true;
3925 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003926 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003927 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003928 }
Eric Laurent10351942014-05-08 18:49:52 -07003929 if (status == NO_ERROR && reconfig) {
3930 readOutputParameters_l();
3931 delete mAudioMixer;
3932 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3933 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003934 int name = getTrackName_l(mTracks[i]->mChannelMask,
3935 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003936 if (name < 0) {
3937 break;
3938 }
3939 mTracks[i]->mName = name;
3940 }
3941 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3942 }
Eric Laurent81784c32012-11-19 14:55:58 -08003943 }
3944
3945 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003946 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003947 FastMixerStateQueue *sq = mFastMixer->sq();
3948 FastMixerState *state = sq->begin();
3949 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3950 state->mCommand = previousCommand;
3951 sq->end();
3952 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3953 }
3954
3955 return reconfig;
3956}
3957
3958
3959void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3960{
3961 const size_t SIZE = 256;
3962 char buffer[SIZE];
3963 String8 result;
3964
3965 PlaybackThread::dumpInternals(fd, args);
3966
Elliott Hughes87cebad2014-05-22 10:14:43 -07003967 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003968
3969 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003970 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003971 copy.dump(fd);
3972
3973#ifdef STATE_QUEUE_DUMP
3974 // Similar for state queue
3975 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3976 observerCopy.dump(fd);
3977 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3978 mutatorCopy.dump(fd);
3979#endif
3980
Glenn Kasten46909e72013-02-26 09:20:22 -08003981#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003982 // Write the tee output to a .wav file
3983 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003984#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003985
3986#ifdef AUDIO_WATCHDOG
3987 if (mAudioWatchdog != 0) {
3988 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3989 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3990 wdCopy.dump(fd);
3991 }
3992#endif
3993}
3994
3995uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3996{
3997 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3998}
3999
4000uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4001{
4002 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4003}
4004
4005void AudioFlinger::MixerThread::cacheParameters_l()
4006{
4007 PlaybackThread::cacheParameters_l();
4008
4009 // FIXME: Relaxed timing because of a certain device that can't meet latency
4010 // Should be reduced to 2x after the vendor fixes the driver issue
4011 // increase threshold again due to low power audio mode. The way this warning
4012 // threshold is calculated and its usefulness should be reconsidered anyway.
4013 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4014}
4015
4016// ----------------------------------------------------------------------------
4017
4018AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4019 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4020 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4021 // mLeftVolFloat, mRightVolFloat
4022{
4023}
4024
Eric Laurentbfb1b832013-01-07 09:53:42 -08004025AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4026 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4027 ThreadBase::type_t type)
4028 : PlaybackThread(audioFlinger, output, id, device, type)
4029 // mLeftVolFloat, mRightVolFloat
4030{
4031}
4032
Eric Laurent81784c32012-11-19 14:55:58 -08004033AudioFlinger::DirectOutputThread::~DirectOutputThread()
4034{
4035}
4036
Eric Laurentbfb1b832013-01-07 09:53:42 -08004037void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4038{
4039 audio_track_cblk_t* cblk = track->cblk();
4040 float left, right;
4041
4042 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4043 left = right = 0;
4044 } else {
4045 float typeVolume = mStreamTypes[track->streamType()].volume;
4046 float v = mMasterVolume * typeVolume;
4047 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004048 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4049 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4050 if (left > GAIN_FLOAT_UNITY) {
4051 left = GAIN_FLOAT_UNITY;
4052 }
4053 left *= v;
4054 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4055 if (right > GAIN_FLOAT_UNITY) {
4056 right = GAIN_FLOAT_UNITY;
4057 }
4058 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 }
4060
4061 if (lastTrack) {
4062 if (left != mLeftVolFloat || right != mRightVolFloat) {
4063 mLeftVolFloat = left;
4064 mRightVolFloat = right;
4065
4066 // Convert volumes from float to 8.24
4067 uint32_t vl = (uint32_t)(left * (1 << 24));
4068 uint32_t vr = (uint32_t)(right * (1 << 24));
4069
4070 // Delegate volume control to effect in track effect chain if needed
4071 // only one effect chain can be present on DirectOutputThread, so if
4072 // there is one, the track is connected to it
4073 if (!mEffectChains.isEmpty()) {
4074 mEffectChains[0]->setVolume_l(&vl, &vr);
4075 left = (float)vl / (1 << 24);
4076 right = (float)vr / (1 << 24);
4077 }
4078 if (mOutput->stream->set_volume) {
4079 mOutput->stream->set_volume(mOutput->stream, left, right);
4080 }
4081 }
4082 }
4083}
4084
4085
Eric Laurent81784c32012-11-19 14:55:58 -08004086AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4087 Vector< sp<Track> > *tracksToRemove
4088)
4089{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004090 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004091 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004092 bool doHwPause = false;
4093 bool doHwResume = false;
4094 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004095
4096 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004097 for (size_t i = 0; i < count; i++) {
4098 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004099 // The track died recently
4100 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004101 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004102 }
4103
4104 Track* const track = t.get();
4105 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004106 // Only consider last track started for volume and mixer state control.
4107 // In theory an older track could underrun and restart after the new one starts
4108 // but as we only care about the transition phase between two tracks on a
4109 // direct output, it is not a problem to ignore the underrun case.
4110 sp<Track> l = mLatestActiveTrack.promote();
4111 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004112
Eric Laurentd1f69b02014-12-15 14:33:13 -08004113 if (mHwSupportsPause && track->isPausing()) {
4114 track->setPaused();
4115 if (last && !mHwPaused) {
4116 doHwPause = true;
4117 mHwPaused = true;
4118 }
4119 tracksToRemove->add(track);
4120 } else if (track->isFlushPending()) {
4121 track->flushAck();
4122 if (last) {
4123 flushPending = true;
4124 }
4125 } else if (mHwSupportsPause && track->isResumePending()){
4126 track->resumeAck();
4127 if (last) {
4128 if (mHwPaused) {
4129 doHwResume = true;
4130 mHwPaused = false;
4131 }
4132 }
4133 }
4134
Eric Laurent81784c32012-11-19 14:55:58 -08004135 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004136 // for all its buffers to be filled before processing it.
4137 // Allow draining the buffer in case the client
4138 // app does not call stop() and relies on underrun to stop:
4139 // hence the test on (track->mRetryCount > 1).
4140 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004141 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004142 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4143 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004144 minFrames = mNormalFrameCount;
4145 } else {
4146 minFrames = 1;
4147 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004148
Eric Laurentab5cdba2014-06-09 17:22:27 -07004149 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4150 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004151 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004152 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004153
4154 if (track->mFillingUpStatus == Track::FS_FILLED) {
4155 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004156 // make sure processVolume_l() will apply new volume even if 0
4157 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004158 if (!mHwSupportsPause) {
4159 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004160 }
4161 }
4162
4163 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004164 processVolume_l(track, last);
4165 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004166 // reset retry count
4167 track->mRetryCount = kMaxTrackRetriesDirect;
4168 mActiveTrack = t;
4169 mixerStatus = MIXER_TRACKS_READY;
4170 }
Eric Laurent81784c32012-11-19 14:55:58 -08004171 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004172 // clear effect chain input buffer if the last active track started underruns
4173 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004174 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004175 mEffectChains[0]->clearInputBuffer();
4176 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004177 if (track->isStopping_1()) {
4178 track->mState = TrackBase::STOPPING_2;
4179 }
4180 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4181 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004182 // We have consumed all the buffers of this track.
4183 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004184 size_t audioHALFrames;
4185 if (audio_is_linear_pcm(mFormat)) {
4186 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4187 } else {
4188 audioHALFrames = 0;
4189 }
4190
Eric Laurent81784c32012-11-19 14:55:58 -08004191 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004192 if (mStandby || !last ||
4193 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004194 if (track->isStopping_2()) {
4195 track->mState = TrackBase::STOPPED;
4196 }
Eric Laurent81784c32012-11-19 14:55:58 -08004197 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004198 if (track->mState == TrackBase::FLUSHED) {
4199 flushHw_l();
4200 }
Eric Laurent81784c32012-11-19 14:55:58 -08004201 track->reset();
4202 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004203 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004204 }
4205 } else {
4206 // No buffers for this track. Give it a few chances to
4207 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004208 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004209 if (--(track->mRetryCount) <= 0) {
4210 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004211 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004212 // indicate to client process that the track was disabled because of underrun;
4213 // it will then automatically call start() when data is available
4214 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004216 mixerStatus = MIXER_TRACKS_ENABLED;
4217 }
4218 }
4219 }
4220 }
4221
Eric Laurentd1f69b02014-12-15 14:33:13 -08004222 // if an active track did not command a flush, check for pending flush on stopped tracks
4223 if (!flushPending) {
4224 for (size_t i = 0; i < mTracks.size(); i++) {
4225 if (mTracks[i]->isFlushPending()) {
4226 mTracks[i]->flushAck();
4227 flushPending = true;
4228 }
4229 }
4230 }
4231
4232 // make sure the pause/flush/resume sequence is executed in the right order.
4233 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4234 // before flush and then resume HW. This can happen in case of pause/flush/resume
4235 // if resume is received before pause is executed.
4236 if (mHwSupportsPause && !mStandby &&
4237 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4238 mOutput->stream->pause(mOutput->stream);
4239 }
4240 if (flushPending) {
4241 flushHw_l();
4242 }
4243 if (mHwSupportsPause && !mStandby && doHwResume) {
4244 mOutput->stream->resume(mOutput->stream);
4245 }
Eric Laurent81784c32012-11-19 14:55:58 -08004246 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004247 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004248
4249 return mixerStatus;
4250}
4251
4252void AudioFlinger::DirectOutputThread::threadLoop_mix()
4253{
Eric Laurent81784c32012-11-19 14:55:58 -08004254 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004255 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004256 // output audio to hardware
4257 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004258 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004259 buffer.frameCount = frameCount;
4260 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004261 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004262 memset(curBuf, 0, frameCount * mFrameSize);
4263 break;
4264 }
4265 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4266 frameCount -= buffer.frameCount;
4267 curBuf += buffer.frameCount * mFrameSize;
4268 mActiveTrack->releaseBuffer(&buffer);
4269 }
Andy Hung2098f272014-02-27 14:00:06 -08004270 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004271 sleepTime = 0;
4272 standbyTime = systemTime() + standbyDelay;
4273 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004274}
4275
4276void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4277{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004278 // do not write to HAL when paused
4279 if (mHwPaused) {
4280 sleepTime = idleSleepTime;
4281 return;
4282 }
Eric Laurent81784c32012-11-19 14:55:58 -08004283 if (sleepTime == 0) {
4284 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4285 sleepTime = activeSleepTime;
4286 } else {
4287 sleepTime = idleSleepTime;
4288 }
4289 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004290 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004291 sleepTime = 0;
4292 }
4293}
4294
Eric Laurentd1f69b02014-12-15 14:33:13 -08004295void AudioFlinger::DirectOutputThread::threadLoop_exit()
4296{
4297 {
4298 Mutex::Autolock _l(mLock);
4299 bool flushPending = false;
4300 for (size_t i = 0; i < mTracks.size(); i++) {
4301 if (mTracks[i]->isFlushPending()) {
4302 mTracks[i]->flushAck();
4303 flushPending = true;
4304 }
4305 }
4306 if (flushPending) {
4307 flushHw_l();
4308 }
4309 }
4310 PlaybackThread::threadLoop_exit();
4311}
4312
4313// must be called with thread mutex locked
4314bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4315{
4316 bool trackPaused = false;
4317
4318 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4319 // after a timeout and we will enter standby then.
4320 if (mTracks.size() > 0) {
4321 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4322 }
4323
4324 return !mStandby && !trackPaused;
4325}
4326
Eric Laurent81784c32012-11-19 14:55:58 -08004327// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004328int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004329 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004330{
4331 return 0;
4332}
4333
4334// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004335void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004336{
4337}
4338
Eric Laurent10351942014-05-08 18:49:52 -07004339// checkForNewParameter_l() must be called with ThreadBase::mLock held
4340bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4341 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004342{
4343 bool reconfig = false;
4344
Eric Laurent10351942014-05-08 18:49:52 -07004345 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004346
Eric Laurent10351942014-05-08 18:49:52 -07004347 AudioParameter param = AudioParameter(keyValuePair);
4348 int value;
4349 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4350 // forward device change to effects that have requested to be
4351 // aware of attached audio device.
4352 if (value != AUDIO_DEVICE_NONE) {
4353 mOutDevice = value;
4354 for (size_t i = 0; i < mEffectChains.size(); i++) {
4355 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004356 }
4357 }
Eric Laurent81784c32012-11-19 14:55:58 -08004358 }
Eric Laurent10351942014-05-08 18:49:52 -07004359 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4360 // do not accept frame count changes if tracks are open as the track buffer
4361 // size depends on frame count and correct behavior would not be garantied
4362 // if frame count is changed after track creation
4363 if (!mTracks.isEmpty()) {
4364 status = INVALID_OPERATION;
4365 } else {
4366 reconfig = true;
4367 }
4368 }
4369 if (status == NO_ERROR) {
4370 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4371 keyValuePair.string());
4372 if (!mStandby && status == INVALID_OPERATION) {
4373 mOutput->stream->common.standby(&mOutput->stream->common);
4374 mStandby = true;
4375 mBytesWritten = 0;
4376 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4377 keyValuePair.string());
4378 }
4379 if (status == NO_ERROR && reconfig) {
4380 readOutputParameters_l();
4381 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4382 }
4383 }
4384
Eric Laurent81784c32012-11-19 14:55:58 -08004385 return reconfig;
4386}
4387
4388uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4389{
4390 uint32_t time;
4391 if (audio_is_linear_pcm(mFormat)) {
4392 time = PlaybackThread::activeSleepTimeUs();
4393 } else {
4394 time = 10000;
4395 }
4396 return time;
4397}
4398
4399uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4400{
4401 uint32_t time;
4402 if (audio_is_linear_pcm(mFormat)) {
4403 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4404 } else {
4405 time = 10000;
4406 }
4407 return time;
4408}
4409
4410uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4411{
4412 uint32_t time;
4413 if (audio_is_linear_pcm(mFormat)) {
4414 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4415 } else {
4416 time = 10000;
4417 }
4418 return time;
4419}
4420
4421void AudioFlinger::DirectOutputThread::cacheParameters_l()
4422{
4423 PlaybackThread::cacheParameters_l();
4424
4425 // use shorter standby delay as on normal output to release
4426 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004427 if (audio_is_linear_pcm(mFormat)) {
4428 standbyDelay = microseconds(activeSleepTime*2);
4429 } else {
4430 standbyDelay = kOffloadStandbyDelayNs;
4431 }
Eric Laurent81784c32012-11-19 14:55:58 -08004432}
4433
Eric Laurente659ef42014-09-29 13:06:46 -07004434void AudioFlinger::DirectOutputThread::flushHw_l()
4435{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004436 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004437 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004438 }
4439 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004440}
4441
Eric Laurent81784c32012-11-19 14:55:58 -08004442// ----------------------------------------------------------------------------
4443
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004445 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004446 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004447 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004448 mWriteAckSequence(0),
4449 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004450{
4451}
4452
4453AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4454{
4455}
4456
4457void AudioFlinger::AsyncCallbackThread::onFirstRef()
4458{
4459 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4460}
4461
4462bool AudioFlinger::AsyncCallbackThread::threadLoop()
4463{
4464 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004465 uint32_t writeAckSequence;
4466 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004467
4468 {
4469 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004470 while (!((mWriteAckSequence & 1) ||
4471 (mDrainSequence & 1) ||
4472 exitPending())) {
4473 mWaitWorkCV.wait(mLock);
4474 }
4475
Eric Laurentbfb1b832013-01-07 09:53:42 -08004476 if (exitPending()) {
4477 break;
4478 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004479 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4480 mWriteAckSequence, mDrainSequence);
4481 writeAckSequence = mWriteAckSequence;
4482 mWriteAckSequence &= ~1;
4483 drainSequence = mDrainSequence;
4484 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485 }
4486 {
Eric Laurent4de95592013-09-26 15:28:21 -07004487 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4488 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004489 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004490 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004492 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004493 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 }
4495 }
4496 }
4497 }
4498 return false;
4499}
4500
4501void AudioFlinger::AsyncCallbackThread::exit()
4502{
4503 ALOGV("AsyncCallbackThread::exit");
4504 Mutex::Autolock _l(mLock);
4505 requestExit();
4506 mWaitWorkCV.broadcast();
4507}
4508
Eric Laurent3b4529e2013-09-05 18:09:19 -07004509void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004510{
4511 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004512 // bit 0 is cleared
4513 mWriteAckSequence = sequence << 1;
4514}
4515
4516void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4517{
4518 Mutex::Autolock _l(mLock);
4519 // ignore unexpected callbacks
4520 if (mWriteAckSequence & 2) {
4521 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 mWaitWorkCV.signal();
4523 }
4524}
4525
Eric Laurent3b4529e2013-09-05 18:09:19 -07004526void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527{
4528 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004529 // bit 0 is cleared
4530 mDrainSequence = sequence << 1;
4531}
4532
4533void AudioFlinger::AsyncCallbackThread::resetDraining()
4534{
4535 Mutex::Autolock _l(mLock);
4536 // ignore unexpected callbacks
4537 if (mDrainSequence & 2) {
4538 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004539 mWaitWorkCV.signal();
4540 }
4541}
4542
4543
4544// ----------------------------------------------------------------------------
4545AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4546 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4547 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004548 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004549{
Eric Laurentfd477972013-10-25 18:10:40 -07004550 //FIXME: mStandby should be set to true by ThreadBase constructor
4551 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004552}
4553
Eric Laurentbfb1b832013-01-07 09:53:42 -08004554void AudioFlinger::OffloadThread::threadLoop_exit()
4555{
4556 if (mFlushPending || mHwPaused) {
4557 // If a flush is pending or track was paused, just discard buffered data
4558 flushHw_l();
4559 } else {
4560 mMixerStatus = MIXER_DRAIN_ALL;
4561 threadLoop_drain();
4562 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004563 if (mUseAsyncWrite) {
4564 ALOG_ASSERT(mCallbackThread != 0);
4565 mCallbackThread->exit();
4566 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004567 PlaybackThread::threadLoop_exit();
4568}
4569
4570AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4571 Vector< sp<Track> > *tracksToRemove
4572)
4573{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004574 size_t count = mActiveTracks.size();
4575
4576 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004577 bool doHwPause = false;
4578 bool doHwResume = false;
4579
Eric Laurentede6c3b2013-09-19 14:37:46 -07004580 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4581
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582 // find out which tracks need to be processed
4583 for (size_t i = 0; i < count; i++) {
4584 sp<Track> t = mActiveTracks[i].promote();
4585 // The track died recently
4586 if (t == 0) {
4587 continue;
4588 }
4589 Track* const track = t.get();
4590 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004591 // Only consider last track started for volume and mixer state control.
4592 // In theory an older track could underrun and restart after the new one starts
4593 // but as we only care about the transition phase between two tracks on a
4594 // direct output, it is not a problem to ignore the underrun case.
4595 sp<Track> l = mLatestActiveTrack.promote();
4596 bool last = l.get() == track;
4597
Haynes Mathew George7844f672014-01-15 12:32:55 -08004598 if (track->isInvalid()) {
4599 ALOGW("An invalidated track shouldn't be in active list");
4600 tracksToRemove->add(track);
4601 continue;
4602 }
4603
4604 if (track->mState == TrackBase::IDLE) {
4605 ALOGW("An idle track shouldn't be in active list");
4606 continue;
4607 }
4608
Eric Laurentbfb1b832013-01-07 09:53:42 -08004609 if (track->isPausing()) {
4610 track->setPaused();
4611 if (last) {
4612 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004613 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 mHwPaused = true;
4615 }
4616 // If we were part way through writing the mixbuffer to
4617 // the HAL we must save this until we resume
4618 // BUG - this will be wrong if a different track is made active,
4619 // in that case we want to discard the pending data in the
4620 // mixbuffer and tell the client to present it again when the
4621 // track is resumed
4622 mPausedWriteLength = mCurrentWriteLength;
4623 mPausedBytesRemaining = mBytesRemaining;
4624 mBytesRemaining = 0; // stop writing
4625 }
4626 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004627 } else if (track->isFlushPending()) {
4628 track->flushAck();
4629 if (last) {
4630 mFlushPending = true;
4631 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004632 } else if (track->isResumePending()){
4633 track->resumeAck();
4634 if (last) {
4635 if (mPausedBytesRemaining) {
4636 // Need to continue write that was interrupted
4637 mCurrentWriteLength = mPausedWriteLength;
4638 mBytesRemaining = mPausedBytesRemaining;
4639 mPausedBytesRemaining = 0;
4640 }
4641 if (mHwPaused) {
4642 doHwResume = true;
4643 mHwPaused = false;
4644 // threadLoop_mix() will handle the case that we need to
4645 // resume an interrupted write
4646 }
4647 // enable write to audio HAL
4648 sleepTime = 0;
4649
4650 // Do not handle new data in this iteration even if track->framesReady()
4651 mixerStatus = MIXER_TRACKS_ENABLED;
4652 }
4653 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004654 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004655 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004656 if (track->mFillingUpStatus == Track::FS_FILLED) {
4657 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004658 // make sure processVolume_l() will apply new volume even if 0
4659 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660 }
4661
4662 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004663 sp<Track> previousTrack = mPreviousTrack.promote();
4664 if (previousTrack != 0) {
4665 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004666 // Flush any data still being written from last track
4667 mBytesRemaining = 0;
4668 if (mPausedBytesRemaining) {
4669 // Last track was paused so we also need to flush saved
4670 // mixbuffer state and invalidate track so that it will
4671 // re-submit that unwritten data when it is next resumed
4672 mPausedBytesRemaining = 0;
4673 // Invalidate is a bit drastic - would be more efficient
4674 // to have a flag to tell client that some of the
4675 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004676 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004677 }
4678 // flush data already sent to the DSP if changing audio session as audio
4679 // comes from a different source. Also invalidate previous track to force a
4680 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004681 if (previousTrack->sessionId() != track->sessionId()) {
4682 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004683 }
4684 }
4685 }
4686 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004687 // reset retry count
4688 track->mRetryCount = kMaxTrackRetriesOffload;
4689 mActiveTrack = t;
4690 mixerStatus = MIXER_TRACKS_READY;
4691 }
4692 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004693 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004694 if (track->isStopping_1()) {
4695 // Hardware buffer can hold a large amount of audio so we must
4696 // wait for all current track's data to drain before we say
4697 // that the track is stopped.
4698 if (mBytesRemaining == 0) {
4699 // Only start draining when all data in mixbuffer
4700 // has been written
4701 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4702 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004703 // do not drain if no data was ever sent to HAL (mStandby == true)
4704 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004705 // do not modify drain sequence if we are already draining. This happens
4706 // when resuming from pause after drain.
4707 if ((mDrainSequence & 1) == 0) {
4708 sleepTime = 0;
4709 standbyTime = systemTime() + standbyDelay;
4710 mixerStatus = MIXER_DRAIN_TRACK;
4711 mDrainSequence += 2;
4712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713 if (mHwPaused) {
4714 // It is possible to move from PAUSED to STOPPING_1 without
4715 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004716 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717 mHwPaused = false;
4718 }
4719 }
4720 }
4721 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004722 // Drain has completed or we are in standby, signal presentation complete
4723 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004724 track->mState = TrackBase::STOPPED;
4725 size_t audioHALFrames =
4726 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4727 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004728 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729 track->presentationComplete(framesWritten, audioHALFrames);
4730 track->reset();
4731 tracksToRemove->add(track);
4732 }
4733 } else {
4734 // No buffers for this track. Give it a few chances to
4735 // fill a buffer, then remove it from active list.
4736 if (--(track->mRetryCount) <= 0) {
4737 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4738 track->name());
4739 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004740 // indicate to client process that the track was disabled because of underrun;
4741 // it will then automatically call start() when data is available
4742 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004743 } else if (last){
4744 mixerStatus = MIXER_TRACKS_ENABLED;
4745 }
4746 }
4747 }
4748 // compute volume for this track
4749 processVolume_l(track, last);
4750 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004751
Eric Laurentea0fade2013-10-04 16:23:48 -07004752 // make sure the pause/flush/resume sequence is executed in the right order.
4753 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4754 // before flush and then resume HW. This can happen in case of pause/flush/resume
4755 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004756 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004757 mOutput->stream->pause(mOutput->stream);
4758 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004759 if (mFlushPending) {
4760 flushHw_l();
4761 mFlushPending = false;
4762 }
Eric Laurentfd477972013-10-25 18:10:40 -07004763 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004764 mOutput->stream->resume(mOutput->stream);
4765 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004766
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767 // remove all the tracks that need to be...
4768 removeTracks_l(*tracksToRemove);
4769
4770 return mixerStatus;
4771}
4772
Eric Laurentbfb1b832013-01-07 09:53:42 -08004773// must be called with thread mutex locked
4774bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4775{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004776 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4777 mWriteAckSequence, mDrainSequence);
4778 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004779 return true;
4780 }
4781 return false;
4782}
4783
Eric Laurentbfb1b832013-01-07 09:53:42 -08004784bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4785{
4786 Mutex::Autolock _l(mLock);
4787 return waitingAsyncCallback_l();
4788}
4789
4790void AudioFlinger::OffloadThread::flushHw_l()
4791{
Eric Laurente659ef42014-09-29 13:06:46 -07004792 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004793 // Flush anything still waiting in the mixbuffer
4794 mCurrentWriteLength = 0;
4795 mBytesRemaining = 0;
4796 mPausedWriteLength = 0;
4797 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004798
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004800 // discard any pending drain or write ack by incrementing sequence
4801 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4802 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004803 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004804 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4805 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806 }
4807}
4808
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004809void AudioFlinger::OffloadThread::onAddNewTrack_l()
4810{
4811 sp<Track> previousTrack = mPreviousTrack.promote();
4812 sp<Track> latestTrack = mLatestActiveTrack.promote();
4813
4814 if (previousTrack != 0 && latestTrack != 0 &&
4815 (previousTrack->sessionId() != latestTrack->sessionId())) {
4816 mFlushPending = true;
4817 }
4818 PlaybackThread::onAddNewTrack_l();
4819}
4820
Eric Laurentbfb1b832013-01-07 09:53:42 -08004821// ----------------------------------------------------------------------------
4822
Eric Laurent81784c32012-11-19 14:55:58 -08004823AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4824 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4825 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4826 DUPLICATING),
4827 mWaitTimeMs(UINT_MAX)
4828{
4829 addOutputTrack(mainThread);
4830}
4831
4832AudioFlinger::DuplicatingThread::~DuplicatingThread()
4833{
4834 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4835 mOutputTracks[i]->destroy();
4836 }
4837}
4838
4839void AudioFlinger::DuplicatingThread::threadLoop_mix()
4840{
4841 // mix buffers...
4842 if (outputsReady(outputTracks)) {
4843 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4844 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004845 if (mMixerBufferValid) {
4846 memset(mMixerBuffer, 0, mMixerBufferSize);
4847 } else {
4848 memset(mSinkBuffer, 0, mSinkBufferSize);
4849 }
Eric Laurent81784c32012-11-19 14:55:58 -08004850 }
4851 sleepTime = 0;
4852 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004853 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004854 standbyTime = systemTime() + standbyDelay;
4855}
4856
4857void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4858{
4859 if (sleepTime == 0) {
4860 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4861 sleepTime = activeSleepTime;
4862 } else {
4863 sleepTime = idleSleepTime;
4864 }
4865 } else if (mBytesWritten != 0) {
4866 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4867 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004868 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004869 } else {
4870 // flush remaining overflow buffers in output tracks
4871 writeFrames = 0;
4872 }
4873 sleepTime = 0;
4874 }
4875}
4876
Eric Laurentbfb1b832013-01-07 09:53:42 -08004877ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004878{
Haynes Mathew Georgeec0eeaf2014-11-20 11:32:27 -08004879 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4880 // for delivery downstream as needed. This in-place conversion is safe as
4881 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4882 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4883 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4884 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4885 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4886 }
Eric Laurent81784c32012-11-19 14:55:58 -08004887 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004888 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004889 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004890 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004891 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004892}
4893
4894void AudioFlinger::DuplicatingThread::threadLoop_standby()
4895{
4896 // DuplicatingThread implements standby by stopping all tracks
4897 for (size_t i = 0; i < outputTracks.size(); i++) {
4898 outputTracks[i]->stop();
4899 }
4900}
4901
4902void AudioFlinger::DuplicatingThread::saveOutputTracks()
4903{
4904 outputTracks = mOutputTracks;
4905}
4906
4907void AudioFlinger::DuplicatingThread::clearOutputTracks()
4908{
4909 outputTracks.clear();
4910}
4911
4912void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4913{
4914 Mutex::Autolock _l(mLock);
4915 // FIXME explain this formula
4916 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004917 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4918 // due to current usage case and restrictions on the AudioBufferProvider.
4919 // Actual buffer conversion is done in threadLoop_write().
4920 //
4921 // TODO: This may change in the future, depending on multichannel
4922 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004923 OutputTrack *outputTrack = new OutputTrack(thread,
4924 this,
4925 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004926 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004927 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004928 frameCount,
4929 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004930 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004931 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004932 mOutputTracks.add(outputTrack);
4933 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4934 updateWaitTime_l();
4935 }
4936}
4937
4938void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4939{
4940 Mutex::Autolock _l(mLock);
4941 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4942 if (mOutputTracks[i]->thread() == thread) {
4943 mOutputTracks[i]->destroy();
4944 mOutputTracks.removeAt(i);
4945 updateWaitTime_l();
4946 return;
4947 }
4948 }
4949 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4950}
4951
4952// caller must hold mLock
4953void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4954{
4955 mWaitTimeMs = UINT_MAX;
4956 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4957 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4958 if (strong != 0) {
4959 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4960 if (waitTimeMs < mWaitTimeMs) {
4961 mWaitTimeMs = waitTimeMs;
4962 }
4963 }
4964 }
4965}
4966
4967
4968bool AudioFlinger::DuplicatingThread::outputsReady(
4969 const SortedVector< sp<OutputTrack> > &outputTracks)
4970{
4971 for (size_t i = 0; i < outputTracks.size(); i++) {
4972 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4973 if (thread == 0) {
4974 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4975 outputTracks[i].get());
4976 return false;
4977 }
4978 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4979 // see note at standby() declaration
4980 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4981 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4982 thread.get());
4983 return false;
4984 }
4985 }
4986 return true;
4987}
4988
4989uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4990{
4991 return (mWaitTimeMs * 1000) / 2;
4992}
4993
4994void AudioFlinger::DuplicatingThread::cacheParameters_l()
4995{
4996 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4997 updateWaitTime_l();
4998
4999 MixerThread::cacheParameters_l();
5000}
5001
5002// ----------------------------------------------------------------------------
5003// Record
5004// ----------------------------------------------------------------------------
5005
5006AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5007 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005008 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005009 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005010 audio_devices_t inDevice
5011#ifdef TEE_SINK
5012 , const sp<NBAIO_Sink>& teeSink
5013#endif
5014 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005015 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005016 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005017 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005018 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005019#ifdef TEE_SINK
5020 , mTeeSink(teeSink)
5021#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005022 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5023 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005024 // mFastCapture below
5025 , mFastCaptureFutex(0)
5026 // mInputSource
5027 // mPipeSink
5028 // mPipeSource
5029 , mPipeFramesP2(0)
5030 // mPipeMemory
5031 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005032 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005033{
5034 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005035 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005036
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005037 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005038
5039 // create an NBAIO source for the HAL input stream, and negotiate
5040 mInputSource = new AudioStreamInSource(input->stream);
5041 size_t numCounterOffers = 0;
5042 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5043 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5044 ALOG_ASSERT(index == 0);
5045
5046 // initialize fast capture depending on configuration
5047 bool initFastCapture;
5048 switch (kUseFastCapture) {
5049 case FastCapture_Never:
5050 initFastCapture = false;
5051 break;
5052 case FastCapture_Always:
5053 initFastCapture = true;
5054 break;
5055 case FastCapture_Static:
5056 uint32_t primaryOutputSampleRate;
5057 {
5058 AutoMutex _l(audioFlinger->mHardwareLock);
5059 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5060 }
5061 initFastCapture =
5062 // either capture sample rate is same as (a reasonable) primary output sample rate
5063 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5064 (mSampleRate == primaryOutputSampleRate)) ||
5065 // or primary output sample rate is unknown, and capture sample rate is reasonable
5066 ((primaryOutputSampleRate == 0) &&
5067 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005068 // and the buffer size is < 12 ms
5069 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005070 break;
5071 // case FastCapture_Dynamic:
5072 }
5073
5074 if (initFastCapture) {
5075 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5076 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005077 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005078 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5079 void *pipeBuffer;
5080 const sp<MemoryDealer> roHeap(readOnlyHeap());
5081 sp<IMemory> pipeMemory;
5082 if ((roHeap == 0) ||
5083 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5084 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5085 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5086 goto failed;
5087 }
5088 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5089 memset(pipeBuffer, 0, pipeSize);
5090 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5091 const NBAIO_Format offers[1] = {format};
5092 size_t numCounterOffers = 0;
5093 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5094 ALOG_ASSERT(index == 0);
5095 mPipeSink = pipe;
5096 PipeReader *pipeReader = new PipeReader(*pipe);
5097 numCounterOffers = 0;
5098 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5099 ALOG_ASSERT(index == 0);
5100 mPipeSource = pipeReader;
5101 mPipeFramesP2 = pipeFramesP2;
5102 mPipeMemory = pipeMemory;
5103
5104 // create fast capture
5105 mFastCapture = new FastCapture();
5106 FastCaptureStateQueue *sq = mFastCapture->sq();
5107#ifdef STATE_QUEUE_DUMP
5108 // FIXME
5109#endif
5110 FastCaptureState *state = sq->begin();
5111 state->mCblk = NULL;
5112 state->mInputSource = mInputSource.get();
5113 state->mInputSourceGen++;
5114 state->mPipeSink = pipe;
5115 state->mPipeSinkGen++;
5116 state->mFrameCount = mFrameCount;
5117 state->mCommand = FastCaptureState::COLD_IDLE;
5118 // already done in constructor initialization list
5119 //mFastCaptureFutex = 0;
5120 state->mColdFutexAddr = &mFastCaptureFutex;
5121 state->mColdGen++;
5122 state->mDumpState = &mFastCaptureDumpState;
5123#ifdef TEE_SINK
5124 // FIXME
5125#endif
5126 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5127 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5128 sq->end();
5129 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5130
5131 // start the fast capture
5132 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5133 pid_t tid = mFastCapture->getTid();
5134 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5135 if (err != 0) {
5136 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5137 kPriorityFastCapture, getpid_cached, tid, err);
5138 }
5139
5140#ifdef AUDIO_WATCHDOG
5141 // FIXME
5142#endif
5143
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005144 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005145 }
5146failed: ;
5147
5148 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005149}
5150
5151
5152AudioFlinger::RecordThread::~RecordThread()
5153{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005154 if (mFastCapture != 0) {
5155 FastCaptureStateQueue *sq = mFastCapture->sq();
5156 FastCaptureState *state = sq->begin();
5157 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5158 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5159 if (old == -1) {
5160 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5161 }
5162 }
5163 state->mCommand = FastCaptureState::EXIT;
5164 sq->end();
5165 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5166 mFastCapture->join();
5167 mFastCapture.clear();
5168 }
5169 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005170 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005171 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005172}
5173
5174void AudioFlinger::RecordThread::onFirstRef()
5175{
5176 run(mName, PRIORITY_URGENT_AUDIO);
5177}
5178
Eric Laurent81784c32012-11-19 14:55:58 -08005179bool AudioFlinger::RecordThread::threadLoop()
5180{
Eric Laurent81784c32012-11-19 14:55:58 -08005181 nsecs_t lastWarning = 0;
5182
5183 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005184
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005185reacquire_wakelock:
5186 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005187 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005188 {
5189 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005190 size_t size = mActiveTracks.size();
5191 activeTracksGen = mActiveTracksGen;
5192 if (size > 0) {
5193 // FIXME an arbitrary choice
5194 activeTrack = mActiveTracks[0];
5195 acquireWakeLock_l(activeTrack->uid());
5196 if (size > 1) {
5197 SortedVector<int> tmp;
5198 for (size_t i = 0; i < size; i++) {
5199 tmp.add(mActiveTracks[i]->uid());
5200 }
5201 updateWakeLockUids_l(tmp);
5202 }
5203 } else {
5204 acquireWakeLock_l(-1);
5205 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005206 }
5207
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005208 // used to request a deferred sleep, to be executed later while mutex is unlocked
5209 uint32_t sleepUs = 0;
5210
5211 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005212 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005213 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005214
Glenn Kasten5edadd42013-08-14 16:30:49 -07005215 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005216 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005217 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005218 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005219 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005220 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005221 }
5222
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005223 // activeTracks accumulates a copy of a subset of mActiveTracks
5224 Vector< sp<RecordTrack> > activeTracks;
5225
Glenn Kasten735f45f2014-08-18 15:51:59 -07005226 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005227 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005228
Glenn Kasten735f45f2014-08-18 15:51:59 -07005229 // reference to a fast track which is about to be removed
5230 sp<RecordTrack> fastTrackToRemove;
5231
Eric Laurent81784c32012-11-19 14:55:58 -08005232 { // scope for mLock
5233 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005234
Eric Laurent021cf962014-05-13 10:18:14 -07005235 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005236
Eric Laurent000a4192014-01-29 15:17:32 -08005237 // check exitPending here because checkForNewParameters_l() and
5238 // checkForNewParameters_l() can temporarily release mLock
5239 if (exitPending()) {
5240 break;
5241 }
5242
Glenn Kasten2b806402013-11-20 16:37:38 -08005243 // if no active track(s), then standby and release wakelock
5244 size_t size = mActiveTracks.size();
5245 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005246 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005247 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005248 releaseWakeLock_l();
5249 ALOGV("RecordThread: loop stopping");
5250 // go to sleep
5251 mWaitWorkCV.wait(mLock);
5252 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005253 goto reacquire_wakelock;
5254 }
5255
Glenn Kasten2b806402013-11-20 16:37:38 -08005256 if (mActiveTracksGen != activeTracksGen) {
5257 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005258 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005259 for (size_t i = 0; i < size; i++) {
5260 tmp.add(mActiveTracks[i]->uid());
5261 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005262 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005263 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005265 bool doBroadcast = false;
5266 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005267
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005268 activeTrack = mActiveTracks[i];
5269 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005270 if (activeTrack->isFastTrack()) {
5271 ALOG_ASSERT(fastTrackToRemove == 0);
5272 fastTrackToRemove = activeTrack;
5273 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005274 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005275 mActiveTracks.remove(activeTrack);
5276 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005277 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005278 continue;
5279 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005280
5281 TrackBase::track_state activeTrackState = activeTrack->mState;
5282 switch (activeTrackState) {
5283
5284 case TrackBase::PAUSING:
5285 mActiveTracks.remove(activeTrack);
5286 mActiveTracksGen++;
5287 doBroadcast = true;
5288 size--;
5289 continue;
5290
5291 case TrackBase::STARTING_1:
5292 sleepUs = 10000;
5293 i++;
5294 continue;
5295
5296 case TrackBase::STARTING_2:
5297 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005299 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005300 break;
5301
5302 case TrackBase::ACTIVE:
5303 break;
5304
5305 case TrackBase::IDLE:
5306 i++;
5307 continue;
5308
5309 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005310 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005311 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005312
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005313 activeTracks.add(activeTrack);
5314 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005315
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005316 if (activeTrack->isFastTrack()) {
5317 ALOG_ASSERT(!mFastTrackAvail);
5318 ALOG_ASSERT(fastTrack == 0);
5319 fastTrack = activeTrack;
5320 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005321 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005322 if (doBroadcast) {
5323 mStartStopCond.broadcast();
5324 }
5325
5326 // sleep if there are no active tracks to process
5327 if (activeTracks.size() == 0) {
5328 if (sleepUs == 0) {
5329 sleepUs = kRecordThreadSleepUs;
5330 }
5331 continue;
5332 }
5333 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005334
Eric Laurent81784c32012-11-19 14:55:58 -08005335 lockEffectChains_l(effectChains);
5336 }
5337
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005338 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005340 size_t size = effectChains.size();
5341 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005342 // thread mutex is not locked, but effect chain is locked
5343 effectChains[i]->process_l();
5344 }
5345
Glenn Kasten735f45f2014-08-18 15:51:59 -07005346 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005347 if (mFastCapture != 0) {
5348 FastCaptureStateQueue *sq = mFastCapture->sq();
5349 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005350 bool didModify = false;
5351 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005352 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5353 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5354 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5355 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5356 if (old == -1) {
5357 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5358 }
5359 }
5360 state->mCommand = FastCaptureState::READ_WRITE;
5361#if 0 // FIXME
5362 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005363 FastCaptureDumpState::kSamplingNforLowRamDevice :
5364 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005365#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005366 didModify = true;
5367 }
5368 audio_track_cblk_t *cblkOld = state->mCblk;
5369 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5370 if (cblkNew != cblkOld) {
5371 state->mCblk = cblkNew;
5372 // block until acked if removing a fast track
5373 if (cblkOld != NULL) {
5374 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5375 }
5376 didModify = true;
5377 }
5378 sq->end(didModify);
5379 if (didModify) {
5380 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005381#if 0
5382 if (kUseFastCapture == FastCapture_Dynamic) {
5383 mNormalSource = mPipeSource;
5384 }
5385#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005386 }
5387 }
5388
Glenn Kasten735f45f2014-08-18 15:51:59 -07005389 // now run the fast track destructor with thread mutex unlocked
5390 fastTrackToRemove.clear();
5391
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005392 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5393 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5394 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5395 // If destination is non-contiguous, first read past the nominal end of buffer, then
5396 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005397
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005398 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005399 ssize_t framesRead;
5400
5401 // If an NBAIO source is present, use it to read the normal capture's data
5402 if (mPipeSource != 0) {
5403 size_t framesToRead = mBufferSize / mFrameSize;
5404 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5405 framesToRead, AudioBufferProvider::kInvalidPTS);
5406 if (framesRead == 0) {
5407 // since pipe is non-blocking, simulate blocking input
5408 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5409 }
5410 // otherwise use the HAL / AudioStreamIn directly
5411 } else {
5412 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5413 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5414 if (bytesRead < 0) {
5415 framesRead = bytesRead;
5416 } else {
5417 framesRead = bytesRead / mFrameSize;
5418 }
5419 }
5420
5421 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5422 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005423 // Force input into standby so that it tries to recover at next read attempt
5424 inputStandBy();
5425 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005426 }
5427 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005428 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005429 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005430 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005431
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005432 if (mTeeSink != 0) {
5433 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5434 }
5435 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005436 {
5437 size_t part1 = mRsmpInFramesP2 - rear;
5438 if ((size_t) framesRead > part1) {
5439 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5440 (framesRead - part1) * mFrameSize);
5441 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005442 }
5443 rear = mRsmpInRear += framesRead;
5444
5445 size = activeTracks.size();
5446 // loop over each active track
5447 for (size_t i = 0; i < size; i++) {
5448 activeTrack = activeTracks[i];
5449
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005450 // skip fast tracks, as those are handled directly by FastCapture
5451 if (activeTrack->isFastTrack()) {
5452 continue;
5453 }
5454
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005455 enum {
5456 OVERRUN_UNKNOWN,
5457 OVERRUN_TRUE,
5458 OVERRUN_FALSE
5459 } overrun = OVERRUN_UNKNOWN;
5460
5461 // loop over getNextBuffer to handle circular sink
5462 for (;;) {
5463
5464 activeTrack->mSink.frameCount = ~0;
5465 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5466 size_t framesOut = activeTrack->mSink.frameCount;
5467 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5468
5469 int32_t front = activeTrack->mRsmpInFront;
5470 ssize_t filled = rear - front;
5471 size_t framesIn;
5472
5473 if (filled < 0) {
5474 // should not happen, but treat like a massive overrun and re-sync
5475 framesIn = 0;
5476 activeTrack->mRsmpInFront = rear;
5477 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005478 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005479 framesIn = (size_t) filled;
5480 } else {
5481 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005482 framesIn = mRsmpInFrames;
5483 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005484 overrun = OVERRUN_TRUE;
5485 }
5486
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005487 if (framesOut == 0 || framesIn == 0) {
5488 break;
5489 }
5490
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005491 if (activeTrack->mResampler == NULL) {
5492 // no resampling
5493 if (framesIn > framesOut) {
5494 framesIn = framesOut;
5495 } else {
5496 framesOut = framesIn;
5497 }
5498 int8_t *dst = activeTrack->mSink.i8;
5499 while (framesIn > 0) {
5500 front &= mRsmpInFramesP2 - 1;
5501 size_t part1 = mRsmpInFramesP2 - front;
5502 if (part1 > framesIn) {
5503 part1 = framesIn;
5504 }
5505 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005506 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005507 memcpy(dst, src, part1 * mFrameSize);
5508 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005509 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005510 part1);
5511 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005512 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5513 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005514 }
5515 dst += part1 * activeTrack->mFrameSize;
5516 front += part1;
5517 framesIn -= part1;
5518 }
5519 activeTrack->mRsmpInFront += framesOut;
5520
5521 } else {
5522 // resampling
5523 // FIXME framesInNeeded should really be part of resampler API, and should
5524 // depend on the SRC ratio
5525 // to keep mRsmpInBuffer full so resampler always has sufficient input
5526 size_t framesInNeeded;
5527 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005528 // Do not precompute in/out because floating point is not associative
5529 // e.g. a*b/c != a*(b/c).
5530 const double in(mSampleRate);
5531 const double out(activeTrack->mSampleRate);
5532 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005533 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005534 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005535 // Although we theoretically have framesIn in circular buffer, some of those are
5536 // unreleased frames, and thus must be discounted for purpose of budgeting.
5537 size_t unreleased = activeTrack->mRsmpInUnrel;
5538 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005540 ALOGV("not enough to resample: have %u frames in but need %u in to "
5541 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005542 framesIn, framesInNeeded, framesOut, in / out);
5543 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005544 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5545 if (newFramesOut == 0) {
5546 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005547 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005548 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005549 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005550 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005551 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5552 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5553 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005554 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005555 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005556 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005557 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005558 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005559 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005560 }
5561
5562 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5563 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005564 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005565 delete[] activeTrack->mRsmpOutBuffer;
5566 // resampler always outputs stereo
5567 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5568 activeTrack->mRsmpOutFrameCount = framesOut;
5569 }
5570
5571 // resampler accumulates, but we only have one source track
5572 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5573 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005574 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005575 activeTrack->mResamplerBufferProvider
5576 /*this*/ /* AudioBufferProvider* */);
5577 // ditherAndClamp() works as long as all buffers returned by
5578 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005579 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005580 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005581 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5582 framesOut);
5583 // the resampler always outputs stereo samples:
5584 // do post stereo to mono conversion
5585 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005586 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005587 } else {
5588 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5589 activeTrack->mRsmpOutBuffer, framesOut);
5590 }
5591 // now done with mRsmpOutBuffer
5592
5593 }
5594
5595 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5596 overrun = OVERRUN_FALSE;
5597 }
5598
5599 if (activeTrack->mFramesToDrop == 0) {
5600 if (framesOut > 0) {
5601 activeTrack->mSink.frameCount = framesOut;
5602 activeTrack->releaseBuffer(&activeTrack->mSink);
5603 }
5604 } else {
5605 // FIXME could do a partial drop of framesOut
5606 if (activeTrack->mFramesToDrop > 0) {
5607 activeTrack->mFramesToDrop -= framesOut;
5608 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005609 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 }
5611 } else {
5612 activeTrack->mFramesToDrop += framesOut;
5613 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5614 activeTrack->mSyncStartEvent->isCancelled()) {
5615 ALOGW("Synced record %s, session %d, trigger session %d",
5616 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5617 activeTrack->sessionId(),
5618 (activeTrack->mSyncStartEvent != 0) ?
5619 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005620 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005621 }
5622 }
5623 }
5624
5625 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005626 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005627 }
5628 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005629
5630 switch (overrun) {
5631 case OVERRUN_TRUE:
5632 // client isn't retrieving buffers fast enough
5633 if (!activeTrack->setOverflow()) {
5634 nsecs_t now = systemTime();
5635 // FIXME should lastWarning per track?
5636 if ((now - lastWarning) > kWarningThrottleNs) {
5637 ALOGW("RecordThread: buffer overflow");
5638 lastWarning = now;
5639 }
5640 }
5641 break;
5642 case OVERRUN_FALSE:
5643 activeTrack->clearOverflow();
5644 break;
5645 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 break;
5647 }
5648
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005649 }
5650
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005651unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005652 // enable changes in effect chain
5653 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005654 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005655 }
5656
Glenn Kasten93e471f2013-08-19 08:40:07 -07005657 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005658
5659 {
5660 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005661 for (size_t i = 0; i < mTracks.size(); i++) {
5662 sp<RecordTrack> track = mTracks[i];
5663 track->invalidate();
5664 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005665 mActiveTracks.clear();
5666 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005667 mStartStopCond.broadcast();
5668 }
5669
5670 releaseWakeLock();
5671
5672 ALOGV("RecordThread %p exiting", this);
5673 return false;
5674}
5675
Glenn Kasten93e471f2013-08-19 08:40:07 -07005676void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005677{
5678 if (!mStandby) {
5679 inputStandBy();
5680 mStandby = true;
5681 }
5682}
5683
5684void AudioFlinger::RecordThread::inputStandBy()
5685{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005686 // Idle the fast capture if it's currently running
5687 if (mFastCapture != 0) {
5688 FastCaptureStateQueue *sq = mFastCapture->sq();
5689 FastCaptureState *state = sq->begin();
5690 if (!(state->mCommand & FastCaptureState::IDLE)) {
5691 state->mCommand = FastCaptureState::COLD_IDLE;
5692 state->mColdFutexAddr = &mFastCaptureFutex;
5693 state->mColdGen++;
5694 mFastCaptureFutex = 0;
5695 sq->end();
5696 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5697 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5698#if 0
5699 if (kUseFastCapture == FastCapture_Dynamic) {
5700 // FIXME
5701 }
5702#endif
5703#ifdef AUDIO_WATCHDOG
5704 // FIXME
5705#endif
5706 } else {
5707 sq->end(false /*didModify*/);
5708 }
5709 }
Eric Laurent81784c32012-11-19 14:55:58 -08005710 mInput->stream->common.standby(&mInput->stream->common);
5711}
5712
Glenn Kasten05997e22014-03-13 15:08:33 -07005713// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005714sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005715 const sp<AudioFlinger::Client>& client,
5716 uint32_t sampleRate,
5717 audio_format_t format,
5718 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005719 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005720 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005721 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005722 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005723 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005724 pid_t tid,
5725 status_t *status)
5726{
Glenn Kasten74935e42013-12-19 08:56:45 -08005727 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005728 sp<RecordTrack> track;
5729 status_t lStatus;
5730
Glenn Kasten90e58b12013-07-31 16:16:02 -07005731 // client expresses a preference for FAST, but we get the final say
5732 if (*flags & IAudioFlinger::TRACK_FAST) {
5733 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005734 // use case: callback handler
5735 (tid != -1) &&
5736 // frame count is not specified, or is exactly the pipe depth
5737 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005738 // PCM data
5739 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005740 // native format
5741 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005742 // native channel mask
5743 (channelMask == mChannelMask) &&
5744 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005745 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005746 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005747 hasFastCapture() &&
5748 // there are sufficient fast track slots available
5749 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005750 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005751 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005752 frameCount, mFrameCount);
5753 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005754 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5755 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005756 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005757 frameCount, mFrameCount, mPipeFramesP2,
5758 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5759 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005760 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005761 }
5762 }
5763
5764 // compute track buffer size in frames, and suggest the notification frame count
5765 if (*flags & IAudioFlinger::TRACK_FAST) {
5766 // fast track: frame count is exactly the pipe depth
5767 frameCount = mPipeFramesP2;
5768 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5769 *notificationFrames = mFrameCount;
5770 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005771 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5772 // or 20 ms if there is a fast capture
5773 // TODO This could be a roundupRatio inline, and const
5774 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5775 * sampleRate + mSampleRate - 1) / mSampleRate;
5776 // minimum number of notification periods is at least kMinNotifications,
5777 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5778 static const size_t kMinNotifications = 3;
5779 static const uint32_t kMinMs = 30;
5780 // TODO This could be a roundupRatio inline
5781 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5782 // TODO This could be a roundupRatio inline
5783 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5784 maxNotificationFrames;
5785 const size_t minFrameCount = maxNotificationFrames *
5786 max(kMinNotifications, minNotificationsByMs);
5787 frameCount = max(frameCount, minFrameCount);
5788 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5789 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005790 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005791 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005792 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005793
Glenn Kasten15e57982013-09-24 11:52:37 -07005794 lStatus = initCheck();
5795 if (lStatus != NO_ERROR) {
5796 ALOGE("createRecordTrack_l() audio driver not initialized");
5797 goto Exit;
5798 }
Eric Laurent81784c32012-11-19 14:55:58 -08005799
5800 { // scope for mLock
5801 Mutex::Autolock _l(mLock);
5802
5803 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005804 format, channelMask, frameCount, NULL, sessionId, uid,
5805 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005806
Glenn Kasten03003332013-08-06 15:40:54 -07005807 lStatus = track->initCheck();
5808 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005809 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005810 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005811 goto Exit;
5812 }
5813 mTracks.add(track);
5814
5815 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5816 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5817 mAudioFlinger->btNrecIsOff();
5818 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5819 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005820
5821 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5822 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5823 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5824 // so ask activity manager to do this on our behalf
5825 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5826 }
Eric Laurent81784c32012-11-19 14:55:58 -08005827 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005828
Eric Laurent81784c32012-11-19 14:55:58 -08005829 lStatus = NO_ERROR;
5830
5831Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005832 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005833 return track;
5834}
5835
5836status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5837 AudioSystem::sync_event_t event,
5838 int triggerSession)
5839{
5840 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5841 sp<ThreadBase> strongMe = this;
5842 status_t status = NO_ERROR;
5843
5844 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005845 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005846 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005847 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005848 triggerSession,
5849 recordTrack->sessionId(),
5850 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005851 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005852 // Sync event can be cancelled by the trigger session if the track is not in a
5853 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005854 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005855 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005856 } else {
5857 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005859 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
5861 }
5862
5863 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005864 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005865 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005866 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5867 if (recordTrack->mState == TrackBase::PAUSING) {
5868 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005869 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005870 } else {
5871 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005872 }
5873 return status;
5874 }
5875
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005876 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5877 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5878 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005880 mActiveTracks.add(recordTrack);
5881 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005882 status_t status = NO_ERROR;
5883 if (recordTrack->isExternalTrack()) {
5884 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005885 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005886 mLock.lock();
5887 // FIXME should verify that recordTrack is still in mActiveTracks
5888 if (status != NO_ERROR) {
5889 mActiveTracks.remove(recordTrack);
5890 mActiveTracksGen++;
5891 recordTrack->clearSyncStartEvent();
5892 ALOGV("RecordThread::start error %d", status);
5893 return status;
5894 }
Eric Laurent81784c32012-11-19 14:55:58 -08005895 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 // Catch up with current buffer indices if thread is already running.
5897 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5898 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5899 // see previously buffered data before it called start(), but with greater risk of overrun.
5900
5901 recordTrack->mRsmpInFront = mRsmpInRear;
5902 recordTrack->mRsmpInUnrel = 0;
5903 // FIXME why reset?
5904 if (recordTrack->mResampler != NULL) {
5905 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005908 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005909 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005910 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005911 ALOGV("Record failed to start");
5912 status = BAD_VALUE;
5913 goto startError;
5914 }
Eric Laurent81784c32012-11-19 14:55:58 -08005915 return status;
5916 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005917
Eric Laurent81784c32012-11-19 14:55:58 -08005918startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005919 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005920 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005921 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005922 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005923 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005924 return status;
5925}
5926
Eric Laurent81784c32012-11-19 14:55:58 -08005927void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5928{
5929 sp<SyncEvent> strongEvent = event.promote();
5930
5931 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005932 sp<RefBase> ptr = strongEvent->cookie().promote();
5933 if (ptr != 0) {
5934 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5935 recordTrack->handleSyncStartEvent(strongEvent);
5936 }
Eric Laurent81784c32012-11-19 14:55:58 -08005937 }
5938}
5939
Glenn Kastena8356f62013-07-25 14:37:52 -07005940bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005941 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005942 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005943 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 return false;
5945 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005946 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005947 recordTrack->mState = TrackBase::PAUSING;
5948 // do not wait for mStartStopCond if exiting
5949 if (exitPending()) {
5950 return true;
5951 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005952 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005953 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005954 // if we have been restarted, recordTrack is in mActiveTracks here
5955 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005956 ALOGV("Record stopped OK");
5957 return true;
5958 }
5959 return false;
5960}
5961
Glenn Kasten0f11b512014-01-31 16:18:54 -08005962bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005963{
5964 return false;
5965}
5966
Glenn Kasten0f11b512014-01-31 16:18:54 -08005967status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005968{
5969#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5970 if (!isValidSyncEvent(event)) {
5971 return BAD_VALUE;
5972 }
5973
5974 int eventSession = event->triggerSession();
5975 status_t ret = NAME_NOT_FOUND;
5976
5977 Mutex::Autolock _l(mLock);
5978
5979 for (size_t i = 0; i < mTracks.size(); i++) {
5980 sp<RecordTrack> track = mTracks[i];
5981 if (eventSession == track->sessionId()) {
5982 (void) track->setSyncEvent(event);
5983 ret = NO_ERROR;
5984 }
5985 }
5986 return ret;
5987#else
5988 return BAD_VALUE;
5989#endif
5990}
5991
5992// destroyTrack_l() must be called with ThreadBase::mLock held
5993void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5994{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005995 track->terminate();
5996 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005998 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005999 removeTrack_l(track);
6000 }
6001}
6002
6003void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6004{
6005 mTracks.remove(track);
6006 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006007 if (track->isFastTrack()) {
6008 ALOG_ASSERT(!mFastTrackAvail);
6009 mFastTrackAvail = true;
6010 }
Eric Laurent81784c32012-11-19 14:55:58 -08006011}
6012
6013void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6014{
6015 dumpInternals(fd, args);
6016 dumpTracks(fd, args);
6017 dumpEffectChains(fd, args);
6018}
6019
6020void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6021{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006022 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006023
Glenn Kasten2b806402013-11-20 16:37:38 -08006024 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006025 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006026 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006027 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006029 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006030 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006031
Eric Laurent81784c32012-11-19 14:55:58 -08006032 dumpBase(fd, args);
6033}
6034
Glenn Kasten0f11b512014-01-31 16:18:54 -08006035void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006036{
6037 const size_t SIZE = 256;
6038 char buffer[SIZE];
6039 String8 result;
6040
Marco Nelissenb2208842014-02-07 14:00:50 -08006041 size_t numtracks = mTracks.size();
6042 size_t numactive = mActiveTracks.size();
6043 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006044 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006045 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006046 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006047 RecordTrack::appendDumpHeader(result);
6048 for (size_t i = 0; i < numtracks ; ++i) {
6049 sp<RecordTrack> track = mTracks[i];
6050 if (track != 0) {
6051 bool active = mActiveTracks.indexOf(track) >= 0;
6052 if (active) {
6053 numactiveseen++;
6054 }
6055 track->dump(buffer, SIZE, active);
6056 result.append(buffer);
6057 }
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006059 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006060 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006061 }
6062
Marco Nelissenb2208842014-02-07 14:00:50 -08006063 if (numactiveseen != numactive) {
6064 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6065 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006066 result.append(buffer);
6067 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006068 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006069 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006070 if (mTracks.indexOf(track) < 0) {
6071 track->dump(buffer, SIZE, true);
6072 result.append(buffer);
6073 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006074 }
Eric Laurent81784c32012-11-19 14:55:58 -08006075
6076 }
6077 write(fd, result.string(), result.size());
6078}
6079
6080// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6082 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006083{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006084 RecordTrack *activeTrack = mRecordTrack;
6085 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6086 if (threadBase == 0) {
6087 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006088 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006089 return NOT_ENOUGH_DATA;
6090 }
6091 RecordThread *recordThread = (RecordThread *) threadBase.get();
6092 int32_t rear = recordThread->mRsmpInRear;
6093 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006094 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006095 // FIXME should not be P2 (don't want to increase latency)
6096 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006097 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006098 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006099 front &= recordThread->mRsmpInFramesP2 - 1;
6100 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006101 if (part1 > (size_t) filled) {
6102 part1 = filled;
6103 }
6104 size_t ask = buffer->frameCount;
6105 ALOG_ASSERT(ask > 0);
6106 if (part1 > ask) {
6107 part1 = ask;
6108 }
6109 if (part1 == 0) {
6110 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006111 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006112 buffer->raw = NULL;
6113 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006114 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006115 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006116 }
6117
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006118 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006119 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006121 return NO_ERROR;
6122}
6123
6124// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6126 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006127{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006128 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006129 size_t stepCount = buffer->frameCount;
6130 if (stepCount == 0) {
6131 return;
6132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6134 activeTrack->mRsmpInUnrel -= stepCount;
6135 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006136 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006137 buffer->frameCount = 0;
6138}
6139
Eric Laurent10351942014-05-08 18:49:52 -07006140bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6141 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006142{
6143 bool reconfig = false;
6144
Eric Laurent10351942014-05-08 18:49:52 -07006145 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006146
Eric Laurent10351942014-05-08 18:49:52 -07006147 audio_format_t reqFormat = mFormat;
6148 uint32_t samplingRate = mSampleRate;
6149 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6150
6151 AudioParameter param = AudioParameter(keyValuePair);
6152 int value;
6153 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6154 // channel count change can be requested. Do we mandate the first client defines the
6155 // HAL sampling rate and channel count or do we allow changes on the fly?
6156 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6157 samplingRate = value;
6158 reconfig = true;
6159 }
6160 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6161 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6162 status = BAD_VALUE;
6163 } else {
6164 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006165 reconfig = true;
6166 }
Eric Laurent10351942014-05-08 18:49:52 -07006167 }
6168 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6169 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6170 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6171 status = BAD_VALUE;
6172 } else {
6173 channelMask = mask;
6174 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006175 }
Eric Laurent10351942014-05-08 18:49:52 -07006176 }
6177 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6178 // do not accept frame count changes if tracks are open as the track buffer
6179 // size depends on frame count and correct behavior would not be guaranteed
6180 // if frame count is changed after track creation
6181 if (mActiveTracks.size() > 0) {
6182 status = INVALID_OPERATION;
6183 } else {
6184 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006185 }
Eric Laurent10351942014-05-08 18:49:52 -07006186 }
6187 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6188 // forward device change to effects that have requested to be
6189 // aware of attached audio device.
6190 for (size_t i = 0; i < mEffectChains.size(); i++) {
6191 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006192 }
Eric Laurent81784c32012-11-19 14:55:58 -08006193
Eric Laurent10351942014-05-08 18:49:52 -07006194 // store input device and output device but do not forward output device to audio HAL.
6195 // Note that status is ignored by the caller for output device
6196 // (see AudioFlinger::setParameters()
6197 if (audio_is_output_devices(value)) {
6198 mOutDevice = value;
6199 status = BAD_VALUE;
6200 } else {
6201 mInDevice = value;
6202 // disable AEC and NS if the device is a BT SCO headset supporting those
6203 // pre processings
6204 if (mTracks.size() > 0) {
6205 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6206 mAudioFlinger->btNrecIsOff();
6207 for (size_t i = 0; i < mTracks.size(); i++) {
6208 sp<RecordTrack> track = mTracks[i];
6209 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6210 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
6212 }
6213 }
Eric Laurent10351942014-05-08 18:49:52 -07006214 }
6215 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6216 mAudioSource != (audio_source_t)value) {
6217 // forward device change to effects that have requested to be
6218 // aware of attached audio device.
6219 for (size_t i = 0; i < mEffectChains.size(); i++) {
6220 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006221 }
Eric Laurent10351942014-05-08 18:49:52 -07006222 mAudioSource = (audio_source_t)value;
6223 }
Glenn Kastene198c362013-08-13 09:13:36 -07006224
Eric Laurent10351942014-05-08 18:49:52 -07006225 if (status == NO_ERROR) {
6226 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6227 keyValuePair.string());
6228 if (status == INVALID_OPERATION) {
6229 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006230 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6231 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006232 }
6233 if (reconfig) {
6234 if (status == BAD_VALUE &&
6235 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6236 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6237 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6238 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006239 audio_channel_count_from_in_mask(
6240 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006241 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6242 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6243 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006244 }
Eric Laurent10351942014-05-08 18:49:52 -07006245 if (status == NO_ERROR) {
6246 readInputParameters_l();
6247 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
6249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250 }
Eric Laurent10351942014-05-08 18:49:52 -07006251
Eric Laurent81784c32012-11-19 14:55:58 -08006252 return reconfig;
6253}
6254
6255String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6256{
Eric Laurent81784c32012-11-19 14:55:58 -08006257 Mutex::Autolock _l(mLock);
6258 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006259 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006260 }
6261
Glenn Kastend8ea6992013-07-16 14:17:15 -07006262 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6263 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006264 free(s);
6265 return out_s8;
6266}
6267
Eric Laurent021cf962014-05-13 10:18:14 -07006268void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006269 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006270 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006271
6272 switch (event) {
6273 case AudioSystem::INPUT_OPENED:
6274 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006275 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006276 desc.samplingRate = mSampleRate;
6277 desc.format = mFormat;
6278 desc.frameCount = mFrameCount;
6279 desc.latency = 0;
6280 param2 = &desc;
6281 break;
6282
6283 case AudioSystem::INPUT_CLOSED:
6284 default:
6285 break;
6286 }
Eric Laurent021cf962014-05-13 10:18:14 -07006287 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006288}
6289
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006290void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006291{
Eric Laurent81784c32012-11-19 14:55:58 -08006292 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6293 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006294 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006295 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6296 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006297 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006298 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006299 }
Eric Laurent665470b2014-07-03 16:37:08 -07006300 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006301 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6302 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006304 // 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 -07006305 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006306 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 // A larger value should allow more old data to be read after a track calls start(),
6308 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006309 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006310 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006312
6313 // TODO optimize audio capture buffer sizes ...
6314 // Here we calculate the size of the sliding buffer used as a source
6315 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6316 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6317 // be better to have it derived from the pipe depth in the long term.
6318 // The current value is higher than necessary. However it should not add to latency.
6319
Glenn Kasten85948432013-08-19 12:09:05 -07006320 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6321 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006322
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006323 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6324 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006325}
6326
Glenn Kasten5f972c02014-01-13 09:59:31 -08006327uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006328{
6329 Mutex::Autolock _l(mLock);
6330 if (initCheck() != NO_ERROR) {
6331 return 0;
6332 }
6333
6334 return mInput->stream->get_input_frames_lost(mInput->stream);
6335}
6336
6337uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6338{
6339 Mutex::Autolock _l(mLock);
6340 uint32_t result = 0;
6341 if (getEffectChain_l(sessionId) != 0) {
6342 result = EFFECT_SESSION;
6343 }
6344
6345 for (size_t i = 0; i < mTracks.size(); ++i) {
6346 if (sessionId == mTracks[i]->sessionId()) {
6347 result |= TRACK_SESSION;
6348 break;
6349 }
6350 }
6351
6352 return result;
6353}
6354
6355KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6356{
6357 KeyedVector<int, bool> ids;
6358 Mutex::Autolock _l(mLock);
6359 for (size_t j = 0; j < mTracks.size(); ++j) {
6360 sp<RecordThread::RecordTrack> track = mTracks[j];
6361 int sessionId = track->sessionId();
6362 if (ids.indexOfKey(sessionId) < 0) {
6363 ids.add(sessionId, true);
6364 }
6365 }
6366 return ids;
6367}
6368
6369AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6370{
6371 Mutex::Autolock _l(mLock);
6372 AudioStreamIn *input = mInput;
6373 mInput = NULL;
6374 return input;
6375}
6376
6377// this method must always be called either with ThreadBase mLock held or inside the thread loop
6378audio_stream_t* AudioFlinger::RecordThread::stream() const
6379{
6380 if (mInput == NULL) {
6381 return NULL;
6382 }
6383 return &mInput->stream->common;
6384}
6385
6386status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6387{
6388 // only one chain per input thread
6389 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006390 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006391 return INVALID_OPERATION;
6392 }
6393 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006394 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006395 chain->setInBuffer(NULL);
6396 chain->setOutBuffer(NULL);
6397
6398 checkSuspendOnAddEffectChain_l(chain);
6399
Eric Laurent1b928682014-10-02 19:41:47 -07006400 // make sure enabled pre processing effects state is communicated to the HAL as we
6401 // just moved them to a new input stream.
6402 chain->syncHalEffectsState();
6403
Eric Laurent81784c32012-11-19 14:55:58 -08006404 mEffectChains.add(chain);
6405
6406 return NO_ERROR;
6407}
6408
6409size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6410{
6411 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6412 ALOGW_IF(mEffectChains.size() != 1,
6413 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6414 chain.get(), mEffectChains.size(), this);
6415 if (mEffectChains.size() == 1) {
6416 mEffectChains.removeAt(0);
6417 }
6418 return 0;
6419}
6420
Eric Laurent1c333e22014-05-20 10:48:17 -07006421status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6422 audio_patch_handle_t *handle)
6423{
6424 status_t status = NO_ERROR;
6425 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6426 // store new device and send to effects
6427 mInDevice = patch->sources[0].ext.device.type;
6428 for (size_t i = 0; i < mEffectChains.size(); i++) {
6429 mEffectChains[i]->setDevice_l(mInDevice);
6430 }
6431
6432 // disable AEC and NS if the device is a BT SCO headset supporting those
6433 // pre processings
6434 if (mTracks.size() > 0) {
6435 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6436 mAudioFlinger->btNrecIsOff();
6437 for (size_t i = 0; i < mTracks.size(); i++) {
6438 sp<RecordTrack> track = mTracks[i];
6439 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6440 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6441 }
6442 }
6443
6444 // store new source and send to effects
6445 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6446 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6447 for (size_t i = 0; i < mEffectChains.size(); i++) {
6448 mEffectChains[i]->setAudioSource_l(mAudioSource);
6449 }
6450 }
6451
6452 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6453 status = hwDevice->create_audio_patch(hwDevice,
6454 patch->num_sources,
6455 patch->sources,
6456 patch->num_sinks,
6457 patch->sinks,
6458 handle);
6459 } else {
6460 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6461 }
6462 return status;
6463}
6464
6465status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6466{
6467 status_t status = NO_ERROR;
6468 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6469 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6470 status = hwDevice->release_audio_patch(hwDevice, handle);
6471 } else {
6472 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6473 }
6474 return status;
6475}
6476
Eric Laurent83b88082014-06-20 18:31:16 -07006477void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6478{
6479 Mutex::Autolock _l(mLock);
6480 mTracks.add(record);
6481}
6482
6483void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6484{
6485 Mutex::Autolock _l(mLock);
6486 destroyTrack_l(record);
6487}
6488
6489void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6490{
6491 ThreadBase::getAudioPortConfig(config);
6492 config->role = AUDIO_PORT_ROLE_SINK;
6493 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6494 config->ext.mix.usecase.source = mAudioSource;
6495}
Eric Laurent1c333e22014-05-20 10:48:17 -07006496
Eric Laurent81784c32012-11-19 14:55:58 -08006497}; // namespace android