blob: e24832f9ac9b8e16d0a5f2a72cb3a8b883ece861 [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 {
Glenn Kastene7754022014-10-31 12:11:26 -07002686 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002688 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 }
Eric Laurent81784c32012-11-19 14:55:58 -08002690 }
2691
2692 // Finally let go of removed track(s), without the lock held
2693 // since we can't guarantee the destructors won't acquire that
2694 // same lock. This will also mutate and push a new fast mixer state.
2695 threadLoop_removeTracks(tracksToRemove);
2696 tracksToRemove.clear();
2697
2698 // FIXME I don't understand the need for this here;
2699 // it was in the original code but maybe the
2700 // assignment in saveOutputTracks() makes this unnecessary?
2701 clearOutputTracks();
2702
2703 // Effect chains will be actually deleted here if they were removed from
2704 // mEffectChains list during mixing or effects processing
2705 effectChains.clear();
2706
2707 // FIXME Note that the above .clear() is no longer necessary since effectChains
2708 // is now local to this block, but will keep it for now (at least until merge done).
2709 }
2710
Eric Laurentbfb1b832013-01-07 09:53:42 -08002711 threadLoop_exit();
2712
Eric Laurentcf817a22014-08-04 20:36:31 -07002713 if (!mStandby) {
2714 threadLoop_standby();
2715 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002716 }
2717
2718 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002719 mWakeLockUids.clear();
2720 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002721
2722 ALOGV("Thread %p type %d exiting", this, mType);
2723 return false;
2724}
2725
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726// removeTracks_l() must be called with ThreadBase::mLock held
2727void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2728{
2729 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002730 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 for (size_t i=0 ; i<count ; i++) {
2732 const sp<Track>& track = tracksToRemove.itemAt(i);
2733 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002734 mWakeLockUids.remove(track->uid());
2735 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2737 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2738 if (chain != 0) {
2739 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2740 track->sessionId());
2741 chain->decActiveTrackCnt();
2742 }
2743 if (track->isTerminated()) {
2744 removeTrack_l(track);
2745 }
2746 }
2747 }
2748
2749}
Eric Laurent81784c32012-11-19 14:55:58 -08002750
Eric Laurentaccc1472013-09-20 09:36:34 -07002751status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2752{
2753 if (mNormalSink != 0) {
2754 return mNormalSink->getTimestamp(timestamp);
2755 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002756 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002757 uint64_t position64;
2758 int ret = mOutput->stream->get_presentation_position(
2759 mOutput->stream, &position64, &timestamp.mTime);
2760 if (ret == 0) {
2761 timestamp.mPosition = (uint32_t)position64;
2762 return NO_ERROR;
2763 }
2764 }
2765 return INVALID_OPERATION;
2766}
Eric Laurent1c333e22014-05-20 10:48:17 -07002767
2768status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2769 audio_patch_handle_t *handle)
2770{
2771 status_t status = NO_ERROR;
2772 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2773 // store new device and send to effects
2774 audio_devices_t type = AUDIO_DEVICE_NONE;
2775 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2776 type |= patch->sinks[i].ext.device.type;
2777 }
2778 mOutDevice = type;
2779 for (size_t i = 0; i < mEffectChains.size(); i++) {
2780 mEffectChains[i]->setDevice_l(mOutDevice);
2781 }
2782
2783 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2784 status = hwDevice->create_audio_patch(hwDevice,
2785 patch->num_sources,
2786 patch->sources,
2787 patch->num_sinks,
2788 patch->sinks,
2789 handle);
2790 } else {
2791 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2792 }
2793 return status;
2794}
2795
2796status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2797{
2798 status_t status = NO_ERROR;
2799 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2800 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2801 status = hwDevice->release_audio_patch(hwDevice, handle);
2802 } else {
2803 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2804 }
2805 return status;
2806}
2807
Eric Laurent83b88082014-06-20 18:31:16 -07002808void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2809{
2810 Mutex::Autolock _l(mLock);
2811 mTracks.add(track);
2812}
2813
2814void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2815{
2816 Mutex::Autolock _l(mLock);
2817 destroyTrack_l(track);
2818}
2819
2820void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2821{
2822 ThreadBase::getAudioPortConfig(config);
2823 config->role = AUDIO_PORT_ROLE_SOURCE;
2824 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2825 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2826}
2827
Eric Laurent81784c32012-11-19 14:55:58 -08002828// ----------------------------------------------------------------------------
2829
2830AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2831 audio_io_handle_t id, audio_devices_t device, type_t type)
2832 : PlaybackThread(audioFlinger, output, id, device, type),
2833 // mAudioMixer below
2834 // mFastMixer below
2835 mFastMixerFutex(0)
2836 // mOutputSink below
2837 // mPipeSink below
2838 // mNormalSink below
2839{
2840 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002841 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002842 "mFrameCount=%d, mNormalFrameCount=%d",
2843 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2844 mNormalFrameCount);
2845 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2846
Eric Laurent81784c32012-11-19 14:55:58 -08002847 // create an NBAIO sink for the HAL output stream, and negotiate
2848 mOutputSink = new AudioStreamOutSink(output->stream);
2849 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002850 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002851 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2852 ALOG_ASSERT(index == 0);
2853
2854 // initialize fast mixer depending on configuration
2855 bool initFastMixer;
2856 switch (kUseFastMixer) {
2857 case FastMixer_Never:
2858 initFastMixer = false;
2859 break;
2860 case FastMixer_Always:
2861 initFastMixer = true;
2862 break;
2863 case FastMixer_Static:
2864 case FastMixer_Dynamic:
2865 initFastMixer = mFrameCount < mNormalFrameCount;
2866 break;
2867 }
2868 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002869 audio_format_t fastMixerFormat;
2870 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2871 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2872 } else {
2873 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2874 }
2875 if (mFormat != fastMixerFormat) {
2876 // change our Sink format to accept our intermediate precision
2877 mFormat = fastMixerFormat;
2878 free(mSinkBuffer);
2879 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2880 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2881 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2882 }
Eric Laurent81784c32012-11-19 14:55:58 -08002883
2884 // create a MonoPipe to connect our submix to FastMixer
2885 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002886 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002887 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002888 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002889 format.mFormat = fastMixerFormat;
2890 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2891
Eric Laurent81784c32012-11-19 14:55:58 -08002892 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2893 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2894 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2895 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2896 const NBAIO_Format offers[1] = {format};
2897 size_t numCounterOffers = 0;
2898 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2899 ALOG_ASSERT(index == 0);
2900 monoPipe->setAvgFrames((mScreenState & 1) ?
2901 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2902 mPipeSink = monoPipe;
2903
Glenn Kasten46909e72013-02-26 09:20:22 -08002904#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002905 if (mTeeSinkOutputEnabled) {
2906 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002907 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2908 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002909 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002910 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002911 ALOG_ASSERT(index == 0);
2912 mTeeSink = teeSink;
2913 PipeReader *teeSource = new PipeReader(*teeSink);
2914 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002915 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002916 ALOG_ASSERT(index == 0);
2917 mTeeSource = teeSource;
2918 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002919#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002920
2921 // create fast mixer and configure it initially with just one fast track for our submix
2922 mFastMixer = new FastMixer();
2923 FastMixerStateQueue *sq = mFastMixer->sq();
2924#ifdef STATE_QUEUE_DUMP
2925 sq->setObserverDump(&mStateQueueObserverDump);
2926 sq->setMutatorDump(&mStateQueueMutatorDump);
2927#endif
2928 FastMixerState *state = sq->begin();
2929 FastTrack *fastTrack = &state->mFastTracks[0];
2930 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2931 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2932 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002933 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2934 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002935 fastTrack->mGeneration++;
2936 state->mFastTracksGen++;
2937 state->mTrackMask = 1;
2938 // fast mixer will use the HAL output sink
2939 state->mOutputSink = mOutputSink.get();
2940 state->mOutputSinkGen++;
2941 state->mFrameCount = mFrameCount;
2942 state->mCommand = FastMixerState::COLD_IDLE;
2943 // already done in constructor initialization list
2944 //mFastMixerFutex = 0;
2945 state->mColdFutexAddr = &mFastMixerFutex;
2946 state->mColdGen++;
2947 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002948#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002949 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002950#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002951 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2952 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002953 sq->end();
2954 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2955
2956 // start the fast mixer
2957 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2958 pid_t tid = mFastMixer->getTid();
2959 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2960 if (err != 0) {
2961 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2962 kPriorityFastMixer, getpid_cached, tid, err);
2963 }
2964
2965#ifdef AUDIO_WATCHDOG
2966 // create and start the watchdog
2967 mAudioWatchdog = new AudioWatchdog();
2968 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2969 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2970 tid = mAudioWatchdog->getTid();
2971 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2972 if (err != 0) {
2973 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2974 kPriorityFastMixer, getpid_cached, tid, err);
2975 }
2976#endif
2977
Eric Laurent81784c32012-11-19 14:55:58 -08002978 }
2979
2980 switch (kUseFastMixer) {
2981 case FastMixer_Never:
2982 case FastMixer_Dynamic:
2983 mNormalSink = mOutputSink;
2984 break;
2985 case FastMixer_Always:
2986 mNormalSink = mPipeSink;
2987 break;
2988 case FastMixer_Static:
2989 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2990 break;
2991 }
2992}
2993
2994AudioFlinger::MixerThread::~MixerThread()
2995{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002996 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002997 FastMixerStateQueue *sq = mFastMixer->sq();
2998 FastMixerState *state = sq->begin();
2999 if (state->mCommand == FastMixerState::COLD_IDLE) {
3000 int32_t old = android_atomic_inc(&mFastMixerFutex);
3001 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003002 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003003 }
3004 }
3005 state->mCommand = FastMixerState::EXIT;
3006 sq->end();
3007 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3008 mFastMixer->join();
3009 // Though the fast mixer thread has exited, it's state queue is still valid.
3010 // We'll use that extract the final state which contains one remaining fast track
3011 // corresponding to our sub-mix.
3012 state = sq->begin();
3013 ALOG_ASSERT(state->mTrackMask == 1);
3014 FastTrack *fastTrack = &state->mFastTracks[0];
3015 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3016 delete fastTrack->mBufferProvider;
3017 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003018 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003019#ifdef AUDIO_WATCHDOG
3020 if (mAudioWatchdog != 0) {
3021 mAudioWatchdog->requestExit();
3022 mAudioWatchdog->requestExitAndWait();
3023 mAudioWatchdog.clear();
3024 }
3025#endif
3026 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003027 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003028 delete mAudioMixer;
3029}
3030
3031
3032uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3033{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003034 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003035 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3036 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3037 }
3038 return latency;
3039}
3040
3041
3042void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3043{
3044 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3045}
3046
Eric Laurentbfb1b832013-01-07 09:53:42 -08003047ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003048{
3049 // FIXME we should only do one push per cycle; confirm this is true
3050 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003051 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003052 FastMixerStateQueue *sq = mFastMixer->sq();
3053 FastMixerState *state = sq->begin();
3054 if (state->mCommand != FastMixerState::MIX_WRITE &&
3055 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3056 if (state->mCommand == FastMixerState::COLD_IDLE) {
3057 int32_t old = android_atomic_inc(&mFastMixerFutex);
3058 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003059 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003060 }
3061#ifdef AUDIO_WATCHDOG
3062 if (mAudioWatchdog != 0) {
3063 mAudioWatchdog->resume();
3064 }
3065#endif
3066 }
3067 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003068 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3069 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003070 sq->end();
3071 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3072 if (kUseFastMixer == FastMixer_Dynamic) {
3073 mNormalSink = mPipeSink;
3074 }
3075 } else {
3076 sq->end(false /*didModify*/);
3077 }
3078 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003080}
3081
3082void AudioFlinger::MixerThread::threadLoop_standby()
3083{
3084 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003085 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003086 FastMixerStateQueue *sq = mFastMixer->sq();
3087 FastMixerState *state = sq->begin();
3088 if (!(state->mCommand & FastMixerState::IDLE)) {
3089 state->mCommand = FastMixerState::COLD_IDLE;
3090 state->mColdFutexAddr = &mFastMixerFutex;
3091 state->mColdGen++;
3092 mFastMixerFutex = 0;
3093 sq->end();
3094 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3095 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3096 if (kUseFastMixer == FastMixer_Dynamic) {
3097 mNormalSink = mOutputSink;
3098 }
3099#ifdef AUDIO_WATCHDOG
3100 if (mAudioWatchdog != 0) {
3101 mAudioWatchdog->pause();
3102 }
3103#endif
3104 } else {
3105 sq->end(false /*didModify*/);
3106 }
3107 }
3108 PlaybackThread::threadLoop_standby();
3109}
3110
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3112{
3113 return false;
3114}
3115
3116bool AudioFlinger::PlaybackThread::shouldStandby_l()
3117{
3118 return !mStandby;
3119}
3120
3121bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3122{
3123 Mutex::Autolock _l(mLock);
3124 return waitingAsyncCallback_l();
3125}
3126
Eric Laurent81784c32012-11-19 14:55:58 -08003127// shared by MIXER and DIRECT, overridden by DUPLICATING
3128void AudioFlinger::PlaybackThread::threadLoop_standby()
3129{
3130 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3131 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003133 // discard any pending drain or write ack by incrementing sequence
3134 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3135 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003137 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3138 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139 }
Eric Laurent81784c32012-11-19 14:55:58 -08003140}
3141
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003142void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3143{
3144 ALOGV("signal playback thread");
3145 broadcast_l();
3146}
3147
Eric Laurent81784c32012-11-19 14:55:58 -08003148void AudioFlinger::MixerThread::threadLoop_mix()
3149{
3150 // obtain the presentation timestamp of the next output buffer
3151 int64_t pts;
3152 status_t status = INVALID_OPERATION;
3153
3154 if (mNormalSink != 0) {
3155 status = mNormalSink->getNextWriteTimestamp(&pts);
3156 } else {
3157 status = mOutputSink->getNextWriteTimestamp(&pts);
3158 }
3159
3160 if (status != NO_ERROR) {
3161 pts = AudioBufferProvider::kInvalidPTS;
3162 }
3163
3164 // mix buffers...
3165 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003166 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003167 // increase sleep time progressively when application underrun condition clears.
3168 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3169 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3170 // such that we would underrun the audio HAL.
3171 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3172 sleepTimeShift--;
3173 }
3174 sleepTime = 0;
3175 standbyTime = systemTime() + standbyDelay;
3176 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003177
Eric Laurent81784c32012-11-19 14:55:58 -08003178}
3179
3180void AudioFlinger::MixerThread::threadLoop_sleepTime()
3181{
3182 // If no tracks are ready, sleep once for the duration of an output
3183 // buffer size, then write 0s to the output
3184 if (sleepTime == 0) {
3185 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3186 sleepTime = activeSleepTime >> sleepTimeShift;
3187 if (sleepTime < kMinThreadSleepTimeUs) {
3188 sleepTime = kMinThreadSleepTimeUs;
3189 }
3190 // reduce sleep time in case of consecutive application underruns to avoid
3191 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3192 // duration we would end up writing less data than needed by the audio HAL if
3193 // the condition persists.
3194 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3195 sleepTimeShift++;
3196 }
3197 } else {
3198 sleepTime = idleSleepTime;
3199 }
3200 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003201 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3202 // before effects processing or output.
3203 if (mMixerBufferValid) {
3204 memset(mMixerBuffer, 0, mMixerBufferSize);
3205 } else {
3206 memset(mSinkBuffer, 0, mSinkBufferSize);
3207 }
Eric Laurent81784c32012-11-19 14:55:58 -08003208 sleepTime = 0;
3209 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3210 "anticipated start");
3211 }
3212 // TODO add standby time extension fct of effect tail
3213}
3214
3215// prepareTracks_l() must be called with ThreadBase::mLock held
3216AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3217 Vector< sp<Track> > *tracksToRemove)
3218{
3219
3220 mixer_state mixerStatus = MIXER_IDLE;
3221 // find out which tracks need to be processed
3222 size_t count = mActiveTracks.size();
3223 size_t mixedTracks = 0;
3224 size_t tracksWithEffect = 0;
3225 // counts only _active_ fast tracks
3226 size_t fastTracks = 0;
3227 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3228
3229 float masterVolume = mMasterVolume;
3230 bool masterMute = mMasterMute;
3231
3232 if (masterMute) {
3233 masterVolume = 0;
3234 }
3235 // Delegate master volume control to effect in output mix effect chain if needed
3236 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3237 if (chain != 0) {
3238 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3239 chain->setVolume_l(&v, &v);
3240 masterVolume = (float)((v + (1 << 23)) >> 24);
3241 chain.clear();
3242 }
3243
3244 // prepare a new state to push
3245 FastMixerStateQueue *sq = NULL;
3246 FastMixerState *state = NULL;
3247 bool didModify = false;
3248 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003249 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003250 sq = mFastMixer->sq();
3251 state = sq->begin();
3252 }
3253
Andy Hung69aed5f2014-02-25 17:24:40 -08003254 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003255 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003256
Eric Laurent81784c32012-11-19 14:55:58 -08003257 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003258 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003259 if (t == 0) {
3260 continue;
3261 }
3262
3263 // this const just means the local variable doesn't change
3264 Track* const track = t.get();
3265
3266 // process fast tracks
3267 if (track->isFastTrack()) {
3268
3269 // It's theoretically possible (though unlikely) for a fast track to be created
3270 // and then removed within the same normal mix cycle. This is not a problem, as
3271 // the track never becomes active so it's fast mixer slot is never touched.
3272 // The converse, of removing an (active) track and then creating a new track
3273 // at the identical fast mixer slot within the same normal mix cycle,
3274 // is impossible because the slot isn't marked available until the end of each cycle.
3275 int j = track->mFastIndex;
3276 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3277 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3278 FastTrack *fastTrack = &state->mFastTracks[j];
3279
3280 // Determine whether the track is currently in underrun condition,
3281 // and whether it had a recent underrun.
3282 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3283 FastTrackUnderruns underruns = ftDump->mUnderruns;
3284 uint32_t recentFull = (underruns.mBitFields.mFull -
3285 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3286 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3287 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3288 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3289 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3290 uint32_t recentUnderruns = recentPartial + recentEmpty;
3291 track->mObservedUnderruns = underruns;
3292 // don't count underruns that occur while stopping or pausing
3293 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003294 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3295 recentUnderruns > 0) {
3296 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3297 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
3299
3300 // This is similar to the state machine for normal tracks,
3301 // with a few modifications for fast tracks.
3302 bool isActive = true;
3303 switch (track->mState) {
3304 case TrackBase::STOPPING_1:
3305 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003307 track->mState = TrackBase::STOPPING_2;
3308 }
3309 break;
3310 case TrackBase::PAUSING:
3311 // ramp down is not yet implemented
3312 track->setPaused();
3313 break;
3314 case TrackBase::RESUMING:
3315 // ramp up is not yet implemented
3316 track->mState = TrackBase::ACTIVE;
3317 break;
3318 case TrackBase::ACTIVE:
3319 if (recentFull > 0 || recentPartial > 0) {
3320 // track has provided at least some frames recently: reset retry count
3321 track->mRetryCount = kMaxTrackRetries;
3322 }
3323 if (recentUnderruns == 0) {
3324 // no recent underruns: stay active
3325 break;
3326 }
3327 // there has recently been an underrun of some kind
3328 if (track->sharedBuffer() == 0) {
3329 // were any of the recent underruns "empty" (no frames available)?
3330 if (recentEmpty == 0) {
3331 // no, then ignore the partial underruns as they are allowed indefinitely
3332 break;
3333 }
3334 // there has recently been an "empty" underrun: decrement the retry counter
3335 if (--(track->mRetryCount) > 0) {
3336 break;
3337 }
3338 // indicate to client process that the track was disabled because of underrun;
3339 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003340 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003341 // remove from active list, but state remains ACTIVE [confusing but true]
3342 isActive = false;
3343 break;
3344 }
3345 // fall through
3346 case TrackBase::STOPPING_2:
3347 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003348 case TrackBase::STOPPED:
3349 case TrackBase::FLUSHED: // flush() while active
3350 // Check for presentation complete if track is inactive
3351 // We have consumed all the buffers of this track.
3352 // This would be incomplete if we auto-paused on underrun
3353 {
3354 size_t audioHALFrames =
3355 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3356 size_t framesWritten = mBytesWritten / mFrameSize;
3357 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3358 // track stays in active list until presentation is complete
3359 break;
3360 }
3361 }
3362 if (track->isStopping_2()) {
3363 track->mState = TrackBase::STOPPED;
3364 }
3365 if (track->isStopped()) {
3366 // Can't reset directly, as fast mixer is still polling this track
3367 // track->reset();
3368 // So instead mark this track as needing to be reset after push with ack
3369 resetMask |= 1 << i;
3370 }
3371 isActive = false;
3372 break;
3373 case TrackBase::IDLE:
3374 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003375 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
3377
3378 if (isActive) {
3379 // was it previously inactive?
3380 if (!(state->mTrackMask & (1 << j))) {
3381 ExtendedAudioBufferProvider *eabp = track;
3382 VolumeProvider *vp = track;
3383 fastTrack->mBufferProvider = eabp;
3384 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003385 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003386 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003387 fastTrack->mGeneration++;
3388 state->mTrackMask |= 1 << j;
3389 didModify = true;
3390 // no acknowledgement required for newly active tracks
3391 }
3392 // cache the combined master volume and stream type volume for fast mixer; this
3393 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003394 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003395 ++fastTracks;
3396 } else {
3397 // was it previously active?
3398 if (state->mTrackMask & (1 << j)) {
3399 fastTrack->mBufferProvider = NULL;
3400 fastTrack->mGeneration++;
3401 state->mTrackMask &= ~(1 << j);
3402 didModify = true;
3403 // If any fast tracks were removed, we must wait for acknowledgement
3404 // because we're about to decrement the last sp<> on those tracks.
3405 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3406 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003407 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003408 }
3409 tracksToRemove->add(track);
3410 // Avoids a misleading display in dumpsys
3411 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3412 }
3413 continue;
3414 }
3415
3416 { // local variable scope to avoid goto warning
3417
3418 audio_track_cblk_t* cblk = track->cblk();
3419
3420 // The first time a track is added we wait
3421 // for all its buffers to be filled before processing it
3422 int name = track->name();
3423 // make sure that we have enough frames to mix one full buffer.
3424 // enforce this condition only once to enable draining the buffer in case the client
3425 // app does not call stop() and relies on underrun to stop:
3426 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3427 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003428 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003429 uint32_t sr = track->sampleRate();
3430 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003431 desiredFrames = mNormalFrameCount;
3432 } else {
3433 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003434 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003435 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003436 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003437 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003438#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003439 // the minimum track buffer size is normally twice the number of frames necessary
3440 // to fill one buffer and the resampler should not leave more than one buffer worth
3441 // of unreleased frames after each pass, but just in case...
3442 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003443#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003444 }
Eric Laurent81784c32012-11-19 14:55:58 -08003445 uint32_t minFrames = 1;
3446 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3447 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003448 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003450
3451 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003452 if (ATRACE_ENABLED()) {
3453 // I wish we had formatted trace names
3454 char traceName[16];
3455 strcpy(traceName, "nRdy");
3456 int name = track->name();
3457 if (AudioMixer::TRACK0 <= name &&
3458 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3459 name -= AudioMixer::TRACK0;
3460 traceName[4] = (name / 10) + '0';
3461 traceName[5] = (name % 10) + '0';
3462 } else {
3463 traceName[4] = '?';
3464 traceName[5] = '?';
3465 }
3466 traceName[6] = '\0';
3467 ATRACE_INT(traceName, framesReady);
3468 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003469 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003470 !track->isPaused() && !track->isTerminated())
3471 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003472 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003473
3474 mixedTracks++;
3475
Andy Hung69aed5f2014-02-25 17:24:40 -08003476 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3477 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003478 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003479 if (track->mainBuffer() != mSinkBuffer &&
3480 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003481 if (mEffectBufferEnabled) {
3482 mEffectBufferValid = true; // Later can set directly.
3483 }
Eric Laurent81784c32012-11-19 14:55:58 -08003484 chain = getEffectChain_l(track->sessionId());
3485 // Delegate volume control to effect in track effect chain if needed
3486 if (chain != 0) {
3487 tracksWithEffect++;
3488 } else {
3489 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3490 "session %d",
3491 name, track->sessionId());
3492 }
3493 }
3494
3495
3496 int param = AudioMixer::VOLUME;
3497 if (track->mFillingUpStatus == Track::FS_FILLED) {
3498 // no ramp for the first volume setting
3499 track->mFillingUpStatus = Track::FS_ACTIVE;
3500 if (track->mState == TrackBase::RESUMING) {
3501 track->mState = TrackBase::ACTIVE;
3502 param = AudioMixer::RAMP_VOLUME;
3503 }
3504 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003505 // FIXME should not make a decision based on mServer
3506 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003507 // If the track is stopped before the first frame was mixed,
3508 // do not apply ramp
3509 param = AudioMixer::RAMP_VOLUME;
3510 }
3511
3512 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003513 uint32_t vl, vr; // in U8.24 integer format
3514 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003515 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003516 vl = vr = 0;
3517 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003518 if (track->isPausing()) {
3519 track->setPaused();
3520 }
3521 } else {
3522
3523 // read original volumes with volume control
3524 float typeVolume = mStreamTypes[track->streamType()].volume;
3525 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003526 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003527 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003528 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3529 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003530 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003531 if (vlf > GAIN_FLOAT_UNITY) {
3532 ALOGV("Track left volume out of range: %.3g", vlf);
3533 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003534 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003535 if (vrf > GAIN_FLOAT_UNITY) {
3536 ALOGV("Track right volume out of range: %.3g", vrf);
3537 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003538 }
3539 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003540 vlf *= v;
3541 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003542 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003543 // then derive vl and vr as U8.24 versions for the effect chain
3544 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3545 vl = (uint32_t) (scaleto8_24 * vlf);
3546 vr = (uint32_t) (scaleto8_24 * vrf);
3547 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003548 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003549 // send level comes from shared memory and so may be corrupt
3550 if (sendLevel > MAX_GAIN_INT) {
3551 ALOGV("Track send level out of range: %04X", sendLevel);
3552 sendLevel = MAX_GAIN_INT;
3553 }
Andy Hung6be49402014-05-30 10:42:03 -07003554 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3555 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003556 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557
Eric Laurent81784c32012-11-19 14:55:58 -08003558 // Delegate volume control to effect in track effect chain if needed
3559 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3560 // Do not ramp volume if volume is controlled by effect
3561 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003562 // Update remaining floating point volume levels
3563 vlf = (float)vl / (1 << 24);
3564 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003565 track->mHasVolumeController = true;
3566 } else {
3567 // force no volume ramp when volume controller was just disabled or removed
3568 // from effect chain to avoid volume spike
3569 if (track->mHasVolumeController) {
3570 param = AudioMixer::VOLUME;
3571 }
3572 track->mHasVolumeController = false;
3573 }
3574
Eric Laurent81784c32012-11-19 14:55:58 -08003575 // XXX: these things DON'T need to be done each time
3576 mAudioMixer->setBufferProvider(name, track);
3577 mAudioMixer->enable(name);
3578
Andy Hung6be49402014-05-30 10:42:03 -07003579 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3580 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3581 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003582 mAudioMixer->setParameter(
3583 name,
3584 AudioMixer::TRACK,
3585 AudioMixer::FORMAT, (void *)track->format());
3586 mAudioMixer->setParameter(
3587 name,
3588 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003589 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003590 mAudioMixer->setParameter(
3591 name,
3592 AudioMixer::TRACK,
3593 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003594 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003595 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003596 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003597 if (reqSampleRate == 0) {
3598 reqSampleRate = mSampleRate;
3599 } else if (reqSampleRate > maxSampleRate) {
3600 reqSampleRate = maxSampleRate;
3601 }
Eric Laurent81784c32012-11-19 14:55:58 -08003602 mAudioMixer->setParameter(
3603 name,
3604 AudioMixer::RESAMPLE,
3605 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003606 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003607 /*
3608 * Select the appropriate output buffer for the track.
3609 *
Andy Hung98ef9782014-03-04 14:46:50 -08003610 * Tracks with effects go into their own effects chain buffer
3611 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003612 *
3613 * Other tracks can use mMixerBuffer for higher precision
3614 * channel accumulation. If this buffer is enabled
3615 * (mMixerBufferEnabled true), then selected tracks will accumulate
3616 * into it.
3617 *
3618 */
3619 if (mMixerBufferEnabled
3620 && (track->mainBuffer() == mSinkBuffer
3621 || track->mainBuffer() == mMixerBuffer)) {
3622 mAudioMixer->setParameter(
3623 name,
3624 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003625 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003626 mAudioMixer->setParameter(
3627 name,
3628 AudioMixer::TRACK,
3629 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3630 // TODO: override track->mainBuffer()?
3631 mMixerBufferValid = true;
3632 } else {
3633 mAudioMixer->setParameter(
3634 name,
3635 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003636 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003637 mAudioMixer->setParameter(
3638 name,
3639 AudioMixer::TRACK,
3640 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3641 }
Eric Laurent81784c32012-11-19 14:55:58 -08003642 mAudioMixer->setParameter(
3643 name,
3644 AudioMixer::TRACK,
3645 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3646
3647 // reset retry count
3648 track->mRetryCount = kMaxTrackRetries;
3649
3650 // If one track is ready, set the mixer ready if:
3651 // - the mixer was not ready during previous round OR
3652 // - no other track is not ready
3653 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3654 mixerStatus != MIXER_TRACKS_ENABLED) {
3655 mixerStatus = MIXER_TRACKS_READY;
3656 }
3657 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003658 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003659 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003660 }
Eric Laurent81784c32012-11-19 14:55:58 -08003661 // clear effect chain input buffer if an active track underruns to avoid sending
3662 // previous audio buffer again to effects
3663 chain = getEffectChain_l(track->sessionId());
3664 if (chain != 0) {
3665 chain->clearInputBuffer();
3666 }
3667
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003668 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003669 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3670 track->isStopped() || track->isPaused()) {
3671 // We have consumed all the buffers of this track.
3672 // Remove it from the list of active tracks.
3673 // TODO: use actual buffer filling status instead of latency when available from
3674 // audio HAL
3675 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3676 size_t framesWritten = mBytesWritten / mFrameSize;
3677 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3678 if (track->isStopped()) {
3679 track->reset();
3680 }
3681 tracksToRemove->add(track);
3682 }
3683 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003684 // No buffers for this track. Give it a few chances to
3685 // fill a buffer, then remove it from active list.
3686 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003687 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003688 tracksToRemove->add(track);
3689 // indicate to client process that the track was disabled because of underrun;
3690 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003691 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003692 // If one track is not ready, mark the mixer also not ready if:
3693 // - the mixer was ready during previous round OR
3694 // - no other track is ready
3695 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3696 mixerStatus != MIXER_TRACKS_READY) {
3697 mixerStatus = MIXER_TRACKS_ENABLED;
3698 }
3699 }
3700 mAudioMixer->disable(name);
3701 }
3702
3703 } // local variable scope to avoid goto warning
3704track_is_ready: ;
3705
3706 }
3707
3708 // Push the new FastMixer state if necessary
3709 bool pauseAudioWatchdog = false;
3710 if (didModify) {
3711 state->mFastTracksGen++;
3712 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3713 if (kUseFastMixer == FastMixer_Dynamic &&
3714 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3715 state->mCommand = FastMixerState::COLD_IDLE;
3716 state->mColdFutexAddr = &mFastMixerFutex;
3717 state->mColdGen++;
3718 mFastMixerFutex = 0;
3719 if (kUseFastMixer == FastMixer_Dynamic) {
3720 mNormalSink = mOutputSink;
3721 }
3722 // If we go into cold idle, need to wait for acknowledgement
3723 // so that fast mixer stops doing I/O.
3724 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3725 pauseAudioWatchdog = true;
3726 }
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728 if (sq != NULL) {
3729 sq->end(didModify);
3730 sq->push(block);
3731 }
3732#ifdef AUDIO_WATCHDOG
3733 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3734 mAudioWatchdog->pause();
3735 }
3736#endif
3737
3738 // Now perform the deferred reset on fast tracks that have stopped
3739 while (resetMask != 0) {
3740 size_t i = __builtin_ctz(resetMask);
3741 ALOG_ASSERT(i < count);
3742 resetMask &= ~(1 << i);
3743 sp<Track> t = mActiveTracks[i].promote();
3744 if (t == 0) {
3745 continue;
3746 }
3747 Track* track = t.get();
3748 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3749 track->reset();
3750 }
3751
3752 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003753 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Eric Laurent97d547d2014-09-02 14:45:53 -07003755 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3756 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003757 }
3758
3759 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003760 // as long as there are effects we should clear the effects buffer, to avoid
3761 // passing a non-clean buffer to the effect chain
3762 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003763 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003764 // sink or mix buffer must be cleared if all tracks are connected to an
3765 // effect chain as in this case the mixer will not write to the sink or mix buffer
3766 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3768 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003769 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003770 if (mMixerBufferValid) {
3771 memset(mMixerBuffer, 0, mMixerBufferSize);
3772 // TODO: In testing, mSinkBuffer below need not be cleared because
3773 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3774 // after mixing.
3775 //
3776 // To enforce this guarantee:
3777 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3778 // (mixedTracks == 0 && fastTracks > 0))
3779 // must imply MIXER_TRACKS_READY.
3780 // Later, we may clear buffers regardless, and skip much of this logic.
3781 }
Andy Hung98ef9782014-03-04 14:46:50 -08003782 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003783 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 }
3785
3786 // if any fast tracks, then status is ready
3787 mMixerStatusIgnoringFastTracks = mixerStatus;
3788 if (fastTracks > 0) {
3789 mixerStatus = MIXER_TRACKS_READY;
3790 }
3791 return mixerStatus;
3792}
3793
3794// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003795int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3796 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003797{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003798 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003799}
3800
3801// deleteTrackName_l() must be called with ThreadBase::mLock held
3802void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3803{
3804 ALOGV("remove track (%d) and delete from mixer", name);
3805 mAudioMixer->deleteTrackName(name);
3806}
3807
Eric Laurent10351942014-05-08 18:49:52 -07003808// checkForNewParameter_l() must be called with ThreadBase::mLock held
3809bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3810 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003811{
Eric Laurent81784c32012-11-19 14:55:58 -08003812 bool reconfig = false;
3813
Eric Laurent10351942014-05-08 18:49:52 -07003814 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003815
Eric Laurent10351942014-05-08 18:49:52 -07003816 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3817 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003818 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003819 FastMixerStateQueue *sq = mFastMixer->sq();
3820 FastMixerState *state = sq->begin();
3821 if (!(state->mCommand & FastMixerState::IDLE)) {
3822 previousCommand = state->mCommand;
3823 state->mCommand = FastMixerState::HOT_IDLE;
3824 sq->end();
3825 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3826 } else {
3827 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003828 }
Eric Laurent10351942014-05-08 18:49:52 -07003829 }
Eric Laurent81784c32012-11-19 14:55:58 -08003830
Eric Laurent10351942014-05-08 18:49:52 -07003831 AudioParameter param = AudioParameter(keyValuePair);
3832 int value;
3833 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3834 reconfig = true;
3835 }
3836 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003837 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003838 status = BAD_VALUE;
3839 } else {
3840 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003841 reconfig = true;
3842 }
Eric Laurent10351942014-05-08 18:49:52 -07003843 }
3844 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003845 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003846 status = BAD_VALUE;
3847 } else {
3848 // no need to save value, since it's constant
3849 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003850 }
Eric Laurent10351942014-05-08 18:49:52 -07003851 }
3852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3853 // do not accept frame count changes if tracks are open as the track buffer
3854 // size depends on frame count and correct behavior would not be guaranteed
3855 // if frame count is changed after track creation
3856 if (!mTracks.isEmpty()) {
3857 status = INVALID_OPERATION;
3858 } else {
3859 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003860 }
Eric Laurent10351942014-05-08 18:49:52 -07003861 }
3862 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003863#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003864 // when changing the audio output device, call addBatteryData to notify
3865 // the change
3866 if (mOutDevice != value) {
3867 uint32_t params = 0;
3868 // check whether speaker is on
3869 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3870 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003871 }
Eric Laurent10351942014-05-08 18:49:52 -07003872
3873 audio_devices_t deviceWithoutSpeaker
3874 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3875 // check if any other device (except speaker) is on
3876 if (value & deviceWithoutSpeaker ) {
3877 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3878 }
3879
3880 if (params != 0) {
3881 addBatteryData(params);
3882 }
3883 }
Eric Laurent81784c32012-11-19 14:55:58 -08003884#endif
3885
Eric Laurent10351942014-05-08 18:49:52 -07003886 // forward device change to effects that have requested to be
3887 // aware of attached audio device.
3888 if (value != AUDIO_DEVICE_NONE) {
3889 mOutDevice = value;
3890 for (size_t i = 0; i < mEffectChains.size(); i++) {
3891 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003892 }
3893 }
Eric Laurent10351942014-05-08 18:49:52 -07003894 }
Eric Laurent81784c32012-11-19 14:55:58 -08003895
Eric Laurent10351942014-05-08 18:49:52 -07003896 if (status == NO_ERROR) {
3897 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3898 keyValuePair.string());
3899 if (!mStandby && status == INVALID_OPERATION) {
3900 mOutput->stream->common.standby(&mOutput->stream->common);
3901 mStandby = true;
3902 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003904 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
Eric Laurent10351942014-05-08 18:49:52 -07003906 if (status == NO_ERROR && reconfig) {
3907 readOutputParameters_l();
3908 delete mAudioMixer;
3909 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3910 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003911 int name = getTrackName_l(mTracks[i]->mChannelMask,
3912 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003913 if (name < 0) {
3914 break;
3915 }
3916 mTracks[i]->mName = name;
3917 }
3918 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3919 }
Eric Laurent81784c32012-11-19 14:55:58 -08003920 }
3921
3922 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003923 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003924 FastMixerStateQueue *sq = mFastMixer->sq();
3925 FastMixerState *state = sq->begin();
3926 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3927 state->mCommand = previousCommand;
3928 sq->end();
3929 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3930 }
3931
3932 return reconfig;
3933}
3934
3935
3936void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3937{
3938 const size_t SIZE = 256;
3939 char buffer[SIZE];
3940 String8 result;
3941
3942 PlaybackThread::dumpInternals(fd, args);
3943
Elliott Hughes87cebad2014-05-22 10:14:43 -07003944 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003945
3946 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003947 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003948 copy.dump(fd);
3949
3950#ifdef STATE_QUEUE_DUMP
3951 // Similar for state queue
3952 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3953 observerCopy.dump(fd);
3954 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3955 mutatorCopy.dump(fd);
3956#endif
3957
Glenn Kasten46909e72013-02-26 09:20:22 -08003958#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003959 // Write the tee output to a .wav file
3960 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003961#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003962
3963#ifdef AUDIO_WATCHDOG
3964 if (mAudioWatchdog != 0) {
3965 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3966 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3967 wdCopy.dump(fd);
3968 }
3969#endif
3970}
3971
3972uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3973{
3974 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3975}
3976
3977uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3978{
3979 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3980}
3981
3982void AudioFlinger::MixerThread::cacheParameters_l()
3983{
3984 PlaybackThread::cacheParameters_l();
3985
3986 // FIXME: Relaxed timing because of a certain device that can't meet latency
3987 // Should be reduced to 2x after the vendor fixes the driver issue
3988 // increase threshold again due to low power audio mode. The way this warning
3989 // threshold is calculated and its usefulness should be reconsidered anyway.
3990 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3991}
3992
3993// ----------------------------------------------------------------------------
3994
3995AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3996 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3997 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3998 // mLeftVolFloat, mRightVolFloat
3999{
4000}
4001
Eric Laurentbfb1b832013-01-07 09:53:42 -08004002AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4003 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4004 ThreadBase::type_t type)
4005 : PlaybackThread(audioFlinger, output, id, device, type)
4006 // mLeftVolFloat, mRightVolFloat
4007{
4008}
4009
Eric Laurent81784c32012-11-19 14:55:58 -08004010AudioFlinger::DirectOutputThread::~DirectOutputThread()
4011{
4012}
4013
Eric Laurentbfb1b832013-01-07 09:53:42 -08004014void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4015{
4016 audio_track_cblk_t* cblk = track->cblk();
4017 float left, right;
4018
4019 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4020 left = right = 0;
4021 } else {
4022 float typeVolume = mStreamTypes[track->streamType()].volume;
4023 float v = mMasterVolume * typeVolume;
4024 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004025 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4026 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4027 if (left > GAIN_FLOAT_UNITY) {
4028 left = GAIN_FLOAT_UNITY;
4029 }
4030 left *= v;
4031 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4032 if (right > GAIN_FLOAT_UNITY) {
4033 right = GAIN_FLOAT_UNITY;
4034 }
4035 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036 }
4037
4038 if (lastTrack) {
4039 if (left != mLeftVolFloat || right != mRightVolFloat) {
4040 mLeftVolFloat = left;
4041 mRightVolFloat = right;
4042
4043 // Convert volumes from float to 8.24
4044 uint32_t vl = (uint32_t)(left * (1 << 24));
4045 uint32_t vr = (uint32_t)(right * (1 << 24));
4046
4047 // Delegate volume control to effect in track effect chain if needed
4048 // only one effect chain can be present on DirectOutputThread, so if
4049 // there is one, the track is connected to it
4050 if (!mEffectChains.isEmpty()) {
4051 mEffectChains[0]->setVolume_l(&vl, &vr);
4052 left = (float)vl / (1 << 24);
4053 right = (float)vr / (1 << 24);
4054 }
4055 if (mOutput->stream->set_volume) {
4056 mOutput->stream->set_volume(mOutput->stream, left, right);
4057 }
4058 }
4059 }
4060}
4061
4062
Eric Laurent81784c32012-11-19 14:55:58 -08004063AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4064 Vector< sp<Track> > *tracksToRemove
4065)
4066{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004067 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004068 mixer_state mixerStatus = MIXER_IDLE;
4069
4070 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004071 for (size_t i = 0; i < count; i++) {
4072 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004073 // The track died recently
4074 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004075 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004076 }
4077
4078 Track* const track = t.get();
4079 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004080 // Only consider last track started for volume and mixer state control.
4081 // In theory an older track could underrun and restart after the new one starts
4082 // but as we only care about the transition phase between two tracks on a
4083 // direct output, it is not a problem to ignore the underrun case.
4084 sp<Track> l = mLatestActiveTrack.promote();
4085 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004086
4087 // The first time a track is added we wait
4088 // for all its buffers to be filled before processing it
4089 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07004090 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004091 minFrames = mNormalFrameCount;
4092 } else {
4093 minFrames = 1;
4094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004095
Eric Laurentab5cdba2014-06-09 17:22:27 -07004096 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4097 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004098 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004099 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004100
4101 if (track->mFillingUpStatus == Track::FS_FILLED) {
4102 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004103 // make sure processVolume_l() will apply new volume even if 0
4104 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004105 if (track->mState == TrackBase::RESUMING) {
4106 track->mState = TrackBase::ACTIVE;
4107 }
4108 }
4109
4110 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004111 processVolume_l(track, last);
4112 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004113 // reset retry count
4114 track->mRetryCount = kMaxTrackRetriesDirect;
4115 mActiveTrack = t;
4116 mixerStatus = MIXER_TRACKS_READY;
4117 }
Eric Laurent81784c32012-11-19 14:55:58 -08004118 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004119 // clear effect chain input buffer if the last active track started underruns
4120 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004121 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004122 mEffectChains[0]->clearInputBuffer();
4123 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004124 if (track->isStopping_1()) {
4125 track->mState = TrackBase::STOPPING_2;
4126 }
4127 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4128 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004129 // We have consumed all the buffers of this track.
4130 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004131 size_t audioHALFrames;
4132 if (audio_is_linear_pcm(mFormat)) {
4133 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4134 } else {
4135 audioHALFrames = 0;
4136 }
4137
Eric Laurent81784c32012-11-19 14:55:58 -08004138 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004139 if (mStandby || !last ||
4140 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004141 if (track->isStopping_2()) {
4142 track->mState = TrackBase::STOPPED;
4143 }
Eric Laurent81784c32012-11-19 14:55:58 -08004144 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004145 if (track->mState == TrackBase::FLUSHED) {
4146 flushHw_l();
4147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148 track->reset();
4149 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004150 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 }
4152 } else {
4153 // No buffers for this track. Give it a few chances to
4154 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004155 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004156 if (--(track->mRetryCount) <= 0) {
4157 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004158 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004159 // indicate to client process that the track was disabled because of underrun;
4160 // it will then automatically call start() when data is available
4161 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004163 mixerStatus = MIXER_TRACKS_ENABLED;
4164 }
4165 }
4166 }
4167 }
4168
Eric Laurent81784c32012-11-19 14:55:58 -08004169 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004171
4172 return mixerStatus;
4173}
4174
4175void AudioFlinger::DirectOutputThread::threadLoop_mix()
4176{
Eric Laurent81784c32012-11-19 14:55:58 -08004177 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004178 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004179 // output audio to hardware
4180 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004181 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004182 buffer.frameCount = frameCount;
4183 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004184 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004185 memset(curBuf, 0, frameCount * mFrameSize);
4186 break;
4187 }
4188 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4189 frameCount -= buffer.frameCount;
4190 curBuf += buffer.frameCount * mFrameSize;
4191 mActiveTrack->releaseBuffer(&buffer);
4192 }
Andy Hung2098f272014-02-27 14:00:06 -08004193 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004194 sleepTime = 0;
4195 standbyTime = systemTime() + standbyDelay;
4196 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004197}
4198
4199void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4200{
4201 if (sleepTime == 0) {
4202 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4203 sleepTime = activeSleepTime;
4204 } else {
4205 sleepTime = idleSleepTime;
4206 }
4207 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004208 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004209 sleepTime = 0;
4210 }
4211}
4212
4213// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004214int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004215 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004216{
4217 return 0;
4218}
4219
4220// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004221void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004222{
4223}
4224
Eric Laurent10351942014-05-08 18:49:52 -07004225// checkForNewParameter_l() must be called with ThreadBase::mLock held
4226bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4227 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004228{
4229 bool reconfig = false;
4230
Eric Laurent10351942014-05-08 18:49:52 -07004231 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004232
Eric Laurent10351942014-05-08 18:49:52 -07004233 AudioParameter param = AudioParameter(keyValuePair);
4234 int value;
4235 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4236 // forward device change to effects that have requested to be
4237 // aware of attached audio device.
4238 if (value != AUDIO_DEVICE_NONE) {
4239 mOutDevice = value;
4240 for (size_t i = 0; i < mEffectChains.size(); i++) {
4241 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004242 }
4243 }
Eric Laurent81784c32012-11-19 14:55:58 -08004244 }
Eric Laurent10351942014-05-08 18:49:52 -07004245 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4246 // do not accept frame count changes if tracks are open as the track buffer
4247 // size depends on frame count and correct behavior would not be garantied
4248 // if frame count is changed after track creation
4249 if (!mTracks.isEmpty()) {
4250 status = INVALID_OPERATION;
4251 } else {
4252 reconfig = true;
4253 }
4254 }
4255 if (status == NO_ERROR) {
4256 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4257 keyValuePair.string());
4258 if (!mStandby && status == INVALID_OPERATION) {
4259 mOutput->stream->common.standby(&mOutput->stream->common);
4260 mStandby = true;
4261 mBytesWritten = 0;
4262 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4263 keyValuePair.string());
4264 }
4265 if (status == NO_ERROR && reconfig) {
4266 readOutputParameters_l();
4267 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4268 }
4269 }
4270
Eric Laurent81784c32012-11-19 14:55:58 -08004271 return reconfig;
4272}
4273
4274uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4275{
4276 uint32_t time;
4277 if (audio_is_linear_pcm(mFormat)) {
4278 time = PlaybackThread::activeSleepTimeUs();
4279 } else {
4280 time = 10000;
4281 }
4282 return time;
4283}
4284
4285uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4286{
4287 uint32_t time;
4288 if (audio_is_linear_pcm(mFormat)) {
4289 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4290 } else {
4291 time = 10000;
4292 }
4293 return time;
4294}
4295
4296uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4297{
4298 uint32_t time;
4299 if (audio_is_linear_pcm(mFormat)) {
4300 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4301 } else {
4302 time = 10000;
4303 }
4304 return time;
4305}
4306
4307void AudioFlinger::DirectOutputThread::cacheParameters_l()
4308{
4309 PlaybackThread::cacheParameters_l();
4310
4311 // use shorter standby delay as on normal output to release
4312 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004313 if (audio_is_linear_pcm(mFormat)) {
4314 standbyDelay = microseconds(activeSleepTime*2);
4315 } else {
4316 standbyDelay = kOffloadStandbyDelayNs;
4317 }
Eric Laurent81784c32012-11-19 14:55:58 -08004318}
4319
Eric Laurente659ef42014-09-29 13:06:46 -07004320void AudioFlinger::DirectOutputThread::flushHw_l()
4321{
4322 if (mOutput->stream->flush != NULL)
4323 mOutput->stream->flush(mOutput->stream);
4324}
4325
Eric Laurent81784c32012-11-19 14:55:58 -08004326// ----------------------------------------------------------------------------
4327
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004329 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004331 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004332 mWriteAckSequence(0),
4333 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004334{
4335}
4336
4337AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4338{
4339}
4340
4341void AudioFlinger::AsyncCallbackThread::onFirstRef()
4342{
4343 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4344}
4345
4346bool AudioFlinger::AsyncCallbackThread::threadLoop()
4347{
4348 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004349 uint32_t writeAckSequence;
4350 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351
4352 {
4353 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004354 while (!((mWriteAckSequence & 1) ||
4355 (mDrainSequence & 1) ||
4356 exitPending())) {
4357 mWaitWorkCV.wait(mLock);
4358 }
4359
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360 if (exitPending()) {
4361 break;
4362 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004363 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4364 mWriteAckSequence, mDrainSequence);
4365 writeAckSequence = mWriteAckSequence;
4366 mWriteAckSequence &= ~1;
4367 drainSequence = mDrainSequence;
4368 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004369 }
4370 {
Eric Laurent4de95592013-09-26 15:28:21 -07004371 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4372 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004373 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004374 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004376 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004377 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004378 }
4379 }
4380 }
4381 }
4382 return false;
4383}
4384
4385void AudioFlinger::AsyncCallbackThread::exit()
4386{
4387 ALOGV("AsyncCallbackThread::exit");
4388 Mutex::Autolock _l(mLock);
4389 requestExit();
4390 mWaitWorkCV.broadcast();
4391}
4392
Eric Laurent3b4529e2013-09-05 18:09:19 -07004393void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004394{
4395 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004396 // bit 0 is cleared
4397 mWriteAckSequence = sequence << 1;
4398}
4399
4400void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4401{
4402 Mutex::Autolock _l(mLock);
4403 // ignore unexpected callbacks
4404 if (mWriteAckSequence & 2) {
4405 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004406 mWaitWorkCV.signal();
4407 }
4408}
4409
Eric Laurent3b4529e2013-09-05 18:09:19 -07004410void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004411{
4412 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004413 // bit 0 is cleared
4414 mDrainSequence = sequence << 1;
4415}
4416
4417void AudioFlinger::AsyncCallbackThread::resetDraining()
4418{
4419 Mutex::Autolock _l(mLock);
4420 // ignore unexpected callbacks
4421 if (mDrainSequence & 2) {
4422 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004423 mWaitWorkCV.signal();
4424 }
4425}
4426
4427
4428// ----------------------------------------------------------------------------
4429AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4430 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4431 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4432 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004433 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004434 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004435{
Eric Laurentfd477972013-10-25 18:10:40 -07004436 //FIXME: mStandby should be set to true by ThreadBase constructor
4437 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004438}
4439
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440void AudioFlinger::OffloadThread::threadLoop_exit()
4441{
4442 if (mFlushPending || mHwPaused) {
4443 // If a flush is pending or track was paused, just discard buffered data
4444 flushHw_l();
4445 } else {
4446 mMixerStatus = MIXER_DRAIN_ALL;
4447 threadLoop_drain();
4448 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004449 if (mUseAsyncWrite) {
4450 ALOG_ASSERT(mCallbackThread != 0);
4451 mCallbackThread->exit();
4452 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004453 PlaybackThread::threadLoop_exit();
4454}
4455
4456AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4457 Vector< sp<Track> > *tracksToRemove
4458)
4459{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460 size_t count = mActiveTracks.size();
4461
4462 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004463 bool doHwPause = false;
4464 bool doHwResume = false;
4465
Eric Laurentede6c3b2013-09-19 14:37:46 -07004466 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4467
Eric Laurentbfb1b832013-01-07 09:53:42 -08004468 // find out which tracks need to be processed
4469 for (size_t i = 0; i < count; i++) {
4470 sp<Track> t = mActiveTracks[i].promote();
4471 // The track died recently
4472 if (t == 0) {
4473 continue;
4474 }
4475 Track* const track = t.get();
4476 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004477 // Only consider last track started for volume and mixer state control.
4478 // In theory an older track could underrun and restart after the new one starts
4479 // but as we only care about the transition phase between two tracks on a
4480 // direct output, it is not a problem to ignore the underrun case.
4481 sp<Track> l = mLatestActiveTrack.promote();
4482 bool last = l.get() == track;
4483
Haynes Mathew George7844f672014-01-15 12:32:55 -08004484 if (track->isInvalid()) {
4485 ALOGW("An invalidated track shouldn't be in active list");
4486 tracksToRemove->add(track);
4487 continue;
4488 }
4489
4490 if (track->mState == TrackBase::IDLE) {
4491 ALOGW("An idle track shouldn't be in active list");
4492 continue;
4493 }
4494
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 if (track->isPausing()) {
4496 track->setPaused();
4497 if (last) {
4498 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004499 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500 mHwPaused = true;
4501 }
4502 // If we were part way through writing the mixbuffer to
4503 // the HAL we must save this until we resume
4504 // BUG - this will be wrong if a different track is made active,
4505 // in that case we want to discard the pending data in the
4506 // mixbuffer and tell the client to present it again when the
4507 // track is resumed
4508 mPausedWriteLength = mCurrentWriteLength;
4509 mPausedBytesRemaining = mBytesRemaining;
4510 mBytesRemaining = 0; // stop writing
4511 }
4512 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004513 } else if (track->isFlushPending()) {
4514 track->flushAck();
4515 if (last) {
4516 mFlushPending = true;
4517 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004518 } else if (track->isResumePending()){
4519 track->resumeAck();
4520 if (last) {
4521 if (mPausedBytesRemaining) {
4522 // Need to continue write that was interrupted
4523 mCurrentWriteLength = mPausedWriteLength;
4524 mBytesRemaining = mPausedBytesRemaining;
4525 mPausedBytesRemaining = 0;
4526 }
4527 if (mHwPaused) {
4528 doHwResume = true;
4529 mHwPaused = false;
4530 // threadLoop_mix() will handle the case that we need to
4531 // resume an interrupted write
4532 }
4533 // enable write to audio HAL
4534 sleepTime = 0;
4535
4536 // Do not handle new data in this iteration even if track->framesReady()
4537 mixerStatus = MIXER_TRACKS_ENABLED;
4538 }
4539 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004540 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004541 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 if (track->mFillingUpStatus == Track::FS_FILLED) {
4543 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004544 // make sure processVolume_l() will apply new volume even if 0
4545 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004546 }
4547
4548 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004549 sp<Track> previousTrack = mPreviousTrack.promote();
4550 if (previousTrack != 0) {
4551 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004552 // Flush any data still being written from last track
4553 mBytesRemaining = 0;
4554 if (mPausedBytesRemaining) {
4555 // Last track was paused so we also need to flush saved
4556 // mixbuffer state and invalidate track so that it will
4557 // re-submit that unwritten data when it is next resumed
4558 mPausedBytesRemaining = 0;
4559 // Invalidate is a bit drastic - would be more efficient
4560 // to have a flag to tell client that some of the
4561 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004562 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004563 }
4564 // flush data already sent to the DSP if changing audio session as audio
4565 // comes from a different source. Also invalidate previous track to force a
4566 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004567 if (previousTrack->sessionId() != track->sessionId()) {
4568 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004569 }
4570 }
4571 }
4572 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573 // reset retry count
4574 track->mRetryCount = kMaxTrackRetriesOffload;
4575 mActiveTrack = t;
4576 mixerStatus = MIXER_TRACKS_READY;
4577 }
4578 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004579 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580 if (track->isStopping_1()) {
4581 // Hardware buffer can hold a large amount of audio so we must
4582 // wait for all current track's data to drain before we say
4583 // that the track is stopped.
4584 if (mBytesRemaining == 0) {
4585 // Only start draining when all data in mixbuffer
4586 // has been written
4587 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4588 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004589 // do not drain if no data was ever sent to HAL (mStandby == true)
4590 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004591 // do not modify drain sequence if we are already draining. This happens
4592 // when resuming from pause after drain.
4593 if ((mDrainSequence & 1) == 0) {
4594 sleepTime = 0;
4595 standbyTime = systemTime() + standbyDelay;
4596 mixerStatus = MIXER_DRAIN_TRACK;
4597 mDrainSequence += 2;
4598 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004599 if (mHwPaused) {
4600 // It is possible to move from PAUSED to STOPPING_1 without
4601 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004602 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603 mHwPaused = false;
4604 }
4605 }
4606 }
4607 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004608 // Drain has completed or we are in standby, signal presentation complete
4609 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610 track->mState = TrackBase::STOPPED;
4611 size_t audioHALFrames =
4612 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4613 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004614 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004615 track->presentationComplete(framesWritten, audioHALFrames);
4616 track->reset();
4617 tracksToRemove->add(track);
4618 }
4619 } else {
4620 // No buffers for this track. Give it a few chances to
4621 // fill a buffer, then remove it from active list.
4622 if (--(track->mRetryCount) <= 0) {
4623 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4624 track->name());
4625 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004626 // indicate to client process that the track was disabled because of underrun;
4627 // it will then automatically call start() when data is available
4628 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004629 } else if (last){
4630 mixerStatus = MIXER_TRACKS_ENABLED;
4631 }
4632 }
4633 }
4634 // compute volume for this track
4635 processVolume_l(track, last);
4636 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004637
Eric Laurentea0fade2013-10-04 16:23:48 -07004638 // make sure the pause/flush/resume sequence is executed in the right order.
4639 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4640 // before flush and then resume HW. This can happen in case of pause/flush/resume
4641 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004642 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004643 mOutput->stream->pause(mOutput->stream);
4644 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004645 if (mFlushPending) {
4646 flushHw_l();
4647 mFlushPending = false;
4648 }
Eric Laurentfd477972013-10-25 18:10:40 -07004649 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004650 mOutput->stream->resume(mOutput->stream);
4651 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004652
Eric Laurentbfb1b832013-01-07 09:53:42 -08004653 // remove all the tracks that need to be...
4654 removeTracks_l(*tracksToRemove);
4655
4656 return mixerStatus;
4657}
4658
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659// must be called with thread mutex locked
4660bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4661{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004662 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4663 mWriteAckSequence, mDrainSequence);
4664 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665 return true;
4666 }
4667 return false;
4668}
4669
4670// must be called with thread mutex locked
4671bool AudioFlinger::OffloadThread::shouldStandby_l()
4672{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004673 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004674
4675 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4676 // after a timeout and we will enter standby then.
4677 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004678 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004679 }
4680
Glenn Kastene6f35b12013-08-19 09:58:50 -07004681 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682}
4683
4684
4685bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4686{
4687 Mutex::Autolock _l(mLock);
4688 return waitingAsyncCallback_l();
4689}
4690
4691void AudioFlinger::OffloadThread::flushHw_l()
4692{
Eric Laurente659ef42014-09-29 13:06:46 -07004693 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004694 // Flush anything still waiting in the mixbuffer
4695 mCurrentWriteLength = 0;
4696 mBytesRemaining = 0;
4697 mPausedWriteLength = 0;
4698 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004699 mHwPaused = false;
4700
Eric Laurentbfb1b832013-01-07 09:53:42 -08004701 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004702 // discard any pending drain or write ack by incrementing sequence
4703 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4704 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004706 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4707 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 }
4709}
4710
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004711void AudioFlinger::OffloadThread::onAddNewTrack_l()
4712{
4713 sp<Track> previousTrack = mPreviousTrack.promote();
4714 sp<Track> latestTrack = mLatestActiveTrack.promote();
4715
4716 if (previousTrack != 0 && latestTrack != 0 &&
4717 (previousTrack->sessionId() != latestTrack->sessionId())) {
4718 mFlushPending = true;
4719 }
4720 PlaybackThread::onAddNewTrack_l();
4721}
4722
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723// ----------------------------------------------------------------------------
4724
Eric Laurent81784c32012-11-19 14:55:58 -08004725AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4726 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4727 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4728 DUPLICATING),
4729 mWaitTimeMs(UINT_MAX)
4730{
4731 addOutputTrack(mainThread);
4732}
4733
4734AudioFlinger::DuplicatingThread::~DuplicatingThread()
4735{
4736 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4737 mOutputTracks[i]->destroy();
4738 }
4739}
4740
4741void AudioFlinger::DuplicatingThread::threadLoop_mix()
4742{
4743 // mix buffers...
4744 if (outputsReady(outputTracks)) {
4745 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4746 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004747 if (mMixerBufferValid) {
4748 memset(mMixerBuffer, 0, mMixerBufferSize);
4749 } else {
4750 memset(mSinkBuffer, 0, mSinkBufferSize);
4751 }
Eric Laurent81784c32012-11-19 14:55:58 -08004752 }
4753 sleepTime = 0;
4754 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004755 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004756 standbyTime = systemTime() + standbyDelay;
4757}
4758
4759void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4760{
4761 if (sleepTime == 0) {
4762 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4763 sleepTime = activeSleepTime;
4764 } else {
4765 sleepTime = idleSleepTime;
4766 }
4767 } else if (mBytesWritten != 0) {
4768 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4769 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004770 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004771 } else {
4772 // flush remaining overflow buffers in output tracks
4773 writeFrames = 0;
4774 }
4775 sleepTime = 0;
4776 }
4777}
4778
Eric Laurentbfb1b832013-01-07 09:53:42 -08004779ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004780{
4781 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004782 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4783 // for delivery downstream as needed. This in-place conversion is safe as
4784 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4785 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4786 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4787 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4788 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4789 }
4790 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004791 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004792 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004793 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004794}
4795
4796void AudioFlinger::DuplicatingThread::threadLoop_standby()
4797{
4798 // DuplicatingThread implements standby by stopping all tracks
4799 for (size_t i = 0; i < outputTracks.size(); i++) {
4800 outputTracks[i]->stop();
4801 }
4802}
4803
4804void AudioFlinger::DuplicatingThread::saveOutputTracks()
4805{
4806 outputTracks = mOutputTracks;
4807}
4808
4809void AudioFlinger::DuplicatingThread::clearOutputTracks()
4810{
4811 outputTracks.clear();
4812}
4813
4814void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4815{
4816 Mutex::Autolock _l(mLock);
4817 // FIXME explain this formula
4818 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004819 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4820 // due to current usage case and restrictions on the AudioBufferProvider.
4821 // Actual buffer conversion is done in threadLoop_write().
4822 //
4823 // TODO: This may change in the future, depending on multichannel
4824 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004825 OutputTrack *outputTrack = new OutputTrack(thread,
4826 this,
4827 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004828 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004829 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004830 frameCount,
4831 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004832 if (outputTrack->cblk() != NULL) {
4833 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4834 mOutputTracks.add(outputTrack);
4835 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4836 updateWaitTime_l();
4837 }
4838}
4839
4840void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4841{
4842 Mutex::Autolock _l(mLock);
4843 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4844 if (mOutputTracks[i]->thread() == thread) {
4845 mOutputTracks[i]->destroy();
4846 mOutputTracks.removeAt(i);
4847 updateWaitTime_l();
4848 return;
4849 }
4850 }
4851 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4852}
4853
4854// caller must hold mLock
4855void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4856{
4857 mWaitTimeMs = UINT_MAX;
4858 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4859 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4860 if (strong != 0) {
4861 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4862 if (waitTimeMs < mWaitTimeMs) {
4863 mWaitTimeMs = waitTimeMs;
4864 }
4865 }
4866 }
4867}
4868
4869
4870bool AudioFlinger::DuplicatingThread::outputsReady(
4871 const SortedVector< sp<OutputTrack> > &outputTracks)
4872{
4873 for (size_t i = 0; i < outputTracks.size(); i++) {
4874 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4875 if (thread == 0) {
4876 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4877 outputTracks[i].get());
4878 return false;
4879 }
4880 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4881 // see note at standby() declaration
4882 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4883 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4884 thread.get());
4885 return false;
4886 }
4887 }
4888 return true;
4889}
4890
4891uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4892{
4893 return (mWaitTimeMs * 1000) / 2;
4894}
4895
4896void AudioFlinger::DuplicatingThread::cacheParameters_l()
4897{
4898 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4899 updateWaitTime_l();
4900
4901 MixerThread::cacheParameters_l();
4902}
4903
4904// ----------------------------------------------------------------------------
4905// Record
4906// ----------------------------------------------------------------------------
4907
4908AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4909 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004910 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004911 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004912 audio_devices_t inDevice
4913#ifdef TEE_SINK
4914 , const sp<NBAIO_Sink>& teeSink
4915#endif
4916 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004917 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004918 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004919 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004920 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004921#ifdef TEE_SINK
4922 , mTeeSink(teeSink)
4923#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004924 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4925 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004926 // mFastCapture below
4927 , mFastCaptureFutex(0)
4928 // mInputSource
4929 // mPipeSink
4930 // mPipeSource
4931 , mPipeFramesP2(0)
4932 // mPipeMemory
4933 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004934 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004935{
4936 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004937 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004938
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004939 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004940
4941 // create an NBAIO source for the HAL input stream, and negotiate
4942 mInputSource = new AudioStreamInSource(input->stream);
4943 size_t numCounterOffers = 0;
4944 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4945 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4946 ALOG_ASSERT(index == 0);
4947
4948 // initialize fast capture depending on configuration
4949 bool initFastCapture;
4950 switch (kUseFastCapture) {
4951 case FastCapture_Never:
4952 initFastCapture = false;
4953 break;
4954 case FastCapture_Always:
4955 initFastCapture = true;
4956 break;
4957 case FastCapture_Static:
4958 uint32_t primaryOutputSampleRate;
4959 {
4960 AutoMutex _l(audioFlinger->mHardwareLock);
4961 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4962 }
4963 initFastCapture =
4964 // either capture sample rate is same as (a reasonable) primary output sample rate
4965 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4966 (mSampleRate == primaryOutputSampleRate)) ||
4967 // or primary output sample rate is unknown, and capture sample rate is reasonable
4968 ((primaryOutputSampleRate == 0) &&
4969 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004970 // and the buffer size is < 12 ms
4971 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004972 break;
4973 // case FastCapture_Dynamic:
4974 }
4975
4976 if (initFastCapture) {
4977 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4978 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004979 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004980 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4981 void *pipeBuffer;
4982 const sp<MemoryDealer> roHeap(readOnlyHeap());
4983 sp<IMemory> pipeMemory;
4984 if ((roHeap == 0) ||
4985 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4986 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4987 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4988 goto failed;
4989 }
4990 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4991 memset(pipeBuffer, 0, pipeSize);
4992 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4993 const NBAIO_Format offers[1] = {format};
4994 size_t numCounterOffers = 0;
4995 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4996 ALOG_ASSERT(index == 0);
4997 mPipeSink = pipe;
4998 PipeReader *pipeReader = new PipeReader(*pipe);
4999 numCounterOffers = 0;
5000 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5001 ALOG_ASSERT(index == 0);
5002 mPipeSource = pipeReader;
5003 mPipeFramesP2 = pipeFramesP2;
5004 mPipeMemory = pipeMemory;
5005
5006 // create fast capture
5007 mFastCapture = new FastCapture();
5008 FastCaptureStateQueue *sq = mFastCapture->sq();
5009#ifdef STATE_QUEUE_DUMP
5010 // FIXME
5011#endif
5012 FastCaptureState *state = sq->begin();
5013 state->mCblk = NULL;
5014 state->mInputSource = mInputSource.get();
5015 state->mInputSourceGen++;
5016 state->mPipeSink = pipe;
5017 state->mPipeSinkGen++;
5018 state->mFrameCount = mFrameCount;
5019 state->mCommand = FastCaptureState::COLD_IDLE;
5020 // already done in constructor initialization list
5021 //mFastCaptureFutex = 0;
5022 state->mColdFutexAddr = &mFastCaptureFutex;
5023 state->mColdGen++;
5024 state->mDumpState = &mFastCaptureDumpState;
5025#ifdef TEE_SINK
5026 // FIXME
5027#endif
5028 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5029 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5030 sq->end();
5031 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5032
5033 // start the fast capture
5034 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5035 pid_t tid = mFastCapture->getTid();
5036 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5037 if (err != 0) {
5038 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5039 kPriorityFastCapture, getpid_cached, tid, err);
5040 }
5041
5042#ifdef AUDIO_WATCHDOG
5043 // FIXME
5044#endif
5045
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005046 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005047 }
5048failed: ;
5049
5050 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005051}
5052
5053
5054AudioFlinger::RecordThread::~RecordThread()
5055{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005056 if (mFastCapture != 0) {
5057 FastCaptureStateQueue *sq = mFastCapture->sq();
5058 FastCaptureState *state = sq->begin();
5059 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5060 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5061 if (old == -1) {
5062 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5063 }
5064 }
5065 state->mCommand = FastCaptureState::EXIT;
5066 sq->end();
5067 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5068 mFastCapture->join();
5069 mFastCapture.clear();
5070 }
5071 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005072 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005073 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005074}
5075
5076void AudioFlinger::RecordThread::onFirstRef()
5077{
5078 run(mName, PRIORITY_URGENT_AUDIO);
5079}
5080
Eric Laurent81784c32012-11-19 14:55:58 -08005081bool AudioFlinger::RecordThread::threadLoop()
5082{
Eric Laurent81784c32012-11-19 14:55:58 -08005083 nsecs_t lastWarning = 0;
5084
5085 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005086
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005087reacquire_wakelock:
5088 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005089 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005090 {
5091 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005092 size_t size = mActiveTracks.size();
5093 activeTracksGen = mActiveTracksGen;
5094 if (size > 0) {
5095 // FIXME an arbitrary choice
5096 activeTrack = mActiveTracks[0];
5097 acquireWakeLock_l(activeTrack->uid());
5098 if (size > 1) {
5099 SortedVector<int> tmp;
5100 for (size_t i = 0; i < size; i++) {
5101 tmp.add(mActiveTracks[i]->uid());
5102 }
5103 updateWakeLockUids_l(tmp);
5104 }
5105 } else {
5106 acquireWakeLock_l(-1);
5107 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005108 }
5109
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005110 // used to request a deferred sleep, to be executed later while mutex is unlocked
5111 uint32_t sleepUs = 0;
5112
5113 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005114 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005115 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005116
Glenn Kasten5edadd42013-08-14 16:30:49 -07005117 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005118 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005119 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005120 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005121 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005122 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005123 }
5124
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005125 // activeTracks accumulates a copy of a subset of mActiveTracks
5126 Vector< sp<RecordTrack> > activeTracks;
5127
Glenn Kasten735f45f2014-08-18 15:51:59 -07005128 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005129 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005130
Glenn Kasten735f45f2014-08-18 15:51:59 -07005131 // reference to a fast track which is about to be removed
5132 sp<RecordTrack> fastTrackToRemove;
5133
Eric Laurent81784c32012-11-19 14:55:58 -08005134 { // scope for mLock
5135 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005136
Eric Laurent021cf962014-05-13 10:18:14 -07005137 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005138
Eric Laurent000a4192014-01-29 15:17:32 -08005139 // check exitPending here because checkForNewParameters_l() and
5140 // checkForNewParameters_l() can temporarily release mLock
5141 if (exitPending()) {
5142 break;
5143 }
5144
Glenn Kasten2b806402013-11-20 16:37:38 -08005145 // if no active track(s), then standby and release wakelock
5146 size_t size = mActiveTracks.size();
5147 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005148 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005149 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005150 releaseWakeLock_l();
5151 ALOGV("RecordThread: loop stopping");
5152 // go to sleep
5153 mWaitWorkCV.wait(mLock);
5154 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005155 goto reacquire_wakelock;
5156 }
5157
Glenn Kasten2b806402013-11-20 16:37:38 -08005158 if (mActiveTracksGen != activeTracksGen) {
5159 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005160 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005161 for (size_t i = 0; i < size; i++) {
5162 tmp.add(mActiveTracks[i]->uid());
5163 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005164 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005165 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005166
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005167 bool doBroadcast = false;
5168 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005170 activeTrack = mActiveTracks[i];
5171 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005172 if (activeTrack->isFastTrack()) {
5173 ALOG_ASSERT(fastTrackToRemove == 0);
5174 fastTrackToRemove = activeTrack;
5175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005176 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005177 mActiveTracks.remove(activeTrack);
5178 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005179 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005180 continue;
5181 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005182
5183 TrackBase::track_state activeTrackState = activeTrack->mState;
5184 switch (activeTrackState) {
5185
5186 case TrackBase::PAUSING:
5187 mActiveTracks.remove(activeTrack);
5188 mActiveTracksGen++;
5189 doBroadcast = true;
5190 size--;
5191 continue;
5192
5193 case TrackBase::STARTING_1:
5194 sleepUs = 10000;
5195 i++;
5196 continue;
5197
5198 case TrackBase::STARTING_2:
5199 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005200 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005201 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005202 break;
5203
5204 case TrackBase::ACTIVE:
5205 break;
5206
5207 case TrackBase::IDLE:
5208 i++;
5209 continue;
5210
5211 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005212 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005213 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005214
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005215 activeTracks.add(activeTrack);
5216 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005217
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005218 if (activeTrack->isFastTrack()) {
5219 ALOG_ASSERT(!mFastTrackAvail);
5220 ALOG_ASSERT(fastTrack == 0);
5221 fastTrack = activeTrack;
5222 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005223 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005224 if (doBroadcast) {
5225 mStartStopCond.broadcast();
5226 }
5227
5228 // sleep if there are no active tracks to process
5229 if (activeTracks.size() == 0) {
5230 if (sleepUs == 0) {
5231 sleepUs = kRecordThreadSleepUs;
5232 }
5233 continue;
5234 }
5235 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005236
Eric Laurent81784c32012-11-19 14:55:58 -08005237 lockEffectChains_l(effectChains);
5238 }
5239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005240 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005241
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005242 size_t size = effectChains.size();
5243 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005244 // thread mutex is not locked, but effect chain is locked
5245 effectChains[i]->process_l();
5246 }
5247
Glenn Kasten735f45f2014-08-18 15:51:59 -07005248 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005249 if (mFastCapture != 0) {
5250 FastCaptureStateQueue *sq = mFastCapture->sq();
5251 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005252 bool didModify = false;
5253 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005254 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5255 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5256 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5257 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5258 if (old == -1) {
5259 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5260 }
5261 }
5262 state->mCommand = FastCaptureState::READ_WRITE;
5263#if 0 // FIXME
5264 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5265 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5266#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005267 didModify = true;
5268 }
5269 audio_track_cblk_t *cblkOld = state->mCblk;
5270 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5271 if (cblkNew != cblkOld) {
5272 state->mCblk = cblkNew;
5273 // block until acked if removing a fast track
5274 if (cblkOld != NULL) {
5275 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5276 }
5277 didModify = true;
5278 }
5279 sq->end(didModify);
5280 if (didModify) {
5281 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005282#if 0
5283 if (kUseFastCapture == FastCapture_Dynamic) {
5284 mNormalSource = mPipeSource;
5285 }
5286#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005287 }
5288 }
5289
Glenn Kasten735f45f2014-08-18 15:51:59 -07005290 // now run the fast track destructor with thread mutex unlocked
5291 fastTrackToRemove.clear();
5292
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005293 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5294 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5295 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5296 // If destination is non-contiguous, first read past the nominal end of buffer, then
5297 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005298
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005299 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005300 ssize_t framesRead;
5301
5302 // If an NBAIO source is present, use it to read the normal capture's data
5303 if (mPipeSource != 0) {
5304 size_t framesToRead = mBufferSize / mFrameSize;
5305 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5306 framesToRead, AudioBufferProvider::kInvalidPTS);
5307 if (framesRead == 0) {
5308 // since pipe is non-blocking, simulate blocking input
5309 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5310 }
5311 // otherwise use the HAL / AudioStreamIn directly
5312 } else {
5313 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5314 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5315 if (bytesRead < 0) {
5316 framesRead = bytesRead;
5317 } else {
5318 framesRead = bytesRead / mFrameSize;
5319 }
5320 }
5321
5322 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5323 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005324 // Force input into standby so that it tries to recover at next read attempt
5325 inputStandBy();
5326 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005327 }
5328 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005329 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005330 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005331 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005332
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005333 if (mTeeSink != 0) {
5334 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5335 }
5336 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005337 {
5338 size_t part1 = mRsmpInFramesP2 - rear;
5339 if ((size_t) framesRead > part1) {
5340 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5341 (framesRead - part1) * mFrameSize);
5342 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005343 }
5344 rear = mRsmpInRear += framesRead;
5345
5346 size = activeTracks.size();
5347 // loop over each active track
5348 for (size_t i = 0; i < size; i++) {
5349 activeTrack = activeTracks[i];
5350
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005351 // skip fast tracks, as those are handled directly by FastCapture
5352 if (activeTrack->isFastTrack()) {
5353 continue;
5354 }
5355
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005356 enum {
5357 OVERRUN_UNKNOWN,
5358 OVERRUN_TRUE,
5359 OVERRUN_FALSE
5360 } overrun = OVERRUN_UNKNOWN;
5361
5362 // loop over getNextBuffer to handle circular sink
5363 for (;;) {
5364
5365 activeTrack->mSink.frameCount = ~0;
5366 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5367 size_t framesOut = activeTrack->mSink.frameCount;
5368 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5369
5370 int32_t front = activeTrack->mRsmpInFront;
5371 ssize_t filled = rear - front;
5372 size_t framesIn;
5373
5374 if (filled < 0) {
5375 // should not happen, but treat like a massive overrun and re-sync
5376 framesIn = 0;
5377 activeTrack->mRsmpInFront = rear;
5378 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005379 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005380 framesIn = (size_t) filled;
5381 } else {
5382 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005383 framesIn = mRsmpInFrames;
5384 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005385 overrun = OVERRUN_TRUE;
5386 }
5387
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005388 if (framesOut == 0 || framesIn == 0) {
5389 break;
5390 }
5391
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005392 if (activeTrack->mResampler == NULL) {
5393 // no resampling
5394 if (framesIn > framesOut) {
5395 framesIn = framesOut;
5396 } else {
5397 framesOut = framesIn;
5398 }
5399 int8_t *dst = activeTrack->mSink.i8;
5400 while (framesIn > 0) {
5401 front &= mRsmpInFramesP2 - 1;
5402 size_t part1 = mRsmpInFramesP2 - front;
5403 if (part1 > framesIn) {
5404 part1 = framesIn;
5405 }
5406 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005407 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005408 memcpy(dst, src, part1 * mFrameSize);
5409 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005410 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005411 part1);
5412 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005413 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005414 part1);
5415 }
5416 dst += part1 * activeTrack->mFrameSize;
5417 front += part1;
5418 framesIn -= part1;
5419 }
5420 activeTrack->mRsmpInFront += framesOut;
5421
5422 } else {
5423 // resampling
5424 // FIXME framesInNeeded should really be part of resampler API, and should
5425 // depend on the SRC ratio
5426 // to keep mRsmpInBuffer full so resampler always has sufficient input
5427 size_t framesInNeeded;
5428 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005429 // Do not precompute in/out because floating point is not associative
5430 // e.g. a*b/c != a*(b/c).
5431 const double in(mSampleRate);
5432 const double out(activeTrack->mSampleRate);
5433 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005434 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005435 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005436 // Although we theoretically have framesIn in circular buffer, some of those are
5437 // unreleased frames, and thus must be discounted for purpose of budgeting.
5438 size_t unreleased = activeTrack->mRsmpInUnrel;
5439 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005440 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005441 ALOGV("not enough to resample: have %u frames in but need %u in to "
5442 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005443 framesIn, framesInNeeded, framesOut, in / out);
5444 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005445 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5446 if (newFramesOut == 0) {
5447 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005448 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005449 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005450 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005451 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005452 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5453 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5454 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005455 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005456 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005457 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005458 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005459 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005460 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005461 }
5462
5463 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5464 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005465 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005466 delete[] activeTrack->mRsmpOutBuffer;
5467 // resampler always outputs stereo
5468 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5469 activeTrack->mRsmpOutFrameCount = framesOut;
5470 }
5471
5472 // resampler accumulates, but we only have one source track
5473 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5474 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005475 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005476 activeTrack->mResamplerBufferProvider
5477 /*this*/ /* AudioBufferProvider* */);
5478 // ditherAndClamp() works as long as all buffers returned by
5479 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005480 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005481 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005482 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5483 framesOut);
5484 // the resampler always outputs stereo samples:
5485 // do post stereo to mono conversion
5486 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005487 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005488 } else {
5489 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5490 activeTrack->mRsmpOutBuffer, framesOut);
5491 }
5492 // now done with mRsmpOutBuffer
5493
5494 }
5495
5496 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5497 overrun = OVERRUN_FALSE;
5498 }
5499
5500 if (activeTrack->mFramesToDrop == 0) {
5501 if (framesOut > 0) {
5502 activeTrack->mSink.frameCount = framesOut;
5503 activeTrack->releaseBuffer(&activeTrack->mSink);
5504 }
5505 } else {
5506 // FIXME could do a partial drop of framesOut
5507 if (activeTrack->mFramesToDrop > 0) {
5508 activeTrack->mFramesToDrop -= framesOut;
5509 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005510 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005511 }
5512 } else {
5513 activeTrack->mFramesToDrop += framesOut;
5514 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5515 activeTrack->mSyncStartEvent->isCancelled()) {
5516 ALOGW("Synced record %s, session %d, trigger session %d",
5517 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5518 activeTrack->sessionId(),
5519 (activeTrack->mSyncStartEvent != 0) ?
5520 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005521 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005522 }
5523 }
5524 }
5525
5526 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005527 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005528 }
5529 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005530
5531 switch (overrun) {
5532 case OVERRUN_TRUE:
5533 // client isn't retrieving buffers fast enough
5534 if (!activeTrack->setOverflow()) {
5535 nsecs_t now = systemTime();
5536 // FIXME should lastWarning per track?
5537 if ((now - lastWarning) > kWarningThrottleNs) {
5538 ALOGW("RecordThread: buffer overflow");
5539 lastWarning = now;
5540 }
5541 }
5542 break;
5543 case OVERRUN_FALSE:
5544 activeTrack->clearOverflow();
5545 break;
5546 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005547 break;
5548 }
5549
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005550 }
5551
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005552unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005553 // enable changes in effect chain
5554 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005555 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005556 }
5557
Glenn Kasten93e471f2013-08-19 08:40:07 -07005558 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005559
5560 {
5561 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005562 for (size_t i = 0; i < mTracks.size(); i++) {
5563 sp<RecordTrack> track = mTracks[i];
5564 track->invalidate();
5565 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005566 mActiveTracks.clear();
5567 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005568 mStartStopCond.broadcast();
5569 }
5570
5571 releaseWakeLock();
5572
5573 ALOGV("RecordThread %p exiting", this);
5574 return false;
5575}
5576
Glenn Kasten93e471f2013-08-19 08:40:07 -07005577void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005578{
5579 if (!mStandby) {
5580 inputStandBy();
5581 mStandby = true;
5582 }
5583}
5584
5585void AudioFlinger::RecordThread::inputStandBy()
5586{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005587 // Idle the fast capture if it's currently running
5588 if (mFastCapture != 0) {
5589 FastCaptureStateQueue *sq = mFastCapture->sq();
5590 FastCaptureState *state = sq->begin();
5591 if (!(state->mCommand & FastCaptureState::IDLE)) {
5592 state->mCommand = FastCaptureState::COLD_IDLE;
5593 state->mColdFutexAddr = &mFastCaptureFutex;
5594 state->mColdGen++;
5595 mFastCaptureFutex = 0;
5596 sq->end();
5597 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5598 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5599#if 0
5600 if (kUseFastCapture == FastCapture_Dynamic) {
5601 // FIXME
5602 }
5603#endif
5604#ifdef AUDIO_WATCHDOG
5605 // FIXME
5606#endif
5607 } else {
5608 sq->end(false /*didModify*/);
5609 }
5610 }
Eric Laurent81784c32012-11-19 14:55:58 -08005611 mInput->stream->common.standby(&mInput->stream->common);
5612}
5613
Glenn Kasten05997e22014-03-13 15:08:33 -07005614// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005615sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005616 const sp<AudioFlinger::Client>& client,
5617 uint32_t sampleRate,
5618 audio_format_t format,
5619 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005620 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005621 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005622 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005623 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005624 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005625 pid_t tid,
5626 status_t *status)
5627{
Glenn Kasten74935e42013-12-19 08:56:45 -08005628 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005629 sp<RecordTrack> track;
5630 status_t lStatus;
5631
Glenn Kasten90e58b12013-07-31 16:16:02 -07005632 // client expresses a preference for FAST, but we get the final say
5633 if (*flags & IAudioFlinger::TRACK_FAST) {
5634 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005635 // use case: callback handler
5636 (tid != -1) &&
5637 // frame count is not specified, or is exactly the pipe depth
5638 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005639 // PCM data
5640 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005641 // native format
5642 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005643 // native channel mask
5644 (channelMask == mChannelMask) &&
5645 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005646 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005647 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005648 hasFastCapture() &&
5649 // there are sufficient fast track slots available
5650 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005651 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005652 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005653 frameCount, mFrameCount);
5654 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005655 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5656 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005657 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005658 frameCount, mFrameCount, mPipeFramesP2,
5659 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5660 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005661 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005662 }
5663 }
5664
5665 // compute track buffer size in frames, and suggest the notification frame count
5666 if (*flags & IAudioFlinger::TRACK_FAST) {
5667 // fast track: frame count is exactly the pipe depth
5668 frameCount = mPipeFramesP2;
5669 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5670 *notificationFrames = mFrameCount;
5671 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005672 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5673 // or 20 ms if there is a fast capture
5674 // TODO This could be a roundupRatio inline, and const
5675 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5676 * sampleRate + mSampleRate - 1) / mSampleRate;
5677 // minimum number of notification periods is at least kMinNotifications,
5678 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5679 static const size_t kMinNotifications = 3;
5680 static const uint32_t kMinMs = 30;
5681 // TODO This could be a roundupRatio inline
5682 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5683 // TODO This could be a roundupRatio inline
5684 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5685 maxNotificationFrames;
5686 const size_t minFrameCount = maxNotificationFrames *
5687 max(kMinNotifications, minNotificationsByMs);
5688 frameCount = max(frameCount, minFrameCount);
5689 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5690 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005691 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005692 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005693 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005694
Glenn Kasten15e57982013-09-24 11:52:37 -07005695 lStatus = initCheck();
5696 if (lStatus != NO_ERROR) {
5697 ALOGE("createRecordTrack_l() audio driver not initialized");
5698 goto Exit;
5699 }
Eric Laurent81784c32012-11-19 14:55:58 -08005700
5701 { // scope for mLock
5702 Mutex::Autolock _l(mLock);
5703
5704 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005705 format, channelMask, frameCount, NULL, sessionId, uid,
5706 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005707
Glenn Kasten03003332013-08-06 15:40:54 -07005708 lStatus = track->initCheck();
5709 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005710 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005711 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005712 goto Exit;
5713 }
5714 mTracks.add(track);
5715
5716 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5717 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5718 mAudioFlinger->btNrecIsOff();
5719 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5720 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005721
5722 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5723 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5724 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5725 // so ask activity manager to do this on our behalf
5726 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5727 }
Eric Laurent81784c32012-11-19 14:55:58 -08005728 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005729
Eric Laurent81784c32012-11-19 14:55:58 -08005730 lStatus = NO_ERROR;
5731
5732Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005733 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005734 return track;
5735}
5736
5737status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5738 AudioSystem::sync_event_t event,
5739 int triggerSession)
5740{
5741 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5742 sp<ThreadBase> strongMe = this;
5743 status_t status = NO_ERROR;
5744
5745 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005746 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005747 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005748 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005749 triggerSession,
5750 recordTrack->sessionId(),
5751 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005752 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005753 // Sync event can be cancelled by the trigger session if the track is not in a
5754 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005756 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005757 } else {
5758 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005759 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005760 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005761 }
5762 }
5763
5764 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005765 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005766 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005767 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5768 if (recordTrack->mState == TrackBase::PAUSING) {
5769 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005770 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005771 } else {
5772 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005773 }
5774 return status;
5775 }
5776
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005777 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5778 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5779 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005781 mActiveTracks.add(recordTrack);
5782 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005783 status_t status = NO_ERROR;
5784 if (recordTrack->isExternalTrack()) {
5785 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005786 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005787 mLock.lock();
5788 // FIXME should verify that recordTrack is still in mActiveTracks
5789 if (status != NO_ERROR) {
5790 mActiveTracks.remove(recordTrack);
5791 mActiveTracksGen++;
5792 recordTrack->clearSyncStartEvent();
5793 ALOGV("RecordThread::start error %d", status);
5794 return status;
5795 }
Eric Laurent81784c32012-11-19 14:55:58 -08005796 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005797 // Catch up with current buffer indices if thread is already running.
5798 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5799 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5800 // see previously buffered data before it called start(), but with greater risk of overrun.
5801
5802 recordTrack->mRsmpInFront = mRsmpInRear;
5803 recordTrack->mRsmpInUnrel = 0;
5804 // FIXME why reset?
5805 if (recordTrack->mResampler != NULL) {
5806 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005807 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005808 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005809 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005810 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005811 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005812 ALOGV("Record failed to start");
5813 status = BAD_VALUE;
5814 goto startError;
5815 }
Eric Laurent81784c32012-11-19 14:55:58 -08005816 return status;
5817 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005818
Eric Laurent81784c32012-11-19 14:55:58 -08005819startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005820 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005821 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005822 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005823 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005824 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005825 return status;
5826}
5827
Eric Laurent81784c32012-11-19 14:55:58 -08005828void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5829{
5830 sp<SyncEvent> strongEvent = event.promote();
5831
5832 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005833 sp<RefBase> ptr = strongEvent->cookie().promote();
5834 if (ptr != 0) {
5835 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5836 recordTrack->handleSyncStartEvent(strongEvent);
5837 }
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
5839}
5840
Glenn Kastena8356f62013-07-25 14:37:52 -07005841bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005842 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005843 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005844 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005845 return false;
5846 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005847 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005848 recordTrack->mState = TrackBase::PAUSING;
5849 // do not wait for mStartStopCond if exiting
5850 if (exitPending()) {
5851 return true;
5852 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005853 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005854 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005855 // if we have been restarted, recordTrack is in mActiveTracks here
5856 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005857 ALOGV("Record stopped OK");
5858 return true;
5859 }
5860 return false;
5861}
5862
Glenn Kasten0f11b512014-01-31 16:18:54 -08005863bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005864{
5865 return false;
5866}
5867
Glenn Kasten0f11b512014-01-31 16:18:54 -08005868status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005869{
5870#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5871 if (!isValidSyncEvent(event)) {
5872 return BAD_VALUE;
5873 }
5874
5875 int eventSession = event->triggerSession();
5876 status_t ret = NAME_NOT_FOUND;
5877
5878 Mutex::Autolock _l(mLock);
5879
5880 for (size_t i = 0; i < mTracks.size(); i++) {
5881 sp<RecordTrack> track = mTracks[i];
5882 if (eventSession == track->sessionId()) {
5883 (void) track->setSyncEvent(event);
5884 ret = NO_ERROR;
5885 }
5886 }
5887 return ret;
5888#else
5889 return BAD_VALUE;
5890#endif
5891}
5892
5893// destroyTrack_l() must be called with ThreadBase::mLock held
5894void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5895{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005896 track->terminate();
5897 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005898 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005899 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005900 removeTrack_l(track);
5901 }
5902}
5903
5904void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5905{
5906 mTracks.remove(track);
5907 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005908 if (track->isFastTrack()) {
5909 ALOG_ASSERT(!mFastTrackAvail);
5910 mFastTrackAvail = true;
5911 }
Eric Laurent81784c32012-11-19 14:55:58 -08005912}
5913
5914void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5915{
5916 dumpInternals(fd, args);
5917 dumpTracks(fd, args);
5918 dumpEffectChains(fd, args);
5919}
5920
5921void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5922{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005923 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005924
Glenn Kasten2b806402013-11-20 16:37:38 -08005925 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005926 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005927 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005928 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005930 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005932
Eric Laurent81784c32012-11-19 14:55:58 -08005933 dumpBase(fd, args);
5934}
5935
Glenn Kasten0f11b512014-01-31 16:18:54 -08005936void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005937{
5938 const size_t SIZE = 256;
5939 char buffer[SIZE];
5940 String8 result;
5941
Marco Nelissenb2208842014-02-07 14:00:50 -08005942 size_t numtracks = mTracks.size();
5943 size_t numactive = mActiveTracks.size();
5944 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005945 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005946 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005947 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005948 RecordTrack::appendDumpHeader(result);
5949 for (size_t i = 0; i < numtracks ; ++i) {
5950 sp<RecordTrack> track = mTracks[i];
5951 if (track != 0) {
5952 bool active = mActiveTracks.indexOf(track) >= 0;
5953 if (active) {
5954 numactiveseen++;
5955 }
5956 track->dump(buffer, SIZE, active);
5957 result.append(buffer);
5958 }
Eric Laurent81784c32012-11-19 14:55:58 -08005959 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005960 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005961 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005962 }
5963
Marco Nelissenb2208842014-02-07 14:00:50 -08005964 if (numactiveseen != numactive) {
5965 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5966 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005967 result.append(buffer);
5968 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005969 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005970 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005971 if (mTracks.indexOf(track) < 0) {
5972 track->dump(buffer, SIZE, true);
5973 result.append(buffer);
5974 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005975 }
Eric Laurent81784c32012-11-19 14:55:58 -08005976
5977 }
5978 write(fd, result.string(), result.size());
5979}
5980
5981// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5983 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005984{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005985 RecordTrack *activeTrack = mRecordTrack;
5986 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5987 if (threadBase == 0) {
5988 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005989 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005990 return NOT_ENOUGH_DATA;
5991 }
5992 RecordThread *recordThread = (RecordThread *) threadBase.get();
5993 int32_t rear = recordThread->mRsmpInRear;
5994 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005995 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996 // FIXME should not be P2 (don't want to increase latency)
5997 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005998 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005999 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006000 front &= recordThread->mRsmpInFramesP2 - 1;
6001 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006002 if (part1 > (size_t) filled) {
6003 part1 = filled;
6004 }
6005 size_t ask = buffer->frameCount;
6006 ALOG_ASSERT(ask > 0);
6007 if (part1 > ask) {
6008 part1 = ask;
6009 }
6010 if (part1 == 0) {
6011 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006012 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006013 buffer->raw = NULL;
6014 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006015 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006016 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
6018
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006019 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006020 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006021 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006022 return NO_ERROR;
6023}
6024
6025// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6027 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006028{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006030 size_t stepCount = buffer->frameCount;
6031 if (stepCount == 0) {
6032 return;
6033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6035 activeTrack->mRsmpInUnrel -= stepCount;
6036 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006037 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006038 buffer->frameCount = 0;
6039}
6040
Eric Laurent10351942014-05-08 18:49:52 -07006041bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6042 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006043{
6044 bool reconfig = false;
6045
Eric Laurent10351942014-05-08 18:49:52 -07006046 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006047
Eric Laurent10351942014-05-08 18:49:52 -07006048 audio_format_t reqFormat = mFormat;
6049 uint32_t samplingRate = mSampleRate;
6050 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6051
6052 AudioParameter param = AudioParameter(keyValuePair);
6053 int value;
6054 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6055 // channel count change can be requested. Do we mandate the first client defines the
6056 // HAL sampling rate and channel count or do we allow changes on the fly?
6057 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6058 samplingRate = value;
6059 reconfig = true;
6060 }
6061 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6062 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6063 status = BAD_VALUE;
6064 } else {
6065 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006066 reconfig = true;
6067 }
Eric Laurent10351942014-05-08 18:49:52 -07006068 }
6069 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6070 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6071 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6072 status = BAD_VALUE;
6073 } else {
6074 channelMask = mask;
6075 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006076 }
Eric Laurent10351942014-05-08 18:49:52 -07006077 }
6078 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6079 // do not accept frame count changes if tracks are open as the track buffer
6080 // size depends on frame count and correct behavior would not be guaranteed
6081 // if frame count is changed after track creation
6082 if (mActiveTracks.size() > 0) {
6083 status = INVALID_OPERATION;
6084 } else {
6085 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
Eric Laurent10351942014-05-08 18:49:52 -07006087 }
6088 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6089 // forward device change to effects that have requested to be
6090 // aware of attached audio device.
6091 for (size_t i = 0; i < mEffectChains.size(); i++) {
6092 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006093 }
Eric Laurent81784c32012-11-19 14:55:58 -08006094
Eric Laurent10351942014-05-08 18:49:52 -07006095 // store input device and output device but do not forward output device to audio HAL.
6096 // Note that status is ignored by the caller for output device
6097 // (see AudioFlinger::setParameters()
6098 if (audio_is_output_devices(value)) {
6099 mOutDevice = value;
6100 status = BAD_VALUE;
6101 } else {
6102 mInDevice = value;
6103 // disable AEC and NS if the device is a BT SCO headset supporting those
6104 // pre processings
6105 if (mTracks.size() > 0) {
6106 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6107 mAudioFlinger->btNrecIsOff();
6108 for (size_t i = 0; i < mTracks.size(); i++) {
6109 sp<RecordTrack> track = mTracks[i];
6110 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6111 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006112 }
6113 }
6114 }
Eric Laurent10351942014-05-08 18:49:52 -07006115 }
6116 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6117 mAudioSource != (audio_source_t)value) {
6118 // forward device change to effects that have requested to be
6119 // aware of attached audio device.
6120 for (size_t i = 0; i < mEffectChains.size(); i++) {
6121 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006122 }
Eric Laurent10351942014-05-08 18:49:52 -07006123 mAudioSource = (audio_source_t)value;
6124 }
Glenn Kastene198c362013-08-13 09:13:36 -07006125
Eric Laurent10351942014-05-08 18:49:52 -07006126 if (status == NO_ERROR) {
6127 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6128 keyValuePair.string());
6129 if (status == INVALID_OPERATION) {
6130 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006131 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6132 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006133 }
6134 if (reconfig) {
6135 if (status == BAD_VALUE &&
6136 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6137 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6138 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6139 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006140 audio_channel_count_from_in_mask(
6141 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006142 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6143 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6144 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006145 }
Eric Laurent10351942014-05-08 18:49:52 -07006146 if (status == NO_ERROR) {
6147 readInputParameters_l();
6148 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006149 }
6150 }
Eric Laurent81784c32012-11-19 14:55:58 -08006151 }
Eric Laurent10351942014-05-08 18:49:52 -07006152
Eric Laurent81784c32012-11-19 14:55:58 -08006153 return reconfig;
6154}
6155
6156String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6157{
Eric Laurent81784c32012-11-19 14:55:58 -08006158 Mutex::Autolock _l(mLock);
6159 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006160 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006161 }
6162
Glenn Kastend8ea6992013-07-16 14:17:15 -07006163 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6164 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006165 free(s);
6166 return out_s8;
6167}
6168
Eric Laurent021cf962014-05-13 10:18:14 -07006169void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006170 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006171 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006172
6173 switch (event) {
6174 case AudioSystem::INPUT_OPENED:
6175 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006176 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006177 desc.samplingRate = mSampleRate;
6178 desc.format = mFormat;
6179 desc.frameCount = mFrameCount;
6180 desc.latency = 0;
6181 param2 = &desc;
6182 break;
6183
6184 case AudioSystem::INPUT_CLOSED:
6185 default:
6186 break;
6187 }
Eric Laurent021cf962014-05-13 10:18:14 -07006188 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006189}
6190
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006191void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006192{
Eric Laurent81784c32012-11-19 14:55:58 -08006193 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6194 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006195 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006196 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6197 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006198 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006199 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006200 }
Eric Laurent665470b2014-07-03 16:37:08 -07006201 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006202 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6203 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006205 // 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 -07006206 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006207 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 // A larger value should allow more old data to be read after a track calls start(),
6209 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006210 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006211 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006213
6214 // TODO optimize audio capture buffer sizes ...
6215 // Here we calculate the size of the sliding buffer used as a source
6216 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6217 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6218 // be better to have it derived from the pipe depth in the long term.
6219 // The current value is higher than necessary. However it should not add to latency.
6220
Glenn Kasten85948432013-08-19 12:09:05 -07006221 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6222 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006223
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006224 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6225 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006226}
6227
Glenn Kasten5f972c02014-01-13 09:59:31 -08006228uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006229{
6230 Mutex::Autolock _l(mLock);
6231 if (initCheck() != NO_ERROR) {
6232 return 0;
6233 }
6234
6235 return mInput->stream->get_input_frames_lost(mInput->stream);
6236}
6237
6238uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6239{
6240 Mutex::Autolock _l(mLock);
6241 uint32_t result = 0;
6242 if (getEffectChain_l(sessionId) != 0) {
6243 result = EFFECT_SESSION;
6244 }
6245
6246 for (size_t i = 0; i < mTracks.size(); ++i) {
6247 if (sessionId == mTracks[i]->sessionId()) {
6248 result |= TRACK_SESSION;
6249 break;
6250 }
6251 }
6252
6253 return result;
6254}
6255
6256KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6257{
6258 KeyedVector<int, bool> ids;
6259 Mutex::Autolock _l(mLock);
6260 for (size_t j = 0; j < mTracks.size(); ++j) {
6261 sp<RecordThread::RecordTrack> track = mTracks[j];
6262 int sessionId = track->sessionId();
6263 if (ids.indexOfKey(sessionId) < 0) {
6264 ids.add(sessionId, true);
6265 }
6266 }
6267 return ids;
6268}
6269
6270AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6271{
6272 Mutex::Autolock _l(mLock);
6273 AudioStreamIn *input = mInput;
6274 mInput = NULL;
6275 return input;
6276}
6277
6278// this method must always be called either with ThreadBase mLock held or inside the thread loop
6279audio_stream_t* AudioFlinger::RecordThread::stream() const
6280{
6281 if (mInput == NULL) {
6282 return NULL;
6283 }
6284 return &mInput->stream->common;
6285}
6286
6287status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6288{
6289 // only one chain per input thread
6290 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006291 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006292 return INVALID_OPERATION;
6293 }
6294 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006295 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006296 chain->setInBuffer(NULL);
6297 chain->setOutBuffer(NULL);
6298
6299 checkSuspendOnAddEffectChain_l(chain);
6300
Eric Laurent1b928682014-10-02 19:41:47 -07006301 // make sure enabled pre processing effects state is communicated to the HAL as we
6302 // just moved them to a new input stream.
6303 chain->syncHalEffectsState();
6304
Eric Laurent81784c32012-11-19 14:55:58 -08006305 mEffectChains.add(chain);
6306
6307 return NO_ERROR;
6308}
6309
6310size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6311{
6312 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6313 ALOGW_IF(mEffectChains.size() != 1,
6314 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6315 chain.get(), mEffectChains.size(), this);
6316 if (mEffectChains.size() == 1) {
6317 mEffectChains.removeAt(0);
6318 }
6319 return 0;
6320}
6321
Eric Laurent1c333e22014-05-20 10:48:17 -07006322status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6323 audio_patch_handle_t *handle)
6324{
6325 status_t status = NO_ERROR;
6326 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6327 // store new device and send to effects
6328 mInDevice = patch->sources[0].ext.device.type;
6329 for (size_t i = 0; i < mEffectChains.size(); i++) {
6330 mEffectChains[i]->setDevice_l(mInDevice);
6331 }
6332
6333 // disable AEC and NS if the device is a BT SCO headset supporting those
6334 // pre processings
6335 if (mTracks.size() > 0) {
6336 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6337 mAudioFlinger->btNrecIsOff();
6338 for (size_t i = 0; i < mTracks.size(); i++) {
6339 sp<RecordTrack> track = mTracks[i];
6340 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6341 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6342 }
6343 }
6344
6345 // store new source and send to effects
6346 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6347 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6348 for (size_t i = 0; i < mEffectChains.size(); i++) {
6349 mEffectChains[i]->setAudioSource_l(mAudioSource);
6350 }
6351 }
6352
6353 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6354 status = hwDevice->create_audio_patch(hwDevice,
6355 patch->num_sources,
6356 patch->sources,
6357 patch->num_sinks,
6358 patch->sinks,
6359 handle);
6360 } else {
6361 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6362 }
6363 return status;
6364}
6365
6366status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6367{
6368 status_t status = NO_ERROR;
6369 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6370 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6371 status = hwDevice->release_audio_patch(hwDevice, handle);
6372 } else {
6373 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6374 }
6375 return status;
6376}
6377
Eric Laurent83b88082014-06-20 18:31:16 -07006378void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6379{
6380 Mutex::Autolock _l(mLock);
6381 mTracks.add(record);
6382}
6383
6384void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6385{
6386 Mutex::Autolock _l(mLock);
6387 destroyTrack_l(record);
6388}
6389
6390void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6391{
6392 ThreadBase::getAudioPortConfig(config);
6393 config->role = AUDIO_PORT_ROLE_SINK;
6394 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6395 config->ext.mix.usecase.source = mAudioSource;
6396}
Eric Laurent1c333e22014-05-20 10:48:17 -07006397
Eric Laurent81784c32012-11-19 14:55:58 -08006398}; // namespace android