blob: dc974e94fb6b921b7cdd81dec6b0ec3960868732 [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) {
399 sp<IBinder> binder = mPowerManager->asBinder();
400 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),
1259 // mLatchD, mLatchQ,
1260 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001261{
1262 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001263 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001264
1265 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1266 // it would be safer to explicitly pass initial masterVolume/masterMute as
1267 // parameter.
1268 //
1269 // If the HAL we are using has support for master volume or master mute,
1270 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1271 // and the mute set to false).
1272 mMasterVolume = audioFlinger->masterVolume_l();
1273 mMasterMute = audioFlinger->masterMute_l();
1274 if (mOutput && mOutput->audioHwDev) {
1275 if (mOutput->audioHwDev->canSetMasterVolume()) {
1276 mMasterVolume = 1.0;
1277 }
1278
1279 if (mOutput->audioHwDev->canSetMasterMute()) {
1280 mMasterMute = false;
1281 }
1282 }
1283
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001284 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001285
1286 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1287 // There is no AUDIO_STREAM_MIN, and ++ 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 }
1293 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1294 // because mAudioFlinger doesn't have one to copy from
1295}
1296
1297AudioFlinger::PlaybackThread::~PlaybackThread()
1298{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001299 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001300 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001301 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001302 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001303}
1304
1305void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1306{
1307 dumpInternals(fd, args);
1308 dumpTracks(fd, args);
1309 dumpEffectChains(fd, args);
1310}
1311
Glenn Kasten0f11b512014-01-31 16:18:54 -08001312void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001313{
1314 const size_t SIZE = 256;
1315 char buffer[SIZE];
1316 String8 result;
1317
Marco Nelissenb2208842014-02-07 14:00:50 -08001318 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001319 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1320 const stream_type_t *st = &mStreamTypes[i];
1321 if (i > 0) {
1322 result.appendFormat(", ");
1323 }
1324 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1325 if (st->mute) {
1326 result.append("M");
1327 }
1328 }
1329 result.append("\n");
1330 write(fd, result.string(), result.length());
1331 result.clear();
1332
Eric Laurent81784c32012-11-19 14:55:58 -08001333 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1334 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001335 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001336 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001337
1338 size_t numtracks = mTracks.size();
1339 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001340 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001341 size_t numactiveseen = 0;
1342 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001343 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001344 Track::appendDumpHeader(result);
1345 for (size_t i = 0; i < numtracks; ++i) {
1346 sp<Track> track = mTracks[i];
1347 if (track != 0) {
1348 bool active = mActiveTracks.indexOf(track) >= 0;
1349 if (active) {
1350 numactiveseen++;
1351 }
1352 track->dump(buffer, SIZE, active);
1353 result.append(buffer);
1354 }
1355 }
1356 } else {
1357 result.append("\n");
1358 }
1359 if (numactiveseen != numactive) {
1360 // some tracks in the active list were not in the tracks list
1361 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1362 " not in the track list\n");
1363 result.append(buffer);
1364 Track::appendDumpHeader(result);
1365 for (size_t i = 0; i < numactive; ++i) {
1366 sp<Track> track = mActiveTracks[i].promote();
1367 if (track != 0 && mTracks.indexOf(track) < 0) {
1368 track->dump(buffer, SIZE, true);
1369 result.append(buffer);
1370 }
1371 }
1372 }
1373
1374 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001375}
1376
1377void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1378{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001379 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001380 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1381 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1382 dprintf(fd, " Total writes: %d\n", mNumWrites);
1383 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1384 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1385 dprintf(fd, " Suspend count: %d\n", mSuspended);
1386 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1387 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1388 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1389 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001390 AudioStreamOut *output = mOutput;
1391 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1392 String8 flagsAsString = outputFlagsToString(flags);
1393 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001394
1395 dumpBase(fd, args);
1396}
1397
1398// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001399
1400void AudioFlinger::PlaybackThread::onFirstRef()
1401{
1402 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1403}
1404
1405// ThreadBase virtuals
1406void AudioFlinger::PlaybackThread::preExit()
1407{
1408 ALOGV(" preExit()");
1409 // FIXME this is using hard-coded strings but in the future, this functionality will be
1410 // converted to use audio HAL extensions required to support tunneling
1411 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1412}
1413
1414// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1415sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1416 const sp<AudioFlinger::Client>& client,
1417 audio_stream_type_t streamType,
1418 uint32_t sampleRate,
1419 audio_format_t format,
1420 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001421 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001422 const sp<IMemory>& sharedBuffer,
1423 int sessionId,
1424 IAudioFlinger::track_flags_t *flags,
1425 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001426 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001427 status_t *status)
1428{
Glenn Kasten74935e42013-12-19 08:56:45 -08001429 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001430 sp<Track> track;
1431 status_t lStatus;
1432
1433 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1434
1435 // client expresses a preference for FAST, but we get the final say
1436 if (*flags & IAudioFlinger::TRACK_FAST) {
1437 if (
1438 // not timed
1439 (!isTimed) &&
1440 // either of these use cases:
1441 (
1442 // use case 1: shared buffer with any frame count
1443 (
1444 (sharedBuffer != 0)
1445 ) ||
1446 // use case 2: callback handler and frame count is default or at least as large as HAL
1447 (
1448 (tid != -1) &&
1449 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001450 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001451 )
1452 ) &&
1453 // PCM data
1454 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001455 // identical channel mask to sink, or mono in and stereo sink
1456 (channelMask == mChannelMask ||
1457 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1458 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001459 // hardware sample rate
1460 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001461 // normal mixer has an associated fast mixer
1462 hasFastMixer() &&
1463 // there are sufficient fast track slots available
1464 (mFastTrackAvailMask != 0)
1465 // FIXME test that MixerThread for this fast track has a capable output HAL
1466 // FIXME add a permission test also?
1467 ) {
1468 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1469 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001470 // read the fast track multiplier property the first time it is needed
1471 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1472 if (ok != 0) {
1473 ALOGE("%s pthread_once failed: %d", __func__, ok);
1474 }
1475 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001476 }
1477 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1478 frameCount, mFrameCount);
1479 } else {
1480 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001481 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1482 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001483 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001484 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001485 audio_is_linear_pcm(format),
1486 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1487 *flags &= ~IAudioFlinger::TRACK_FAST;
1488 // For compatibility with AudioTrack calculation, buffer depth is forced
1489 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1490 // This is probably too conservative, but legacy application code may depend on it.
1491 // If you change this calculation, also review the start threshold which is related.
1492 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1493 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1494 if (minBufCount < 2) {
1495 minBufCount = 2;
1496 }
1497 size_t minFrameCount = mNormalFrameCount * minBufCount;
1498 if (frameCount < minFrameCount) {
1499 frameCount = minFrameCount;
1500 }
1501 }
1502 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001503 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001504
Glenn Kastenc3df8382014-03-13 15:05:25 -07001505 switch (mType) {
1506
1507 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001508 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001509 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001510 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1511 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001512 sampleRate, format, channelMask, mOutput, mFormat);
1513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
1516 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001517 break;
1518
1519 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001520 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001521 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1522 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001523 sampleRate, format, channelMask, mOutput, mFormat);
1524 lStatus = BAD_VALUE;
1525 goto Exit;
1526 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001527 break;
1528
1529 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001530 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001531 ALOGE("createTrack_l() Bad parameter: format %#x \""
1532 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001533 format, mOutput, mFormat);
1534 lStatus = BAD_VALUE;
1535 goto Exit;
1536 }
Andy Hungcd044842014-08-07 11:04:34 -07001537 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001538 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001542 break;
1543
Eric Laurent81784c32012-11-19 14:55:58 -08001544 }
1545
1546 lStatus = initCheck();
1547 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001548 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001549 goto Exit;
1550 }
1551
1552 { // scope for mLock
1553 Mutex::Autolock _l(mLock);
1554
1555 // all tracks in same audio session must share the same routing strategy otherwise
1556 // conflicts will happen when tracks are moved from one output to another by audio policy
1557 // manager
1558 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1559 for (size_t i = 0; i < mTracks.size(); ++i) {
1560 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001561 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001562 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1563 if (sessionId == t->sessionId() && strategy != actual) {
1564 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1565 strategy, actual);
1566 lStatus = BAD_VALUE;
1567 goto Exit;
1568 }
1569 }
1570 }
1571
1572 if (!isTimed) {
1573 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001574 channelMask, frameCount, NULL, sharedBuffer,
1575 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001576 } else {
1577 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001578 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001579 }
Glenn Kasten03003332013-08-06 15:40:54 -07001580
1581 // new Track always returns non-NULL,
1582 // but TimedTrack::create() is a factory that could fail by returning NULL
1583 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1584 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001585 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001586 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001587 goto Exit;
1588 }
1589 mTracks.add(track);
1590
1591 sp<EffectChain> chain = getEffectChain_l(sessionId);
1592 if (chain != 0) {
1593 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1594 track->setMainBuffer(chain->inBuffer());
1595 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1596 chain->incTrackCnt();
1597 }
1598
1599 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1600 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1601 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1602 // so ask activity manager to do this on our behalf
1603 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1604 }
1605 }
1606
1607 lStatus = NO_ERROR;
1608
1609Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001610 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001611 return track;
1612}
1613
1614uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1615{
1616 return latency;
1617}
1618
1619uint32_t AudioFlinger::PlaybackThread::latency() const
1620{
1621 Mutex::Autolock _l(mLock);
1622 return latency_l();
1623}
1624uint32_t AudioFlinger::PlaybackThread::latency_l() const
1625{
1626 if (initCheck() == NO_ERROR) {
1627 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1628 } else {
1629 return 0;
1630 }
1631}
1632
1633void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1634{
1635 Mutex::Autolock _l(mLock);
1636 // Don't apply master volume in SW if our HAL can do it for us.
1637 if (mOutput && mOutput->audioHwDev &&
1638 mOutput->audioHwDev->canSetMasterVolume()) {
1639 mMasterVolume = 1.0;
1640 } else {
1641 mMasterVolume = value;
1642 }
1643}
1644
1645void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1646{
1647 Mutex::Autolock _l(mLock);
1648 // Don't apply master mute in SW if our HAL can do it for us.
1649 if (mOutput && mOutput->audioHwDev &&
1650 mOutput->audioHwDev->canSetMasterMute()) {
1651 mMasterMute = false;
1652 } else {
1653 mMasterMute = muted;
1654 }
1655}
1656
1657void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1658{
1659 Mutex::Autolock _l(mLock);
1660 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001661 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001662}
1663
1664void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1665{
1666 Mutex::Autolock _l(mLock);
1667 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001668 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001669}
1670
1671float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1672{
1673 Mutex::Autolock _l(mLock);
1674 return mStreamTypes[stream].volume;
1675}
1676
1677// addTrack_l() must be called with ThreadBase::mLock held
1678status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1679{
1680 status_t status = ALREADY_EXISTS;
1681
1682 // set retry count for buffer fill
1683 track->mRetryCount = kMaxTrackStartupRetries;
1684 if (mActiveTracks.indexOf(track) < 0) {
1685 // the track is newly added, make sure it fills up all its
1686 // buffers before playing. This is to ensure the client will
1687 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001688 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689 TrackBase::track_state state = track->mState;
1690 mLock.unlock();
1691 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1692 mLock.lock();
1693 // abort track was stopped/paused while we released the lock
1694 if (state != track->mState) {
1695 if (status == NO_ERROR) {
1696 mLock.unlock();
1697 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1698 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
Andy Hung09a50072014-02-27 14:30:47 -08001914 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001915 double multiplier = 1.0;
1916 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1917 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001918 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1919 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001920 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1921 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1922 maxNormalFrameCount = maxNormalFrameCount & ~15;
1923 if (maxNormalFrameCount < minNormalFrameCount) {
1924 maxNormalFrameCount = minNormalFrameCount;
1925 }
1926 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1927 if (multiplier <= 1.0) {
1928 multiplier = 1.0;
1929 } else if (multiplier <= 2.0) {
1930 if (2 * mFrameCount <= maxNormalFrameCount) {
1931 multiplier = 2.0;
1932 } else {
1933 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1934 }
1935 } else {
1936 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001937 // 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 -08001938 // track, but we sometimes have to do this to satisfy the maximum frame count
1939 // constraint)
1940 // FIXME this rounding up should not be done if no HAL SRC
1941 uint32_t truncMult = (uint32_t) multiplier;
1942 if ((truncMult & 1)) {
1943 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1944 ++truncMult;
1945 }
1946 }
1947 multiplier = (double) truncMult;
1948 }
1949 }
1950 mNormalFrameCount = multiplier * mFrameCount;
1951 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001952 if (mType == MIXER || mType == DUPLICATING) {
1953 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1954 }
Andy Hung09a50072014-02-27 14:30:47 -08001955 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001956 mNormalFrameCount);
1957
Andy Hung010a1a12014-03-13 13:57:33 -07001958 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1959 // Originally this was int16_t[] array, need to remove legacy implications.
1960 free(mSinkBuffer);
1961 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001962 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1963 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1964 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001965 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001966
Andy Hung69aed5f2014-02-25 17:24:40 -08001967 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1968 // drives the output.
1969 free(mMixerBuffer);
1970 mMixerBuffer = NULL;
1971 if (mMixerBufferEnabled) {
1972 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1973 mMixerBufferSize = mNormalFrameCount * mChannelCount
1974 * audio_bytes_per_sample(mMixerBufferFormat);
1975 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1976 }
Andy Hung98ef9782014-03-04 14:46:50 -08001977 free(mEffectBuffer);
1978 mEffectBuffer = NULL;
1979 if (mEffectBufferEnabled) {
1980 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1981 mEffectBufferSize = mNormalFrameCount * mChannelCount
1982 * audio_bytes_per_sample(mEffectBufferFormat);
1983 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1984 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001985
Eric Laurent81784c32012-11-19 14:55:58 -08001986 // force reconfiguration of effect chains and engines to take new buffer size and audio
1987 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001988 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001989 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1990 // matter.
1991 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1992 Vector< sp<EffectChain> > effectChains = mEffectChains;
1993 for (size_t i = 0; i < effectChains.size(); i ++) {
1994 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1995 }
1996}
1997
1998
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001999status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002000{
2001 if (halFrames == NULL || dspFrames == NULL) {
2002 return BAD_VALUE;
2003 }
2004 Mutex::Autolock _l(mLock);
2005 if (initCheck() != NO_ERROR) {
2006 return INVALID_OPERATION;
2007 }
2008 size_t framesWritten = mBytesWritten / mFrameSize;
2009 *halFrames = framesWritten;
2010
2011 if (isSuspended()) {
2012 // return an estimation of rendered frames when the output is suspended
2013 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2014 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2015 return NO_ERROR;
2016 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002017 status_t status;
2018 uint32_t frames;
2019 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2020 *dspFrames = (size_t)frames;
2021 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023}
2024
2025uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2026{
2027 Mutex::Autolock _l(mLock);
2028 uint32_t result = 0;
2029 if (getEffectChain_l(sessionId) != 0) {
2030 result = EFFECT_SESSION;
2031 }
2032
2033 for (size_t i = 0; i < mTracks.size(); ++i) {
2034 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002035 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002036 result |= TRACK_SESSION;
2037 break;
2038 }
2039 }
2040
2041 return result;
2042}
2043
2044uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2045{
2046 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2047 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2048 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2049 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2050 }
2051 for (size_t i = 0; i < mTracks.size(); i++) {
2052 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002053 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002054 return AudioSystem::getStrategyForStream(track->streamType());
2055 }
2056 }
2057 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2058}
2059
2060
2061AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2062{
2063 Mutex::Autolock _l(mLock);
2064 return mOutput;
2065}
2066
2067AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2068{
2069 Mutex::Autolock _l(mLock);
2070 AudioStreamOut *output = mOutput;
2071 mOutput = NULL;
2072 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2073 // must push a NULL and wait for ack
2074 mOutputSink.clear();
2075 mPipeSink.clear();
2076 mNormalSink.clear();
2077 return output;
2078}
2079
2080// this method must always be called either with ThreadBase mLock held or inside the thread loop
2081audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2082{
2083 if (mOutput == NULL) {
2084 return NULL;
2085 }
2086 return &mOutput->stream->common;
2087}
2088
2089uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2090{
2091 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2092}
2093
2094status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2095{
2096 if (!isValidSyncEvent(event)) {
2097 return BAD_VALUE;
2098 }
2099
2100 Mutex::Autolock _l(mLock);
2101
2102 for (size_t i = 0; i < mTracks.size(); ++i) {
2103 sp<Track> track = mTracks[i];
2104 if (event->triggerSession() == track->sessionId()) {
2105 (void) track->setSyncEvent(event);
2106 return NO_ERROR;
2107 }
2108 }
2109
2110 return NAME_NOT_FOUND;
2111}
2112
2113bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2114{
2115 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2116}
2117
2118void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2119 const Vector< sp<Track> >& tracksToRemove)
2120{
2121 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002122 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002123 for (size_t i = 0 ; i < count ; i++) {
2124 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002125 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002126 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127#ifdef ADD_BATTERY_DATA
2128 // to track the speaker usage
2129 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2130#endif
2131 if (track->isTerminated()) {
2132 AudioSystem::releaseOutput(mId);
2133 }
Eric Laurent81784c32012-11-19 14:55:58 -08002134 }
2135 }
2136 }
Eric Laurent81784c32012-11-19 14:55:58 -08002137}
2138
2139void AudioFlinger::PlaybackThread::checkSilentMode_l()
2140{
2141 if (!mMasterMute) {
2142 char value[PROPERTY_VALUE_MAX];
2143 if (property_get("ro.audio.silent", value, "0") > 0) {
2144 char *endptr;
2145 unsigned long ul = strtoul(value, &endptr, 0);
2146 if (*endptr == '\0' && ul != 0) {
2147 ALOGD("Silence is golden");
2148 // The setprop command will not allow a property to be changed after
2149 // the first time it is set, so we don't have to worry about un-muting.
2150 setMasterMute_l(true);
2151 }
2152 }
2153 }
2154}
2155
2156// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002158{
2159 // FIXME rewrite to reduce number of system calls
2160 mLastWriteTime = systemTime();
2161 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002163 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002164
2165 // If an NBAIO sink is present, use it to write the normal mixer's submix
2166 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002167
Andy Hung010a1a12014-03-13 13:57:33 -07002168 const size_t count = mBytesRemaining / mFrameSize;
2169
Simon Wilson2d590962012-11-29 15:18:50 -08002170 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // update the setpoint when AudioFlinger::mScreenState changes
2172 uint32_t screenState = AudioFlinger::mScreenState;
2173 if (screenState != mScreenState) {
2174 mScreenState = screenState;
2175 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2176 if (pipe != NULL) {
2177 pipe->setAvgFrames((mScreenState & 1) ?
2178 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2179 }
2180 }
Andy Hung010a1a12014-03-13 13:57:33 -07002181 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002182 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002183 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002184 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002185 } else {
2186 bytesWritten = framesWritten;
2187 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002188 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002189 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002190 if (status == NO_ERROR) {
2191 size_t totalFramesWritten = mNormalSink->framesWritten();
2192 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2193 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002194 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002195 mLatchDValid = true;
2196 }
2197 }
Eric Laurent81784c32012-11-19 14:55:58 -08002198 // otherwise use the HAL / AudioStreamOut directly
2199 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002201
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002203 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2204 mWriteAckSequence += 2;
2205 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002207 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002208 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002209 // FIXME We should have an implementation of timestamps for direct output threads.
2210 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002212 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213 if (mUseAsyncWrite &&
2214 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2215 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002216 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002218 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002219 }
Eric Laurent81784c32012-11-19 14:55:58 -08002220 }
2221
Eric Laurent81784c32012-11-19 14:55:58 -08002222 mNumWrites++;
2223 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002224 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225 return bytesWritten;
2226}
2227
2228void AudioFlinger::PlaybackThread::threadLoop_drain()
2229{
2230 if (mOutput->stream->drain) {
2231 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2232 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002233 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2234 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002236 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237 }
2238 mOutput->stream->drain(mOutput->stream,
2239 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2240 : AUDIO_DRAIN_ALL);
2241 }
2242}
2243
2244void AudioFlinger::PlaybackThread::threadLoop_exit()
2245{
2246 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002247}
2248
2249/*
2250The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002251 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002252 - activeSleepTime from activeSleepTimeUs()
2253 - idleSleepTime from idleSleepTimeUs()
2254 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2255 - maxPeriod from frame count and sample rate (MIXER only)
2256
2257The parameters that affect these derived values are:
2258 - frame count
2259 - frame size
2260 - sample rate
2261 - device type: A2DP or not
2262 - device latency
2263 - format: PCM or not
2264 - active sleep time
2265 - idle sleep time
2266*/
2267
2268void AudioFlinger::PlaybackThread::cacheParameters_l()
2269{
Andy Hung25c2dac2014-02-27 14:56:00 -08002270 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002271 activeSleepTime = activeSleepTimeUs();
2272 idleSleepTime = idleSleepTimeUs();
2273}
2274
2275void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2276{
Glenn Kasten7c027242012-12-26 14:43:16 -08002277 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002278 this, streamType, mTracks.size());
2279 Mutex::Autolock _l(mLock);
2280
2281 size_t size = mTracks.size();
2282 for (size_t i = 0; i < size; i++) {
2283 sp<Track> t = mTracks[i];
2284 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002285 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002286 }
2287 }
2288}
2289
2290status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2291{
2292 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002293 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2294 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002295 bool ownsBuffer = false;
2296
2297 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2298 if (session > 0) {
2299 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002300 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002301 if (mType != DIRECT) {
2302 size_t numSamples = mNormalFrameCount * mChannelCount;
2303 buffer = new int16_t[numSamples];
2304 memset(buffer, 0, numSamples * sizeof(int16_t));
2305 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2306 ownsBuffer = true;
2307 }
2308
2309 // Attach all tracks with same session ID to this chain.
2310 for (size_t i = 0; i < mTracks.size(); ++i) {
2311 sp<Track> track = mTracks[i];
2312 if (session == track->sessionId()) {
2313 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2314 buffer);
2315 track->setMainBuffer(buffer);
2316 chain->incTrackCnt();
2317 }
2318 }
2319
2320 // indicate all active tracks in the chain
2321 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2322 sp<Track> track = mActiveTracks[i].promote();
2323 if (track == 0) {
2324 continue;
2325 }
2326 if (session == track->sessionId()) {
2327 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2328 chain->incActiveTrackCnt();
2329 }
2330 }
2331 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002332 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002333 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002334 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2335 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002336 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2337 // chains list in order to be processed last as it contains output stage effects
2338 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2339 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2340 // after track specific effects and before output stage
2341 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2342 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2343 // Effect chain for other sessions are inserted at beginning of effect
2344 // chains list to be processed before output mix effects. Relative order between other
2345 // sessions is not important
2346 size_t size = mEffectChains.size();
2347 size_t i = 0;
2348 for (i = 0; i < size; i++) {
2349 if (mEffectChains[i]->sessionId() < session) {
2350 break;
2351 }
2352 }
2353 mEffectChains.insertAt(chain, i);
2354 checkSuspendOnAddEffectChain_l(chain);
2355
2356 return NO_ERROR;
2357}
2358
2359size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2360{
2361 int session = chain->sessionId();
2362
2363 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2364
2365 for (size_t i = 0; i < mEffectChains.size(); i++) {
2366 if (chain == mEffectChains[i]) {
2367 mEffectChains.removeAt(i);
2368 // detach all active tracks from the chain
2369 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2370 sp<Track> track = mActiveTracks[i].promote();
2371 if (track == 0) {
2372 continue;
2373 }
2374 if (session == track->sessionId()) {
2375 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2376 chain.get(), session);
2377 chain->decActiveTrackCnt();
2378 }
2379 }
2380
2381 // detach all tracks with same session ID from this chain
2382 for (size_t i = 0; i < mTracks.size(); ++i) {
2383 sp<Track> track = mTracks[i];
2384 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002385 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002386 chain->decTrackCnt();
2387 }
2388 }
2389 break;
2390 }
2391 }
2392 return mEffectChains.size();
2393}
2394
2395status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2396 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2397{
2398 Mutex::Autolock _l(mLock);
2399 return attachAuxEffect_l(track, EffectId);
2400}
2401
2402status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2403 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2404{
2405 status_t status = NO_ERROR;
2406
2407 if (EffectId == 0) {
2408 track->setAuxBuffer(0, NULL);
2409 } else {
2410 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2411 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2412 if (effect != 0) {
2413 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2414 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2415 } else {
2416 status = INVALID_OPERATION;
2417 }
2418 } else {
2419 status = BAD_VALUE;
2420 }
2421 }
2422 return status;
2423}
2424
2425void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2426{
2427 for (size_t i = 0; i < mTracks.size(); ++i) {
2428 sp<Track> track = mTracks[i];
2429 if (track->auxEffectId() == effectId) {
2430 attachAuxEffect_l(track, 0);
2431 }
2432 }
2433}
2434
2435bool AudioFlinger::PlaybackThread::threadLoop()
2436{
2437 Vector< sp<Track> > tracksToRemove;
2438
2439 standbyTime = systemTime();
2440
2441 // MIXER
2442 nsecs_t lastWarning = 0;
2443
2444 // DUPLICATING
2445 // FIXME could this be made local to while loop?
2446 writeFrames = 0;
2447
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002448 int lastGeneration = 0;
2449
Eric Laurent81784c32012-11-19 14:55:58 -08002450 cacheParameters_l();
2451 sleepTime = idleSleepTime;
2452
2453 if (mType == MIXER) {
2454 sleepTimeShift = 0;
2455 }
2456
2457 CpuStats cpuStats;
2458 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2459
2460 acquireWakeLock();
2461
Glenn Kasten9e58b552013-01-18 15:09:48 -08002462 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2463 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2464 // and then that string will be logged at the next convenient opportunity.
2465 const char *logString = NULL;
2466
Eric Laurent664539d2013-09-23 18:24:31 -07002467 checkSilentMode_l();
2468
Eric Laurent81784c32012-11-19 14:55:58 -08002469 while (!exitPending())
2470 {
2471 cpuStats.sample(myName);
2472
2473 Vector< sp<EffectChain> > effectChains;
2474
Eric Laurent81784c32012-11-19 14:55:58 -08002475 { // scope for mLock
2476
2477 Mutex::Autolock _l(mLock);
2478
Eric Laurent021cf962014-05-13 10:18:14 -07002479 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002480
Glenn Kasten9e58b552013-01-18 15:09:48 -08002481 if (logString != NULL) {
2482 mNBLogWriter->logTimestamp();
2483 mNBLogWriter->log(logString);
2484 logString = NULL;
2485 }
2486
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002487 // Gather the framesReleased counters for all active tracks,
2488 // and latch them atomically with the timestamp.
2489 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2490 mLatchD.mFramesReleased.clear();
2491 size_t size = mActiveTracks.size();
2492 for (size_t i = 0; i < size; i++) {
2493 sp<Track> t = mActiveTracks[i].promote();
2494 if (t != 0) {
2495 mLatchD.mFramesReleased.add(t.get(),
2496 t->mAudioTrackServerProxy->framesReleased());
2497 }
2498 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002499 if (mLatchDValid) {
2500 mLatchQ = mLatchD;
2501 mLatchDValid = false;
2502 mLatchQValid = true;
2503 }
2504
Eric Laurent81784c32012-11-19 14:55:58 -08002505 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506 if (mSignalPending) {
2507 // A signal was raised while we were unlocked
2508 mSignalPending = false;
2509 } else if (waitingAsyncCallback_l()) {
2510 if (exitPending()) {
2511 break;
2512 }
2513 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002514 mWakeLockUids.clear();
2515 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002516 ALOGV("wait async completion");
2517 mWaitWorkCV.wait(mLock);
2518 ALOGV("async completion/wake");
2519 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002520 standbyTime = systemTime() + standbyDelay;
2521 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002522
2523 continue;
2524 }
2525 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002526 isSuspended()) {
2527 // put audio hardware into standby after short delay
2528 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002529
2530 threadLoop_standby();
2531
2532 mStandby = true;
2533 }
2534
2535 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2536 // we're about to wait, flush the binder command buffer
2537 IPCThreadState::self()->flushCommands();
2538
2539 clearOutputTracks();
2540
2541 if (exitPending()) {
2542 break;
2543 }
2544
2545 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002546 mWakeLockUids.clear();
2547 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002548 // wait until we have something to do...
2549 ALOGV("%s going to sleep", myName.string());
2550 mWaitWorkCV.wait(mLock);
2551 ALOGV("%s waking up", myName.string());
2552 acquireWakeLock_l();
2553
2554 mMixerStatus = MIXER_IDLE;
2555 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2556 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002557 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002558 checkSilentMode_l();
2559
2560 standbyTime = systemTime() + standbyDelay;
2561 sleepTime = idleSleepTime;
2562 if (mType == MIXER) {
2563 sleepTimeShift = 0;
2564 }
2565
2566 continue;
2567 }
2568 }
Eric Laurent81784c32012-11-19 14:55:58 -08002569 // mMixerStatusIgnoringFastTracks is also updated internally
2570 mMixerStatus = prepareTracks_l(&tracksToRemove);
2571
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002572 // compare with previously applied list
2573 if (lastGeneration != mActiveTracksGeneration) {
2574 // update wakelock
2575 updateWakeLockUids_l(mWakeLockUids);
2576 lastGeneration = mActiveTracksGeneration;
2577 }
2578
Eric Laurent81784c32012-11-19 14:55:58 -08002579 // prevent any changes in effect chain list and in each effect chain
2580 // during mixing and effect process as the audio buffers could be deleted
2581 // or modified if an effect is created or deleted
2582 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002583 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002584
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 if (mBytesRemaining == 0) {
2586 mCurrentWriteLength = 0;
2587 if (mMixerStatus == MIXER_TRACKS_READY) {
2588 // threadLoop_mix() sets mCurrentWriteLength
2589 threadLoop_mix();
2590 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2591 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2592 // threadLoop_sleepTime sets sleepTime to 0 if data
2593 // must be written to HAL
2594 threadLoop_sleepTime();
2595 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002596 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 }
2598 }
Andy Hung98ef9782014-03-04 14:46:50 -08002599 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2600 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2601 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2602 // or mSinkBuffer (if there are no effects).
2603 //
2604 // This is done pre-effects computation; if effects change to
2605 // support higher precision, this needs to move.
2606 //
2607 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2608 // TODO use sleepTime == 0 as an additional condition.
2609 if (mMixerBufferValid) {
2610 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2611 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2612
2613 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2614 mNormalFrameCount * mChannelCount);
2615 }
2616
Eric Laurentbfb1b832013-01-07 09:53:42 -08002617 mBytesRemaining = mCurrentWriteLength;
2618 if (isSuspended()) {
2619 sleepTime = suspendSleepTimeUs();
2620 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002621 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002622 mBytesRemaining = 0;
2623 }
Eric Laurent81784c32012-11-19 14:55:58 -08002624
Eric Laurentbfb1b832013-01-07 09:53:42 -08002625 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002626 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002627 for (size_t i = 0; i < effectChains.size(); i ++) {
2628 effectChains[i]->process_l();
2629 }
Eric Laurent81784c32012-11-19 14:55:58 -08002630 }
2631 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002632 // Process effect chains for offloaded thread even if no audio
2633 // was read from audio track: process only updates effect state
2634 // and thus does have to be synchronized with audio writes but may have
2635 // to be called while waiting for async write callback
2636 if (mType == OFFLOAD) {
2637 for (size_t i = 0; i < effectChains.size(); i ++) {
2638 effectChains[i]->process_l();
2639 }
2640 }
Eric Laurent81784c32012-11-19 14:55:58 -08002641
Andy Hung98ef9782014-03-04 14:46:50 -08002642 // Only if the Effects buffer is enabled and there is data in the
2643 // Effects buffer (buffer valid), we need to
2644 // copy into the sink buffer.
2645 // TODO use sleepTime == 0 as an additional condition.
2646 if (mEffectBufferValid) {
2647 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2648 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2649 mNormalFrameCount * mChannelCount);
2650 }
2651
Eric Laurent81784c32012-11-19 14:55:58 -08002652 // enable changes in effect chain
2653 unlockEffectChains(effectChains);
2654
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 if (!waitingAsyncCallback()) {
2656 // sleepTime == 0 means we must write to audio hardware
2657 if (sleepTime == 0) {
2658 if (mBytesRemaining) {
2659 ssize_t ret = threadLoop_write();
2660 if (ret < 0) {
2661 mBytesRemaining = 0;
2662 } else {
2663 mBytesWritten += ret;
2664 mBytesRemaining -= ret;
2665 }
2666 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2667 (mMixerStatus == MIXER_DRAIN_ALL)) {
2668 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002669 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002670 if (mType == MIXER) {
2671 // write blocked detection
2672 nsecs_t now = systemTime();
2673 nsecs_t delta = now - mLastWriteTime;
2674 if (!mStandby && delta > maxPeriod) {
2675 mNumDelayedWrites++;
2676 if ((now - lastWarning) > kWarningThrottleNs) {
2677 ATRACE_NAME("underrun");
2678 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2679 ns2ms(delta), mNumDelayedWrites, this);
2680 lastWarning = now;
2681 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 }
2683 }
Eric Laurent81784c32012-11-19 14:55:58 -08002684
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685 } else {
2686 usleep(sleepTime);
2687 }
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
2689
2690 // Finally let go of removed track(s), without the lock held
2691 // since we can't guarantee the destructors won't acquire that
2692 // same lock. This will also mutate and push a new fast mixer state.
2693 threadLoop_removeTracks(tracksToRemove);
2694 tracksToRemove.clear();
2695
2696 // FIXME I don't understand the need for this here;
2697 // it was in the original code but maybe the
2698 // assignment in saveOutputTracks() makes this unnecessary?
2699 clearOutputTracks();
2700
2701 // Effect chains will be actually deleted here if they were removed from
2702 // mEffectChains list during mixing or effects processing
2703 effectChains.clear();
2704
2705 // FIXME Note that the above .clear() is no longer necessary since effectChains
2706 // is now local to this block, but will keep it for now (at least until merge done).
2707 }
2708
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 threadLoop_exit();
2710
Eric Laurentcf817a22014-08-04 20:36:31 -07002711 if (!mStandby) {
2712 threadLoop_standby();
2713 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002714 }
2715
2716 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002717 mWakeLockUids.clear();
2718 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002719
2720 ALOGV("Thread %p type %d exiting", this, mType);
2721 return false;
2722}
2723
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724// removeTracks_l() must be called with ThreadBase::mLock held
2725void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2726{
2727 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002728 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 for (size_t i=0 ; i<count ; i++) {
2730 const sp<Track>& track = tracksToRemove.itemAt(i);
2731 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002732 mWakeLockUids.remove(track->uid());
2733 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002734 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2735 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2736 if (chain != 0) {
2737 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2738 track->sessionId());
2739 chain->decActiveTrackCnt();
2740 }
2741 if (track->isTerminated()) {
2742 removeTrack_l(track);
2743 }
2744 }
2745 }
2746
2747}
Eric Laurent81784c32012-11-19 14:55:58 -08002748
Eric Laurentaccc1472013-09-20 09:36:34 -07002749status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2750{
2751 if (mNormalSink != 0) {
2752 return mNormalSink->getTimestamp(timestamp);
2753 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002754 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002755 uint64_t position64;
2756 int ret = mOutput->stream->get_presentation_position(
2757 mOutput->stream, &position64, &timestamp.mTime);
2758 if (ret == 0) {
2759 timestamp.mPosition = (uint32_t)position64;
2760 return NO_ERROR;
2761 }
2762 }
2763 return INVALID_OPERATION;
2764}
Eric Laurent1c333e22014-05-20 10:48:17 -07002765
2766status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2767 audio_patch_handle_t *handle)
2768{
2769 status_t status = NO_ERROR;
2770 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2771 // store new device and send to effects
2772 audio_devices_t type = AUDIO_DEVICE_NONE;
2773 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2774 type |= patch->sinks[i].ext.device.type;
2775 }
2776 mOutDevice = type;
2777 for (size_t i = 0; i < mEffectChains.size(); i++) {
2778 mEffectChains[i]->setDevice_l(mOutDevice);
2779 }
2780
2781 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2782 status = hwDevice->create_audio_patch(hwDevice,
2783 patch->num_sources,
2784 patch->sources,
2785 patch->num_sinks,
2786 patch->sinks,
2787 handle);
2788 } else {
2789 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2790 }
2791 return status;
2792}
2793
2794status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2795{
2796 status_t status = NO_ERROR;
2797 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2798 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2799 status = hwDevice->release_audio_patch(hwDevice, handle);
2800 } else {
2801 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2802 }
2803 return status;
2804}
2805
Eric Laurent83b88082014-06-20 18:31:16 -07002806void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2807{
2808 Mutex::Autolock _l(mLock);
2809 mTracks.add(track);
2810}
2811
2812void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2813{
2814 Mutex::Autolock _l(mLock);
2815 destroyTrack_l(track);
2816}
2817
2818void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2819{
2820 ThreadBase::getAudioPortConfig(config);
2821 config->role = AUDIO_PORT_ROLE_SOURCE;
2822 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2823 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2824}
2825
Eric Laurent81784c32012-11-19 14:55:58 -08002826// ----------------------------------------------------------------------------
2827
2828AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2829 audio_io_handle_t id, audio_devices_t device, type_t type)
2830 : PlaybackThread(audioFlinger, output, id, device, type),
2831 // mAudioMixer below
2832 // mFastMixer below
2833 mFastMixerFutex(0)
2834 // mOutputSink below
2835 // mPipeSink below
2836 // mNormalSink below
2837{
2838 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002839 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002840 "mFrameCount=%d, mNormalFrameCount=%d",
2841 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2842 mNormalFrameCount);
2843 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2844
Eric Laurent81784c32012-11-19 14:55:58 -08002845 // create an NBAIO sink for the HAL output stream, and negotiate
2846 mOutputSink = new AudioStreamOutSink(output->stream);
2847 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002848 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002849 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2850 ALOG_ASSERT(index == 0);
2851
2852 // initialize fast mixer depending on configuration
2853 bool initFastMixer;
2854 switch (kUseFastMixer) {
2855 case FastMixer_Never:
2856 initFastMixer = false;
2857 break;
2858 case FastMixer_Always:
2859 initFastMixer = true;
2860 break;
2861 case FastMixer_Static:
2862 case FastMixer_Dynamic:
2863 initFastMixer = mFrameCount < mNormalFrameCount;
2864 break;
2865 }
2866 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002867 audio_format_t fastMixerFormat;
2868 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2869 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2870 } else {
2871 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2872 }
2873 if (mFormat != fastMixerFormat) {
2874 // change our Sink format to accept our intermediate precision
2875 mFormat = fastMixerFormat;
2876 free(mSinkBuffer);
2877 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2878 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2879 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2880 }
Eric Laurent81784c32012-11-19 14:55:58 -08002881
2882 // create a MonoPipe to connect our submix to FastMixer
2883 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002884 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002885 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002886 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002887 format.mFormat = fastMixerFormat;
2888 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2889
Eric Laurent81784c32012-11-19 14:55:58 -08002890 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2891 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2892 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2893 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2894 const NBAIO_Format offers[1] = {format};
2895 size_t numCounterOffers = 0;
2896 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2897 ALOG_ASSERT(index == 0);
2898 monoPipe->setAvgFrames((mScreenState & 1) ?
2899 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2900 mPipeSink = monoPipe;
2901
Glenn Kasten46909e72013-02-26 09:20:22 -08002902#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002903 if (mTeeSinkOutputEnabled) {
2904 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002905 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2906 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002907 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002908 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002909 ALOG_ASSERT(index == 0);
2910 mTeeSink = teeSink;
2911 PipeReader *teeSource = new PipeReader(*teeSink);
2912 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002913 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002914 ALOG_ASSERT(index == 0);
2915 mTeeSource = teeSource;
2916 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002917#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002918
2919 // create fast mixer and configure it initially with just one fast track for our submix
2920 mFastMixer = new FastMixer();
2921 FastMixerStateQueue *sq = mFastMixer->sq();
2922#ifdef STATE_QUEUE_DUMP
2923 sq->setObserverDump(&mStateQueueObserverDump);
2924 sq->setMutatorDump(&mStateQueueMutatorDump);
2925#endif
2926 FastMixerState *state = sq->begin();
2927 FastTrack *fastTrack = &state->mFastTracks[0];
2928 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2929 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2930 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002931 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2932 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002933 fastTrack->mGeneration++;
2934 state->mFastTracksGen++;
2935 state->mTrackMask = 1;
2936 // fast mixer will use the HAL output sink
2937 state->mOutputSink = mOutputSink.get();
2938 state->mOutputSinkGen++;
2939 state->mFrameCount = mFrameCount;
2940 state->mCommand = FastMixerState::COLD_IDLE;
2941 // already done in constructor initialization list
2942 //mFastMixerFutex = 0;
2943 state->mColdFutexAddr = &mFastMixerFutex;
2944 state->mColdGen++;
2945 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002946#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002947 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002948#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002949 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2950 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 sq->end();
2952 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2953
2954 // start the fast mixer
2955 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2956 pid_t tid = mFastMixer->getTid();
2957 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2958 if (err != 0) {
2959 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2960 kPriorityFastMixer, getpid_cached, tid, err);
2961 }
2962
2963#ifdef AUDIO_WATCHDOG
2964 // create and start the watchdog
2965 mAudioWatchdog = new AudioWatchdog();
2966 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2967 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2968 tid = mAudioWatchdog->getTid();
2969 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2970 if (err != 0) {
2971 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2972 kPriorityFastMixer, getpid_cached, tid, err);
2973 }
2974#endif
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976 }
2977
2978 switch (kUseFastMixer) {
2979 case FastMixer_Never:
2980 case FastMixer_Dynamic:
2981 mNormalSink = mOutputSink;
2982 break;
2983 case FastMixer_Always:
2984 mNormalSink = mPipeSink;
2985 break;
2986 case FastMixer_Static:
2987 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2988 break;
2989 }
2990}
2991
2992AudioFlinger::MixerThread::~MixerThread()
2993{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002994 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002995 FastMixerStateQueue *sq = mFastMixer->sq();
2996 FastMixerState *state = sq->begin();
2997 if (state->mCommand == FastMixerState::COLD_IDLE) {
2998 int32_t old = android_atomic_inc(&mFastMixerFutex);
2999 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003000 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003001 }
3002 }
3003 state->mCommand = FastMixerState::EXIT;
3004 sq->end();
3005 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3006 mFastMixer->join();
3007 // Though the fast mixer thread has exited, it's state queue is still valid.
3008 // We'll use that extract the final state which contains one remaining fast track
3009 // corresponding to our sub-mix.
3010 state = sq->begin();
3011 ALOG_ASSERT(state->mTrackMask == 1);
3012 FastTrack *fastTrack = &state->mFastTracks[0];
3013 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3014 delete fastTrack->mBufferProvider;
3015 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003016 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003017#ifdef AUDIO_WATCHDOG
3018 if (mAudioWatchdog != 0) {
3019 mAudioWatchdog->requestExit();
3020 mAudioWatchdog->requestExitAndWait();
3021 mAudioWatchdog.clear();
3022 }
3023#endif
3024 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003025 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003026 delete mAudioMixer;
3027}
3028
3029
3030uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3031{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003032 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003033 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3034 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3035 }
3036 return latency;
3037}
3038
3039
3040void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3041{
3042 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3043}
3044
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003046{
3047 // FIXME we should only do one push per cycle; confirm this is true
3048 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003049 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003050 FastMixerStateQueue *sq = mFastMixer->sq();
3051 FastMixerState *state = sq->begin();
3052 if (state->mCommand != FastMixerState::MIX_WRITE &&
3053 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3054 if (state->mCommand == FastMixerState::COLD_IDLE) {
3055 int32_t old = android_atomic_inc(&mFastMixerFutex);
3056 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003057 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003058 }
3059#ifdef AUDIO_WATCHDOG
3060 if (mAudioWatchdog != 0) {
3061 mAudioWatchdog->resume();
3062 }
3063#endif
3064 }
3065 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003066 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3067 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003068 sq->end();
3069 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3070 if (kUseFastMixer == FastMixer_Dynamic) {
3071 mNormalSink = mPipeSink;
3072 }
3073 } else {
3074 sq->end(false /*didModify*/);
3075 }
3076 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003077 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003078}
3079
3080void AudioFlinger::MixerThread::threadLoop_standby()
3081{
3082 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003083 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003084 FastMixerStateQueue *sq = mFastMixer->sq();
3085 FastMixerState *state = sq->begin();
3086 if (!(state->mCommand & FastMixerState::IDLE)) {
3087 state->mCommand = FastMixerState::COLD_IDLE;
3088 state->mColdFutexAddr = &mFastMixerFutex;
3089 state->mColdGen++;
3090 mFastMixerFutex = 0;
3091 sq->end();
3092 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3093 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3094 if (kUseFastMixer == FastMixer_Dynamic) {
3095 mNormalSink = mOutputSink;
3096 }
3097#ifdef AUDIO_WATCHDOG
3098 if (mAudioWatchdog != 0) {
3099 mAudioWatchdog->pause();
3100 }
3101#endif
3102 } else {
3103 sq->end(false /*didModify*/);
3104 }
3105 }
3106 PlaybackThread::threadLoop_standby();
3107}
3108
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3110{
3111 return false;
3112}
3113
3114bool AudioFlinger::PlaybackThread::shouldStandby_l()
3115{
3116 return !mStandby;
3117}
3118
3119bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3120{
3121 Mutex::Autolock _l(mLock);
3122 return waitingAsyncCallback_l();
3123}
3124
Eric Laurent81784c32012-11-19 14:55:58 -08003125// shared by MIXER and DIRECT, overridden by DUPLICATING
3126void AudioFlinger::PlaybackThread::threadLoop_standby()
3127{
3128 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3129 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003131 // discard any pending drain or write ack by incrementing sequence
3132 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3133 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003135 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3136 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 }
Eric Laurent81784c32012-11-19 14:55:58 -08003138}
3139
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003140void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3141{
3142 ALOGV("signal playback thread");
3143 broadcast_l();
3144}
3145
Eric Laurent81784c32012-11-19 14:55:58 -08003146void AudioFlinger::MixerThread::threadLoop_mix()
3147{
3148 // obtain the presentation timestamp of the next output buffer
3149 int64_t pts;
3150 status_t status = INVALID_OPERATION;
3151
3152 if (mNormalSink != 0) {
3153 status = mNormalSink->getNextWriteTimestamp(&pts);
3154 } else {
3155 status = mOutputSink->getNextWriteTimestamp(&pts);
3156 }
3157
3158 if (status != NO_ERROR) {
3159 pts = AudioBufferProvider::kInvalidPTS;
3160 }
3161
3162 // mix buffers...
3163 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003164 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003165 // increase sleep time progressively when application underrun condition clears.
3166 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3167 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3168 // such that we would underrun the audio HAL.
3169 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3170 sleepTimeShift--;
3171 }
3172 sleepTime = 0;
3173 standbyTime = systemTime() + standbyDelay;
3174 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003175
Eric Laurent81784c32012-11-19 14:55:58 -08003176}
3177
3178void AudioFlinger::MixerThread::threadLoop_sleepTime()
3179{
3180 // If no tracks are ready, sleep once for the duration of an output
3181 // buffer size, then write 0s to the output
3182 if (sleepTime == 0) {
3183 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3184 sleepTime = activeSleepTime >> sleepTimeShift;
3185 if (sleepTime < kMinThreadSleepTimeUs) {
3186 sleepTime = kMinThreadSleepTimeUs;
3187 }
3188 // reduce sleep time in case of consecutive application underruns to avoid
3189 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3190 // duration we would end up writing less data than needed by the audio HAL if
3191 // the condition persists.
3192 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3193 sleepTimeShift++;
3194 }
3195 } else {
3196 sleepTime = idleSleepTime;
3197 }
3198 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003199 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3200 // before effects processing or output.
3201 if (mMixerBufferValid) {
3202 memset(mMixerBuffer, 0, mMixerBufferSize);
3203 } else {
3204 memset(mSinkBuffer, 0, mSinkBufferSize);
3205 }
Eric Laurent81784c32012-11-19 14:55:58 -08003206 sleepTime = 0;
3207 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3208 "anticipated start");
3209 }
3210 // TODO add standby time extension fct of effect tail
3211}
3212
3213// prepareTracks_l() must be called with ThreadBase::mLock held
3214AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3215 Vector< sp<Track> > *tracksToRemove)
3216{
3217
3218 mixer_state mixerStatus = MIXER_IDLE;
3219 // find out which tracks need to be processed
3220 size_t count = mActiveTracks.size();
3221 size_t mixedTracks = 0;
3222 size_t tracksWithEffect = 0;
3223 // counts only _active_ fast tracks
3224 size_t fastTracks = 0;
3225 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3226
3227 float masterVolume = mMasterVolume;
3228 bool masterMute = mMasterMute;
3229
3230 if (masterMute) {
3231 masterVolume = 0;
3232 }
3233 // Delegate master volume control to effect in output mix effect chain if needed
3234 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3235 if (chain != 0) {
3236 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3237 chain->setVolume_l(&v, &v);
3238 masterVolume = (float)((v + (1 << 23)) >> 24);
3239 chain.clear();
3240 }
3241
3242 // prepare a new state to push
3243 FastMixerStateQueue *sq = NULL;
3244 FastMixerState *state = NULL;
3245 bool didModify = false;
3246 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003247 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003248 sq = mFastMixer->sq();
3249 state = sq->begin();
3250 }
3251
Andy Hung69aed5f2014-02-25 17:24:40 -08003252 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003253 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003254
Eric Laurent81784c32012-11-19 14:55:58 -08003255 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003256 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003257 if (t == 0) {
3258 continue;
3259 }
3260
3261 // this const just means the local variable doesn't change
3262 Track* const track = t.get();
3263
3264 // process fast tracks
3265 if (track->isFastTrack()) {
3266
3267 // It's theoretically possible (though unlikely) for a fast track to be created
3268 // and then removed within the same normal mix cycle. This is not a problem, as
3269 // the track never becomes active so it's fast mixer slot is never touched.
3270 // The converse, of removing an (active) track and then creating a new track
3271 // at the identical fast mixer slot within the same normal mix cycle,
3272 // is impossible because the slot isn't marked available until the end of each cycle.
3273 int j = track->mFastIndex;
3274 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3275 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3276 FastTrack *fastTrack = &state->mFastTracks[j];
3277
3278 // Determine whether the track is currently in underrun condition,
3279 // and whether it had a recent underrun.
3280 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3281 FastTrackUnderruns underruns = ftDump->mUnderruns;
3282 uint32_t recentFull = (underruns.mBitFields.mFull -
3283 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3284 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3285 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3286 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3287 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3288 uint32_t recentUnderruns = recentPartial + recentEmpty;
3289 track->mObservedUnderruns = underruns;
3290 // don't count underruns that occur while stopping or pausing
3291 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003292 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3293 recentUnderruns > 0) {
3294 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3295 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003296 }
3297
3298 // This is similar to the state machine for normal tracks,
3299 // with a few modifications for fast tracks.
3300 bool isActive = true;
3301 switch (track->mState) {
3302 case TrackBase::STOPPING_1:
3303 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003305 track->mState = TrackBase::STOPPING_2;
3306 }
3307 break;
3308 case TrackBase::PAUSING:
3309 // ramp down is not yet implemented
3310 track->setPaused();
3311 break;
3312 case TrackBase::RESUMING:
3313 // ramp up is not yet implemented
3314 track->mState = TrackBase::ACTIVE;
3315 break;
3316 case TrackBase::ACTIVE:
3317 if (recentFull > 0 || recentPartial > 0) {
3318 // track has provided at least some frames recently: reset retry count
3319 track->mRetryCount = kMaxTrackRetries;
3320 }
3321 if (recentUnderruns == 0) {
3322 // no recent underruns: stay active
3323 break;
3324 }
3325 // there has recently been an underrun of some kind
3326 if (track->sharedBuffer() == 0) {
3327 // were any of the recent underruns "empty" (no frames available)?
3328 if (recentEmpty == 0) {
3329 // no, then ignore the partial underruns as they are allowed indefinitely
3330 break;
3331 }
3332 // there has recently been an "empty" underrun: decrement the retry counter
3333 if (--(track->mRetryCount) > 0) {
3334 break;
3335 }
3336 // indicate to client process that the track was disabled because of underrun;
3337 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003338 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // remove from active list, but state remains ACTIVE [confusing but true]
3340 isActive = false;
3341 break;
3342 }
3343 // fall through
3344 case TrackBase::STOPPING_2:
3345 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003346 case TrackBase::STOPPED:
3347 case TrackBase::FLUSHED: // flush() while active
3348 // Check for presentation complete if track is inactive
3349 // We have consumed all the buffers of this track.
3350 // This would be incomplete if we auto-paused on underrun
3351 {
3352 size_t audioHALFrames =
3353 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3354 size_t framesWritten = mBytesWritten / mFrameSize;
3355 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3356 // track stays in active list until presentation is complete
3357 break;
3358 }
3359 }
3360 if (track->isStopping_2()) {
3361 track->mState = TrackBase::STOPPED;
3362 }
3363 if (track->isStopped()) {
3364 // Can't reset directly, as fast mixer is still polling this track
3365 // track->reset();
3366 // So instead mark this track as needing to be reset after push with ack
3367 resetMask |= 1 << i;
3368 }
3369 isActive = false;
3370 break;
3371 case TrackBase::IDLE:
3372 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003373 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003374 }
3375
3376 if (isActive) {
3377 // was it previously inactive?
3378 if (!(state->mTrackMask & (1 << j))) {
3379 ExtendedAudioBufferProvider *eabp = track;
3380 VolumeProvider *vp = track;
3381 fastTrack->mBufferProvider = eabp;
3382 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003383 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003384 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003385 fastTrack->mGeneration++;
3386 state->mTrackMask |= 1 << j;
3387 didModify = true;
3388 // no acknowledgement required for newly active tracks
3389 }
3390 // cache the combined master volume and stream type volume for fast mixer; this
3391 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003392 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003393 ++fastTracks;
3394 } else {
3395 // was it previously active?
3396 if (state->mTrackMask & (1 << j)) {
3397 fastTrack->mBufferProvider = NULL;
3398 fastTrack->mGeneration++;
3399 state->mTrackMask &= ~(1 << j);
3400 didModify = true;
3401 // If any fast tracks were removed, we must wait for acknowledgement
3402 // because we're about to decrement the last sp<> on those tracks.
3403 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3404 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003405 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003406 }
3407 tracksToRemove->add(track);
3408 // Avoids a misleading display in dumpsys
3409 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3410 }
3411 continue;
3412 }
3413
3414 { // local variable scope to avoid goto warning
3415
3416 audio_track_cblk_t* cblk = track->cblk();
3417
3418 // The first time a track is added we wait
3419 // for all its buffers to be filled before processing it
3420 int name = track->name();
3421 // make sure that we have enough frames to mix one full buffer.
3422 // enforce this condition only once to enable draining the buffer in case the client
3423 // app does not call stop() and relies on underrun to stop:
3424 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3425 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003426 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003427 uint32_t sr = track->sampleRate();
3428 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003429 desiredFrames = mNormalFrameCount;
3430 } else {
3431 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003432 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003433 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003434 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003435 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003436#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003437 // the minimum track buffer size is normally twice the number of frames necessary
3438 // to fill one buffer and the resampler should not leave more than one buffer worth
3439 // of unreleased frames after each pass, but just in case...
3440 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003441#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003442 }
Eric Laurent81784c32012-11-19 14:55:58 -08003443 uint32_t minFrames = 1;
3444 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3445 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003446 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003447 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003448
3449 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003450 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003451 !track->isPaused() && !track->isTerminated())
3452 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003453 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003454
3455 mixedTracks++;
3456
Andy Hung69aed5f2014-02-25 17:24:40 -08003457 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3458 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003459 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003460 if (track->mainBuffer() != mSinkBuffer &&
3461 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003462 if (mEffectBufferEnabled) {
3463 mEffectBufferValid = true; // Later can set directly.
3464 }
Eric Laurent81784c32012-11-19 14:55:58 -08003465 chain = getEffectChain_l(track->sessionId());
3466 // Delegate volume control to effect in track effect chain if needed
3467 if (chain != 0) {
3468 tracksWithEffect++;
3469 } else {
3470 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3471 "session %d",
3472 name, track->sessionId());
3473 }
3474 }
3475
3476
3477 int param = AudioMixer::VOLUME;
3478 if (track->mFillingUpStatus == Track::FS_FILLED) {
3479 // no ramp for the first volume setting
3480 track->mFillingUpStatus = Track::FS_ACTIVE;
3481 if (track->mState == TrackBase::RESUMING) {
3482 track->mState = TrackBase::ACTIVE;
3483 param = AudioMixer::RAMP_VOLUME;
3484 }
3485 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003486 // FIXME should not make a decision based on mServer
3487 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // If the track is stopped before the first frame was mixed,
3489 // do not apply ramp
3490 param = AudioMixer::RAMP_VOLUME;
3491 }
3492
3493 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003494 uint32_t vl, vr; // in U8.24 integer format
3495 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003496 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003497 vl = vr = 0;
3498 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003499 if (track->isPausing()) {
3500 track->setPaused();
3501 }
3502 } else {
3503
3504 // read original volumes with volume control
3505 float typeVolume = mStreamTypes[track->streamType()].volume;
3506 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003507 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003508 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003509 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3510 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003511 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003512 if (vlf > GAIN_FLOAT_UNITY) {
3513 ALOGV("Track left volume out of range: %.3g", vlf);
3514 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003515 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003516 if (vrf > GAIN_FLOAT_UNITY) {
3517 ALOGV("Track right volume out of range: %.3g", vrf);
3518 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003519 }
3520 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003521 vlf *= v;
3522 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003523 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003524 // then derive vl and vr as U8.24 versions for the effect chain
3525 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3526 vl = (uint32_t) (scaleto8_24 * vlf);
3527 vr = (uint32_t) (scaleto8_24 * vrf);
3528 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003529 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003530 // send level comes from shared memory and so may be corrupt
3531 if (sendLevel > MAX_GAIN_INT) {
3532 ALOGV("Track send level out of range: %04X", sendLevel);
3533 sendLevel = MAX_GAIN_INT;
3534 }
Andy Hung6be49402014-05-30 10:42:03 -07003535 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3536 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538
Eric Laurent81784c32012-11-19 14:55:58 -08003539 // Delegate volume control to effect in track effect chain if needed
3540 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3541 // Do not ramp volume if volume is controlled by effect
3542 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003543 // Update remaining floating point volume levels
3544 vlf = (float)vl / (1 << 24);
3545 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003546 track->mHasVolumeController = true;
3547 } else {
3548 // force no volume ramp when volume controller was just disabled or removed
3549 // from effect chain to avoid volume spike
3550 if (track->mHasVolumeController) {
3551 param = AudioMixer::VOLUME;
3552 }
3553 track->mHasVolumeController = false;
3554 }
3555
Eric Laurent81784c32012-11-19 14:55:58 -08003556 // XXX: these things DON'T need to be done each time
3557 mAudioMixer->setBufferProvider(name, track);
3558 mAudioMixer->enable(name);
3559
Andy Hung6be49402014-05-30 10:42:03 -07003560 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3561 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3562 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003563 mAudioMixer->setParameter(
3564 name,
3565 AudioMixer::TRACK,
3566 AudioMixer::FORMAT, (void *)track->format());
3567 mAudioMixer->setParameter(
3568 name,
3569 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003570 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003571 mAudioMixer->setParameter(
3572 name,
3573 AudioMixer::TRACK,
3574 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003575 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003576 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003577 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003578 if (reqSampleRate == 0) {
3579 reqSampleRate = mSampleRate;
3580 } else if (reqSampleRate > maxSampleRate) {
3581 reqSampleRate = maxSampleRate;
3582 }
Eric Laurent81784c32012-11-19 14:55:58 -08003583 mAudioMixer->setParameter(
3584 name,
3585 AudioMixer::RESAMPLE,
3586 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003587 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003588 /*
3589 * Select the appropriate output buffer for the track.
3590 *
Andy Hung98ef9782014-03-04 14:46:50 -08003591 * Tracks with effects go into their own effects chain buffer
3592 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003593 *
3594 * Other tracks can use mMixerBuffer for higher precision
3595 * channel accumulation. If this buffer is enabled
3596 * (mMixerBufferEnabled true), then selected tracks will accumulate
3597 * into it.
3598 *
3599 */
3600 if (mMixerBufferEnabled
3601 && (track->mainBuffer() == mSinkBuffer
3602 || track->mainBuffer() == mMixerBuffer)) {
3603 mAudioMixer->setParameter(
3604 name,
3605 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003606 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003607 mAudioMixer->setParameter(
3608 name,
3609 AudioMixer::TRACK,
3610 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3611 // TODO: override track->mainBuffer()?
3612 mMixerBufferValid = true;
3613 } else {
3614 mAudioMixer->setParameter(
3615 name,
3616 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003617 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003618 mAudioMixer->setParameter(
3619 name,
3620 AudioMixer::TRACK,
3621 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3622 }
Eric Laurent81784c32012-11-19 14:55:58 -08003623 mAudioMixer->setParameter(
3624 name,
3625 AudioMixer::TRACK,
3626 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3627
3628 // reset retry count
3629 track->mRetryCount = kMaxTrackRetries;
3630
3631 // If one track is ready, set the mixer ready if:
3632 // - the mixer was not ready during previous round OR
3633 // - no other track is not ready
3634 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3635 mixerStatus != MIXER_TRACKS_ENABLED) {
3636 mixerStatus = MIXER_TRACKS_READY;
3637 }
3638 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003639 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003640 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003641 }
Eric Laurent81784c32012-11-19 14:55:58 -08003642 // clear effect chain input buffer if an active track underruns to avoid sending
3643 // previous audio buffer again to effects
3644 chain = getEffectChain_l(track->sessionId());
3645 if (chain != 0) {
3646 chain->clearInputBuffer();
3647 }
3648
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003649 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003650 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3651 track->isStopped() || track->isPaused()) {
3652 // We have consumed all the buffers of this track.
3653 // Remove it from the list of active tracks.
3654 // TODO: use actual buffer filling status instead of latency when available from
3655 // audio HAL
3656 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3657 size_t framesWritten = mBytesWritten / mFrameSize;
3658 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3659 if (track->isStopped()) {
3660 track->reset();
3661 }
3662 tracksToRemove->add(track);
3663 }
3664 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003665 // No buffers for this track. Give it a few chances to
3666 // fill a buffer, then remove it from active list.
3667 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003668 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003669 tracksToRemove->add(track);
3670 // indicate to client process that the track was disabled because of underrun;
3671 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003672 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003673 // If one track is not ready, mark the mixer also not ready if:
3674 // - the mixer was ready during previous round OR
3675 // - no other track is ready
3676 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3677 mixerStatus != MIXER_TRACKS_READY) {
3678 mixerStatus = MIXER_TRACKS_ENABLED;
3679 }
3680 }
3681 mAudioMixer->disable(name);
3682 }
3683
3684 } // local variable scope to avoid goto warning
3685track_is_ready: ;
3686
3687 }
3688
3689 // Push the new FastMixer state if necessary
3690 bool pauseAudioWatchdog = false;
3691 if (didModify) {
3692 state->mFastTracksGen++;
3693 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3694 if (kUseFastMixer == FastMixer_Dynamic &&
3695 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3696 state->mCommand = FastMixerState::COLD_IDLE;
3697 state->mColdFutexAddr = &mFastMixerFutex;
3698 state->mColdGen++;
3699 mFastMixerFutex = 0;
3700 if (kUseFastMixer == FastMixer_Dynamic) {
3701 mNormalSink = mOutputSink;
3702 }
3703 // If we go into cold idle, need to wait for acknowledgement
3704 // so that fast mixer stops doing I/O.
3705 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3706 pauseAudioWatchdog = true;
3707 }
Eric Laurent81784c32012-11-19 14:55:58 -08003708 }
3709 if (sq != NULL) {
3710 sq->end(didModify);
3711 sq->push(block);
3712 }
3713#ifdef AUDIO_WATCHDOG
3714 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3715 mAudioWatchdog->pause();
3716 }
3717#endif
3718
3719 // Now perform the deferred reset on fast tracks that have stopped
3720 while (resetMask != 0) {
3721 size_t i = __builtin_ctz(resetMask);
3722 ALOG_ASSERT(i < count);
3723 resetMask &= ~(1 << i);
3724 sp<Track> t = mActiveTracks[i].promote();
3725 if (t == 0) {
3726 continue;
3727 }
3728 Track* track = t.get();
3729 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3730 track->reset();
3731 }
3732
3733 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003734 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003735
Eric Laurent97d547d2014-09-02 14:45:53 -07003736 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3737 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003738 }
3739
3740 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003741 // as long as there are effects we should clear the effects buffer, to avoid
3742 // passing a non-clean buffer to the effect chain
3743 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003744 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003745 // sink or mix buffer must be cleared if all tracks are connected to an
3746 // effect chain as in this case the mixer will not write to the sink or mix buffer
3747 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003748 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3749 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003750 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003751 if (mMixerBufferValid) {
3752 memset(mMixerBuffer, 0, mMixerBufferSize);
3753 // TODO: In testing, mSinkBuffer below need not be cleared because
3754 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3755 // after mixing.
3756 //
3757 // To enforce this guarantee:
3758 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3759 // (mixedTracks == 0 && fastTracks > 0))
3760 // must imply MIXER_TRACKS_READY.
3761 // Later, we may clear buffers regardless, and skip much of this logic.
3762 }
Andy Hung98ef9782014-03-04 14:46:50 -08003763 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003764 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
3766
3767 // if any fast tracks, then status is ready
3768 mMixerStatusIgnoringFastTracks = mixerStatus;
3769 if (fastTracks > 0) {
3770 mixerStatus = MIXER_TRACKS_READY;
3771 }
3772 return mixerStatus;
3773}
3774
3775// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003776int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3777 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003778{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003779 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003780}
3781
3782// deleteTrackName_l() must be called with ThreadBase::mLock held
3783void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3784{
3785 ALOGV("remove track (%d) and delete from mixer", name);
3786 mAudioMixer->deleteTrackName(name);
3787}
3788
Eric Laurent10351942014-05-08 18:49:52 -07003789// checkForNewParameter_l() must be called with ThreadBase::mLock held
3790bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3791 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003792{
Eric Laurent81784c32012-11-19 14:55:58 -08003793 bool reconfig = false;
3794
Eric Laurent10351942014-05-08 18:49:52 -07003795 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003796
Eric Laurent10351942014-05-08 18:49:52 -07003797 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3798 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003799 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003800 FastMixerStateQueue *sq = mFastMixer->sq();
3801 FastMixerState *state = sq->begin();
3802 if (!(state->mCommand & FastMixerState::IDLE)) {
3803 previousCommand = state->mCommand;
3804 state->mCommand = FastMixerState::HOT_IDLE;
3805 sq->end();
3806 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3807 } else {
3808 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003809 }
Eric Laurent10351942014-05-08 18:49:52 -07003810 }
Eric Laurent81784c32012-11-19 14:55:58 -08003811
Eric Laurent10351942014-05-08 18:49:52 -07003812 AudioParameter param = AudioParameter(keyValuePair);
3813 int value;
3814 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3815 reconfig = true;
3816 }
3817 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003818 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003819 status = BAD_VALUE;
3820 } else {
3821 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003822 reconfig = true;
3823 }
Eric Laurent10351942014-05-08 18:49:52 -07003824 }
3825 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003826 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003827 status = BAD_VALUE;
3828 } else {
3829 // no need to save value, since it's constant
3830 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003831 }
Eric Laurent10351942014-05-08 18:49:52 -07003832 }
3833 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3834 // do not accept frame count changes if tracks are open as the track buffer
3835 // size depends on frame count and correct behavior would not be guaranteed
3836 // if frame count is changed after track creation
3837 if (!mTracks.isEmpty()) {
3838 status = INVALID_OPERATION;
3839 } else {
3840 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003841 }
Eric Laurent10351942014-05-08 18:49:52 -07003842 }
3843 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003844#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003845 // when changing the audio output device, call addBatteryData to notify
3846 // the change
3847 if (mOutDevice != value) {
3848 uint32_t params = 0;
3849 // check whether speaker is on
3850 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3851 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 }
Eric Laurent10351942014-05-08 18:49:52 -07003853
3854 audio_devices_t deviceWithoutSpeaker
3855 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3856 // check if any other device (except speaker) is on
3857 if (value & deviceWithoutSpeaker ) {
3858 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3859 }
3860
3861 if (params != 0) {
3862 addBatteryData(params);
3863 }
3864 }
Eric Laurent81784c32012-11-19 14:55:58 -08003865#endif
3866
Eric Laurent10351942014-05-08 18:49:52 -07003867 // forward device change to effects that have requested to be
3868 // aware of attached audio device.
3869 if (value != AUDIO_DEVICE_NONE) {
3870 mOutDevice = value;
3871 for (size_t i = 0; i < mEffectChains.size(); i++) {
3872 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003873 }
3874 }
Eric Laurent10351942014-05-08 18:49:52 -07003875 }
Eric Laurent81784c32012-11-19 14:55:58 -08003876
Eric Laurent10351942014-05-08 18:49:52 -07003877 if (status == NO_ERROR) {
3878 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3879 keyValuePair.string());
3880 if (!mStandby && status == INVALID_OPERATION) {
3881 mOutput->stream->common.standby(&mOutput->stream->common);
3882 mStandby = true;
3883 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003884 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003885 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003886 }
Eric Laurent10351942014-05-08 18:49:52 -07003887 if (status == NO_ERROR && reconfig) {
3888 readOutputParameters_l();
3889 delete mAudioMixer;
3890 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3891 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003892 int name = getTrackName_l(mTracks[i]->mChannelMask,
3893 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003894 if (name < 0) {
3895 break;
3896 }
3897 mTracks[i]->mName = name;
3898 }
3899 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3900 }
Eric Laurent81784c32012-11-19 14:55:58 -08003901 }
3902
3903 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003904 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003905 FastMixerStateQueue *sq = mFastMixer->sq();
3906 FastMixerState *state = sq->begin();
3907 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3908 state->mCommand = previousCommand;
3909 sq->end();
3910 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3911 }
3912
3913 return reconfig;
3914}
3915
3916
3917void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3918{
3919 const size_t SIZE = 256;
3920 char buffer[SIZE];
3921 String8 result;
3922
3923 PlaybackThread::dumpInternals(fd, args);
3924
Elliott Hughes87cebad2014-05-22 10:14:43 -07003925 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003926
3927 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003928 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003929 copy.dump(fd);
3930
3931#ifdef STATE_QUEUE_DUMP
3932 // Similar for state queue
3933 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3934 observerCopy.dump(fd);
3935 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3936 mutatorCopy.dump(fd);
3937#endif
3938
Glenn Kasten46909e72013-02-26 09:20:22 -08003939#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003940 // Write the tee output to a .wav file
3941 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003942#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003943
3944#ifdef AUDIO_WATCHDOG
3945 if (mAudioWatchdog != 0) {
3946 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3947 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3948 wdCopy.dump(fd);
3949 }
3950#endif
3951}
3952
3953uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3954{
3955 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3956}
3957
3958uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3959{
3960 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3961}
3962
3963void AudioFlinger::MixerThread::cacheParameters_l()
3964{
3965 PlaybackThread::cacheParameters_l();
3966
3967 // FIXME: Relaxed timing because of a certain device that can't meet latency
3968 // Should be reduced to 2x after the vendor fixes the driver issue
3969 // increase threshold again due to low power audio mode. The way this warning
3970 // threshold is calculated and its usefulness should be reconsidered anyway.
3971 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3972}
3973
3974// ----------------------------------------------------------------------------
3975
3976AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3977 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3978 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3979 // mLeftVolFloat, mRightVolFloat
3980{
3981}
3982
Eric Laurentbfb1b832013-01-07 09:53:42 -08003983AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3984 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3985 ThreadBase::type_t type)
3986 : PlaybackThread(audioFlinger, output, id, device, type)
3987 // mLeftVolFloat, mRightVolFloat
3988{
3989}
3990
Eric Laurent81784c32012-11-19 14:55:58 -08003991AudioFlinger::DirectOutputThread::~DirectOutputThread()
3992{
3993}
3994
Eric Laurentbfb1b832013-01-07 09:53:42 -08003995void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3996{
3997 audio_track_cblk_t* cblk = track->cblk();
3998 float left, right;
3999
4000 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4001 left = right = 0;
4002 } else {
4003 float typeVolume = mStreamTypes[track->streamType()].volume;
4004 float v = mMasterVolume * typeVolume;
4005 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004006 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4007 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4008 if (left > GAIN_FLOAT_UNITY) {
4009 left = GAIN_FLOAT_UNITY;
4010 }
4011 left *= v;
4012 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4013 if (right > GAIN_FLOAT_UNITY) {
4014 right = GAIN_FLOAT_UNITY;
4015 }
4016 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004017 }
4018
4019 if (lastTrack) {
4020 if (left != mLeftVolFloat || right != mRightVolFloat) {
4021 mLeftVolFloat = left;
4022 mRightVolFloat = right;
4023
4024 // Convert volumes from float to 8.24
4025 uint32_t vl = (uint32_t)(left * (1 << 24));
4026 uint32_t vr = (uint32_t)(right * (1 << 24));
4027
4028 // Delegate volume control to effect in track effect chain if needed
4029 // only one effect chain can be present on DirectOutputThread, so if
4030 // there is one, the track is connected to it
4031 if (!mEffectChains.isEmpty()) {
4032 mEffectChains[0]->setVolume_l(&vl, &vr);
4033 left = (float)vl / (1 << 24);
4034 right = (float)vr / (1 << 24);
4035 }
4036 if (mOutput->stream->set_volume) {
4037 mOutput->stream->set_volume(mOutput->stream, left, right);
4038 }
4039 }
4040 }
4041}
4042
4043
Eric Laurent81784c32012-11-19 14:55:58 -08004044AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4045 Vector< sp<Track> > *tracksToRemove
4046)
4047{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004048 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004049 mixer_state mixerStatus = MIXER_IDLE;
4050
4051 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004052 for (size_t i = 0; i < count; i++) {
4053 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004054 // The track died recently
4055 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004056 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058
4059 Track* const track = t.get();
4060 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004061 // Only consider last track started for volume and mixer state control.
4062 // In theory an older track could underrun and restart after the new one starts
4063 // but as we only care about the transition phase between two tracks on a
4064 // direct output, it is not a problem to ignore the underrun case.
4065 sp<Track> l = mLatestActiveTrack.promote();
4066 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004067
4068 // The first time a track is added we wait
4069 // for all its buffers to be filled before processing it
4070 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07004071 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004072 minFrames = mNormalFrameCount;
4073 } else {
4074 minFrames = 1;
4075 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004076
Eric Laurentab5cdba2014-06-09 17:22:27 -07004077 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4078 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004079 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004080 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004081
4082 if (track->mFillingUpStatus == Track::FS_FILLED) {
4083 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004084 // make sure processVolume_l() will apply new volume even if 0
4085 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004086 if (track->mState == TrackBase::RESUMING) {
4087 track->mState = TrackBase::ACTIVE;
4088 }
4089 }
4090
4091 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004092 processVolume_l(track, last);
4093 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004094 // reset retry count
4095 track->mRetryCount = kMaxTrackRetriesDirect;
4096 mActiveTrack = t;
4097 mixerStatus = MIXER_TRACKS_READY;
4098 }
Eric Laurent81784c32012-11-19 14:55:58 -08004099 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004100 // clear effect chain input buffer if the last active track started underruns
4101 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004102 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004103 mEffectChains[0]->clearInputBuffer();
4104 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004105 if (track->isStopping_1()) {
4106 track->mState = TrackBase::STOPPING_2;
4107 }
4108 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4109 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // We have consumed all the buffers of this track.
4111 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004112 size_t audioHALFrames;
4113 if (audio_is_linear_pcm(mFormat)) {
4114 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4115 } else {
4116 audioHALFrames = 0;
4117 }
4118
Eric Laurent81784c32012-11-19 14:55:58 -08004119 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004120 if (mStandby || !last ||
4121 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004122 if (track->isStopping_2()) {
4123 track->mState = TrackBase::STOPPED;
4124 }
Eric Laurent81784c32012-11-19 14:55:58 -08004125 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004126 if (track->mState == TrackBase::FLUSHED) {
4127 flushHw_l();
4128 }
Eric Laurent81784c32012-11-19 14:55:58 -08004129 track->reset();
4130 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004131 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004132 }
4133 } else {
4134 // No buffers for this track. Give it a few chances to
4135 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004136 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004137 if (--(track->mRetryCount) <= 0) {
4138 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004139 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004140 // indicate to client process that the track was disabled because of underrun;
4141 // it will then automatically call start() when data is available
4142 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004143 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004144 mixerStatus = MIXER_TRACKS_ENABLED;
4145 }
4146 }
4147 }
4148 }
4149
Eric Laurent81784c32012-11-19 14:55:58 -08004150 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004152
4153 return mixerStatus;
4154}
4155
4156void AudioFlinger::DirectOutputThread::threadLoop_mix()
4157{
Eric Laurent81784c32012-11-19 14:55:58 -08004158 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004159 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004160 // output audio to hardware
4161 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004162 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 buffer.frameCount = frameCount;
4164 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004165 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004166 memset(curBuf, 0, frameCount * mFrameSize);
4167 break;
4168 }
4169 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4170 frameCount -= buffer.frameCount;
4171 curBuf += buffer.frameCount * mFrameSize;
4172 mActiveTrack->releaseBuffer(&buffer);
4173 }
Andy Hung2098f272014-02-27 14:00:06 -08004174 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004175 sleepTime = 0;
4176 standbyTime = systemTime() + standbyDelay;
4177 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004178}
4179
4180void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4181{
4182 if (sleepTime == 0) {
4183 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4184 sleepTime = activeSleepTime;
4185 } else {
4186 sleepTime = idleSleepTime;
4187 }
4188 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004189 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004190 sleepTime = 0;
4191 }
4192}
4193
4194// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004195int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004196 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004197{
4198 return 0;
4199}
4200
4201// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004202void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004203{
4204}
4205
Eric Laurent10351942014-05-08 18:49:52 -07004206// checkForNewParameter_l() must be called with ThreadBase::mLock held
4207bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4208 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004209{
4210 bool reconfig = false;
4211
Eric Laurent10351942014-05-08 18:49:52 -07004212 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004213
Eric Laurent10351942014-05-08 18:49:52 -07004214 AudioParameter param = AudioParameter(keyValuePair);
4215 int value;
4216 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4217 // forward device change to effects that have requested to be
4218 // aware of attached audio device.
4219 if (value != AUDIO_DEVICE_NONE) {
4220 mOutDevice = value;
4221 for (size_t i = 0; i < mEffectChains.size(); i++) {
4222 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004223 }
4224 }
Eric Laurent81784c32012-11-19 14:55:58 -08004225 }
Eric Laurent10351942014-05-08 18:49:52 -07004226 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4227 // do not accept frame count changes if tracks are open as the track buffer
4228 // size depends on frame count and correct behavior would not be garantied
4229 // if frame count is changed after track creation
4230 if (!mTracks.isEmpty()) {
4231 status = INVALID_OPERATION;
4232 } else {
4233 reconfig = true;
4234 }
4235 }
4236 if (status == NO_ERROR) {
4237 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4238 keyValuePair.string());
4239 if (!mStandby && status == INVALID_OPERATION) {
4240 mOutput->stream->common.standby(&mOutput->stream->common);
4241 mStandby = true;
4242 mBytesWritten = 0;
4243 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4244 keyValuePair.string());
4245 }
4246 if (status == NO_ERROR && reconfig) {
4247 readOutputParameters_l();
4248 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4249 }
4250 }
4251
Eric Laurent81784c32012-11-19 14:55:58 -08004252 return reconfig;
4253}
4254
4255uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4256{
4257 uint32_t time;
4258 if (audio_is_linear_pcm(mFormat)) {
4259 time = PlaybackThread::activeSleepTimeUs();
4260 } else {
4261 time = 10000;
4262 }
4263 return time;
4264}
4265
4266uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4267{
4268 uint32_t time;
4269 if (audio_is_linear_pcm(mFormat)) {
4270 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4271 } else {
4272 time = 10000;
4273 }
4274 return time;
4275}
4276
4277uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4278{
4279 uint32_t time;
4280 if (audio_is_linear_pcm(mFormat)) {
4281 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4282 } else {
4283 time = 10000;
4284 }
4285 return time;
4286}
4287
4288void AudioFlinger::DirectOutputThread::cacheParameters_l()
4289{
4290 PlaybackThread::cacheParameters_l();
4291
4292 // use shorter standby delay as on normal output to release
4293 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004294 if (audio_is_linear_pcm(mFormat)) {
4295 standbyDelay = microseconds(activeSleepTime*2);
4296 } else {
4297 standbyDelay = kOffloadStandbyDelayNs;
4298 }
Eric Laurent81784c32012-11-19 14:55:58 -08004299}
4300
Eric Laurente659ef42014-09-29 13:06:46 -07004301void AudioFlinger::DirectOutputThread::flushHw_l()
4302{
4303 if (mOutput->stream->flush != NULL)
4304 mOutput->stream->flush(mOutput->stream);
4305}
4306
Eric Laurent81784c32012-11-19 14:55:58 -08004307// ----------------------------------------------------------------------------
4308
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004310 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004311 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004312 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004313 mWriteAckSequence(0),
4314 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315{
4316}
4317
4318AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4319{
4320}
4321
4322void AudioFlinger::AsyncCallbackThread::onFirstRef()
4323{
4324 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4325}
4326
4327bool AudioFlinger::AsyncCallbackThread::threadLoop()
4328{
4329 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004330 uint32_t writeAckSequence;
4331 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332
4333 {
4334 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004335 while (!((mWriteAckSequence & 1) ||
4336 (mDrainSequence & 1) ||
4337 exitPending())) {
4338 mWaitWorkCV.wait(mLock);
4339 }
4340
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 if (exitPending()) {
4342 break;
4343 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004344 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4345 mWriteAckSequence, mDrainSequence);
4346 writeAckSequence = mWriteAckSequence;
4347 mWriteAckSequence &= ~1;
4348 drainSequence = mDrainSequence;
4349 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350 }
4351 {
Eric Laurent4de95592013-09-26 15:28:21 -07004352 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4353 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004354 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004355 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004357 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004358 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004359 }
4360 }
4361 }
4362 }
4363 return false;
4364}
4365
4366void AudioFlinger::AsyncCallbackThread::exit()
4367{
4368 ALOGV("AsyncCallbackThread::exit");
4369 Mutex::Autolock _l(mLock);
4370 requestExit();
4371 mWaitWorkCV.broadcast();
4372}
4373
Eric Laurent3b4529e2013-09-05 18:09:19 -07004374void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375{
4376 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004377 // bit 0 is cleared
4378 mWriteAckSequence = sequence << 1;
4379}
4380
4381void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4382{
4383 Mutex::Autolock _l(mLock);
4384 // ignore unexpected callbacks
4385 if (mWriteAckSequence & 2) {
4386 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 mWaitWorkCV.signal();
4388 }
4389}
4390
Eric Laurent3b4529e2013-09-05 18:09:19 -07004391void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392{
4393 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004394 // bit 0 is cleared
4395 mDrainSequence = sequence << 1;
4396}
4397
4398void AudioFlinger::AsyncCallbackThread::resetDraining()
4399{
4400 Mutex::Autolock _l(mLock);
4401 // ignore unexpected callbacks
4402 if (mDrainSequence & 2) {
4403 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 mWaitWorkCV.signal();
4405 }
4406}
4407
4408
4409// ----------------------------------------------------------------------------
4410AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4411 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4412 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4413 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004414 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004415 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004416{
Eric Laurentfd477972013-10-25 18:10:40 -07004417 //FIXME: mStandby should be set to true by ThreadBase constructor
4418 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004419}
4420
Eric Laurentbfb1b832013-01-07 09:53:42 -08004421void AudioFlinger::OffloadThread::threadLoop_exit()
4422{
4423 if (mFlushPending || mHwPaused) {
4424 // If a flush is pending or track was paused, just discard buffered data
4425 flushHw_l();
4426 } else {
4427 mMixerStatus = MIXER_DRAIN_ALL;
4428 threadLoop_drain();
4429 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004430 if (mUseAsyncWrite) {
4431 ALOG_ASSERT(mCallbackThread != 0);
4432 mCallbackThread->exit();
4433 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004434 PlaybackThread::threadLoop_exit();
4435}
4436
4437AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4438 Vector< sp<Track> > *tracksToRemove
4439)
4440{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004441 size_t count = mActiveTracks.size();
4442
4443 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004444 bool doHwPause = false;
4445 bool doHwResume = false;
4446
Eric Laurentede6c3b2013-09-19 14:37:46 -07004447 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4448
Eric Laurentbfb1b832013-01-07 09:53:42 -08004449 // find out which tracks need to be processed
4450 for (size_t i = 0; i < count; i++) {
4451 sp<Track> t = mActiveTracks[i].promote();
4452 // The track died recently
4453 if (t == 0) {
4454 continue;
4455 }
4456 Track* const track = t.get();
4457 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004458 // Only consider last track started for volume and mixer state control.
4459 // In theory an older track could underrun and restart after the new one starts
4460 // but as we only care about the transition phase between two tracks on a
4461 // direct output, it is not a problem to ignore the underrun case.
4462 sp<Track> l = mLatestActiveTrack.promote();
4463 bool last = l.get() == track;
4464
Haynes Mathew George7844f672014-01-15 12:32:55 -08004465 if (track->isInvalid()) {
4466 ALOGW("An invalidated track shouldn't be in active list");
4467 tracksToRemove->add(track);
4468 continue;
4469 }
4470
4471 if (track->mState == TrackBase::IDLE) {
4472 ALOGW("An idle track shouldn't be in active list");
4473 continue;
4474 }
4475
Eric Laurentbfb1b832013-01-07 09:53:42 -08004476 if (track->isPausing()) {
4477 track->setPaused();
4478 if (last) {
4479 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004480 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 mHwPaused = true;
4482 }
4483 // If we were part way through writing the mixbuffer to
4484 // the HAL we must save this until we resume
4485 // BUG - this will be wrong if a different track is made active,
4486 // in that case we want to discard the pending data in the
4487 // mixbuffer and tell the client to present it again when the
4488 // track is resumed
4489 mPausedWriteLength = mCurrentWriteLength;
4490 mPausedBytesRemaining = mBytesRemaining;
4491 mBytesRemaining = 0; // stop writing
4492 }
4493 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004494 } else if (track->isFlushPending()) {
4495 track->flushAck();
4496 if (last) {
4497 mFlushPending = true;
4498 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004499 } else if (track->isResumePending()){
4500 track->resumeAck();
4501 if (last) {
4502 if (mPausedBytesRemaining) {
4503 // Need to continue write that was interrupted
4504 mCurrentWriteLength = mPausedWriteLength;
4505 mBytesRemaining = mPausedBytesRemaining;
4506 mPausedBytesRemaining = 0;
4507 }
4508 if (mHwPaused) {
4509 doHwResume = true;
4510 mHwPaused = false;
4511 // threadLoop_mix() will handle the case that we need to
4512 // resume an interrupted write
4513 }
4514 // enable write to audio HAL
4515 sleepTime = 0;
4516
4517 // Do not handle new data in this iteration even if track->framesReady()
4518 mixerStatus = MIXER_TRACKS_ENABLED;
4519 }
4520 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004521 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004522 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523 if (track->mFillingUpStatus == Track::FS_FILLED) {
4524 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004525 // make sure processVolume_l() will apply new volume even if 0
4526 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 }
4528
4529 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004530 sp<Track> previousTrack = mPreviousTrack.promote();
4531 if (previousTrack != 0) {
4532 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004533 // Flush any data still being written from last track
4534 mBytesRemaining = 0;
4535 if (mPausedBytesRemaining) {
4536 // Last track was paused so we also need to flush saved
4537 // mixbuffer state and invalidate track so that it will
4538 // re-submit that unwritten data when it is next resumed
4539 mPausedBytesRemaining = 0;
4540 // Invalidate is a bit drastic - would be more efficient
4541 // to have a flag to tell client that some of the
4542 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004543 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004544 }
4545 // flush data already sent to the DSP if changing audio session as audio
4546 // comes from a different source. Also invalidate previous track to force a
4547 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004548 if (previousTrack->sessionId() != track->sessionId()) {
4549 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004550 }
4551 }
4552 }
4553 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004554 // reset retry count
4555 track->mRetryCount = kMaxTrackRetriesOffload;
4556 mActiveTrack = t;
4557 mixerStatus = MIXER_TRACKS_READY;
4558 }
4559 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004560 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 if (track->isStopping_1()) {
4562 // Hardware buffer can hold a large amount of audio so we must
4563 // wait for all current track's data to drain before we say
4564 // that the track is stopped.
4565 if (mBytesRemaining == 0) {
4566 // Only start draining when all data in mixbuffer
4567 // has been written
4568 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4569 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004570 // do not drain if no data was ever sent to HAL (mStandby == true)
4571 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004572 // do not modify drain sequence if we are already draining. This happens
4573 // when resuming from pause after drain.
4574 if ((mDrainSequence & 1) == 0) {
4575 sleepTime = 0;
4576 standbyTime = systemTime() + standbyDelay;
4577 mixerStatus = MIXER_DRAIN_TRACK;
4578 mDrainSequence += 2;
4579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580 if (mHwPaused) {
4581 // It is possible to move from PAUSED to STOPPING_1 without
4582 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004583 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004584 mHwPaused = false;
4585 }
4586 }
4587 }
4588 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004589 // Drain has completed or we are in standby, signal presentation complete
4590 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004591 track->mState = TrackBase::STOPPED;
4592 size_t audioHALFrames =
4593 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4594 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004595 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 track->presentationComplete(framesWritten, audioHALFrames);
4597 track->reset();
4598 tracksToRemove->add(track);
4599 }
4600 } else {
4601 // No buffers for this track. Give it a few chances to
4602 // fill a buffer, then remove it from active list.
4603 if (--(track->mRetryCount) <= 0) {
4604 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4605 track->name());
4606 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004607 // indicate to client process that the track was disabled because of underrun;
4608 // it will then automatically call start() when data is available
4609 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610 } else if (last){
4611 mixerStatus = MIXER_TRACKS_ENABLED;
4612 }
4613 }
4614 }
4615 // compute volume for this track
4616 processVolume_l(track, last);
4617 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004618
Eric Laurentea0fade2013-10-04 16:23:48 -07004619 // make sure the pause/flush/resume sequence is executed in the right order.
4620 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4621 // before flush and then resume HW. This can happen in case of pause/flush/resume
4622 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004623 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004624 mOutput->stream->pause(mOutput->stream);
4625 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004626 if (mFlushPending) {
4627 flushHw_l();
4628 mFlushPending = false;
4629 }
Eric Laurentfd477972013-10-25 18:10:40 -07004630 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004631 mOutput->stream->resume(mOutput->stream);
4632 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004633
Eric Laurentbfb1b832013-01-07 09:53:42 -08004634 // remove all the tracks that need to be...
4635 removeTracks_l(*tracksToRemove);
4636
4637 return mixerStatus;
4638}
4639
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640// must be called with thread mutex locked
4641bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4642{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004643 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4644 mWriteAckSequence, mDrainSequence);
4645 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646 return true;
4647 }
4648 return false;
4649}
4650
4651// must be called with thread mutex locked
4652bool AudioFlinger::OffloadThread::shouldStandby_l()
4653{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004654 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655
4656 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4657 // after a timeout and we will enter standby then.
4658 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004659 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660 }
4661
Glenn Kastene6f35b12013-08-19 09:58:50 -07004662 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004663}
4664
4665
4666bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4667{
4668 Mutex::Autolock _l(mLock);
4669 return waitingAsyncCallback_l();
4670}
4671
4672void AudioFlinger::OffloadThread::flushHw_l()
4673{
Eric Laurente659ef42014-09-29 13:06:46 -07004674 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004675 // Flush anything still waiting in the mixbuffer
4676 mCurrentWriteLength = 0;
4677 mBytesRemaining = 0;
4678 mPausedWriteLength = 0;
4679 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004680 mHwPaused = false;
4681
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004683 // discard any pending drain or write ack by incrementing sequence
4684 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4685 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004686 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004687 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4688 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004689 }
4690}
4691
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004692void AudioFlinger::OffloadThread::onAddNewTrack_l()
4693{
4694 sp<Track> previousTrack = mPreviousTrack.promote();
4695 sp<Track> latestTrack = mLatestActiveTrack.promote();
4696
4697 if (previousTrack != 0 && latestTrack != 0 &&
4698 (previousTrack->sessionId() != latestTrack->sessionId())) {
4699 mFlushPending = true;
4700 }
4701 PlaybackThread::onAddNewTrack_l();
4702}
4703
Eric Laurentbfb1b832013-01-07 09:53:42 -08004704// ----------------------------------------------------------------------------
4705
Eric Laurent81784c32012-11-19 14:55:58 -08004706AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4707 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4708 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4709 DUPLICATING),
4710 mWaitTimeMs(UINT_MAX)
4711{
4712 addOutputTrack(mainThread);
4713}
4714
4715AudioFlinger::DuplicatingThread::~DuplicatingThread()
4716{
4717 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4718 mOutputTracks[i]->destroy();
4719 }
4720}
4721
4722void AudioFlinger::DuplicatingThread::threadLoop_mix()
4723{
4724 // mix buffers...
4725 if (outputsReady(outputTracks)) {
4726 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4727 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004728 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004729 }
4730 sleepTime = 0;
4731 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004732 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004733 standbyTime = systemTime() + standbyDelay;
4734}
4735
4736void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4737{
4738 if (sleepTime == 0) {
4739 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4740 sleepTime = activeSleepTime;
4741 } else {
4742 sleepTime = idleSleepTime;
4743 }
4744 } else if (mBytesWritten != 0) {
4745 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4746 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004747 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004748 } else {
4749 // flush remaining overflow buffers in output tracks
4750 writeFrames = 0;
4751 }
4752 sleepTime = 0;
4753 }
4754}
4755
Eric Laurentbfb1b832013-01-07 09:53:42 -08004756ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004757{
4758 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004759 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4760 // for delivery downstream as needed. This in-place conversion is safe as
4761 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4762 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4763 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4764 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4765 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4766 }
4767 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004768 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004769 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004770 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004771}
4772
4773void AudioFlinger::DuplicatingThread::threadLoop_standby()
4774{
4775 // DuplicatingThread implements standby by stopping all tracks
4776 for (size_t i = 0; i < outputTracks.size(); i++) {
4777 outputTracks[i]->stop();
4778 }
4779}
4780
4781void AudioFlinger::DuplicatingThread::saveOutputTracks()
4782{
4783 outputTracks = mOutputTracks;
4784}
4785
4786void AudioFlinger::DuplicatingThread::clearOutputTracks()
4787{
4788 outputTracks.clear();
4789}
4790
4791void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4792{
4793 Mutex::Autolock _l(mLock);
4794 // FIXME explain this formula
4795 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004796 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4797 // due to current usage case and restrictions on the AudioBufferProvider.
4798 // Actual buffer conversion is done in threadLoop_write().
4799 //
4800 // TODO: This may change in the future, depending on multichannel
4801 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004802 OutputTrack *outputTrack = new OutputTrack(thread,
4803 this,
4804 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004805 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004806 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004807 frameCount,
4808 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004809 if (outputTrack->cblk() != NULL) {
4810 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4811 mOutputTracks.add(outputTrack);
4812 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4813 updateWaitTime_l();
4814 }
4815}
4816
4817void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4818{
4819 Mutex::Autolock _l(mLock);
4820 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4821 if (mOutputTracks[i]->thread() == thread) {
4822 mOutputTracks[i]->destroy();
4823 mOutputTracks.removeAt(i);
4824 updateWaitTime_l();
4825 return;
4826 }
4827 }
4828 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4829}
4830
4831// caller must hold mLock
4832void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4833{
4834 mWaitTimeMs = UINT_MAX;
4835 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4836 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4837 if (strong != 0) {
4838 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4839 if (waitTimeMs < mWaitTimeMs) {
4840 mWaitTimeMs = waitTimeMs;
4841 }
4842 }
4843 }
4844}
4845
4846
4847bool AudioFlinger::DuplicatingThread::outputsReady(
4848 const SortedVector< sp<OutputTrack> > &outputTracks)
4849{
4850 for (size_t i = 0; i < outputTracks.size(); i++) {
4851 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4852 if (thread == 0) {
4853 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4854 outputTracks[i].get());
4855 return false;
4856 }
4857 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4858 // see note at standby() declaration
4859 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4860 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4861 thread.get());
4862 return false;
4863 }
4864 }
4865 return true;
4866}
4867
4868uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4869{
4870 return (mWaitTimeMs * 1000) / 2;
4871}
4872
4873void AudioFlinger::DuplicatingThread::cacheParameters_l()
4874{
4875 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4876 updateWaitTime_l();
4877
4878 MixerThread::cacheParameters_l();
4879}
4880
4881// ----------------------------------------------------------------------------
4882// Record
4883// ----------------------------------------------------------------------------
4884
4885AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4886 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004887 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004888 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004889 audio_devices_t inDevice
4890#ifdef TEE_SINK
4891 , const sp<NBAIO_Sink>& teeSink
4892#endif
4893 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004894 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004895 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004896 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004897 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004898#ifdef TEE_SINK
4899 , mTeeSink(teeSink)
4900#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004901 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4902 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004903 // mFastCapture below
4904 , mFastCaptureFutex(0)
4905 // mInputSource
4906 // mPipeSink
4907 // mPipeSource
4908 , mPipeFramesP2(0)
4909 // mPipeMemory
4910 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004911 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004912{
4913 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004914 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004915
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004916 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004917
4918 // create an NBAIO source for the HAL input stream, and negotiate
4919 mInputSource = new AudioStreamInSource(input->stream);
4920 size_t numCounterOffers = 0;
4921 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4922 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4923 ALOG_ASSERT(index == 0);
4924
4925 // initialize fast capture depending on configuration
4926 bool initFastCapture;
4927 switch (kUseFastCapture) {
4928 case FastCapture_Never:
4929 initFastCapture = false;
4930 break;
4931 case FastCapture_Always:
4932 initFastCapture = true;
4933 break;
4934 case FastCapture_Static:
4935 uint32_t primaryOutputSampleRate;
4936 {
4937 AutoMutex _l(audioFlinger->mHardwareLock);
4938 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4939 }
4940 initFastCapture =
4941 // either capture sample rate is same as (a reasonable) primary output sample rate
4942 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4943 (mSampleRate == primaryOutputSampleRate)) ||
4944 // or primary output sample rate is unknown, and capture sample rate is reasonable
4945 ((primaryOutputSampleRate == 0) &&
4946 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004947 // and the buffer size is < 12 ms
4948 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004949 break;
4950 // case FastCapture_Dynamic:
4951 }
4952
4953 if (initFastCapture) {
4954 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4955 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004956 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004957 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4958 void *pipeBuffer;
4959 const sp<MemoryDealer> roHeap(readOnlyHeap());
4960 sp<IMemory> pipeMemory;
4961 if ((roHeap == 0) ||
4962 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4963 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4964 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4965 goto failed;
4966 }
4967 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4968 memset(pipeBuffer, 0, pipeSize);
4969 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4970 const NBAIO_Format offers[1] = {format};
4971 size_t numCounterOffers = 0;
4972 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4973 ALOG_ASSERT(index == 0);
4974 mPipeSink = pipe;
4975 PipeReader *pipeReader = new PipeReader(*pipe);
4976 numCounterOffers = 0;
4977 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4978 ALOG_ASSERT(index == 0);
4979 mPipeSource = pipeReader;
4980 mPipeFramesP2 = pipeFramesP2;
4981 mPipeMemory = pipeMemory;
4982
4983 // create fast capture
4984 mFastCapture = new FastCapture();
4985 FastCaptureStateQueue *sq = mFastCapture->sq();
4986#ifdef STATE_QUEUE_DUMP
4987 // FIXME
4988#endif
4989 FastCaptureState *state = sq->begin();
4990 state->mCblk = NULL;
4991 state->mInputSource = mInputSource.get();
4992 state->mInputSourceGen++;
4993 state->mPipeSink = pipe;
4994 state->mPipeSinkGen++;
4995 state->mFrameCount = mFrameCount;
4996 state->mCommand = FastCaptureState::COLD_IDLE;
4997 // already done in constructor initialization list
4998 //mFastCaptureFutex = 0;
4999 state->mColdFutexAddr = &mFastCaptureFutex;
5000 state->mColdGen++;
5001 state->mDumpState = &mFastCaptureDumpState;
5002#ifdef TEE_SINK
5003 // FIXME
5004#endif
5005 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5006 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5007 sq->end();
5008 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5009
5010 // start the fast capture
5011 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5012 pid_t tid = mFastCapture->getTid();
5013 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5014 if (err != 0) {
5015 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5016 kPriorityFastCapture, getpid_cached, tid, err);
5017 }
5018
5019#ifdef AUDIO_WATCHDOG
5020 // FIXME
5021#endif
5022
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005023 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005024 }
5025failed: ;
5026
5027 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005028}
5029
5030
5031AudioFlinger::RecordThread::~RecordThread()
5032{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005033 if (mFastCapture != 0) {
5034 FastCaptureStateQueue *sq = mFastCapture->sq();
5035 FastCaptureState *state = sq->begin();
5036 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5037 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5038 if (old == -1) {
5039 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5040 }
5041 }
5042 state->mCommand = FastCaptureState::EXIT;
5043 sq->end();
5044 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5045 mFastCapture->join();
5046 mFastCapture.clear();
5047 }
5048 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005049 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005050 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005051}
5052
5053void AudioFlinger::RecordThread::onFirstRef()
5054{
5055 run(mName, PRIORITY_URGENT_AUDIO);
5056}
5057
Eric Laurent81784c32012-11-19 14:55:58 -08005058bool AudioFlinger::RecordThread::threadLoop()
5059{
Eric Laurent81784c32012-11-19 14:55:58 -08005060 nsecs_t lastWarning = 0;
5061
5062 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005063
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005064reacquire_wakelock:
5065 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005066 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005067 {
5068 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005069 size_t size = mActiveTracks.size();
5070 activeTracksGen = mActiveTracksGen;
5071 if (size > 0) {
5072 // FIXME an arbitrary choice
5073 activeTrack = mActiveTracks[0];
5074 acquireWakeLock_l(activeTrack->uid());
5075 if (size > 1) {
5076 SortedVector<int> tmp;
5077 for (size_t i = 0; i < size; i++) {
5078 tmp.add(mActiveTracks[i]->uid());
5079 }
5080 updateWakeLockUids_l(tmp);
5081 }
5082 } else {
5083 acquireWakeLock_l(-1);
5084 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005085 }
5086
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005087 // used to request a deferred sleep, to be executed later while mutex is unlocked
5088 uint32_t sleepUs = 0;
5089
5090 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005091 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005092 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005093
Glenn Kasten5edadd42013-08-14 16:30:49 -07005094 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005095 if (sleepUs > 0) {
5096 usleep(sleepUs);
5097 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005098 }
5099
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005100 // activeTracks accumulates a copy of a subset of mActiveTracks
5101 Vector< sp<RecordTrack> > activeTracks;
5102
Glenn Kasten735f45f2014-08-18 15:51:59 -07005103 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005104 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005105
Glenn Kasten735f45f2014-08-18 15:51:59 -07005106 // reference to a fast track which is about to be removed
5107 sp<RecordTrack> fastTrackToRemove;
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109 { // scope for mLock
5110 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005111
Eric Laurent021cf962014-05-13 10:18:14 -07005112 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005113
Eric Laurent000a4192014-01-29 15:17:32 -08005114 // check exitPending here because checkForNewParameters_l() and
5115 // checkForNewParameters_l() can temporarily release mLock
5116 if (exitPending()) {
5117 break;
5118 }
5119
Glenn Kasten2b806402013-11-20 16:37:38 -08005120 // if no active track(s), then standby and release wakelock
5121 size_t size = mActiveTracks.size();
5122 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005123 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005124 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005125 releaseWakeLock_l();
5126 ALOGV("RecordThread: loop stopping");
5127 // go to sleep
5128 mWaitWorkCV.wait(mLock);
5129 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005130 goto reacquire_wakelock;
5131 }
5132
Glenn Kasten2b806402013-11-20 16:37:38 -08005133 if (mActiveTracksGen != activeTracksGen) {
5134 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005135 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005136 for (size_t i = 0; i < size; i++) {
5137 tmp.add(mActiveTracks[i]->uid());
5138 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005139 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005140 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005141
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005142 bool doBroadcast = false;
5143 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005144
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005145 activeTrack = mActiveTracks[i];
5146 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005147 if (activeTrack->isFastTrack()) {
5148 ALOG_ASSERT(fastTrackToRemove == 0);
5149 fastTrackToRemove = activeTrack;
5150 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005151 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005152 mActiveTracks.remove(activeTrack);
5153 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005154 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005155 continue;
5156 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005157
5158 TrackBase::track_state activeTrackState = activeTrack->mState;
5159 switch (activeTrackState) {
5160
5161 case TrackBase::PAUSING:
5162 mActiveTracks.remove(activeTrack);
5163 mActiveTracksGen++;
5164 doBroadcast = true;
5165 size--;
5166 continue;
5167
5168 case TrackBase::STARTING_1:
5169 sleepUs = 10000;
5170 i++;
5171 continue;
5172
5173 case TrackBase::STARTING_2:
5174 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005175 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005176 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005177 break;
5178
5179 case TrackBase::ACTIVE:
5180 break;
5181
5182 case TrackBase::IDLE:
5183 i++;
5184 continue;
5185
5186 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005187 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005188 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005189
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005190 activeTracks.add(activeTrack);
5191 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005192
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005193 if (activeTrack->isFastTrack()) {
5194 ALOG_ASSERT(!mFastTrackAvail);
5195 ALOG_ASSERT(fastTrack == 0);
5196 fastTrack = activeTrack;
5197 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005198 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005199 if (doBroadcast) {
5200 mStartStopCond.broadcast();
5201 }
5202
5203 // sleep if there are no active tracks to process
5204 if (activeTracks.size() == 0) {
5205 if (sleepUs == 0) {
5206 sleepUs = kRecordThreadSleepUs;
5207 }
5208 continue;
5209 }
5210 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005211
Eric Laurent81784c32012-11-19 14:55:58 -08005212 lockEffectChains_l(effectChains);
5213 }
5214
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005215 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005217 size_t size = effectChains.size();
5218 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005219 // thread mutex is not locked, but effect chain is locked
5220 effectChains[i]->process_l();
5221 }
5222
Glenn Kasten735f45f2014-08-18 15:51:59 -07005223 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005224 if (mFastCapture != 0) {
5225 FastCaptureStateQueue *sq = mFastCapture->sq();
5226 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005227 bool didModify = false;
5228 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005229 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5230 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5231 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5232 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5233 if (old == -1) {
5234 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5235 }
5236 }
5237 state->mCommand = FastCaptureState::READ_WRITE;
5238#if 0 // FIXME
5239 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5240 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5241#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005242 didModify = true;
5243 }
5244 audio_track_cblk_t *cblkOld = state->mCblk;
5245 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5246 if (cblkNew != cblkOld) {
5247 state->mCblk = cblkNew;
5248 // block until acked if removing a fast track
5249 if (cblkOld != NULL) {
5250 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5251 }
5252 didModify = true;
5253 }
5254 sq->end(didModify);
5255 if (didModify) {
5256 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005257#if 0
5258 if (kUseFastCapture == FastCapture_Dynamic) {
5259 mNormalSource = mPipeSource;
5260 }
5261#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005262 }
5263 }
5264
Glenn Kasten735f45f2014-08-18 15:51:59 -07005265 // now run the fast track destructor with thread mutex unlocked
5266 fastTrackToRemove.clear();
5267
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005268 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5269 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5270 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5271 // If destination is non-contiguous, first read past the nominal end of buffer, then
5272 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005273
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005274 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005275 ssize_t framesRead;
5276
5277 // If an NBAIO source is present, use it to read the normal capture's data
5278 if (mPipeSource != 0) {
5279 size_t framesToRead = mBufferSize / mFrameSize;
5280 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5281 framesToRead, AudioBufferProvider::kInvalidPTS);
5282 if (framesRead == 0) {
5283 // since pipe is non-blocking, simulate blocking input
5284 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5285 }
5286 // otherwise use the HAL / AudioStreamIn directly
5287 } else {
5288 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5289 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5290 if (bytesRead < 0) {
5291 framesRead = bytesRead;
5292 } else {
5293 framesRead = bytesRead / mFrameSize;
5294 }
5295 }
5296
5297 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5298 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005299 // Force input into standby so that it tries to recover at next read attempt
5300 inputStandBy();
5301 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005302 }
5303 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005304 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005306 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005307
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005308 if (mTeeSink != 0) {
5309 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5310 }
5311 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005312 {
5313 size_t part1 = mRsmpInFramesP2 - rear;
5314 if ((size_t) framesRead > part1) {
5315 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5316 (framesRead - part1) * mFrameSize);
5317 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005318 }
5319 rear = mRsmpInRear += framesRead;
5320
5321 size = activeTracks.size();
5322 // loop over each active track
5323 for (size_t i = 0; i < size; i++) {
5324 activeTrack = activeTracks[i];
5325
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005326 // skip fast tracks, as those are handled directly by FastCapture
5327 if (activeTrack->isFastTrack()) {
5328 continue;
5329 }
5330
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005331 enum {
5332 OVERRUN_UNKNOWN,
5333 OVERRUN_TRUE,
5334 OVERRUN_FALSE
5335 } overrun = OVERRUN_UNKNOWN;
5336
5337 // loop over getNextBuffer to handle circular sink
5338 for (;;) {
5339
5340 activeTrack->mSink.frameCount = ~0;
5341 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5342 size_t framesOut = activeTrack->mSink.frameCount;
5343 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5344
5345 int32_t front = activeTrack->mRsmpInFront;
5346 ssize_t filled = rear - front;
5347 size_t framesIn;
5348
5349 if (filled < 0) {
5350 // should not happen, but treat like a massive overrun and re-sync
5351 framesIn = 0;
5352 activeTrack->mRsmpInFront = rear;
5353 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005354 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005355 framesIn = (size_t) filled;
5356 } else {
5357 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005358 framesIn = mRsmpInFrames;
5359 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005360 overrun = OVERRUN_TRUE;
5361 }
5362
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005363 if (framesOut == 0 || framesIn == 0) {
5364 break;
5365 }
5366
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005367 if (activeTrack->mResampler == NULL) {
5368 // no resampling
5369 if (framesIn > framesOut) {
5370 framesIn = framesOut;
5371 } else {
5372 framesOut = framesIn;
5373 }
5374 int8_t *dst = activeTrack->mSink.i8;
5375 while (framesIn > 0) {
5376 front &= mRsmpInFramesP2 - 1;
5377 size_t part1 = mRsmpInFramesP2 - front;
5378 if (part1 > framesIn) {
5379 part1 = framesIn;
5380 }
5381 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005382 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005383 memcpy(dst, src, part1 * mFrameSize);
5384 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005385 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005386 part1);
5387 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005388 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005389 part1);
5390 }
5391 dst += part1 * activeTrack->mFrameSize;
5392 front += part1;
5393 framesIn -= part1;
5394 }
5395 activeTrack->mRsmpInFront += framesOut;
5396
5397 } else {
5398 // resampling
5399 // FIXME framesInNeeded should really be part of resampler API, and should
5400 // depend on the SRC ratio
5401 // to keep mRsmpInBuffer full so resampler always has sufficient input
5402 size_t framesInNeeded;
5403 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005404 // Do not precompute in/out because floating point is not associative
5405 // e.g. a*b/c != a*(b/c).
5406 const double in(mSampleRate);
5407 const double out(activeTrack->mSampleRate);
5408 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005409 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005410 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005411 // Although we theoretically have framesIn in circular buffer, some of those are
5412 // unreleased frames, and thus must be discounted for purpose of budgeting.
5413 size_t unreleased = activeTrack->mRsmpInUnrel;
5414 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005415 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005416 ALOGV("not enough to resample: have %u frames in but need %u in to "
5417 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005418 framesIn, framesInNeeded, framesOut, in / out);
5419 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005420 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5421 if (newFramesOut == 0) {
5422 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005423 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005424 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005425 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005426 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005427 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5428 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5429 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005430 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005431 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005432 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005433 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005434 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005435 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005436 }
5437
5438 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5439 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005440 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005441 delete[] activeTrack->mRsmpOutBuffer;
5442 // resampler always outputs stereo
5443 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5444 activeTrack->mRsmpOutFrameCount = framesOut;
5445 }
5446
5447 // resampler accumulates, but we only have one source track
5448 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5449 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005450 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005451 activeTrack->mResamplerBufferProvider
5452 /*this*/ /* AudioBufferProvider* */);
5453 // ditherAndClamp() works as long as all buffers returned by
5454 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005455 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005456 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005457 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5458 framesOut);
5459 // the resampler always outputs stereo samples:
5460 // do post stereo to mono conversion
5461 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005462 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005463 } else {
5464 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5465 activeTrack->mRsmpOutBuffer, framesOut);
5466 }
5467 // now done with mRsmpOutBuffer
5468
5469 }
5470
5471 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5472 overrun = OVERRUN_FALSE;
5473 }
5474
5475 if (activeTrack->mFramesToDrop == 0) {
5476 if (framesOut > 0) {
5477 activeTrack->mSink.frameCount = framesOut;
5478 activeTrack->releaseBuffer(&activeTrack->mSink);
5479 }
5480 } else {
5481 // FIXME could do a partial drop of framesOut
5482 if (activeTrack->mFramesToDrop > 0) {
5483 activeTrack->mFramesToDrop -= framesOut;
5484 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005485 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005486 }
5487 } else {
5488 activeTrack->mFramesToDrop += framesOut;
5489 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5490 activeTrack->mSyncStartEvent->isCancelled()) {
5491 ALOGW("Synced record %s, session %d, trigger session %d",
5492 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5493 activeTrack->sessionId(),
5494 (activeTrack->mSyncStartEvent != 0) ?
5495 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005496 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005497 }
5498 }
5499 }
5500
5501 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005502 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005503 }
5504 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005505
5506 switch (overrun) {
5507 case OVERRUN_TRUE:
5508 // client isn't retrieving buffers fast enough
5509 if (!activeTrack->setOverflow()) {
5510 nsecs_t now = systemTime();
5511 // FIXME should lastWarning per track?
5512 if ((now - lastWarning) > kWarningThrottleNs) {
5513 ALOGW("RecordThread: buffer overflow");
5514 lastWarning = now;
5515 }
5516 }
5517 break;
5518 case OVERRUN_FALSE:
5519 activeTrack->clearOverflow();
5520 break;
5521 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005522 break;
5523 }
5524
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005525 }
5526
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005527unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005528 // enable changes in effect chain
5529 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005530 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005531 }
5532
Glenn Kasten93e471f2013-08-19 08:40:07 -07005533 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005534
5535 {
5536 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005537 for (size_t i = 0; i < mTracks.size(); i++) {
5538 sp<RecordTrack> track = mTracks[i];
5539 track->invalidate();
5540 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005541 mActiveTracks.clear();
5542 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005543 mStartStopCond.broadcast();
5544 }
5545
5546 releaseWakeLock();
5547
5548 ALOGV("RecordThread %p exiting", this);
5549 return false;
5550}
5551
Glenn Kasten93e471f2013-08-19 08:40:07 -07005552void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005553{
5554 if (!mStandby) {
5555 inputStandBy();
5556 mStandby = true;
5557 }
5558}
5559
5560void AudioFlinger::RecordThread::inputStandBy()
5561{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005562 // Idle the fast capture if it's currently running
5563 if (mFastCapture != 0) {
5564 FastCaptureStateQueue *sq = mFastCapture->sq();
5565 FastCaptureState *state = sq->begin();
5566 if (!(state->mCommand & FastCaptureState::IDLE)) {
5567 state->mCommand = FastCaptureState::COLD_IDLE;
5568 state->mColdFutexAddr = &mFastCaptureFutex;
5569 state->mColdGen++;
5570 mFastCaptureFutex = 0;
5571 sq->end();
5572 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5573 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5574#if 0
5575 if (kUseFastCapture == FastCapture_Dynamic) {
5576 // FIXME
5577 }
5578#endif
5579#ifdef AUDIO_WATCHDOG
5580 // FIXME
5581#endif
5582 } else {
5583 sq->end(false /*didModify*/);
5584 }
5585 }
Eric Laurent81784c32012-11-19 14:55:58 -08005586 mInput->stream->common.standby(&mInput->stream->common);
5587}
5588
Glenn Kasten05997e22014-03-13 15:08:33 -07005589// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005590sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005591 const sp<AudioFlinger::Client>& client,
5592 uint32_t sampleRate,
5593 audio_format_t format,
5594 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005595 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005596 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005597 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005598 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005599 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005600 pid_t tid,
5601 status_t *status)
5602{
Glenn Kasten74935e42013-12-19 08:56:45 -08005603 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 sp<RecordTrack> track;
5605 status_t lStatus;
5606
Glenn Kasten90e58b12013-07-31 16:16:02 -07005607 // client expresses a preference for FAST, but we get the final say
5608 if (*flags & IAudioFlinger::TRACK_FAST) {
5609 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005610 // use case: callback handler
5611 (tid != -1) &&
5612 // frame count is not specified, or is exactly the pipe depth
5613 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005614 // PCM data
5615 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005616 // native format
5617 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005618 // native channel mask
5619 (channelMask == mChannelMask) &&
5620 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005621 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005622 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005623 hasFastCapture() &&
5624 // there are sufficient fast track slots available
5625 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005626 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005627 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005628 frameCount, mFrameCount);
5629 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005630 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5631 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005632 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005633 frameCount, mFrameCount, mPipeFramesP2,
5634 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5635 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005636 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005637 }
5638 }
5639
5640 // compute track buffer size in frames, and suggest the notification frame count
5641 if (*flags & IAudioFlinger::TRACK_FAST) {
5642 // fast track: frame count is exactly the pipe depth
5643 frameCount = mPipeFramesP2;
5644 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5645 *notificationFrames = mFrameCount;
5646 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005647 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5648 // or 20 ms if there is a fast capture
5649 // TODO This could be a roundupRatio inline, and const
5650 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5651 * sampleRate + mSampleRate - 1) / mSampleRate;
5652 // minimum number of notification periods is at least kMinNotifications,
5653 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5654 static const size_t kMinNotifications = 3;
5655 static const uint32_t kMinMs = 30;
5656 // TODO This could be a roundupRatio inline
5657 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5658 // TODO This could be a roundupRatio inline
5659 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5660 maxNotificationFrames;
5661 const size_t minFrameCount = maxNotificationFrames *
5662 max(kMinNotifications, minNotificationsByMs);
5663 frameCount = max(frameCount, minFrameCount);
5664 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5665 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005666 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005667 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005668 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005669
Glenn Kasten15e57982013-09-24 11:52:37 -07005670 lStatus = initCheck();
5671 if (lStatus != NO_ERROR) {
5672 ALOGE("createRecordTrack_l() audio driver not initialized");
5673 goto Exit;
5674 }
Eric Laurent81784c32012-11-19 14:55:58 -08005675
5676 { // scope for mLock
5677 Mutex::Autolock _l(mLock);
5678
5679 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005680 format, channelMask, frameCount, NULL, sessionId, uid,
5681 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005682
Glenn Kasten03003332013-08-06 15:40:54 -07005683 lStatus = track->initCheck();
5684 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005685 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005686 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005687 goto Exit;
5688 }
5689 mTracks.add(track);
5690
5691 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5692 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5693 mAudioFlinger->btNrecIsOff();
5694 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5695 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005696
5697 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5698 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5699 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5700 // so ask activity manager to do this on our behalf
5701 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5702 }
Eric Laurent81784c32012-11-19 14:55:58 -08005703 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005704
Eric Laurent81784c32012-11-19 14:55:58 -08005705 lStatus = NO_ERROR;
5706
5707Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005708 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005709 return track;
5710}
5711
5712status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5713 AudioSystem::sync_event_t event,
5714 int triggerSession)
5715{
5716 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5717 sp<ThreadBase> strongMe = this;
5718 status_t status = NO_ERROR;
5719
5720 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005721 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005722 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005724 triggerSession,
5725 recordTrack->sessionId(),
5726 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005727 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005728 // Sync event can be cancelled by the trigger session if the track is not in a
5729 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005730 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005731 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005732 } else {
5733 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005734 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005735 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005736 }
5737 }
5738
5739 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005740 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005741 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005742 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5743 if (recordTrack->mState == TrackBase::PAUSING) {
5744 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005745 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005746 } else {
5747 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005748 }
5749 return status;
5750 }
5751
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005752 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5753 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5754 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005756 mActiveTracks.add(recordTrack);
5757 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005758 status_t status = NO_ERROR;
5759 if (recordTrack->isExternalTrack()) {
5760 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005761 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005762 mLock.lock();
5763 // FIXME should verify that recordTrack is still in mActiveTracks
5764 if (status != NO_ERROR) {
5765 mActiveTracks.remove(recordTrack);
5766 mActiveTracksGen++;
5767 recordTrack->clearSyncStartEvent();
5768 ALOGV("RecordThread::start error %d", status);
5769 return status;
5770 }
Eric Laurent81784c32012-11-19 14:55:58 -08005771 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005772 // Catch up with current buffer indices if thread is already running.
5773 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5774 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5775 // see previously buffered data before it called start(), but with greater risk of overrun.
5776
5777 recordTrack->mRsmpInFront = mRsmpInRear;
5778 recordTrack->mRsmpInUnrel = 0;
5779 // FIXME why reset?
5780 if (recordTrack->mResampler != NULL) {
5781 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005782 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005783 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005784 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005785 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005786 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005787 ALOGV("Record failed to start");
5788 status = BAD_VALUE;
5789 goto startError;
5790 }
Eric Laurent81784c32012-11-19 14:55:58 -08005791 return status;
5792 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005793
Eric Laurent81784c32012-11-19 14:55:58 -08005794startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005795 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005796 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005797 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005798 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005799 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005800 return status;
5801}
5802
Eric Laurent81784c32012-11-19 14:55:58 -08005803void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5804{
5805 sp<SyncEvent> strongEvent = event.promote();
5806
5807 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005808 sp<RefBase> ptr = strongEvent->cookie().promote();
5809 if (ptr != 0) {
5810 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5811 recordTrack->handleSyncStartEvent(strongEvent);
5812 }
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
5814}
5815
Glenn Kastena8356f62013-07-25 14:37:52 -07005816bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005817 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005818 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005819 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005820 return false;
5821 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005822 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005823 recordTrack->mState = TrackBase::PAUSING;
5824 // do not wait for mStartStopCond if exiting
5825 if (exitPending()) {
5826 return true;
5827 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005828 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005829 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005830 // if we have been restarted, recordTrack is in mActiveTracks here
5831 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005832 ALOGV("Record stopped OK");
5833 return true;
5834 }
5835 return false;
5836}
5837
Glenn Kasten0f11b512014-01-31 16:18:54 -08005838bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005839{
5840 return false;
5841}
5842
Glenn Kasten0f11b512014-01-31 16:18:54 -08005843status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005844{
5845#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5846 if (!isValidSyncEvent(event)) {
5847 return BAD_VALUE;
5848 }
5849
5850 int eventSession = event->triggerSession();
5851 status_t ret = NAME_NOT_FOUND;
5852
5853 Mutex::Autolock _l(mLock);
5854
5855 for (size_t i = 0; i < mTracks.size(); i++) {
5856 sp<RecordTrack> track = mTracks[i];
5857 if (eventSession == track->sessionId()) {
5858 (void) track->setSyncEvent(event);
5859 ret = NO_ERROR;
5860 }
5861 }
5862 return ret;
5863#else
5864 return BAD_VALUE;
5865#endif
5866}
5867
5868// destroyTrack_l() must be called with ThreadBase::mLock held
5869void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5870{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005871 track->terminate();
5872 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005873 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005874 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005875 removeTrack_l(track);
5876 }
5877}
5878
5879void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5880{
5881 mTracks.remove(track);
5882 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 if (track->isFastTrack()) {
5884 ALOG_ASSERT(!mFastTrackAvail);
5885 mFastTrackAvail = true;
5886 }
Eric Laurent81784c32012-11-19 14:55:58 -08005887}
5888
5889void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5890{
5891 dumpInternals(fd, args);
5892 dumpTracks(fd, args);
5893 dumpEffectChains(fd, args);
5894}
5895
5896void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5897{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005898 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005899
Glenn Kasten2b806402013-11-20 16:37:38 -08005900 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005901 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005902 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005903 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005904 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005905 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005906 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005907
Eric Laurent81784c32012-11-19 14:55:58 -08005908 dumpBase(fd, args);
5909}
5910
Glenn Kasten0f11b512014-01-31 16:18:54 -08005911void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005912{
5913 const size_t SIZE = 256;
5914 char buffer[SIZE];
5915 String8 result;
5916
Marco Nelissenb2208842014-02-07 14:00:50 -08005917 size_t numtracks = mTracks.size();
5918 size_t numactive = mActiveTracks.size();
5919 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005920 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005921 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005922 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005923 RecordTrack::appendDumpHeader(result);
5924 for (size_t i = 0; i < numtracks ; ++i) {
5925 sp<RecordTrack> track = mTracks[i];
5926 if (track != 0) {
5927 bool active = mActiveTracks.indexOf(track) >= 0;
5928 if (active) {
5929 numactiveseen++;
5930 }
5931 track->dump(buffer, SIZE, active);
5932 result.append(buffer);
5933 }
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005935 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005936 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005937 }
5938
Marco Nelissenb2208842014-02-07 14:00:50 -08005939 if (numactiveseen != numactive) {
5940 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5941 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005942 result.append(buffer);
5943 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005944 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005945 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005946 if (mTracks.indexOf(track) < 0) {
5947 track->dump(buffer, SIZE, true);
5948 result.append(buffer);
5949 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005950 }
Eric Laurent81784c32012-11-19 14:55:58 -08005951
5952 }
5953 write(fd, result.string(), result.size());
5954}
5955
5956// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005957status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5958 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005959{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005960 RecordTrack *activeTrack = mRecordTrack;
5961 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5962 if (threadBase == 0) {
5963 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005964 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005965 return NOT_ENOUGH_DATA;
5966 }
5967 RecordThread *recordThread = (RecordThread *) threadBase.get();
5968 int32_t rear = recordThread->mRsmpInRear;
5969 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005970 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005971 // FIXME should not be P2 (don't want to increase latency)
5972 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005973 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005974 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005975 front &= recordThread->mRsmpInFramesP2 - 1;
5976 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005977 if (part1 > (size_t) filled) {
5978 part1 = filled;
5979 }
5980 size_t ask = buffer->frameCount;
5981 ALOG_ASSERT(ask > 0);
5982 if (part1 > ask) {
5983 part1 = ask;
5984 }
5985 if (part1 == 0) {
5986 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005987 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005988 buffer->raw = NULL;
5989 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005990 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005991 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005992 }
5993
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005994 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005995 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 return NO_ERROR;
5998}
5999
6000// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006001void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6002 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006003{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006004 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006005 size_t stepCount = buffer->frameCount;
6006 if (stepCount == 0) {
6007 return;
6008 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006009 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6010 activeTrack->mRsmpInUnrel -= stepCount;
6011 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006012 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006013 buffer->frameCount = 0;
6014}
6015
Eric Laurent10351942014-05-08 18:49:52 -07006016bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6017 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006018{
6019 bool reconfig = false;
6020
Eric Laurent10351942014-05-08 18:49:52 -07006021 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006022
Eric Laurent10351942014-05-08 18:49:52 -07006023 audio_format_t reqFormat = mFormat;
6024 uint32_t samplingRate = mSampleRate;
6025 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6026
6027 AudioParameter param = AudioParameter(keyValuePair);
6028 int value;
6029 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6030 // channel count change can be requested. Do we mandate the first client defines the
6031 // HAL sampling rate and channel count or do we allow changes on the fly?
6032 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6033 samplingRate = value;
6034 reconfig = true;
6035 }
6036 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6037 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6038 status = BAD_VALUE;
6039 } else {
6040 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006041 reconfig = true;
6042 }
Eric Laurent10351942014-05-08 18:49:52 -07006043 }
6044 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6045 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6046 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6047 status = BAD_VALUE;
6048 } else {
6049 channelMask = mask;
6050 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 }
Eric Laurent10351942014-05-08 18:49:52 -07006052 }
6053 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6054 // do not accept frame count changes if tracks are open as the track buffer
6055 // size depends on frame count and correct behavior would not be guaranteed
6056 // if frame count is changed after track creation
6057 if (mActiveTracks.size() > 0) {
6058 status = INVALID_OPERATION;
6059 } else {
6060 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006061 }
Eric Laurent10351942014-05-08 18:49:52 -07006062 }
6063 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6064 // forward device change to effects that have requested to be
6065 // aware of attached audio device.
6066 for (size_t i = 0; i < mEffectChains.size(); i++) {
6067 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006068 }
Eric Laurent81784c32012-11-19 14:55:58 -08006069
Eric Laurent10351942014-05-08 18:49:52 -07006070 // store input device and output device but do not forward output device to audio HAL.
6071 // Note that status is ignored by the caller for output device
6072 // (see AudioFlinger::setParameters()
6073 if (audio_is_output_devices(value)) {
6074 mOutDevice = value;
6075 status = BAD_VALUE;
6076 } else {
6077 mInDevice = value;
6078 // disable AEC and NS if the device is a BT SCO headset supporting those
6079 // pre processings
6080 if (mTracks.size() > 0) {
6081 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6082 mAudioFlinger->btNrecIsOff();
6083 for (size_t i = 0; i < mTracks.size(); i++) {
6084 sp<RecordTrack> track = mTracks[i];
6085 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6086 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006087 }
6088 }
6089 }
Eric Laurent10351942014-05-08 18:49:52 -07006090 }
6091 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6092 mAudioSource != (audio_source_t)value) {
6093 // forward device change to effects that have requested to be
6094 // aware of attached audio device.
6095 for (size_t i = 0; i < mEffectChains.size(); i++) {
6096 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006097 }
Eric Laurent10351942014-05-08 18:49:52 -07006098 mAudioSource = (audio_source_t)value;
6099 }
Glenn Kastene198c362013-08-13 09:13:36 -07006100
Eric Laurent10351942014-05-08 18:49:52 -07006101 if (status == NO_ERROR) {
6102 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6103 keyValuePair.string());
6104 if (status == INVALID_OPERATION) {
6105 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006106 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6107 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006108 }
6109 if (reconfig) {
6110 if (status == BAD_VALUE &&
6111 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6112 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6113 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6114 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006115 audio_channel_count_from_in_mask(
6116 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006117 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6118 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6119 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006120 }
Eric Laurent10351942014-05-08 18:49:52 -07006121 if (status == NO_ERROR) {
6122 readInputParameters_l();
6123 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006124 }
6125 }
Eric Laurent81784c32012-11-19 14:55:58 -08006126 }
Eric Laurent10351942014-05-08 18:49:52 -07006127
Eric Laurent81784c32012-11-19 14:55:58 -08006128 return reconfig;
6129}
6130
6131String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6132{
Eric Laurent81784c32012-11-19 14:55:58 -08006133 Mutex::Autolock _l(mLock);
6134 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006135 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006136 }
6137
Glenn Kastend8ea6992013-07-16 14:17:15 -07006138 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6139 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006140 free(s);
6141 return out_s8;
6142}
6143
Eric Laurent021cf962014-05-13 10:18:14 -07006144void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006145 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006146 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006147
6148 switch (event) {
6149 case AudioSystem::INPUT_OPENED:
6150 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006151 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 desc.samplingRate = mSampleRate;
6153 desc.format = mFormat;
6154 desc.frameCount = mFrameCount;
6155 desc.latency = 0;
6156 param2 = &desc;
6157 break;
6158
6159 case AudioSystem::INPUT_CLOSED:
6160 default:
6161 break;
6162 }
Eric Laurent021cf962014-05-13 10:18:14 -07006163 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006164}
6165
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006166void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006167{
Eric Laurent81784c32012-11-19 14:55:58 -08006168 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6169 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006170 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006171 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6172 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006173 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006174 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006175 }
Eric Laurent665470b2014-07-03 16:37:08 -07006176 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006177 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6178 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006179 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006180 // 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 -07006181 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006182 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006183 // A larger value should allow more old data to be read after a track calls start(),
6184 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006185 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006186 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006187 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006188
6189 // TODO optimize audio capture buffer sizes ...
6190 // Here we calculate the size of the sliding buffer used as a source
6191 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6192 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6193 // be better to have it derived from the pipe depth in the long term.
6194 // The current value is higher than necessary. However it should not add to latency.
6195
Glenn Kasten85948432013-08-19 12:09:05 -07006196 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6197 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006198
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006199 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6200 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006201}
6202
Glenn Kasten5f972c02014-01-13 09:59:31 -08006203uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006204{
6205 Mutex::Autolock _l(mLock);
6206 if (initCheck() != NO_ERROR) {
6207 return 0;
6208 }
6209
6210 return mInput->stream->get_input_frames_lost(mInput->stream);
6211}
6212
6213uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6214{
6215 Mutex::Autolock _l(mLock);
6216 uint32_t result = 0;
6217 if (getEffectChain_l(sessionId) != 0) {
6218 result = EFFECT_SESSION;
6219 }
6220
6221 for (size_t i = 0; i < mTracks.size(); ++i) {
6222 if (sessionId == mTracks[i]->sessionId()) {
6223 result |= TRACK_SESSION;
6224 break;
6225 }
6226 }
6227
6228 return result;
6229}
6230
6231KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6232{
6233 KeyedVector<int, bool> ids;
6234 Mutex::Autolock _l(mLock);
6235 for (size_t j = 0; j < mTracks.size(); ++j) {
6236 sp<RecordThread::RecordTrack> track = mTracks[j];
6237 int sessionId = track->sessionId();
6238 if (ids.indexOfKey(sessionId) < 0) {
6239 ids.add(sessionId, true);
6240 }
6241 }
6242 return ids;
6243}
6244
6245AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6246{
6247 Mutex::Autolock _l(mLock);
6248 AudioStreamIn *input = mInput;
6249 mInput = NULL;
6250 return input;
6251}
6252
6253// this method must always be called either with ThreadBase mLock held or inside the thread loop
6254audio_stream_t* AudioFlinger::RecordThread::stream() const
6255{
6256 if (mInput == NULL) {
6257 return NULL;
6258 }
6259 return &mInput->stream->common;
6260}
6261
6262status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6263{
6264 // only one chain per input thread
6265 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006266 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006267 return INVALID_OPERATION;
6268 }
6269 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006270 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006271 chain->setInBuffer(NULL);
6272 chain->setOutBuffer(NULL);
6273
6274 checkSuspendOnAddEffectChain_l(chain);
6275
Eric Laurent1b928682014-10-02 19:41:47 -07006276 // make sure enabled pre processing effects state is communicated to the HAL as we
6277 // just moved them to a new input stream.
6278 chain->syncHalEffectsState();
6279
Eric Laurent81784c32012-11-19 14:55:58 -08006280 mEffectChains.add(chain);
6281
6282 return NO_ERROR;
6283}
6284
6285size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6286{
6287 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6288 ALOGW_IF(mEffectChains.size() != 1,
6289 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6290 chain.get(), mEffectChains.size(), this);
6291 if (mEffectChains.size() == 1) {
6292 mEffectChains.removeAt(0);
6293 }
6294 return 0;
6295}
6296
Eric Laurent1c333e22014-05-20 10:48:17 -07006297status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6298 audio_patch_handle_t *handle)
6299{
6300 status_t status = NO_ERROR;
6301 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6302 // store new device and send to effects
6303 mInDevice = patch->sources[0].ext.device.type;
6304 for (size_t i = 0; i < mEffectChains.size(); i++) {
6305 mEffectChains[i]->setDevice_l(mInDevice);
6306 }
6307
6308 // disable AEC and NS if the device is a BT SCO headset supporting those
6309 // pre processings
6310 if (mTracks.size() > 0) {
6311 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6312 mAudioFlinger->btNrecIsOff();
6313 for (size_t i = 0; i < mTracks.size(); i++) {
6314 sp<RecordTrack> track = mTracks[i];
6315 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6316 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6317 }
6318 }
6319
6320 // store new source and send to effects
6321 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6322 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6323 for (size_t i = 0; i < mEffectChains.size(); i++) {
6324 mEffectChains[i]->setAudioSource_l(mAudioSource);
6325 }
6326 }
6327
6328 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6329 status = hwDevice->create_audio_patch(hwDevice,
6330 patch->num_sources,
6331 patch->sources,
6332 patch->num_sinks,
6333 patch->sinks,
6334 handle);
6335 } else {
6336 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6337 }
6338 return status;
6339}
6340
6341status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6342{
6343 status_t status = NO_ERROR;
6344 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6345 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6346 status = hwDevice->release_audio_patch(hwDevice, handle);
6347 } else {
6348 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6349 }
6350 return status;
6351}
6352
Eric Laurent83b88082014-06-20 18:31:16 -07006353void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6354{
6355 Mutex::Autolock _l(mLock);
6356 mTracks.add(record);
6357}
6358
6359void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6360{
6361 Mutex::Autolock _l(mLock);
6362 destroyTrack_l(record);
6363}
6364
6365void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6366{
6367 ThreadBase::getAudioPortConfig(config);
6368 config->role = AUDIO_PORT_ROLE_SINK;
6369 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6370 config->ext.mix.usecase.source = mAudioSource;
6371}
Eric Laurent1c333e22014-05-20 10:48:17 -07006372
Eric Laurent81784c32012-11-19 14:55:58 -08006373}; // namespace android