blob: 1a20fae2c4ba6172851bcd9eb6f6b55e1c3cab01 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Eric Laurent81784c32012-11-19 14:55:58 -080097namespace android {
98
99// retry counts for buffer fill timeout
100// 50 * ~20msecs = 1 second
101static const int8_t kMaxTrackRetries = 50;
102static const int8_t kMaxTrackStartupRetries = 50;
103// allow less retry attempts on direct output thread.
104// direct outputs can be a scarce resource in audio hardware and should
105// be released as quickly as possible.
106static const int8_t kMaxTrackRetriesDirect = 2;
107
108// don't warn about blocked writes or record buffer overflows more often than this
109static const nsecs_t kWarningThrottleNs = seconds(5);
110
111// RecordThread loop sleep time upon application overrun or audio HAL read error
112static const int kRecordThreadSleepUs = 5000;
113
Eric Laurent10351942014-05-08 18:49:52 -0700114// maximum time to wait in sendConfigEvent_l() for a status to be received
115static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800116
117// minimum sleep time for the mixer thread loop when tracks are active but in underrun
118static const uint32_t kMinThreadSleepTimeUs = 5000;
119// maximum divider applied to the active sleep time in the mixer thread loop
120static const uint32_t kMaxThreadSleepTimeShift = 2;
121
Andy Hung09a50072014-02-27 14:30:47 -0800122// minimum normal sink buffer size, expressed in milliseconds rather than frames
123static const uint32_t kMinNormalSinkBufferSizeMs = 20;
124// maximum normal sink buffer size
125static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800126
Eric Laurent972a1732013-09-04 09:42:59 -0700127// Offloaded output thread standby delay: allows track transition without going to standby
128static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// Whether to use fast mixer
131static const enum {
132 FastMixer_Never, // never initialize or use: for debugging only
133 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
134 // normal mixer multiplier is 1
135 FastMixer_Static, // initialize if needed, then use all the time if initialized,
136 // multiplier is calculated based on min & max normal mixer buffer size
137 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
138 // multiplier is calculated based on min & max normal mixer buffer size
139 // FIXME for FastMixer_Dynamic:
140 // Supporting this option will require fixing HALs that can't handle large writes.
141 // For example, one HAL implementation returns an error from a large write,
142 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
143 // We could either fix the HAL implementations, or provide a wrapper that breaks
144 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
145} kUseFastMixer = FastMixer_Static;
146
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700147// Whether to use fast capture
148static const enum {
149 FastCapture_Never, // never initialize or use: for debugging only
150 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
151 FastCapture_Static, // initialize if needed, then use all the time if initialized
152} kUseFastCapture = FastCapture_Static;
153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Priorities for requestPriority
155static const int kPriorityAudioApp = 2;
156static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700157static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800158
159// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
160// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800161// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
162// So for now we just assume that client is double-buffered for fast tracks.
163// FIXME It would be better for client to tell AudioFlinger the value of N,
164// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800165// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700166
167// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800168static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
Glenn Kasten03490092014-05-27 12:30:54 -0700170// The minimum and maximum allowed values
171static const int kFastTrackMultiplierMin = 1;
172static const int kFastTrackMultiplierMax = 2;
173
174// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
175static int sFastTrackMultiplier = kFastTrackMultiplier;
176
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700177// See Thread::readOnlyHeap().
178// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
179// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
180// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700181static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182
Eric Laurent81784c32012-11-19 14:55:58 -0800183// ----------------------------------------------------------------------------
184
Glenn Kasten03490092014-05-27 12:30:54 -0700185static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
186
187static void sFastTrackMultiplierInit()
188{
189 char value[PROPERTY_VALUE_MAX];
190 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
191 char *endptr;
192 unsigned long ul = strtoul(value, &endptr, 0);
193 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
194 sFastTrackMultiplier = (int) ul;
195 }
196 }
197}
198
199// ----------------------------------------------------------------------------
200
Eric Laurent81784c32012-11-19 14:55:58 -0800201#ifdef ADD_BATTERY_DATA
202// To collect the amplifier usage
203static void addBatteryData(uint32_t params) {
204 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
205 if (service == NULL) {
206 // it already logged
207 return;
208 }
209
210 service->addBatteryData(params);
211}
212#endif
213
214
215// ----------------------------------------------------------------------------
216// CPU Stats
217// ----------------------------------------------------------------------------
218
219class CpuStats {
220public:
221 CpuStats();
222 void sample(const String8 &title);
223#ifdef DEBUG_CPU_USAGE
224private:
225 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
226 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
227
228 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
229
230 int mCpuNum; // thread's current CPU number
231 int mCpukHz; // frequency of thread's current CPU in kHz
232#endif
233};
234
235CpuStats::CpuStats()
236#ifdef DEBUG_CPU_USAGE
237 : mCpuNum(-1), mCpukHz(-1)
238#endif
239{
240}
241
Glenn Kasten0f11b512014-01-31 16:18:54 -0800242void CpuStats::sample(const String8 &title
243#ifndef DEBUG_CPU_USAGE
244 __unused
245#endif
246 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800247#ifdef DEBUG_CPU_USAGE
248 // get current thread's delta CPU time in wall clock ns
249 double wcNs;
250 bool valid = mCpuUsage.sampleAndEnable(wcNs);
251
252 // record sample for wall clock statistics
253 if (valid) {
254 mWcStats.sample(wcNs);
255 }
256
257 // get the current CPU number
258 int cpuNum = sched_getcpu();
259
260 // get the current CPU frequency in kHz
261 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
262
263 // check if either CPU number or frequency changed
264 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
265 mCpuNum = cpuNum;
266 mCpukHz = cpukHz;
267 // ignore sample for purposes of cycles
268 valid = false;
269 }
270
271 // if no change in CPU number or frequency, then record sample for cycle statistics
272 if (valid && mCpukHz > 0) {
273 double cycles = wcNs * cpukHz * 0.000001;
274 mHzStats.sample(cycles);
275 }
276
277 unsigned n = mWcStats.n();
278 // mCpuUsage.elapsed() is expensive, so don't call it every loop
279 if ((n & 127) == 1) {
280 long long elapsed = mCpuUsage.elapsed();
281 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
282 double perLoop = elapsed / (double) n;
283 double perLoop100 = perLoop * 0.01;
284 double perLoop1k = perLoop * 0.001;
285 double mean = mWcStats.mean();
286 double stddev = mWcStats.stddev();
287 double minimum = mWcStats.minimum();
288 double maximum = mWcStats.maximum();
289 double meanCycles = mHzStats.mean();
290 double stddevCycles = mHzStats.stddev();
291 double minCycles = mHzStats.minimum();
292 double maxCycles = mHzStats.maximum();
293 mCpuUsage.resetElapsed();
294 mWcStats.reset();
295 mHzStats.reset();
296 ALOGD("CPU usage for %s over past %.1f secs\n"
297 " (%u mixer loops at %.1f mean ms per loop):\n"
298 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
299 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
300 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
301 title.string(),
302 elapsed * .000000001, n, perLoop * .000001,
303 mean * .001,
304 stddev * .001,
305 minimum * .001,
306 maximum * .001,
307 mean / perLoop100,
308 stddev / perLoop100,
309 minimum / perLoop100,
310 maximum / perLoop100,
311 meanCycles / perLoop1k,
312 stddevCycles / perLoop1k,
313 minCycles / perLoop1k,
314 maxCycles / perLoop1k);
315
316 }
317 }
318#endif
319};
320
321// ----------------------------------------------------------------------------
322// ThreadBase
323// ----------------------------------------------------------------------------
324
Glenn Kasten97b7b752014-09-28 13:04:24 -0700325// static
326const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
327{
328 switch (type) {
329 case MIXER:
330 return "MIXER";
331 case DIRECT:
332 return "DIRECT";
333 case DUPLICATING:
334 return "DUPLICATING";
335 case RECORD:
336 return "RECORD";
337 case OFFLOAD:
338 return "OFFLOAD";
339 default:
340 return "unknown";
341 }
342}
343
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800344String8 devicesToString(audio_devices_t devices)
345{
346 static const struct mapping {
347 audio_devices_t mDevices;
348 const char * mString;
349 } mappingsOut[] = {
350 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
351 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
352 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
353 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
354 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
355 AUDIO_DEVICE_NONE, "NONE", // must be last
356 }, mappingsIn[] = {
357 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
358 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
359 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
360 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
361 AUDIO_DEVICE_NONE, "NONE", // must be last
362 };
363 String8 result;
364 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
365 const mapping *entry;
366 if (devices & AUDIO_DEVICE_BIT_IN) {
367 devices &= ~AUDIO_DEVICE_BIT_IN;
368 entry = mappingsIn;
369 } else {
370 entry = mappingsOut;
371 }
372 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
373 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
374 if (devices & entry->mDevices) {
375 if (!result.isEmpty()) {
376 result.append("|");
377 }
378 result.append(entry->mString);
379 }
380 }
381 if (devices & ~allDevices) {
382 if (!result.isEmpty()) {
383 result.append("|");
384 }
385 result.appendFormat("0x%X", devices & ~allDevices);
386 }
387 if (result.isEmpty()) {
388 result.append(entry->mString);
389 }
390 return result;
391}
392
393String8 inputFlagsToString(audio_input_flags_t flags)
394{
395 static const struct mapping {
396 audio_input_flags_t mFlag;
397 const char * mString;
398 } mappings[] = {
399 AUDIO_INPUT_FLAG_FAST, "FAST",
400 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
401 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
402 };
403 String8 result;
404 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
405 const mapping *entry;
406 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
407 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
408 if (flags & entry->mFlag) {
409 if (!result.isEmpty()) {
410 result.append("|");
411 }
412 result.append(entry->mString);
413 }
414 }
415 if (flags & ~allFlags) {
416 if (!result.isEmpty()) {
417 result.append("|");
418 }
419 result.appendFormat("0x%X", flags & ~allFlags);
420 }
421 if (result.isEmpty()) {
422 result.append(entry->mString);
423 }
424 return result;
425}
426
427String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700428{
429 static const struct mapping {
430 audio_output_flags_t mFlag;
431 const char * mString;
432 } mappings[] = {
433 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
434 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
435 AUDIO_OUTPUT_FLAG_FAST, "FAST",
436 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800437 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700438 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
439 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
440 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
441 };
442 String8 result;
443 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
444 const mapping *entry;
445 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
446 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
447 if (flags & entry->mFlag) {
448 if (!result.isEmpty()) {
449 result.append("|");
450 }
451 result.append(entry->mString);
452 }
453 }
454 if (flags & ~allFlags) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.appendFormat("0x%X", flags & ~allFlags);
459 }
460 if (result.isEmpty()) {
461 result.append(entry->mString);
462 }
463 return result;
464}
465
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800466const char *sourceToString(audio_source_t source)
467{
468 switch (source) {
469 case AUDIO_SOURCE_DEFAULT: return "default";
470 case AUDIO_SOURCE_MIC: return "mic";
471 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
472 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
473 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
474 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
475 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
476 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
477 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
478 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
479 case AUDIO_SOURCE_HOTWORD: return "hotword";
480 default: return "unknown";
481 }
482}
483
Eric Laurent81784c32012-11-19 14:55:58 -0800484AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
485 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
486 : Thread(false /*canCallJava*/),
487 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700488 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700489 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800490 // are set by PlaybackThread::readOutputParameters_l() or
491 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700492 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800493 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
494 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
495 // mName will be set by concrete (non-virtual) subclass
496 mDeathRecipient(new PMDeathRecipient(this))
497{
498}
499
500AudioFlinger::ThreadBase::~ThreadBase()
501{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700502 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700503 mConfigEvents.clear();
504
Eric Laurent81784c32012-11-19 14:55:58 -0800505 // do not lock the mutex in destructor
506 releaseWakeLock_l();
507 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800508 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 binder->unlinkToDeath(mDeathRecipient);
510 }
511}
512
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700513status_t AudioFlinger::ThreadBase::readyToRun()
514{
515 status_t status = initCheck();
516 if (status == NO_ERROR) {
517 ALOGI("AudioFlinger's thread %p ready to run", this);
518 } else {
519 ALOGE("No working audio driver found.");
520 }
521 return status;
522}
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524void AudioFlinger::ThreadBase::exit()
525{
526 ALOGV("ThreadBase::exit");
527 // do any cleanup required for exit to succeed
528 preExit();
529 {
530 // This lock prevents the following race in thread (uniprocessor for illustration):
531 // if (!exitPending()) {
532 // // context switch from here to exit()
533 // // exit() calls requestExit(), what exitPending() observes
534 // // exit() calls signal(), which is dropped since no waiters
535 // // context switch back from exit() to here
536 // mWaitWorkCV.wait(...);
537 // // now thread is hung
538 // }
539 AutoMutex lock(mLock);
540 requestExit();
541 mWaitWorkCV.broadcast();
542 }
543 // When Thread::requestExitAndWait is made virtual and this method is renamed to
544 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
545 requestExitAndWait();
546}
547
548status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
549{
550 status_t status;
551
552 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
553 Mutex::Autolock _l(mLock);
554
Eric Laurent10351942014-05-08 18:49:52 -0700555 return sendSetParameterConfigEvent_l(keyValuePairs);
556}
557
558// sendConfigEvent_l() must be called with ThreadBase::mLock held
559// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
560status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
561{
562 status_t status = NO_ERROR;
563
564 mConfigEvents.add(event);
565 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800566 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700567 mLock.unlock();
568 {
569 Mutex::Autolock _l(event->mLock);
570 while (event->mWaitStatus) {
571 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
572 event->mStatus = TIMED_OUT;
573 event->mWaitStatus = false;
574 }
575 }
576 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800577 }
Eric Laurent10351942014-05-08 18:49:52 -0700578 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800579 return status;
580}
581
582void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
583{
584 Mutex::Autolock _l(mLock);
585 sendIoConfigEvent_l(event, param);
586}
587
588// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
589void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
590{
Eric Laurent10351942014-05-08 18:49:52 -0700591 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
592 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800593}
594
595// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
596void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
597{
Eric Laurent10351942014-05-08 18:49:52 -0700598 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
599 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800600}
601
Eric Laurent10351942014-05-08 18:49:52 -0700602// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
603status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800604{
Eric Laurent10351942014-05-08 18:49:52 -0700605 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
606 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700607}
608
Eric Laurent1c333e22014-05-20 10:48:17 -0700609status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
610 const struct audio_patch *patch,
611 audio_patch_handle_t *handle)
612{
613 Mutex::Autolock _l(mLock);
614 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
615 status_t status = sendConfigEvent_l(configEvent);
616 if (status == NO_ERROR) {
617 CreateAudioPatchConfigEventData *data =
618 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
619 *handle = data->mHandle;
620 }
621 return status;
622}
623
624status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
625 const audio_patch_handle_t handle)
626{
627 Mutex::Autolock _l(mLock);
628 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
629 return sendConfigEvent_l(configEvent);
630}
631
632
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700633// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700634void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700635{
Eric Laurent10351942014-05-08 18:49:52 -0700636 bool configChanged = false;
637
Eric Laurent81784c32012-11-19 14:55:58 -0800638 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700639 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
640 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800641 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700642 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700643 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700644 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
645 // FIXME Need to understand why this has to be done asynchronously
646 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700647 true /*asynchronous*/);
648 if (err != 0) {
649 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700650 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700651 }
652 } break;
653 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700654 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700655 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700656 } break;
657 case CFG_EVENT_SET_PARAMETER: {
658 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
659 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
660 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700661 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700662 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700663 case CFG_EVENT_CREATE_AUDIO_PATCH: {
664 CreateAudioPatchConfigEventData *data =
665 (CreateAudioPatchConfigEventData *)event->mData.get();
666 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
667 } break;
668 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
669 ReleaseAudioPatchConfigEventData *data =
670 (ReleaseAudioPatchConfigEventData *)event->mData.get();
671 event->mStatus = releaseAudioPatch_l(data->mHandle);
672 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700673 default:
Eric Laurent10351942014-05-08 18:49:52 -0700674 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700675 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800676 }
Eric Laurent10351942014-05-08 18:49:52 -0700677 {
678 Mutex::Autolock _l(event->mLock);
679 if (event->mWaitStatus) {
680 event->mWaitStatus = false;
681 event->mCond.signal();
682 }
683 }
684 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
685 }
686
687 if (configChanged) {
688 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800689 }
Eric Laurent81784c32012-11-19 14:55:58 -0800690}
691
Marco Nelissenb2208842014-02-07 14:00:50 -0800692String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
693 String8 s;
694 if (output) {
695 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
696 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
697 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
698 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
699 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
700 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
701 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
702 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
703 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
704 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
705 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
706 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
707 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
708 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
709 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
710 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
711 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
712 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
713 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
714 } else {
715 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
716 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
717 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
718 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
719 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
720 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
721 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
722 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
723 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
724 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
725 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
726 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
727 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
728 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
729 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
730 }
731 int len = s.length();
732 if (s.length() > 2) {
733 char *str = s.lockBuffer(len);
734 s.unlockBuffer(len - 2);
735 }
736 return s;
737}
738
Glenn Kasten0f11b512014-01-31 16:18:54 -0800739void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800740{
741 const size_t SIZE = 256;
742 char buffer[SIZE];
743 String8 result;
744
745 bool locked = AudioFlinger::dumpTryLock(mLock);
746 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700747 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800748 }
749
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800750 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700751 dprintf(fd, " I/O handle: %d\n", mId);
752 dprintf(fd, " TID: %d\n", getTid());
753 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700754 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700755 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700756 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700757 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700758 dprintf(fd, " Channel count: %u\n", mChannelCount);
759 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800760 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700761 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
762 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700763 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800764 size_t numConfig = mConfigEvents.size();
765 if (numConfig) {
766 for (size_t i = 0; i < numConfig; i++) {
767 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700768 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800769 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700770 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800771 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700772 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800773 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800774 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
775 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
776 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800777
778 if (locked) {
779 mLock.unlock();
780 }
781}
782
783void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
784{
785 const size_t SIZE = 256;
786 char buffer[SIZE];
787 String8 result;
788
Marco Nelissenb2208842014-02-07 14:00:50 -0800789 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000790 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800791 write(fd, buffer, strlen(buffer));
792
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800794 sp<EffectChain> chain = mEffectChains[i];
795 if (chain != 0) {
796 chain->dump(fd, args);
797 }
798 }
799}
800
Marco Nelissene14a5d62013-10-03 08:51:24 -0700801void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800802{
803 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700804 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800805}
806
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100807String16 AudioFlinger::ThreadBase::getWakeLockTag()
808{
809 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800810 case MIXER:
811 return String16("AudioMix");
812 case DIRECT:
813 return String16("AudioDirectOut");
814 case DUPLICATING:
815 return String16("AudioDup");
816 case RECORD:
817 return String16("AudioIn");
818 case OFFLOAD:
819 return String16("AudioOffload");
820 default:
821 ALOG_ASSERT(false);
822 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100823 }
824}
825
Marco Nelissene14a5d62013-10-03 08:51:24 -0700826void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800827{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800828 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800829 if (mPowerManager != 0) {
830 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700831 status_t status;
832 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700833 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700834 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100835 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700836 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700837 uid,
838 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700839 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700840 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700841 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100842 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700843 String16("media"),
844 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700845 }
Eric Laurent81784c32012-11-19 14:55:58 -0800846 if (status == NO_ERROR) {
847 mWakeLockToken = binder;
848 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800849 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800850 }
851}
852
853void AudioFlinger::ThreadBase::releaseWakeLock()
854{
855 Mutex::Autolock _l(mLock);
856 releaseWakeLock_l();
857}
858
859void AudioFlinger::ThreadBase::releaseWakeLock_l()
860{
861 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800862 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800863 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700864 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
865 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800866 }
867 mWakeLockToken.clear();
868 }
869}
870
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800871void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
872 Mutex::Autolock _l(mLock);
873 updateWakeLockUids_l(uids);
874}
875
876void AudioFlinger::ThreadBase::getPowerManager_l() {
877
878 if (mPowerManager == 0) {
879 // use checkService() to avoid blocking if power service is not up yet
880 sp<IBinder> binder =
881 defaultServiceManager()->checkService(String16("power"));
882 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800883 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800884 } else {
885 mPowerManager = interface_cast<IPowerManager>(binder);
886 binder->linkToDeath(mDeathRecipient);
887 }
888 }
889}
890
891void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
892
893 getPowerManager_l();
894 if (mWakeLockToken == NULL) {
895 ALOGE("no wake lock to update!");
896 return;
897 }
898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
900 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700901 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
902 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800903 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800904 }
905}
906
Eric Laurent81784c32012-11-19 14:55:58 -0800907void AudioFlinger::ThreadBase::clearPowerManager()
908{
909 Mutex::Autolock _l(mLock);
910 releaseWakeLock_l();
911 mPowerManager.clear();
912}
913
Glenn Kasten0f11b512014-01-31 16:18:54 -0800914void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800915{
916 sp<ThreadBase> thread = mThread.promote();
917 if (thread != 0) {
918 thread->clearPowerManager();
919 }
920 ALOGW("power manager service died !!!");
921}
922
923void AudioFlinger::ThreadBase::setEffectSuspended(
924 const effect_uuid_t *type, bool suspend, int sessionId)
925{
926 Mutex::Autolock _l(mLock);
927 setEffectSuspended_l(type, suspend, sessionId);
928}
929
930void AudioFlinger::ThreadBase::setEffectSuspended_l(
931 const effect_uuid_t *type, bool suspend, int sessionId)
932{
933 sp<EffectChain> chain = getEffectChain_l(sessionId);
934 if (chain != 0) {
935 if (type != NULL) {
936 chain->setEffectSuspended_l(type, suspend);
937 } else {
938 chain->setEffectSuspendedAll_l(suspend);
939 }
940 }
941
942 updateSuspendedSessions_l(type, suspend, sessionId);
943}
944
945void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
946{
947 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
948 if (index < 0) {
949 return;
950 }
951
952 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
953 mSuspendedSessions.valueAt(index);
954
955 for (size_t i = 0; i < sessionEffects.size(); i++) {
956 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
957 for (int j = 0; j < desc->mRefCount; j++) {
958 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
959 chain->setEffectSuspendedAll_l(true);
960 } else {
961 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
962 desc->mType.timeLow);
963 chain->setEffectSuspended_l(&desc->mType, true);
964 }
965 }
966 }
967}
968
969void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
970 bool suspend,
971 int sessionId)
972{
973 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
974
975 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
976
977 if (suspend) {
978 if (index >= 0) {
979 sessionEffects = mSuspendedSessions.valueAt(index);
980 } else {
981 mSuspendedSessions.add(sessionId, sessionEffects);
982 }
983 } else {
984 if (index < 0) {
985 return;
986 }
987 sessionEffects = mSuspendedSessions.valueAt(index);
988 }
989
990
991 int key = EffectChain::kKeyForSuspendAll;
992 if (type != NULL) {
993 key = type->timeLow;
994 }
995 index = sessionEffects.indexOfKey(key);
996
997 sp<SuspendedSessionDesc> desc;
998 if (suspend) {
999 if (index >= 0) {
1000 desc = sessionEffects.valueAt(index);
1001 } else {
1002 desc = new SuspendedSessionDesc();
1003 if (type != NULL) {
1004 desc->mType = *type;
1005 }
1006 sessionEffects.add(key, desc);
1007 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1008 }
1009 desc->mRefCount++;
1010 } else {
1011 if (index < 0) {
1012 return;
1013 }
1014 desc = sessionEffects.valueAt(index);
1015 if (--desc->mRefCount == 0) {
1016 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1017 sessionEffects.removeItemsAt(index);
1018 if (sessionEffects.isEmpty()) {
1019 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1020 sessionId);
1021 mSuspendedSessions.removeItem(sessionId);
1022 }
1023 }
1024 }
1025 if (!sessionEffects.isEmpty()) {
1026 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1027 }
1028}
1029
1030void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1031 bool enabled,
1032 int sessionId)
1033{
1034 Mutex::Autolock _l(mLock);
1035 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1036}
1037
1038void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1039 bool enabled,
1040 int sessionId)
1041{
1042 if (mType != RECORD) {
1043 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1044 // another session. This gives the priority to well behaved effect control panels
1045 // and applications not using global effects.
1046 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1047 // global effects
1048 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1049 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1050 }
1051 }
1052
1053 sp<EffectChain> chain = getEffectChain_l(sessionId);
1054 if (chain != 0) {
1055 chain->checkSuspendOnEffectEnabled(effect, enabled);
1056 }
1057}
1058
1059// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1060sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1061 const sp<AudioFlinger::Client>& client,
1062 const sp<IEffectClient>& effectClient,
1063 int32_t priority,
1064 int sessionId,
1065 effect_descriptor_t *desc,
1066 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001067 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001068{
1069 sp<EffectModule> effect;
1070 sp<EffectHandle> handle;
1071 status_t lStatus;
1072 sp<EffectChain> chain;
1073 bool chainCreated = false;
1074 bool effectCreated = false;
1075 bool effectRegistered = false;
1076
1077 lStatus = initCheck();
1078 if (lStatus != NO_ERROR) {
1079 ALOGW("createEffect_l() Audio driver not initialized.");
1080 goto Exit;
1081 }
1082
Andy Hung98ef9782014-03-04 14:46:50 -08001083 // Reject any effect on Direct output threads for now, since the format of
1084 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1085 if (mType == DIRECT) {
1086 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001087 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001088 lStatus = BAD_VALUE;
1089 goto Exit;
1090 }
1091
Andy Hung389cfdb2014-08-07 17:49:53 -07001092 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001093 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001094 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1095 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1096 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001097 lStatus = BAD_VALUE;
1098 goto Exit;
1099 }
1100
Eric Laurent5baf2af2013-09-12 17:37:00 -07001101 // Allow global effects only on offloaded and mixer threads
1102 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1103 switch (mType) {
1104 case MIXER:
1105 case OFFLOAD:
1106 break;
1107 case DIRECT:
1108 case DUPLICATING:
1109 case RECORD:
1110 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001111 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1112 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001113 lStatus = BAD_VALUE;
1114 goto Exit;
1115 }
Eric Laurent81784c32012-11-19 14:55:58 -08001116 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001117
Eric Laurent81784c32012-11-19 14:55:58 -08001118 // Only Pre processor effects are allowed on input threads and only on input threads
1119 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1120 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1121 desc->name, desc->flags, mType);
1122 lStatus = BAD_VALUE;
1123 goto Exit;
1124 }
1125
1126 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1127
1128 { // scope for mLock
1129 Mutex::Autolock _l(mLock);
1130
1131 // check for existing effect chain with the requested audio session
1132 chain = getEffectChain_l(sessionId);
1133 if (chain == 0) {
1134 // create a new chain for this session
1135 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1136 chain = new EffectChain(this, sessionId);
1137 addEffectChain_l(chain);
1138 chain->setStrategy(getStrategyForSession_l(sessionId));
1139 chainCreated = true;
1140 } else {
1141 effect = chain->getEffectFromDesc_l(desc);
1142 }
1143
1144 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1145
1146 if (effect == 0) {
1147 int id = mAudioFlinger->nextUniqueId();
1148 // Check CPU and memory usage
1149 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1150 if (lStatus != NO_ERROR) {
1151 goto Exit;
1152 }
1153 effectRegistered = true;
1154 // create a new effect module if none present in the chain
1155 effect = new EffectModule(this, chain, desc, id, sessionId);
1156 lStatus = effect->status();
1157 if (lStatus != NO_ERROR) {
1158 goto Exit;
1159 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001160 effect->setOffloaded(mType == OFFLOAD, mId);
1161
Eric Laurent81784c32012-11-19 14:55:58 -08001162 lStatus = chain->addEffect_l(effect);
1163 if (lStatus != NO_ERROR) {
1164 goto Exit;
1165 }
1166 effectCreated = true;
1167
1168 effect->setDevice(mOutDevice);
1169 effect->setDevice(mInDevice);
1170 effect->setMode(mAudioFlinger->getMode());
1171 effect->setAudioSource(mAudioSource);
1172 }
1173 // create effect handle and connect it to effect module
1174 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001175 lStatus = handle->initCheck();
1176 if (lStatus == OK) {
1177 lStatus = effect->addHandle(handle.get());
1178 }
Eric Laurent81784c32012-11-19 14:55:58 -08001179 if (enabled != NULL) {
1180 *enabled = (int)effect->isEnabled();
1181 }
1182 }
1183
1184Exit:
1185 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1186 Mutex::Autolock _l(mLock);
1187 if (effectCreated) {
1188 chain->removeEffect_l(effect);
1189 }
1190 if (effectRegistered) {
1191 AudioSystem::unregisterEffect(effect->id());
1192 }
1193 if (chainCreated) {
1194 removeEffectChain_l(chain);
1195 }
1196 handle.clear();
1197 }
1198
Glenn Kasten9156ef32013-08-06 15:39:08 -07001199 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001200 return handle;
1201}
1202
1203sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1204{
1205 Mutex::Autolock _l(mLock);
1206 return getEffect_l(sessionId, effectId);
1207}
1208
1209sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1210{
1211 sp<EffectChain> chain = getEffectChain_l(sessionId);
1212 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1213}
1214
1215// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1216// PlaybackThread::mLock held
1217status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1218{
1219 // check for existing effect chain with the requested audio session
1220 int sessionId = effect->sessionId();
1221 sp<EffectChain> chain = getEffectChain_l(sessionId);
1222 bool chainCreated = false;
1223
Eric Laurent5baf2af2013-09-12 17:37:00 -07001224 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1225 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1226 this, effect->desc().name, effect->desc().flags);
1227
Eric Laurent81784c32012-11-19 14:55:58 -08001228 if (chain == 0) {
1229 // create a new chain for this session
1230 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1231 chain = new EffectChain(this, sessionId);
1232 addEffectChain_l(chain);
1233 chain->setStrategy(getStrategyForSession_l(sessionId));
1234 chainCreated = true;
1235 }
1236 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1237
1238 if (chain->getEffectFromId_l(effect->id()) != 0) {
1239 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1240 this, effect->desc().name, chain.get());
1241 return BAD_VALUE;
1242 }
1243
Eric Laurent5baf2af2013-09-12 17:37:00 -07001244 effect->setOffloaded(mType == OFFLOAD, mId);
1245
Eric Laurent81784c32012-11-19 14:55:58 -08001246 status_t status = chain->addEffect_l(effect);
1247 if (status != NO_ERROR) {
1248 if (chainCreated) {
1249 removeEffectChain_l(chain);
1250 }
1251 return status;
1252 }
1253
1254 effect->setDevice(mOutDevice);
1255 effect->setDevice(mInDevice);
1256 effect->setMode(mAudioFlinger->getMode());
1257 effect->setAudioSource(mAudioSource);
1258 return NO_ERROR;
1259}
1260
1261void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1262
1263 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1264 effect_descriptor_t desc = effect->desc();
1265 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1266 detachAuxEffect_l(effect->id());
1267 }
1268
1269 sp<EffectChain> chain = effect->chain().promote();
1270 if (chain != 0) {
1271 // remove effect chain if removing last effect
1272 if (chain->removeEffect_l(effect) == 0) {
1273 removeEffectChain_l(chain);
1274 }
1275 } else {
1276 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1277 }
1278}
1279
1280void AudioFlinger::ThreadBase::lockEffectChains_l(
1281 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1282{
1283 effectChains = mEffectChains;
1284 for (size_t i = 0; i < mEffectChains.size(); i++) {
1285 mEffectChains[i]->lock();
1286 }
1287}
1288
1289void AudioFlinger::ThreadBase::unlockEffectChains(
1290 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1291{
1292 for (size_t i = 0; i < effectChains.size(); i++) {
1293 effectChains[i]->unlock();
1294 }
1295}
1296
1297sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1298{
1299 Mutex::Autolock _l(mLock);
1300 return getEffectChain_l(sessionId);
1301}
1302
1303sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1304{
1305 size_t size = mEffectChains.size();
1306 for (size_t i = 0; i < size; i++) {
1307 if (mEffectChains[i]->sessionId() == sessionId) {
1308 return mEffectChains[i];
1309 }
1310 }
1311 return 0;
1312}
1313
1314void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1315{
1316 Mutex::Autolock _l(mLock);
1317 size_t size = mEffectChains.size();
1318 for (size_t i = 0; i < size; i++) {
1319 mEffectChains[i]->setMode_l(mode);
1320 }
1321}
1322
Eric Laurent83b88082014-06-20 18:31:16 -07001323void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1324{
1325 config->type = AUDIO_PORT_TYPE_MIX;
1326 config->ext.mix.handle = mId;
1327 config->sample_rate = mSampleRate;
1328 config->format = mFormat;
1329 config->channel_mask = mChannelMask;
1330 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1331 AUDIO_PORT_CONFIG_FORMAT;
1332}
1333
1334
Eric Laurent81784c32012-11-19 14:55:58 -08001335// ----------------------------------------------------------------------------
1336// Playback
1337// ----------------------------------------------------------------------------
1338
1339AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1340 AudioStreamOut* output,
1341 audio_io_handle_t id,
1342 audio_devices_t device,
1343 type_t type)
1344 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001345 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001346 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001347 mMixerBuffer(NULL),
1348 mMixerBufferSize(0),
1349 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1350 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001351 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001352 mEffectBuffer(NULL),
1353 mEffectBufferSize(0),
1354 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1355 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001356 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001357 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001358 // mStreamTypes[] initialized in constructor body
1359 mOutput(output),
1360 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1361 mMixerStatus(MIXER_IDLE),
1362 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1363 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001364 mBytesRemaining(0),
1365 mCurrentWriteLength(0),
1366 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001367 mWriteAckSequence(0),
1368 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001369 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001370 mScreenState(AudioFlinger::mScreenState),
1371 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001372 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001373 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001374 // mLatchD, mLatchQ,
1375 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001376{
Glenn Kastend7dca052015-03-05 16:05:54 -08001377 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1378 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001379
1380 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1381 // it would be safer to explicitly pass initial masterVolume/masterMute as
1382 // parameter.
1383 //
1384 // If the HAL we are using has support for master volume or master mute,
1385 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1386 // and the mute set to false).
1387 mMasterVolume = audioFlinger->masterVolume_l();
1388 mMasterMute = audioFlinger->masterMute_l();
1389 if (mOutput && mOutput->audioHwDev) {
1390 if (mOutput->audioHwDev->canSetMasterVolume()) {
1391 mMasterVolume = 1.0;
1392 }
1393
1394 if (mOutput->audioHwDev->canSetMasterMute()) {
1395 mMasterMute = false;
1396 }
1397 }
1398
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001399 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001400
Eric Laurent223fd5c2014-11-11 13:43:36 -08001401 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001402 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001403 stream = (audio_stream_type_t) (stream + 1)) {
1404 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1405 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1406 }
Eric Laurent81784c32012-11-19 14:55:58 -08001407}
1408
1409AudioFlinger::PlaybackThread::~PlaybackThread()
1410{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001411 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001412 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001413 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001414 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001415}
1416
1417void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1418{
1419 dumpInternals(fd, args);
1420 dumpTracks(fd, args);
1421 dumpEffectChains(fd, args);
1422}
1423
Glenn Kasten0f11b512014-01-31 16:18:54 -08001424void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001425{
1426 const size_t SIZE = 256;
1427 char buffer[SIZE];
1428 String8 result;
1429
Marco Nelissenb2208842014-02-07 14:00:50 -08001430 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001431 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1432 const stream_type_t *st = &mStreamTypes[i];
1433 if (i > 0) {
1434 result.appendFormat(", ");
1435 }
1436 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1437 if (st->mute) {
1438 result.append("M");
1439 }
1440 }
1441 result.append("\n");
1442 write(fd, result.string(), result.length());
1443 result.clear();
1444
Eric Laurent81784c32012-11-19 14:55:58 -08001445 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1446 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001447 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001448 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001449
1450 size_t numtracks = mTracks.size();
1451 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001452 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001453 size_t numactiveseen = 0;
1454 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001455 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001456 Track::appendDumpHeader(result);
1457 for (size_t i = 0; i < numtracks; ++i) {
1458 sp<Track> track = mTracks[i];
1459 if (track != 0) {
1460 bool active = mActiveTracks.indexOf(track) >= 0;
1461 if (active) {
1462 numactiveseen++;
1463 }
1464 track->dump(buffer, SIZE, active);
1465 result.append(buffer);
1466 }
1467 }
1468 } else {
1469 result.append("\n");
1470 }
1471 if (numactiveseen != numactive) {
1472 // some tracks in the active list were not in the tracks list
1473 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1474 " not in the track list\n");
1475 result.append(buffer);
1476 Track::appendDumpHeader(result);
1477 for (size_t i = 0; i < numactive; ++i) {
1478 sp<Track> track = mActiveTracks[i].promote();
1479 if (track != 0 && mTracks.indexOf(track) < 0) {
1480 track->dump(buffer, SIZE, true);
1481 result.append(buffer);
1482 }
1483 }
1484 }
1485
1486 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001487}
1488
1489void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1490{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001491 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001492
1493 dumpBase(fd, args);
1494
Elliott Hughes87cebad2014-05-22 10:14:43 -07001495 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1496 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1497 dprintf(fd, " Total writes: %d\n", mNumWrites);
1498 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1499 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1500 dprintf(fd, " Suspend count: %d\n", mSuspended);
1501 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1502 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1503 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1504 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001505 AudioStreamOut *output = mOutput;
1506 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1507 String8 flagsAsString = outputFlagsToString(flags);
1508 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001509}
1510
1511// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001512
1513void AudioFlinger::PlaybackThread::onFirstRef()
1514{
Glenn Kastend7dca052015-03-05 16:05:54 -08001515 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001516}
1517
1518// ThreadBase virtuals
1519void AudioFlinger::PlaybackThread::preExit()
1520{
1521 ALOGV(" preExit()");
1522 // FIXME this is using hard-coded strings but in the future, this functionality will be
1523 // converted to use audio HAL extensions required to support tunneling
1524 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1525}
1526
1527// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1528sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1529 const sp<AudioFlinger::Client>& client,
1530 audio_stream_type_t streamType,
1531 uint32_t sampleRate,
1532 audio_format_t format,
1533 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001534 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001535 const sp<IMemory>& sharedBuffer,
1536 int sessionId,
1537 IAudioFlinger::track_flags_t *flags,
1538 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001539 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001540 status_t *status)
1541{
Glenn Kasten74935e42013-12-19 08:56:45 -08001542 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001543 sp<Track> track;
1544 status_t lStatus;
1545
1546 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1547
1548 // client expresses a preference for FAST, but we get the final say
1549 if (*flags & IAudioFlinger::TRACK_FAST) {
1550 if (
1551 // not timed
1552 (!isTimed) &&
1553 // either of these use cases:
1554 (
1555 // use case 1: shared buffer with any frame count
1556 (
1557 (sharedBuffer != 0)
1558 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001559 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001560 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001561 // we formerly checked for a callback handler (non-0 tid),
1562 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001563 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001564 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001565 )
1566 ) &&
1567 // PCM data
1568 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001569 // identical channel mask to sink, or mono in and stereo sink
1570 (channelMask == mChannelMask ||
1571 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1572 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001573 // hardware sample rate
1574 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001575 // normal mixer has an associated fast mixer
1576 hasFastMixer() &&
1577 // there are sufficient fast track slots available
1578 (mFastTrackAvailMask != 0)
1579 // FIXME test that MixerThread for this fast track has a capable output HAL
1580 // FIXME add a permission test also?
1581 ) {
1582 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1583 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001584 // read the fast track multiplier property the first time it is needed
1585 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1586 if (ok != 0) {
1587 ALOGE("%s pthread_once failed: %d", __func__, ok);
1588 }
1589 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001590 }
1591 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1592 frameCount, mFrameCount);
1593 } else {
1594 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001595 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1596 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001597 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001598 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001599 audio_is_linear_pcm(format),
1600 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1601 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001602 }
1603 }
1604 // For normal PCM streaming tracks, update minimum frame count.
1605 // For compatibility with AudioTrack calculation, buffer depth is forced
1606 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1607 // This is probably too conservative, but legacy application code may depend on it.
1608 // If you change this calculation, also review the start threshold which is related.
1609 if (!(*flags & IAudioFlinger::TRACK_FAST)
1610 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001611 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1612 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1613 if (minBufCount < 2) {
1614 minBufCount = 2;
1615 }
Andy Hung0e48d252015-01-26 11:43:15 -08001616 size_t minFrameCount =
1617 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1618 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001619 frameCount = minFrameCount;
1620 }
Eric Laurent81784c32012-11-19 14:55:58 -08001621 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001622 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001623
Glenn Kastenc3df8382014-03-13 15:05:25 -07001624 switch (mType) {
1625
1626 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001627 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001628 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001629 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1630 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001631 sampleRate, format, channelMask, mOutput, mFormat);
1632 lStatus = BAD_VALUE;
1633 goto Exit;
1634 }
1635 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001636 break;
1637
1638 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001639 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001640 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1641 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001642 sampleRate, format, channelMask, mOutput, mFormat);
1643 lStatus = BAD_VALUE;
1644 goto Exit;
1645 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001646 break;
1647
1648 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001649 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001650 ALOGE("createTrack_l() Bad parameter: format %#x \""
1651 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001652 format, mOutput, mFormat);
1653 lStatus = BAD_VALUE;
1654 goto Exit;
1655 }
Andy Hungcd044842014-08-07 11:04:34 -07001656 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001657 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1658 lStatus = BAD_VALUE;
1659 goto Exit;
1660 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001661 break;
1662
Eric Laurent81784c32012-11-19 14:55:58 -08001663 }
1664
1665 lStatus = initCheck();
1666 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001667 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001668 goto Exit;
1669 }
1670
1671 { // scope for mLock
1672 Mutex::Autolock _l(mLock);
1673
1674 // all tracks in same audio session must share the same routing strategy otherwise
1675 // conflicts will happen when tracks are moved from one output to another by audio policy
1676 // manager
1677 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1678 for (size_t i = 0; i < mTracks.size(); ++i) {
1679 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001680 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001681 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1682 if (sessionId == t->sessionId() && strategy != actual) {
1683 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1684 strategy, actual);
1685 lStatus = BAD_VALUE;
1686 goto Exit;
1687 }
1688 }
1689 }
1690
1691 if (!isTimed) {
1692 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001693 channelMask, frameCount, NULL, sharedBuffer,
1694 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001695 } else {
1696 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001697 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001698 }
Glenn Kasten03003332013-08-06 15:40:54 -07001699
1700 // new Track always returns non-NULL,
1701 // but TimedTrack::create() is a factory that could fail by returning NULL
1702 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1703 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001704 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001705 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001706 goto Exit;
1707 }
1708 mTracks.add(track);
1709
1710 sp<EffectChain> chain = getEffectChain_l(sessionId);
1711 if (chain != 0) {
1712 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1713 track->setMainBuffer(chain->inBuffer());
1714 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1715 chain->incTrackCnt();
1716 }
1717
1718 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1719 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1720 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1721 // so ask activity manager to do this on our behalf
1722 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1723 }
1724 }
1725
1726 lStatus = NO_ERROR;
1727
1728Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001729 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001730 return track;
1731}
1732
1733uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1734{
1735 return latency;
1736}
1737
1738uint32_t AudioFlinger::PlaybackThread::latency() const
1739{
1740 Mutex::Autolock _l(mLock);
1741 return latency_l();
1742}
1743uint32_t AudioFlinger::PlaybackThread::latency_l() const
1744{
1745 if (initCheck() == NO_ERROR) {
1746 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1747 } else {
1748 return 0;
1749 }
1750}
1751
1752void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1753{
1754 Mutex::Autolock _l(mLock);
1755 // Don't apply master volume in SW if our HAL can do it for us.
1756 if (mOutput && mOutput->audioHwDev &&
1757 mOutput->audioHwDev->canSetMasterVolume()) {
1758 mMasterVolume = 1.0;
1759 } else {
1760 mMasterVolume = value;
1761 }
1762}
1763
1764void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1765{
1766 Mutex::Autolock _l(mLock);
1767 // Don't apply master mute in SW if our HAL can do it for us.
1768 if (mOutput && mOutput->audioHwDev &&
1769 mOutput->audioHwDev->canSetMasterMute()) {
1770 mMasterMute = false;
1771 } else {
1772 mMasterMute = muted;
1773 }
1774}
1775
1776void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1777{
1778 Mutex::Autolock _l(mLock);
1779 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001780 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001781}
1782
1783void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1784{
1785 Mutex::Autolock _l(mLock);
1786 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001787 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001788}
1789
1790float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1791{
1792 Mutex::Autolock _l(mLock);
1793 return mStreamTypes[stream].volume;
1794}
1795
1796// addTrack_l() must be called with ThreadBase::mLock held
1797status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1798{
1799 status_t status = ALREADY_EXISTS;
1800
1801 // set retry count for buffer fill
1802 track->mRetryCount = kMaxTrackStartupRetries;
1803 if (mActiveTracks.indexOf(track) < 0) {
1804 // the track is newly added, make sure it fills up all its
1805 // buffers before playing. This is to ensure the client will
1806 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001807 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001808 TrackBase::track_state state = track->mState;
1809 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001810 status = AudioSystem::startOutput(mId, track->streamType(),
1811 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001812 mLock.lock();
1813 // abort track was stopped/paused while we released the lock
1814 if (state != track->mState) {
1815 if (status == NO_ERROR) {
1816 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001817 AudioSystem::stopOutput(mId, track->streamType(),
1818 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001819 mLock.lock();
1820 }
1821 return INVALID_OPERATION;
1822 }
1823 // abort if start is rejected by audio policy manager
1824 if (status != NO_ERROR) {
1825 return PERMISSION_DENIED;
1826 }
1827#ifdef ADD_BATTERY_DATA
1828 // to track the speaker usage
1829 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1830#endif
1831 }
1832
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001833 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001834 track->mResetDone = false;
1835 track->mPresentationCompleteFrames = 0;
1836 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001837 mWakeLockUids.add(track->uid());
1838 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001839 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001840 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1841 if (chain != 0) {
1842 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1843 track->sessionId());
1844 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001845 }
1846
1847 status = NO_ERROR;
1848 }
1849
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001850 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001851 return status;
1852}
1853
Eric Laurentbfb1b832013-01-07 09:53:42 -08001854bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001855{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001857 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001858 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1859 track->mState = TrackBase::STOPPED;
1860 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001861 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001862 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001863 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001864 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001865
1866 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1870{
1871 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1872 mTracks.remove(track);
1873 deleteTrackName_l(track->name());
1874 // redundant as track is about to be destroyed, for dumpsys only
1875 track->mName = -1;
1876 if (track->isFastTrack()) {
1877 int index = track->mFastIndex;
1878 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1879 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1880 mFastTrackAvailMask |= 1 << index;
1881 // redundant as track is about to be destroyed, for dumpsys only
1882 track->mFastIndex = -1;
1883 }
1884 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1885 if (chain != 0) {
1886 chain->decTrackCnt();
1887 }
1888}
1889
Eric Laurentede6c3b2013-09-19 14:37:46 -07001890void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891{
1892 // Thread could be blocked waiting for async
1893 // so signal it to handle state changes immediately
1894 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1895 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1896 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001897 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898}
1899
Eric Laurent81784c32012-11-19 14:55:58 -08001900String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1901{
Eric Laurent81784c32012-11-19 14:55:58 -08001902 Mutex::Autolock _l(mLock);
1903 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001904 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001905 }
1906
Glenn Kastend8ea6992013-07-16 14:17:15 -07001907 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1908 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001909 free(s);
1910 return out_s8;
1911}
1912
Eric Laurent021cf962014-05-13 10:18:14 -07001913void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001914 AudioSystem::OutputDescriptor desc;
1915 void *param2 = NULL;
1916
Eric Laurent021cf962014-05-13 10:18:14 -07001917 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001918 param);
1919
1920 switch (event) {
1921 case AudioSystem::OUTPUT_OPENED:
1922 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001923 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001924 desc.samplingRate = mSampleRate;
1925 desc.format = mFormat;
1926 desc.frameCount = mNormalFrameCount; // FIXME see
1927 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001928 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001929 param2 = &desc;
1930 break;
1931
1932 case AudioSystem::STREAM_CONFIG_CHANGED:
1933 param2 = &param;
1934 case AudioSystem::OUTPUT_CLOSED:
1935 default:
1936 break;
1937 }
Eric Laurent021cf962014-05-13 10:18:14 -07001938 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001939}
1940
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941void AudioFlinger::PlaybackThread::writeCallback()
1942{
1943 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001944 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945}
1946
1947void AudioFlinger::PlaybackThread::drainCallback()
1948{
1949 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951}
1952
Eric Laurent3b4529e2013-09-05 18:09:19 -07001953void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954{
1955 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001956 // reject out of sequence requests
1957 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1958 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001959 mWaitWorkCV.signal();
1960 }
1961}
1962
Eric Laurent3b4529e2013-09-05 18:09:19 -07001963void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001964{
1965 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001966 // reject out of sequence requests
1967 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1968 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001969 mWaitWorkCV.signal();
1970 }
1971}
1972
1973// static
1974int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001975 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976 void *cookie)
1977{
1978 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1979 ALOGV("asyncCallback() event %d", event);
1980 switch (event) {
1981 case STREAM_CBK_EVENT_WRITE_READY:
1982 me->writeCallback();
1983 break;
1984 case STREAM_CBK_EVENT_DRAIN_READY:
1985 me->drainCallback();
1986 break;
1987 default:
1988 ALOGW("asyncCallback() unknown event %d", event);
1989 break;
1990 }
1991 return 0;
1992}
1993
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001994void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001995{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001996 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001997 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1998 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001999 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002000 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002001 }
Andy Hung9a592762014-07-21 21:56:01 -07002002 if ((mType == MIXER || mType == DUPLICATING)
2003 && !isValidPcmSinkChannelMask(mChannelMask)) {
2004 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2005 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002006 }
Andy Hunge5412692014-05-16 11:25:07 -07002007 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002008 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2009 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002010 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002011 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002012 }
Andy Hung6146c082014-03-18 11:56:15 -07002013 if ((mType == MIXER || mType == DUPLICATING)
2014 && !isValidPcmSinkFormat(mFormat)) {
2015 LOG_FATAL("HAL format %#x not supported for mixed output",
2016 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002017 }
Phil Burk062e67a2015-02-11 13:40:50 -08002018 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002019 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2020 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002021 if (mFrameCount & 15) {
2022 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2023 mFrameCount);
2024 }
2025
Eric Laurentbfb1b832013-01-07 09:53:42 -08002026 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2027 (mOutput->stream->set_callback != NULL)) {
2028 if (mOutput->stream->set_callback(mOutput->stream,
2029 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2030 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002031 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 }
2033 }
2034
Eric Laurentd1f69b02014-12-15 14:33:13 -08002035 mHwSupportsPause = false;
2036 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2037 if (mOutput->stream->pause != NULL) {
2038 if (mOutput->stream->resume != NULL) {
2039 mHwSupportsPause = true;
2040 } else {
2041 ALOGW("direct output implements pause but not resume");
2042 }
2043 } else if (mOutput->stream->resume != NULL) {
2044 ALOGW("direct output implements resume but not pause");
2045 }
2046 }
2047
Andy Hungfbfc3952015-01-15 13:33:51 -08002048 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2049 // For best precision, we use float instead of the associated output
2050 // device format (typically PCM 16 bit).
2051
2052 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2053 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2054 mBufferSize = mFrameSize * mFrameCount;
2055
2056 // TODO: We currently use the associated output device channel mask and sample rate.
2057 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2058 // (if a valid mask) to avoid premature downmix.
2059 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2060 // instead of the output device sample rate to avoid loss of high frequency information.
2061 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2062 }
2063
Andy Hung09a50072014-02-27 14:30:47 -08002064 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002065 double multiplier = 1.0;
2066 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2067 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002068 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2069 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002070 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2071 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2072 maxNormalFrameCount = maxNormalFrameCount & ~15;
2073 if (maxNormalFrameCount < minNormalFrameCount) {
2074 maxNormalFrameCount = minNormalFrameCount;
2075 }
2076 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2077 if (multiplier <= 1.0) {
2078 multiplier = 1.0;
2079 } else if (multiplier <= 2.0) {
2080 if (2 * mFrameCount <= maxNormalFrameCount) {
2081 multiplier = 2.0;
2082 } else {
2083 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2084 }
2085 } else {
2086 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002087 // 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 -08002088 // track, but we sometimes have to do this to satisfy the maximum frame count
2089 // constraint)
2090 // FIXME this rounding up should not be done if no HAL SRC
2091 uint32_t truncMult = (uint32_t) multiplier;
2092 if ((truncMult & 1)) {
2093 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2094 ++truncMult;
2095 }
2096 }
2097 multiplier = (double) truncMult;
2098 }
2099 }
2100 mNormalFrameCount = multiplier * mFrameCount;
2101 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002102 if (mType == MIXER || mType == DUPLICATING) {
2103 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2104 }
Andy Hung09a50072014-02-27 14:30:47 -08002105 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002106 mNormalFrameCount);
2107
Andy Hung010a1a12014-03-13 13:57:33 -07002108 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2109 // Originally this was int16_t[] array, need to remove legacy implications.
2110 free(mSinkBuffer);
2111 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002112 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2113 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2114 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002115 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002116
Andy Hung69aed5f2014-02-25 17:24:40 -08002117 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2118 // drives the output.
2119 free(mMixerBuffer);
2120 mMixerBuffer = NULL;
2121 if (mMixerBufferEnabled) {
2122 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2123 mMixerBufferSize = mNormalFrameCount * mChannelCount
2124 * audio_bytes_per_sample(mMixerBufferFormat);
2125 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2126 }
Andy Hung98ef9782014-03-04 14:46:50 -08002127 free(mEffectBuffer);
2128 mEffectBuffer = NULL;
2129 if (mEffectBufferEnabled) {
2130 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2131 mEffectBufferSize = mNormalFrameCount * mChannelCount
2132 * audio_bytes_per_sample(mEffectBufferFormat);
2133 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2134 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002135
Eric Laurent81784c32012-11-19 14:55:58 -08002136 // force reconfiguration of effect chains and engines to take new buffer size and audio
2137 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002138 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002139 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2140 // matter.
2141 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2142 Vector< sp<EffectChain> > effectChains = mEffectChains;
2143 for (size_t i = 0; i < effectChains.size(); i ++) {
2144 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2145 }
2146}
2147
2148
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002149status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002150{
2151 if (halFrames == NULL || dspFrames == NULL) {
2152 return BAD_VALUE;
2153 }
2154 Mutex::Autolock _l(mLock);
2155 if (initCheck() != NO_ERROR) {
2156 return INVALID_OPERATION;
2157 }
2158 size_t framesWritten = mBytesWritten / mFrameSize;
2159 *halFrames = framesWritten;
2160
2161 if (isSuspended()) {
2162 // return an estimation of rendered frames when the output is suspended
2163 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2164 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2165 return NO_ERROR;
2166 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002167 status_t status;
2168 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002169 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002170 *dspFrames = (size_t)frames;
2171 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002172 }
2173}
2174
2175uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2176{
2177 Mutex::Autolock _l(mLock);
2178 uint32_t result = 0;
2179 if (getEffectChain_l(sessionId) != 0) {
2180 result = EFFECT_SESSION;
2181 }
2182
2183 for (size_t i = 0; i < mTracks.size(); ++i) {
2184 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002185 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002186 result |= TRACK_SESSION;
2187 break;
2188 }
2189 }
2190
2191 return result;
2192}
2193
2194uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2195{
2196 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2197 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2198 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2199 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2200 }
2201 for (size_t i = 0; i < mTracks.size(); i++) {
2202 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002203 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002204 return AudioSystem::getStrategyForStream(track->streamType());
2205 }
2206 }
2207 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2208}
2209
2210
Phil Burk062e67a2015-02-11 13:40:50 -08002211AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002212{
2213 Mutex::Autolock _l(mLock);
2214 return mOutput;
2215}
2216
Phil Burk062e67a2015-02-11 13:40:50 -08002217AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
2219 Mutex::Autolock _l(mLock);
2220 AudioStreamOut *output = mOutput;
2221 mOutput = NULL;
2222 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2223 // must push a NULL and wait for ack
2224 mOutputSink.clear();
2225 mPipeSink.clear();
2226 mNormalSink.clear();
2227 return output;
2228}
2229
2230// this method must always be called either with ThreadBase mLock held or inside the thread loop
2231audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2232{
2233 if (mOutput == NULL) {
2234 return NULL;
2235 }
2236 return &mOutput->stream->common;
2237}
2238
2239uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2240{
2241 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2242}
2243
2244status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2245{
2246 if (!isValidSyncEvent(event)) {
2247 return BAD_VALUE;
2248 }
2249
2250 Mutex::Autolock _l(mLock);
2251
2252 for (size_t i = 0; i < mTracks.size(); ++i) {
2253 sp<Track> track = mTracks[i];
2254 if (event->triggerSession() == track->sessionId()) {
2255 (void) track->setSyncEvent(event);
2256 return NO_ERROR;
2257 }
2258 }
2259
2260 return NAME_NOT_FOUND;
2261}
2262
2263bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2264{
2265 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2266}
2267
2268void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2269 const Vector< sp<Track> >& tracksToRemove)
2270{
2271 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002272 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002273 for (size_t i = 0 ; i < count ; i++) {
2274 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002275 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002276 AudioSystem::stopOutput(mId, track->streamType(),
2277 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278#ifdef ADD_BATTERY_DATA
2279 // to track the speaker usage
2280 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2281#endif
2282 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002283 AudioSystem::releaseOutput(mId, track->streamType(),
2284 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002285 }
Eric Laurent81784c32012-11-19 14:55:58 -08002286 }
2287 }
2288 }
Eric Laurent81784c32012-11-19 14:55:58 -08002289}
2290
2291void AudioFlinger::PlaybackThread::checkSilentMode_l()
2292{
2293 if (!mMasterMute) {
2294 char value[PROPERTY_VALUE_MAX];
2295 if (property_get("ro.audio.silent", value, "0") > 0) {
2296 char *endptr;
2297 unsigned long ul = strtoul(value, &endptr, 0);
2298 if (*endptr == '\0' && ul != 0) {
2299 ALOGD("Silence is golden");
2300 // The setprop command will not allow a property to be changed after
2301 // the first time it is set, so we don't have to worry about un-muting.
2302 setMasterMute_l(true);
2303 }
2304 }
2305 }
2306}
2307
2308// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002309ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002310{
2311 // FIXME rewrite to reduce number of system calls
2312 mLastWriteTime = systemTime();
2313 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002315 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002316
2317 // If an NBAIO sink is present, use it to write the normal mixer's submix
2318 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002319
Andy Hung010a1a12014-03-13 13:57:33 -07002320 const size_t count = mBytesRemaining / mFrameSize;
2321
Simon Wilson2d590962012-11-29 15:18:50 -08002322 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002323 // update the setpoint when AudioFlinger::mScreenState changes
2324 uint32_t screenState = AudioFlinger::mScreenState;
2325 if (screenState != mScreenState) {
2326 mScreenState = screenState;
2327 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2328 if (pipe != NULL) {
2329 pipe->setAvgFrames((mScreenState & 1) ?
2330 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2331 }
2332 }
Andy Hung010a1a12014-03-13 13:57:33 -07002333 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002334 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002335 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002336 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002337 } else {
2338 bytesWritten = framesWritten;
2339 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002340 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002341 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002342 if (status == NO_ERROR) {
2343 size_t totalFramesWritten = mNormalSink->framesWritten();
2344 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2345 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002346 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002347 mLatchDValid = true;
2348 }
2349 }
Eric Laurent81784c32012-11-19 14:55:58 -08002350 // otherwise use the HAL / AudioStreamOut directly
2351 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002353
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002355 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2356 mWriteAckSequence += 2;
2357 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002358 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002359 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002360 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002361 // FIXME We should have an implementation of timestamps for direct output threads.
2362 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002363 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 if (mUseAsyncWrite &&
2365 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2366 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002367 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002369 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 }
Eric Laurent81784c32012-11-19 14:55:58 -08002371 }
2372
Eric Laurent81784c32012-11-19 14:55:58 -08002373 mNumWrites++;
2374 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002375 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 return bytesWritten;
2377}
2378
2379void AudioFlinger::PlaybackThread::threadLoop_drain()
2380{
2381 if (mOutput->stream->drain) {
2382 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2383 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002384 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2385 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002387 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 }
2389 mOutput->stream->drain(mOutput->stream,
2390 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2391 : AUDIO_DRAIN_ALL);
2392 }
2393}
2394
2395void AudioFlinger::PlaybackThread::threadLoop_exit()
2396{
Eric Laurent275e8e92014-11-30 15:14:47 -08002397 {
2398 Mutex::Autolock _l(mLock);
2399 for (size_t i = 0; i < mTracks.size(); i++) {
2400 sp<Track> track = mTracks[i];
2401 track->invalidate();
2402 }
2403 }
Eric Laurent81784c32012-11-19 14:55:58 -08002404}
2405
2406/*
2407The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002408 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002409 - activeSleepTime from activeSleepTimeUs()
2410 - idleSleepTime from idleSleepTimeUs()
2411 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2412 - maxPeriod from frame count and sample rate (MIXER only)
2413
2414The parameters that affect these derived values are:
2415 - frame count
2416 - frame size
2417 - sample rate
2418 - device type: A2DP or not
2419 - device latency
2420 - format: PCM or not
2421 - active sleep time
2422 - idle sleep time
2423*/
2424
2425void AudioFlinger::PlaybackThread::cacheParameters_l()
2426{
Andy Hung25c2dac2014-02-27 14:56:00 -08002427 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002428 activeSleepTime = activeSleepTimeUs();
2429 idleSleepTime = idleSleepTimeUs();
2430}
2431
2432void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2433{
Glenn Kasten7c027242012-12-26 14:43:16 -08002434 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002435 this, streamType, mTracks.size());
2436 Mutex::Autolock _l(mLock);
2437
2438 size_t size = mTracks.size();
2439 for (size_t i = 0; i < size; i++) {
2440 sp<Track> t = mTracks[i];
2441 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002442 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002443 }
2444 }
2445}
2446
2447status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2448{
2449 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002450 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2451 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002452 bool ownsBuffer = false;
2453
2454 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2455 if (session > 0) {
2456 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002457 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002458 if (mType != DIRECT) {
2459 size_t numSamples = mNormalFrameCount * mChannelCount;
2460 buffer = new int16_t[numSamples];
2461 memset(buffer, 0, numSamples * sizeof(int16_t));
2462 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2463 ownsBuffer = true;
2464 }
2465
2466 // Attach all tracks with same session ID to this chain.
2467 for (size_t i = 0; i < mTracks.size(); ++i) {
2468 sp<Track> track = mTracks[i];
2469 if (session == track->sessionId()) {
2470 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2471 buffer);
2472 track->setMainBuffer(buffer);
2473 chain->incTrackCnt();
2474 }
2475 }
2476
2477 // indicate all active tracks in the chain
2478 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2479 sp<Track> track = mActiveTracks[i].promote();
2480 if (track == 0) {
2481 continue;
2482 }
2483 if (session == track->sessionId()) {
2484 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2485 chain->incActiveTrackCnt();
2486 }
2487 }
2488 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002489 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002490 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002491 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2492 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002493 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2494 // chains list in order to be processed last as it contains output stage effects
2495 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2496 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2497 // after track specific effects and before output stage
2498 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2499 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2500 // Effect chain for other sessions are inserted at beginning of effect
2501 // chains list to be processed before output mix effects. Relative order between other
2502 // sessions is not important
2503 size_t size = mEffectChains.size();
2504 size_t i = 0;
2505 for (i = 0; i < size; i++) {
2506 if (mEffectChains[i]->sessionId() < session) {
2507 break;
2508 }
2509 }
2510 mEffectChains.insertAt(chain, i);
2511 checkSuspendOnAddEffectChain_l(chain);
2512
2513 return NO_ERROR;
2514}
2515
2516size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2517{
2518 int session = chain->sessionId();
2519
2520 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2521
2522 for (size_t i = 0; i < mEffectChains.size(); i++) {
2523 if (chain == mEffectChains[i]) {
2524 mEffectChains.removeAt(i);
2525 // detach all active tracks from the chain
2526 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2527 sp<Track> track = mActiveTracks[i].promote();
2528 if (track == 0) {
2529 continue;
2530 }
2531 if (session == track->sessionId()) {
2532 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2533 chain.get(), session);
2534 chain->decActiveTrackCnt();
2535 }
2536 }
2537
2538 // detach all tracks with same session ID from this chain
2539 for (size_t i = 0; i < mTracks.size(); ++i) {
2540 sp<Track> track = mTracks[i];
2541 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002542 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002543 chain->decTrackCnt();
2544 }
2545 }
2546 break;
2547 }
2548 }
2549 return mEffectChains.size();
2550}
2551
2552status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2553 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2554{
2555 Mutex::Autolock _l(mLock);
2556 return attachAuxEffect_l(track, EffectId);
2557}
2558
2559status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2560 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2561{
2562 status_t status = NO_ERROR;
2563
2564 if (EffectId == 0) {
2565 track->setAuxBuffer(0, NULL);
2566 } else {
2567 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2568 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2569 if (effect != 0) {
2570 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2571 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2572 } else {
2573 status = INVALID_OPERATION;
2574 }
2575 } else {
2576 status = BAD_VALUE;
2577 }
2578 }
2579 return status;
2580}
2581
2582void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2583{
2584 for (size_t i = 0; i < mTracks.size(); ++i) {
2585 sp<Track> track = mTracks[i];
2586 if (track->auxEffectId() == effectId) {
2587 attachAuxEffect_l(track, 0);
2588 }
2589 }
2590}
2591
2592bool AudioFlinger::PlaybackThread::threadLoop()
2593{
2594 Vector< sp<Track> > tracksToRemove;
2595
2596 standbyTime = systemTime();
2597
2598 // MIXER
2599 nsecs_t lastWarning = 0;
2600
2601 // DUPLICATING
2602 // FIXME could this be made local to while loop?
2603 writeFrames = 0;
2604
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002605 int lastGeneration = 0;
2606
Eric Laurent81784c32012-11-19 14:55:58 -08002607 cacheParameters_l();
2608 sleepTime = idleSleepTime;
2609
2610 if (mType == MIXER) {
2611 sleepTimeShift = 0;
2612 }
2613
2614 CpuStats cpuStats;
2615 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2616
2617 acquireWakeLock();
2618
Glenn Kasten9e58b552013-01-18 15:09:48 -08002619 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2620 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2621 // and then that string will be logged at the next convenient opportunity.
2622 const char *logString = NULL;
2623
Eric Laurent664539d2013-09-23 18:24:31 -07002624 checkSilentMode_l();
2625
Eric Laurent81784c32012-11-19 14:55:58 -08002626 while (!exitPending())
2627 {
2628 cpuStats.sample(myName);
2629
2630 Vector< sp<EffectChain> > effectChains;
2631
Eric Laurent81784c32012-11-19 14:55:58 -08002632 { // scope for mLock
2633
2634 Mutex::Autolock _l(mLock);
2635
Eric Laurent021cf962014-05-13 10:18:14 -07002636 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002637
Glenn Kasten9e58b552013-01-18 15:09:48 -08002638 if (logString != NULL) {
2639 mNBLogWriter->logTimestamp();
2640 mNBLogWriter->log(logString);
2641 logString = NULL;
2642 }
2643
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002644 // Gather the framesReleased counters for all active tracks,
2645 // and latch them atomically with the timestamp.
2646 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2647 mLatchD.mFramesReleased.clear();
2648 size_t size = mActiveTracks.size();
2649 for (size_t i = 0; i < size; i++) {
2650 sp<Track> t = mActiveTracks[i].promote();
2651 if (t != 0) {
2652 mLatchD.mFramesReleased.add(t.get(),
2653 t->mAudioTrackServerProxy->framesReleased());
2654 }
2655 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002656 if (mLatchDValid) {
2657 mLatchQ = mLatchD;
2658 mLatchDValid = false;
2659 mLatchQValid = true;
2660 }
2661
Eric Laurent81784c32012-11-19 14:55:58 -08002662 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 if (mSignalPending) {
2664 // A signal was raised while we were unlocked
2665 mSignalPending = false;
2666 } else if (waitingAsyncCallback_l()) {
2667 if (exitPending()) {
2668 break;
2669 }
2670 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002671 mWakeLockUids.clear();
2672 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 ALOGV("wait async completion");
2674 mWaitWorkCV.wait(mLock);
2675 ALOGV("async completion/wake");
2676 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002677 standbyTime = systemTime() + standbyDelay;
2678 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002679
2680 continue;
2681 }
2682 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 isSuspended()) {
2684 // put audio hardware into standby after short delay
2685 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002686
2687 threadLoop_standby();
2688
2689 mStandby = true;
2690 }
2691
2692 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2693 // we're about to wait, flush the binder command buffer
2694 IPCThreadState::self()->flushCommands();
2695
2696 clearOutputTracks();
2697
2698 if (exitPending()) {
2699 break;
2700 }
2701
2702 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002703 mWakeLockUids.clear();
2704 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002705 // wait until we have something to do...
2706 ALOGV("%s going to sleep", myName.string());
2707 mWaitWorkCV.wait(mLock);
2708 ALOGV("%s waking up", myName.string());
2709 acquireWakeLock_l();
2710
2711 mMixerStatus = MIXER_IDLE;
2712 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2713 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002715 checkSilentMode_l();
2716
2717 standbyTime = systemTime() + standbyDelay;
2718 sleepTime = idleSleepTime;
2719 if (mType == MIXER) {
2720 sleepTimeShift = 0;
2721 }
2722
2723 continue;
2724 }
2725 }
Eric Laurent81784c32012-11-19 14:55:58 -08002726 // mMixerStatusIgnoringFastTracks is also updated internally
2727 mMixerStatus = prepareTracks_l(&tracksToRemove);
2728
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002729 // compare with previously applied list
2730 if (lastGeneration != mActiveTracksGeneration) {
2731 // update wakelock
2732 updateWakeLockUids_l(mWakeLockUids);
2733 lastGeneration = mActiveTracksGeneration;
2734 }
2735
Eric Laurent81784c32012-11-19 14:55:58 -08002736 // prevent any changes in effect chain list and in each effect chain
2737 // during mixing and effect process as the audio buffers could be deleted
2738 // or modified if an effect is created or deleted
2739 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002740 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002741
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 if (mBytesRemaining == 0) {
2743 mCurrentWriteLength = 0;
2744 if (mMixerStatus == MIXER_TRACKS_READY) {
2745 // threadLoop_mix() sets mCurrentWriteLength
2746 threadLoop_mix();
2747 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2748 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2749 // threadLoop_sleepTime sets sleepTime to 0 if data
2750 // must be written to HAL
2751 threadLoop_sleepTime();
2752 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002753 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 }
2755 }
Andy Hung98ef9782014-03-04 14:46:50 -08002756 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2757 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2758 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2759 // or mSinkBuffer (if there are no effects).
2760 //
2761 // This is done pre-effects computation; if effects change to
2762 // support higher precision, this needs to move.
2763 //
2764 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2765 // TODO use sleepTime == 0 as an additional condition.
2766 if (mMixerBufferValid) {
2767 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2768 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2769
2770 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2771 mNormalFrameCount * mChannelCount);
2772 }
2773
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 mBytesRemaining = mCurrentWriteLength;
2775 if (isSuspended()) {
2776 sleepTime = suspendSleepTimeUs();
2777 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002778 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 mBytesRemaining = 0;
2780 }
Eric Laurent81784c32012-11-19 14:55:58 -08002781
Eric Laurentbfb1b832013-01-07 09:53:42 -08002782 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002783 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784 for (size_t i = 0; i < effectChains.size(); i ++) {
2785 effectChains[i]->process_l();
2786 }
Eric Laurent81784c32012-11-19 14:55:58 -08002787 }
2788 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002789 // Process effect chains for offloaded thread even if no audio
2790 // was read from audio track: process only updates effect state
2791 // and thus does have to be synchronized with audio writes but may have
2792 // to be called while waiting for async write callback
2793 if (mType == OFFLOAD) {
2794 for (size_t i = 0; i < effectChains.size(); i ++) {
2795 effectChains[i]->process_l();
2796 }
2797 }
Eric Laurent81784c32012-11-19 14:55:58 -08002798
Andy Hung98ef9782014-03-04 14:46:50 -08002799 // Only if the Effects buffer is enabled and there is data in the
2800 // Effects buffer (buffer valid), we need to
2801 // copy into the sink buffer.
2802 // TODO use sleepTime == 0 as an additional condition.
2803 if (mEffectBufferValid) {
2804 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2805 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2806 mNormalFrameCount * mChannelCount);
2807 }
2808
Eric Laurent81784c32012-11-19 14:55:58 -08002809 // enable changes in effect chain
2810 unlockEffectChains(effectChains);
2811
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812 if (!waitingAsyncCallback()) {
2813 // sleepTime == 0 means we must write to audio hardware
2814 if (sleepTime == 0) {
2815 if (mBytesRemaining) {
2816 ssize_t ret = threadLoop_write();
2817 if (ret < 0) {
2818 mBytesRemaining = 0;
2819 } else {
2820 mBytesWritten += ret;
2821 mBytesRemaining -= ret;
2822 }
2823 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2824 (mMixerStatus == MIXER_DRAIN_ALL)) {
2825 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002826 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002827 if (mType == MIXER) {
2828 // write blocked detection
2829 nsecs_t now = systemTime();
2830 nsecs_t delta = now - mLastWriteTime;
2831 if (!mStandby && delta > maxPeriod) {
2832 mNumDelayedWrites++;
2833 if ((now - lastWarning) > kWarningThrottleNs) {
2834 ATRACE_NAME("underrun");
2835 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2836 ns2ms(delta), mNumDelayedWrites, this);
2837 lastWarning = now;
2838 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 }
2840 }
Eric Laurent81784c32012-11-19 14:55:58 -08002841
Eric Laurentbfb1b832013-01-07 09:53:42 -08002842 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002843 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002844 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002845 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846 }
Eric Laurent81784c32012-11-19 14:55:58 -08002847 }
2848
2849 // Finally let go of removed track(s), without the lock held
2850 // since we can't guarantee the destructors won't acquire that
2851 // same lock. This will also mutate and push a new fast mixer state.
2852 threadLoop_removeTracks(tracksToRemove);
2853 tracksToRemove.clear();
2854
2855 // FIXME I don't understand the need for this here;
2856 // it was in the original code but maybe the
2857 // assignment in saveOutputTracks() makes this unnecessary?
2858 clearOutputTracks();
2859
2860 // Effect chains will be actually deleted here if they were removed from
2861 // mEffectChains list during mixing or effects processing
2862 effectChains.clear();
2863
2864 // FIXME Note that the above .clear() is no longer necessary since effectChains
2865 // is now local to this block, but will keep it for now (at least until merge done).
2866 }
2867
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 threadLoop_exit();
2869
Eric Laurentcf817a22014-08-04 20:36:31 -07002870 if (!mStandby) {
2871 threadLoop_standby();
2872 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002873 }
2874
2875 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002876 mWakeLockUids.clear();
2877 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002878
2879 ALOGV("Thread %p type %d exiting", this, mType);
2880 return false;
2881}
2882
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883// removeTracks_l() must be called with ThreadBase::mLock held
2884void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2885{
2886 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002887 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 for (size_t i=0 ; i<count ; i++) {
2889 const sp<Track>& track = tracksToRemove.itemAt(i);
2890 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002891 mWakeLockUids.remove(track->uid());
2892 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2894 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2895 if (chain != 0) {
2896 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2897 track->sessionId());
2898 chain->decActiveTrackCnt();
2899 }
2900 if (track->isTerminated()) {
2901 removeTrack_l(track);
2902 }
2903 }
2904 }
2905
2906}
Eric Laurent81784c32012-11-19 14:55:58 -08002907
Eric Laurentaccc1472013-09-20 09:36:34 -07002908status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2909{
2910 if (mNormalSink != 0) {
2911 return mNormalSink->getTimestamp(timestamp);
2912 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002913 if ((mType == OFFLOAD || mType == DIRECT)
2914 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002915 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002916 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002917 if (ret == 0) {
2918 timestamp.mPosition = (uint32_t)position64;
2919 return NO_ERROR;
2920 }
2921 }
2922 return INVALID_OPERATION;
2923}
Eric Laurent1c333e22014-05-20 10:48:17 -07002924
2925status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2926 audio_patch_handle_t *handle)
2927{
2928 status_t status = NO_ERROR;
2929 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2930 // store new device and send to effects
2931 audio_devices_t type = AUDIO_DEVICE_NONE;
2932 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2933 type |= patch->sinks[i].ext.device.type;
2934 }
2935 mOutDevice = type;
2936 for (size_t i = 0; i < mEffectChains.size(); i++) {
2937 mEffectChains[i]->setDevice_l(mOutDevice);
2938 }
2939
2940 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2941 status = hwDevice->create_audio_patch(hwDevice,
2942 patch->num_sources,
2943 patch->sources,
2944 patch->num_sinks,
2945 patch->sinks,
2946 handle);
2947 } else {
2948 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2949 }
2950 return status;
2951}
2952
2953status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2954{
2955 status_t status = NO_ERROR;
2956 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2957 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2958 status = hwDevice->release_audio_patch(hwDevice, handle);
2959 } else {
2960 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2961 }
2962 return status;
2963}
2964
Eric Laurent83b88082014-06-20 18:31:16 -07002965void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2966{
2967 Mutex::Autolock _l(mLock);
2968 mTracks.add(track);
2969}
2970
2971void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2972{
2973 Mutex::Autolock _l(mLock);
2974 destroyTrack_l(track);
2975}
2976
2977void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2978{
2979 ThreadBase::getAudioPortConfig(config);
2980 config->role = AUDIO_PORT_ROLE_SOURCE;
2981 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2982 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2983}
2984
Eric Laurent81784c32012-11-19 14:55:58 -08002985// ----------------------------------------------------------------------------
2986
2987AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2988 audio_io_handle_t id, audio_devices_t device, type_t type)
2989 : PlaybackThread(audioFlinger, output, id, device, type),
2990 // mAudioMixer below
2991 // mFastMixer below
2992 mFastMixerFutex(0)
2993 // mOutputSink below
2994 // mPipeSink below
2995 // mNormalSink below
2996{
2997 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002998 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002999 "mFrameCount=%d, mNormalFrameCount=%d",
3000 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3001 mNormalFrameCount);
3002 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3003
Andy Hungfbfc3952015-01-15 13:33:51 -08003004 if (type == DUPLICATING) {
3005 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3006 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3007 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3008 return;
3009 }
Eric Laurent81784c32012-11-19 14:55:58 -08003010 // create an NBAIO sink for the HAL output stream, and negotiate
3011 mOutputSink = new AudioStreamOutSink(output->stream);
3012 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003013 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003014 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3015 ALOG_ASSERT(index == 0);
3016
3017 // initialize fast mixer depending on configuration
3018 bool initFastMixer;
3019 switch (kUseFastMixer) {
3020 case FastMixer_Never:
3021 initFastMixer = false;
3022 break;
3023 case FastMixer_Always:
3024 initFastMixer = true;
3025 break;
3026 case FastMixer_Static:
3027 case FastMixer_Dynamic:
3028 initFastMixer = mFrameCount < mNormalFrameCount;
3029 break;
3030 }
3031 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003032 audio_format_t fastMixerFormat;
3033 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3034 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3035 } else {
3036 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3037 }
3038 if (mFormat != fastMixerFormat) {
3039 // change our Sink format to accept our intermediate precision
3040 mFormat = fastMixerFormat;
3041 free(mSinkBuffer);
3042 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3043 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3044 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3045 }
Eric Laurent81784c32012-11-19 14:55:58 -08003046
3047 // create a MonoPipe to connect our submix to FastMixer
3048 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003049 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003050 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003051 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003052 format.mFormat = fastMixerFormat;
3053 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3054
Eric Laurent81784c32012-11-19 14:55:58 -08003055 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3056 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3057 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3058 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3059 const NBAIO_Format offers[1] = {format};
3060 size_t numCounterOffers = 0;
3061 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3062 ALOG_ASSERT(index == 0);
3063 monoPipe->setAvgFrames((mScreenState & 1) ?
3064 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3065 mPipeSink = monoPipe;
3066
Glenn Kasten46909e72013-02-26 09:20:22 -08003067#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003068 if (mTeeSinkOutputEnabled) {
3069 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003070 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3071 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003072 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003073 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003074 ALOG_ASSERT(index == 0);
3075 mTeeSink = teeSink;
3076 PipeReader *teeSource = new PipeReader(*teeSink);
3077 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003078 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003079 ALOG_ASSERT(index == 0);
3080 mTeeSource = teeSource;
3081 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003082#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003083
3084 // create fast mixer and configure it initially with just one fast track for our submix
3085 mFastMixer = new FastMixer();
3086 FastMixerStateQueue *sq = mFastMixer->sq();
3087#ifdef STATE_QUEUE_DUMP
3088 sq->setObserverDump(&mStateQueueObserverDump);
3089 sq->setMutatorDump(&mStateQueueMutatorDump);
3090#endif
3091 FastMixerState *state = sq->begin();
3092 FastTrack *fastTrack = &state->mFastTracks[0];
3093 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3094 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3095 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003096 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3097 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003098 fastTrack->mGeneration++;
3099 state->mFastTracksGen++;
3100 state->mTrackMask = 1;
3101 // fast mixer will use the HAL output sink
3102 state->mOutputSink = mOutputSink.get();
3103 state->mOutputSinkGen++;
3104 state->mFrameCount = mFrameCount;
3105 state->mCommand = FastMixerState::COLD_IDLE;
3106 // already done in constructor initialization list
3107 //mFastMixerFutex = 0;
3108 state->mColdFutexAddr = &mFastMixerFutex;
3109 state->mColdGen++;
3110 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003111#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003112 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003113#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003114 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3115 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003116 sq->end();
3117 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3118
3119 // start the fast mixer
3120 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3121 pid_t tid = mFastMixer->getTid();
3122 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3123 if (err != 0) {
3124 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3125 kPriorityFastMixer, getpid_cached, tid, err);
3126 }
3127
3128#ifdef AUDIO_WATCHDOG
3129 // create and start the watchdog
3130 mAudioWatchdog = new AudioWatchdog();
3131 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3132 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3133 tid = mAudioWatchdog->getTid();
3134 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3135 if (err != 0) {
3136 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3137 kPriorityFastMixer, getpid_cached, tid, err);
3138 }
3139#endif
3140
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
3142
3143 switch (kUseFastMixer) {
3144 case FastMixer_Never:
3145 case FastMixer_Dynamic:
3146 mNormalSink = mOutputSink;
3147 break;
3148 case FastMixer_Always:
3149 mNormalSink = mPipeSink;
3150 break;
3151 case FastMixer_Static:
3152 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3153 break;
3154 }
3155}
3156
3157AudioFlinger::MixerThread::~MixerThread()
3158{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003159 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003160 FastMixerStateQueue *sq = mFastMixer->sq();
3161 FastMixerState *state = sq->begin();
3162 if (state->mCommand == FastMixerState::COLD_IDLE) {
3163 int32_t old = android_atomic_inc(&mFastMixerFutex);
3164 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003165 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003166 }
3167 }
3168 state->mCommand = FastMixerState::EXIT;
3169 sq->end();
3170 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3171 mFastMixer->join();
3172 // Though the fast mixer thread has exited, it's state queue is still valid.
3173 // We'll use that extract the final state which contains one remaining fast track
3174 // corresponding to our sub-mix.
3175 state = sq->begin();
3176 ALOG_ASSERT(state->mTrackMask == 1);
3177 FastTrack *fastTrack = &state->mFastTracks[0];
3178 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3179 delete fastTrack->mBufferProvider;
3180 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003181 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003182#ifdef AUDIO_WATCHDOG
3183 if (mAudioWatchdog != 0) {
3184 mAudioWatchdog->requestExit();
3185 mAudioWatchdog->requestExitAndWait();
3186 mAudioWatchdog.clear();
3187 }
3188#endif
3189 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003190 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003191 delete mAudioMixer;
3192}
3193
3194
3195uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3196{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003197 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003198 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3199 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3200 }
3201 return latency;
3202}
3203
3204
3205void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3206{
3207 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3208}
3209
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003211{
3212 // FIXME we should only do one push per cycle; confirm this is true
3213 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003214 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003215 FastMixerStateQueue *sq = mFastMixer->sq();
3216 FastMixerState *state = sq->begin();
3217 if (state->mCommand != FastMixerState::MIX_WRITE &&
3218 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3219 if (state->mCommand == FastMixerState::COLD_IDLE) {
3220 int32_t old = android_atomic_inc(&mFastMixerFutex);
3221 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003222 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003223 }
3224#ifdef AUDIO_WATCHDOG
3225 if (mAudioWatchdog != 0) {
3226 mAudioWatchdog->resume();
3227 }
3228#endif
3229 }
3230 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003231#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003232 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003233 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003234#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003235 sq->end();
3236 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3237 if (kUseFastMixer == FastMixer_Dynamic) {
3238 mNormalSink = mPipeSink;
3239 }
3240 } else {
3241 sq->end(false /*didModify*/);
3242 }
3243 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003244 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003245}
3246
3247void AudioFlinger::MixerThread::threadLoop_standby()
3248{
3249 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003250 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003251 FastMixerStateQueue *sq = mFastMixer->sq();
3252 FastMixerState *state = sq->begin();
3253 if (!(state->mCommand & FastMixerState::IDLE)) {
3254 state->mCommand = FastMixerState::COLD_IDLE;
3255 state->mColdFutexAddr = &mFastMixerFutex;
3256 state->mColdGen++;
3257 mFastMixerFutex = 0;
3258 sq->end();
3259 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3260 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3261 if (kUseFastMixer == FastMixer_Dynamic) {
3262 mNormalSink = mOutputSink;
3263 }
3264#ifdef AUDIO_WATCHDOG
3265 if (mAudioWatchdog != 0) {
3266 mAudioWatchdog->pause();
3267 }
3268#endif
3269 } else {
3270 sq->end(false /*didModify*/);
3271 }
3272 }
3273 PlaybackThread::threadLoop_standby();
3274}
3275
Eric Laurentbfb1b832013-01-07 09:53:42 -08003276bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3277{
3278 return false;
3279}
3280
3281bool AudioFlinger::PlaybackThread::shouldStandby_l()
3282{
3283 return !mStandby;
3284}
3285
3286bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3287{
3288 Mutex::Autolock _l(mLock);
3289 return waitingAsyncCallback_l();
3290}
3291
Eric Laurent81784c32012-11-19 14:55:58 -08003292// shared by MIXER and DIRECT, overridden by DUPLICATING
3293void AudioFlinger::PlaybackThread::threadLoop_standby()
3294{
3295 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003296 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003298 // discard any pending drain or write ack by incrementing sequence
3299 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3300 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003302 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3303 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003305 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003306}
3307
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003308void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3309{
3310 ALOGV("signal playback thread");
3311 broadcast_l();
3312}
3313
Eric Laurent81784c32012-11-19 14:55:58 -08003314void AudioFlinger::MixerThread::threadLoop_mix()
3315{
3316 // obtain the presentation timestamp of the next output buffer
3317 int64_t pts;
3318 status_t status = INVALID_OPERATION;
3319
3320 if (mNormalSink != 0) {
3321 status = mNormalSink->getNextWriteTimestamp(&pts);
3322 } else {
3323 status = mOutputSink->getNextWriteTimestamp(&pts);
3324 }
3325
3326 if (status != NO_ERROR) {
3327 pts = AudioBufferProvider::kInvalidPTS;
3328 }
3329
3330 // mix buffers...
3331 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003332 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003333 // increase sleep time progressively when application underrun condition clears.
3334 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3335 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3336 // such that we would underrun the audio HAL.
3337 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3338 sleepTimeShift--;
3339 }
3340 sleepTime = 0;
3341 standbyTime = systemTime() + standbyDelay;
3342 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003343
Eric Laurent81784c32012-11-19 14:55:58 -08003344}
3345
3346void AudioFlinger::MixerThread::threadLoop_sleepTime()
3347{
3348 // If no tracks are ready, sleep once for the duration of an output
3349 // buffer size, then write 0s to the output
3350 if (sleepTime == 0) {
3351 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3352 sleepTime = activeSleepTime >> sleepTimeShift;
3353 if (sleepTime < kMinThreadSleepTimeUs) {
3354 sleepTime = kMinThreadSleepTimeUs;
3355 }
3356 // reduce sleep time in case of consecutive application underruns to avoid
3357 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3358 // duration we would end up writing less data than needed by the audio HAL if
3359 // the condition persists.
3360 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3361 sleepTimeShift++;
3362 }
3363 } else {
3364 sleepTime = idleSleepTime;
3365 }
3366 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003367 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3368 // before effects processing or output.
3369 if (mMixerBufferValid) {
3370 memset(mMixerBuffer, 0, mMixerBufferSize);
3371 } else {
3372 memset(mSinkBuffer, 0, mSinkBufferSize);
3373 }
Eric Laurent81784c32012-11-19 14:55:58 -08003374 sleepTime = 0;
3375 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3376 "anticipated start");
3377 }
3378 // TODO add standby time extension fct of effect tail
3379}
3380
3381// prepareTracks_l() must be called with ThreadBase::mLock held
3382AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3383 Vector< sp<Track> > *tracksToRemove)
3384{
3385
3386 mixer_state mixerStatus = MIXER_IDLE;
3387 // find out which tracks need to be processed
3388 size_t count = mActiveTracks.size();
3389 size_t mixedTracks = 0;
3390 size_t tracksWithEffect = 0;
3391 // counts only _active_ fast tracks
3392 size_t fastTracks = 0;
3393 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3394
3395 float masterVolume = mMasterVolume;
3396 bool masterMute = mMasterMute;
3397
3398 if (masterMute) {
3399 masterVolume = 0;
3400 }
3401 // Delegate master volume control to effect in output mix effect chain if needed
3402 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3403 if (chain != 0) {
3404 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3405 chain->setVolume_l(&v, &v);
3406 masterVolume = (float)((v + (1 << 23)) >> 24);
3407 chain.clear();
3408 }
3409
3410 // prepare a new state to push
3411 FastMixerStateQueue *sq = NULL;
3412 FastMixerState *state = NULL;
3413 bool didModify = false;
3414 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003415 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003416 sq = mFastMixer->sq();
3417 state = sq->begin();
3418 }
3419
Andy Hung69aed5f2014-02-25 17:24:40 -08003420 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003421 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003422
Eric Laurent81784c32012-11-19 14:55:58 -08003423 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003424 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003425 if (t == 0) {
3426 continue;
3427 }
3428
3429 // this const just means the local variable doesn't change
3430 Track* const track = t.get();
3431
3432 // process fast tracks
3433 if (track->isFastTrack()) {
3434
3435 // It's theoretically possible (though unlikely) for a fast track to be created
3436 // and then removed within the same normal mix cycle. This is not a problem, as
3437 // the track never becomes active so it's fast mixer slot is never touched.
3438 // The converse, of removing an (active) track and then creating a new track
3439 // at the identical fast mixer slot within the same normal mix cycle,
3440 // is impossible because the slot isn't marked available until the end of each cycle.
3441 int j = track->mFastIndex;
3442 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3443 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3444 FastTrack *fastTrack = &state->mFastTracks[j];
3445
3446 // Determine whether the track is currently in underrun condition,
3447 // and whether it had a recent underrun.
3448 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3449 FastTrackUnderruns underruns = ftDump->mUnderruns;
3450 uint32_t recentFull = (underruns.mBitFields.mFull -
3451 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3452 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3453 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3454 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3455 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3456 uint32_t recentUnderruns = recentPartial + recentEmpty;
3457 track->mObservedUnderruns = underruns;
3458 // don't count underruns that occur while stopping or pausing
3459 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003460 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3461 recentUnderruns > 0) {
3462 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3463 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003464 }
3465
3466 // This is similar to the state machine for normal tracks,
3467 // with a few modifications for fast tracks.
3468 bool isActive = true;
3469 switch (track->mState) {
3470 case TrackBase::STOPPING_1:
3471 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003473 track->mState = TrackBase::STOPPING_2;
3474 }
3475 break;
3476 case TrackBase::PAUSING:
3477 // ramp down is not yet implemented
3478 track->setPaused();
3479 break;
3480 case TrackBase::RESUMING:
3481 // ramp up is not yet implemented
3482 track->mState = TrackBase::ACTIVE;
3483 break;
3484 case TrackBase::ACTIVE:
3485 if (recentFull > 0 || recentPartial > 0) {
3486 // track has provided at least some frames recently: reset retry count
3487 track->mRetryCount = kMaxTrackRetries;
3488 }
3489 if (recentUnderruns == 0) {
3490 // no recent underruns: stay active
3491 break;
3492 }
3493 // there has recently been an underrun of some kind
3494 if (track->sharedBuffer() == 0) {
3495 // were any of the recent underruns "empty" (no frames available)?
3496 if (recentEmpty == 0) {
3497 // no, then ignore the partial underruns as they are allowed indefinitely
3498 break;
3499 }
3500 // there has recently been an "empty" underrun: decrement the retry counter
3501 if (--(track->mRetryCount) > 0) {
3502 break;
3503 }
3504 // indicate to client process that the track was disabled because of underrun;
3505 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003506 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003507 // remove from active list, but state remains ACTIVE [confusing but true]
3508 isActive = false;
3509 break;
3510 }
3511 // fall through
3512 case TrackBase::STOPPING_2:
3513 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003514 case TrackBase::STOPPED:
3515 case TrackBase::FLUSHED: // flush() while active
3516 // Check for presentation complete if track is inactive
3517 // We have consumed all the buffers of this track.
3518 // This would be incomplete if we auto-paused on underrun
3519 {
3520 size_t audioHALFrames =
3521 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3522 size_t framesWritten = mBytesWritten / mFrameSize;
3523 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3524 // track stays in active list until presentation is complete
3525 break;
3526 }
3527 }
3528 if (track->isStopping_2()) {
3529 track->mState = TrackBase::STOPPED;
3530 }
3531 if (track->isStopped()) {
3532 // Can't reset directly, as fast mixer is still polling this track
3533 // track->reset();
3534 // So instead mark this track as needing to be reset after push with ack
3535 resetMask |= 1 << i;
3536 }
3537 isActive = false;
3538 break;
3539 case TrackBase::IDLE:
3540 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003541 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003542 }
3543
3544 if (isActive) {
3545 // was it previously inactive?
3546 if (!(state->mTrackMask & (1 << j))) {
3547 ExtendedAudioBufferProvider *eabp = track;
3548 VolumeProvider *vp = track;
3549 fastTrack->mBufferProvider = eabp;
3550 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003551 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003552 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003553 fastTrack->mGeneration++;
3554 state->mTrackMask |= 1 << j;
3555 didModify = true;
3556 // no acknowledgement required for newly active tracks
3557 }
3558 // cache the combined master volume and stream type volume for fast mixer; this
3559 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003560 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003561 ++fastTracks;
3562 } else {
3563 // was it previously active?
3564 if (state->mTrackMask & (1 << j)) {
3565 fastTrack->mBufferProvider = NULL;
3566 fastTrack->mGeneration++;
3567 state->mTrackMask &= ~(1 << j);
3568 didModify = true;
3569 // If any fast tracks were removed, we must wait for acknowledgement
3570 // because we're about to decrement the last sp<> on those tracks.
3571 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3572 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003573 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003574 }
3575 tracksToRemove->add(track);
3576 // Avoids a misleading display in dumpsys
3577 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3578 }
3579 continue;
3580 }
3581
3582 { // local variable scope to avoid goto warning
3583
3584 audio_track_cblk_t* cblk = track->cblk();
3585
3586 // The first time a track is added we wait
3587 // for all its buffers to be filled before processing it
3588 int name = track->name();
3589 // make sure that we have enough frames to mix one full buffer.
3590 // enforce this condition only once to enable draining the buffer in case the client
3591 // app does not call stop() and relies on underrun to stop:
3592 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3593 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003594 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003595 uint32_t sr = track->sampleRate();
3596 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003597 desiredFrames = mNormalFrameCount;
3598 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003599 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003600 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003601 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003602 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003603#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003604 // the minimum track buffer size is normally twice the number of frames necessary
3605 // to fill one buffer and the resampler should not leave more than one buffer worth
3606 // of unreleased frames after each pass, but just in case...
3607 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003608#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003609 }
Eric Laurent81784c32012-11-19 14:55:58 -08003610 uint32_t minFrames = 1;
3611 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3612 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003613 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003615
3616 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003617 if (ATRACE_ENABLED()) {
3618 // I wish we had formatted trace names
3619 char traceName[16];
3620 strcpy(traceName, "nRdy");
3621 int name = track->name();
3622 if (AudioMixer::TRACK0 <= name &&
3623 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3624 name -= AudioMixer::TRACK0;
3625 traceName[4] = (name / 10) + '0';
3626 traceName[5] = (name % 10) + '0';
3627 } else {
3628 traceName[4] = '?';
3629 traceName[5] = '?';
3630 }
3631 traceName[6] = '\0';
3632 ATRACE_INT(traceName, framesReady);
3633 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003634 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003635 !track->isPaused() && !track->isTerminated())
3636 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003637 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003638
3639 mixedTracks++;
3640
Andy Hung69aed5f2014-02-25 17:24:40 -08003641 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3642 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003643 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003644 if (track->mainBuffer() != mSinkBuffer &&
3645 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003646 if (mEffectBufferEnabled) {
3647 mEffectBufferValid = true; // Later can set directly.
3648 }
Eric Laurent81784c32012-11-19 14:55:58 -08003649 chain = getEffectChain_l(track->sessionId());
3650 // Delegate volume control to effect in track effect chain if needed
3651 if (chain != 0) {
3652 tracksWithEffect++;
3653 } else {
3654 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3655 "session %d",
3656 name, track->sessionId());
3657 }
3658 }
3659
3660
3661 int param = AudioMixer::VOLUME;
3662 if (track->mFillingUpStatus == Track::FS_FILLED) {
3663 // no ramp for the first volume setting
3664 track->mFillingUpStatus = Track::FS_ACTIVE;
3665 if (track->mState == TrackBase::RESUMING) {
3666 track->mState = TrackBase::ACTIVE;
3667 param = AudioMixer::RAMP_VOLUME;
3668 }
3669 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003670 // FIXME should not make a decision based on mServer
3671 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003672 // If the track is stopped before the first frame was mixed,
3673 // do not apply ramp
3674 param = AudioMixer::RAMP_VOLUME;
3675 }
3676
3677 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003678 uint32_t vl, vr; // in U8.24 integer format
3679 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003680 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003681 vl = vr = 0;
3682 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003683 if (track->isPausing()) {
3684 track->setPaused();
3685 }
3686 } else {
3687
3688 // read original volumes with volume control
3689 float typeVolume = mStreamTypes[track->streamType()].volume;
3690 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003691 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003692 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003693 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3694 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003696 if (vlf > GAIN_FLOAT_UNITY) {
3697 ALOGV("Track left volume out of range: %.3g", vlf);
3698 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003699 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003700 if (vrf > GAIN_FLOAT_UNITY) {
3701 ALOGV("Track right volume out of range: %.3g", vrf);
3702 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003703 }
3704 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003705 vlf *= v;
3706 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003707 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003708 // then derive vl and vr as U8.24 versions for the effect chain
3709 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3710 vl = (uint32_t) (scaleto8_24 * vlf);
3711 vr = (uint32_t) (scaleto8_24 * vrf);
3712 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003713 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003714 // send level comes from shared memory and so may be corrupt
3715 if (sendLevel > MAX_GAIN_INT) {
3716 ALOGV("Track send level out of range: %04X", sendLevel);
3717 sendLevel = MAX_GAIN_INT;
3718 }
Andy Hung6be49402014-05-30 10:42:03 -07003719 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3720 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003722
Eric Laurent81784c32012-11-19 14:55:58 -08003723 // Delegate volume control to effect in track effect chain if needed
3724 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3725 // Do not ramp volume if volume is controlled by effect
3726 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003727 // Update remaining floating point volume levels
3728 vlf = (float)vl / (1 << 24);
3729 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003730 track->mHasVolumeController = true;
3731 } else {
3732 // force no volume ramp when volume controller was just disabled or removed
3733 // from effect chain to avoid volume spike
3734 if (track->mHasVolumeController) {
3735 param = AudioMixer::VOLUME;
3736 }
3737 track->mHasVolumeController = false;
3738 }
3739
Eric Laurent81784c32012-11-19 14:55:58 -08003740 // XXX: these things DON'T need to be done each time
3741 mAudioMixer->setBufferProvider(name, track);
3742 mAudioMixer->enable(name);
3743
Andy Hung6be49402014-05-30 10:42:03 -07003744 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3745 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3746 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003747 mAudioMixer->setParameter(
3748 name,
3749 AudioMixer::TRACK,
3750 AudioMixer::FORMAT, (void *)track->format());
3751 mAudioMixer->setParameter(
3752 name,
3753 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003754 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003755 mAudioMixer->setParameter(
3756 name,
3757 AudioMixer::TRACK,
3758 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003759 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003760 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003761 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003762 if (reqSampleRate == 0) {
3763 reqSampleRate = mSampleRate;
3764 } else if (reqSampleRate > maxSampleRate) {
3765 reqSampleRate = maxSampleRate;
3766 }
Eric Laurent81784c32012-11-19 14:55:58 -08003767 mAudioMixer->setParameter(
3768 name,
3769 AudioMixer::RESAMPLE,
3770 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003771 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003772 /*
3773 * Select the appropriate output buffer for the track.
3774 *
Andy Hung98ef9782014-03-04 14:46:50 -08003775 * Tracks with effects go into their own effects chain buffer
3776 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003777 *
3778 * Other tracks can use mMixerBuffer for higher precision
3779 * channel accumulation. If this buffer is enabled
3780 * (mMixerBufferEnabled true), then selected tracks will accumulate
3781 * into it.
3782 *
3783 */
3784 if (mMixerBufferEnabled
3785 && (track->mainBuffer() == mSinkBuffer
3786 || track->mainBuffer() == mMixerBuffer)) {
3787 mAudioMixer->setParameter(
3788 name,
3789 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003790 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003791 mAudioMixer->setParameter(
3792 name,
3793 AudioMixer::TRACK,
3794 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3795 // TODO: override track->mainBuffer()?
3796 mMixerBufferValid = true;
3797 } else {
3798 mAudioMixer->setParameter(
3799 name,
3800 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003801 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003802 mAudioMixer->setParameter(
3803 name,
3804 AudioMixer::TRACK,
3805 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3806 }
Eric Laurent81784c32012-11-19 14:55:58 -08003807 mAudioMixer->setParameter(
3808 name,
3809 AudioMixer::TRACK,
3810 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3811
3812 // reset retry count
3813 track->mRetryCount = kMaxTrackRetries;
3814
3815 // If one track is ready, set the mixer ready if:
3816 // - the mixer was not ready during previous round OR
3817 // - no other track is not ready
3818 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3819 mixerStatus != MIXER_TRACKS_ENABLED) {
3820 mixerStatus = MIXER_TRACKS_READY;
3821 }
3822 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003823 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003824 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003825 }
Eric Laurent81784c32012-11-19 14:55:58 -08003826 // clear effect chain input buffer if an active track underruns to avoid sending
3827 // previous audio buffer again to effects
3828 chain = getEffectChain_l(track->sessionId());
3829 if (chain != 0) {
3830 chain->clearInputBuffer();
3831 }
3832
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003833 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003834 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3835 track->isStopped() || track->isPaused()) {
3836 // We have consumed all the buffers of this track.
3837 // Remove it from the list of active tracks.
3838 // TODO: use actual buffer filling status instead of latency when available from
3839 // audio HAL
3840 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3841 size_t framesWritten = mBytesWritten / mFrameSize;
3842 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3843 if (track->isStopped()) {
3844 track->reset();
3845 }
3846 tracksToRemove->add(track);
3847 }
3848 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003849 // No buffers for this track. Give it a few chances to
3850 // fill a buffer, then remove it from active list.
3851 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003852 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003853 tracksToRemove->add(track);
3854 // indicate to client process that the track was disabled because of underrun;
3855 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003856 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003857 // If one track is not ready, mark the mixer also not ready if:
3858 // - the mixer was ready during previous round OR
3859 // - no other track is ready
3860 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3861 mixerStatus != MIXER_TRACKS_READY) {
3862 mixerStatus = MIXER_TRACKS_ENABLED;
3863 }
3864 }
3865 mAudioMixer->disable(name);
3866 }
3867
3868 } // local variable scope to avoid goto warning
3869track_is_ready: ;
3870
3871 }
3872
3873 // Push the new FastMixer state if necessary
3874 bool pauseAudioWatchdog = false;
3875 if (didModify) {
3876 state->mFastTracksGen++;
3877 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3878 if (kUseFastMixer == FastMixer_Dynamic &&
3879 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3880 state->mCommand = FastMixerState::COLD_IDLE;
3881 state->mColdFutexAddr = &mFastMixerFutex;
3882 state->mColdGen++;
3883 mFastMixerFutex = 0;
3884 if (kUseFastMixer == FastMixer_Dynamic) {
3885 mNormalSink = mOutputSink;
3886 }
3887 // If we go into cold idle, need to wait for acknowledgement
3888 // so that fast mixer stops doing I/O.
3889 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3890 pauseAudioWatchdog = true;
3891 }
Eric Laurent81784c32012-11-19 14:55:58 -08003892 }
3893 if (sq != NULL) {
3894 sq->end(didModify);
3895 sq->push(block);
3896 }
3897#ifdef AUDIO_WATCHDOG
3898 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3899 mAudioWatchdog->pause();
3900 }
3901#endif
3902
3903 // Now perform the deferred reset on fast tracks that have stopped
3904 while (resetMask != 0) {
3905 size_t i = __builtin_ctz(resetMask);
3906 ALOG_ASSERT(i < count);
3907 resetMask &= ~(1 << i);
3908 sp<Track> t = mActiveTracks[i].promote();
3909 if (t == 0) {
3910 continue;
3911 }
3912 Track* track = t.get();
3913 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3914 track->reset();
3915 }
3916
3917 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003919
Eric Laurent97d547d2014-09-02 14:45:53 -07003920 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3921 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003922 }
3923
3924 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003925 // as long as there are effects we should clear the effects buffer, to avoid
3926 // passing a non-clean buffer to the effect chain
3927 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003928 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003929 // sink or mix buffer must be cleared if all tracks are connected to an
3930 // effect chain as in this case the mixer will not write to the sink or mix buffer
3931 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3933 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003934 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003935 if (mMixerBufferValid) {
3936 memset(mMixerBuffer, 0, mMixerBufferSize);
3937 // TODO: In testing, mSinkBuffer below need not be cleared because
3938 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3939 // after mixing.
3940 //
3941 // To enforce this guarantee:
3942 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3943 // (mixedTracks == 0 && fastTracks > 0))
3944 // must imply MIXER_TRACKS_READY.
3945 // Later, we may clear buffers regardless, and skip much of this logic.
3946 }
Andy Hung98ef9782014-03-04 14:46:50 -08003947 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003948 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003949 }
3950
3951 // if any fast tracks, then status is ready
3952 mMixerStatusIgnoringFastTracks = mixerStatus;
3953 if (fastTracks > 0) {
3954 mixerStatus = MIXER_TRACKS_READY;
3955 }
3956 return mixerStatus;
3957}
3958
3959// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003960int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3961 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003962{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003963 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003964}
3965
3966// deleteTrackName_l() must be called with ThreadBase::mLock held
3967void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3968{
3969 ALOGV("remove track (%d) and delete from mixer", name);
3970 mAudioMixer->deleteTrackName(name);
3971}
3972
Eric Laurent10351942014-05-08 18:49:52 -07003973// checkForNewParameter_l() must be called with ThreadBase::mLock held
3974bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3975 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003976{
Eric Laurent81784c32012-11-19 14:55:58 -08003977 bool reconfig = false;
3978
Eric Laurent10351942014-05-08 18:49:52 -07003979 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003980
Eric Laurent10351942014-05-08 18:49:52 -07003981 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3982 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003983 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003984 FastMixerStateQueue *sq = mFastMixer->sq();
3985 FastMixerState *state = sq->begin();
3986 if (!(state->mCommand & FastMixerState::IDLE)) {
3987 previousCommand = state->mCommand;
3988 state->mCommand = FastMixerState::HOT_IDLE;
3989 sq->end();
3990 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3991 } else {
3992 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 }
Eric Laurent10351942014-05-08 18:49:52 -07003994 }
Eric Laurent81784c32012-11-19 14:55:58 -08003995
Eric Laurent10351942014-05-08 18:49:52 -07003996 AudioParameter param = AudioParameter(keyValuePair);
3997 int value;
3998 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3999 reconfig = true;
4000 }
4001 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004002 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004003 status = BAD_VALUE;
4004 } else {
4005 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004006 reconfig = true;
4007 }
Eric Laurent10351942014-05-08 18:49:52 -07004008 }
4009 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004010 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004011 status = BAD_VALUE;
4012 } else {
4013 // no need to save value, since it's constant
4014 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004015 }
Eric Laurent10351942014-05-08 18:49:52 -07004016 }
4017 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4018 // do not accept frame count changes if tracks are open as the track buffer
4019 // size depends on frame count and correct behavior would not be guaranteed
4020 // if frame count is changed after track creation
4021 if (!mTracks.isEmpty()) {
4022 status = INVALID_OPERATION;
4023 } else {
4024 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004025 }
Eric Laurent10351942014-05-08 18:49:52 -07004026 }
4027 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004028#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004029 // when changing the audio output device, call addBatteryData to notify
4030 // the change
4031 if (mOutDevice != value) {
4032 uint32_t params = 0;
4033 // check whether speaker is on
4034 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4035 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004036 }
Eric Laurent10351942014-05-08 18:49:52 -07004037
4038 audio_devices_t deviceWithoutSpeaker
4039 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4040 // check if any other device (except speaker) is on
4041 if (value & deviceWithoutSpeaker ) {
4042 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4043 }
4044
4045 if (params != 0) {
4046 addBatteryData(params);
4047 }
4048 }
Eric Laurent81784c32012-11-19 14:55:58 -08004049#endif
4050
Eric Laurent10351942014-05-08 18:49:52 -07004051 // forward device change to effects that have requested to be
4052 // aware of attached audio device.
4053 if (value != AUDIO_DEVICE_NONE) {
4054 mOutDevice = value;
4055 for (size_t i = 0; i < mEffectChains.size(); i++) {
4056 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058 }
Eric Laurent10351942014-05-08 18:49:52 -07004059 }
Eric Laurent81784c32012-11-19 14:55:58 -08004060
Eric Laurent10351942014-05-08 18:49:52 -07004061 if (status == NO_ERROR) {
4062 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4063 keyValuePair.string());
4064 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004065 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004066 mStandby = true;
4067 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004068 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004069 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004070 }
Eric Laurent10351942014-05-08 18:49:52 -07004071 if (status == NO_ERROR && reconfig) {
4072 readOutputParameters_l();
4073 delete mAudioMixer;
4074 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4075 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004076 int name = getTrackName_l(mTracks[i]->mChannelMask,
4077 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004078 if (name < 0) {
4079 break;
4080 }
4081 mTracks[i]->mName = name;
4082 }
4083 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4084 }
Eric Laurent81784c32012-11-19 14:55:58 -08004085 }
4086
4087 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004088 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004089 FastMixerStateQueue *sq = mFastMixer->sq();
4090 FastMixerState *state = sq->begin();
4091 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4092 state->mCommand = previousCommand;
4093 sq->end();
4094 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4095 }
4096
4097 return reconfig;
4098}
4099
4100
4101void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4102{
4103 const size_t SIZE = 256;
4104 char buffer[SIZE];
4105 String8 result;
4106
4107 PlaybackThread::dumpInternals(fd, args);
4108
Elliott Hughes87cebad2014-05-22 10:14:43 -07004109 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004110
4111 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004112 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004113 copy.dump(fd);
4114
4115#ifdef STATE_QUEUE_DUMP
4116 // Similar for state queue
4117 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4118 observerCopy.dump(fd);
4119 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4120 mutatorCopy.dump(fd);
4121#endif
4122
Glenn Kasten46909e72013-02-26 09:20:22 -08004123#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004124 // Write the tee output to a .wav file
4125 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004126#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004127
4128#ifdef AUDIO_WATCHDOG
4129 if (mAudioWatchdog != 0) {
4130 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4131 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4132 wdCopy.dump(fd);
4133 }
4134#endif
4135}
4136
4137uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4138{
4139 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4140}
4141
4142uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4143{
4144 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4145}
4146
4147void AudioFlinger::MixerThread::cacheParameters_l()
4148{
4149 PlaybackThread::cacheParameters_l();
4150
4151 // FIXME: Relaxed timing because of a certain device that can't meet latency
4152 // Should be reduced to 2x after the vendor fixes the driver issue
4153 // increase threshold again due to low power audio mode. The way this warning
4154 // threshold is calculated and its usefulness should be reconsidered anyway.
4155 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4156}
4157
4158// ----------------------------------------------------------------------------
4159
4160AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4161 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4162 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4163 // mLeftVolFloat, mRightVolFloat
4164{
4165}
4166
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4168 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4169 ThreadBase::type_t type)
4170 : PlaybackThread(audioFlinger, output, id, device, type)
4171 // mLeftVolFloat, mRightVolFloat
4172{
4173}
4174
Eric Laurent81784c32012-11-19 14:55:58 -08004175AudioFlinger::DirectOutputThread::~DirectOutputThread()
4176{
4177}
4178
Eric Laurentbfb1b832013-01-07 09:53:42 -08004179void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4180{
4181 audio_track_cblk_t* cblk = track->cblk();
4182 float left, right;
4183
4184 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4185 left = right = 0;
4186 } else {
4187 float typeVolume = mStreamTypes[track->streamType()].volume;
4188 float v = mMasterVolume * typeVolume;
4189 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004190 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4191 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4192 if (left > GAIN_FLOAT_UNITY) {
4193 left = GAIN_FLOAT_UNITY;
4194 }
4195 left *= v;
4196 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4197 if (right > GAIN_FLOAT_UNITY) {
4198 right = GAIN_FLOAT_UNITY;
4199 }
4200 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 }
4202
4203 if (lastTrack) {
4204 if (left != mLeftVolFloat || right != mRightVolFloat) {
4205 mLeftVolFloat = left;
4206 mRightVolFloat = right;
4207
4208 // Convert volumes from float to 8.24
4209 uint32_t vl = (uint32_t)(left * (1 << 24));
4210 uint32_t vr = (uint32_t)(right * (1 << 24));
4211
4212 // Delegate volume control to effect in track effect chain if needed
4213 // only one effect chain can be present on DirectOutputThread, so if
4214 // there is one, the track is connected to it
4215 if (!mEffectChains.isEmpty()) {
4216 mEffectChains[0]->setVolume_l(&vl, &vr);
4217 left = (float)vl / (1 << 24);
4218 right = (float)vr / (1 << 24);
4219 }
4220 if (mOutput->stream->set_volume) {
4221 mOutput->stream->set_volume(mOutput->stream, left, right);
4222 }
4223 }
4224 }
4225}
4226
4227
Eric Laurent81784c32012-11-19 14:55:58 -08004228AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4229 Vector< sp<Track> > *tracksToRemove
4230)
4231{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004232 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004233 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004234 bool doHwPause = false;
4235 bool doHwResume = false;
4236 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004237
4238 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004239 for (size_t i = 0; i < count; i++) {
4240 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004241 // The track died recently
4242 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004243 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004244 }
4245
4246 Track* const track = t.get();
4247 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004248 // Only consider last track started for volume and mixer state control.
4249 // In theory an older track could underrun and restart after the new one starts
4250 // but as we only care about the transition phase between two tracks on a
4251 // direct output, it is not a problem to ignore the underrun case.
4252 sp<Track> l = mLatestActiveTrack.promote();
4253 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004254
Eric Laurentd1f69b02014-12-15 14:33:13 -08004255 if (mHwSupportsPause && track->isPausing()) {
4256 track->setPaused();
4257 if (last && !mHwPaused) {
4258 doHwPause = true;
4259 mHwPaused = true;
4260 }
4261 tracksToRemove->add(track);
4262 } else if (track->isFlushPending()) {
4263 track->flushAck();
4264 if (last) {
4265 flushPending = true;
4266 }
4267 } else if (mHwSupportsPause && track->isResumePending()){
4268 track->resumeAck();
4269 if (last) {
4270 if (mHwPaused) {
4271 doHwResume = true;
4272 mHwPaused = false;
4273 }
4274 }
4275 }
4276
Eric Laurent81784c32012-11-19 14:55:58 -08004277 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004278 // for all its buffers to be filled before processing it.
4279 // Allow draining the buffer in case the client
4280 // app does not call stop() and relies on underrun to stop:
4281 // hence the test on (track->mRetryCount > 1).
4282 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004283 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004284 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4285 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004286 minFrames = mNormalFrameCount;
4287 } else {
4288 minFrames = 1;
4289 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004290
Eric Laurentab5cdba2014-06-09 17:22:27 -07004291 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4292 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004293 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004294 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004295
4296 if (track->mFillingUpStatus == Track::FS_FILLED) {
4297 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004298 // make sure processVolume_l() will apply new volume even if 0
4299 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004300 if (!mHwSupportsPause) {
4301 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004302 }
4303 }
4304
4305 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 processVolume_l(track, last);
4307 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004308 // reset retry count
4309 track->mRetryCount = kMaxTrackRetriesDirect;
4310 mActiveTrack = t;
4311 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004312 if (usesHwAvSync() && mHwPaused) {
4313 doHwResume = true;
4314 mHwPaused = false;
4315 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004316 }
Eric Laurent81784c32012-11-19 14:55:58 -08004317 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004318 // clear effect chain input buffer if the last active track started underruns
4319 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004320 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004321 mEffectChains[0]->clearInputBuffer();
4322 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004323 if (track->isStopping_1()) {
4324 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004325 if (last && mHwPaused) {
4326 doHwResume = true;
4327 mHwPaused = false;
4328 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004329 }
4330 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4331 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004332 // We have consumed all the buffers of this track.
4333 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004334 size_t audioHALFrames;
4335 if (audio_is_linear_pcm(mFormat)) {
4336 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4337 } else {
4338 audioHALFrames = 0;
4339 }
4340
Eric Laurent81784c32012-11-19 14:55:58 -08004341 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004342 if (mStandby || !last ||
4343 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004344 if (track->isStopping_2()) {
4345 track->mState = TrackBase::STOPPED;
4346 }
Eric Laurent81784c32012-11-19 14:55:58 -08004347 if (track->isStopped()) {
4348 track->reset();
4349 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004350 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004351 }
4352 } else {
4353 // No buffers for this track. Give it a few chances to
4354 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004355 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004356 if (--(track->mRetryCount) <= 0) {
4357 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004358 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004359 // indicate to client process that the track was disabled because of underrun;
4360 // it will then automatically call start() when data is available
4361 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004362 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004363 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004364 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4365 doHwPause = true;
4366 mHwPaused = true;
4367 }
Eric Laurent81784c32012-11-19 14:55:58 -08004368 }
4369 }
4370 }
4371 }
4372
Eric Laurentd1f69b02014-12-15 14:33:13 -08004373 // if an active track did not command a flush, check for pending flush on stopped tracks
4374 if (!flushPending) {
4375 for (size_t i = 0; i < mTracks.size(); i++) {
4376 if (mTracks[i]->isFlushPending()) {
4377 mTracks[i]->flushAck();
4378 flushPending = true;
4379 }
4380 }
4381 }
4382
4383 // make sure the pause/flush/resume sequence is executed in the right order.
4384 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4385 // before flush and then resume HW. This can happen in case of pause/flush/resume
4386 // if resume is received before pause is executed.
4387 if (mHwSupportsPause && !mStandby &&
4388 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4389 mOutput->stream->pause(mOutput->stream);
4390 }
4391 if (flushPending) {
4392 flushHw_l();
4393 }
4394 if (mHwSupportsPause && !mStandby && doHwResume) {
4395 mOutput->stream->resume(mOutput->stream);
4396 }
Eric Laurent81784c32012-11-19 14:55:58 -08004397 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004399
4400 return mixerStatus;
4401}
4402
4403void AudioFlinger::DirectOutputThread::threadLoop_mix()
4404{
Eric Laurent81784c32012-11-19 14:55:58 -08004405 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004406 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004407 // output audio to hardware
4408 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004409 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004410 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004411 status_t status = mActiveTrack->getNextBuffer(&buffer);
4412 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004413 memset(curBuf, 0, frameCount * mFrameSize);
4414 break;
4415 }
4416 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4417 frameCount -= buffer.frameCount;
4418 curBuf += buffer.frameCount * mFrameSize;
4419 mActiveTrack->releaseBuffer(&buffer);
4420 }
Andy Hung2098f272014-02-27 14:00:06 -08004421 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004422 sleepTime = 0;
4423 standbyTime = systemTime() + standbyDelay;
4424 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004425}
4426
4427void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4428{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004429 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004430 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004431 sleepTime = idleSleepTime;
4432 return;
4433 }
Eric Laurent81784c32012-11-19 14:55:58 -08004434 if (sleepTime == 0) {
4435 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4436 sleepTime = activeSleepTime;
4437 } else {
4438 sleepTime = idleSleepTime;
4439 }
4440 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004441 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004442 sleepTime = 0;
4443 }
4444}
4445
Eric Laurentd1f69b02014-12-15 14:33:13 -08004446void AudioFlinger::DirectOutputThread::threadLoop_exit()
4447{
4448 {
4449 Mutex::Autolock _l(mLock);
4450 bool flushPending = false;
4451 for (size_t i = 0; i < mTracks.size(); i++) {
4452 if (mTracks[i]->isFlushPending()) {
4453 mTracks[i]->flushAck();
4454 flushPending = true;
4455 }
4456 }
4457 if (flushPending) {
4458 flushHw_l();
4459 }
4460 }
4461 PlaybackThread::threadLoop_exit();
4462}
4463
4464// must be called with thread mutex locked
4465bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4466{
4467 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004468 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004469
4470 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4471 // after a timeout and we will enter standby then.
4472 if (mTracks.size() > 0) {
4473 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004474 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4475 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004476 }
4477
Eric Laurentb369caf2015-03-30 20:51:47 -07004478 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004479}
4480
Eric Laurent81784c32012-11-19 14:55:58 -08004481// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004482int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004483 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004484{
4485 return 0;
4486}
4487
4488// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004489void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004490{
4491}
4492
Eric Laurent10351942014-05-08 18:49:52 -07004493// checkForNewParameter_l() must be called with ThreadBase::mLock held
4494bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4495 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004496{
4497 bool reconfig = false;
4498
Eric Laurent10351942014-05-08 18:49:52 -07004499 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004500
Eric Laurent10351942014-05-08 18:49:52 -07004501 AudioParameter param = AudioParameter(keyValuePair);
4502 int value;
4503 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4504 // forward device change to effects that have requested to be
4505 // aware of attached audio device.
4506 if (value != AUDIO_DEVICE_NONE) {
4507 mOutDevice = value;
4508 for (size_t i = 0; i < mEffectChains.size(); i++) {
4509 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004510 }
4511 }
Eric Laurent81784c32012-11-19 14:55:58 -08004512 }
Eric Laurent10351942014-05-08 18:49:52 -07004513 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4514 // do not accept frame count changes if tracks are open as the track buffer
4515 // size depends on frame count and correct behavior would not be garantied
4516 // if frame count is changed after track creation
4517 if (!mTracks.isEmpty()) {
4518 status = INVALID_OPERATION;
4519 } else {
4520 reconfig = true;
4521 }
4522 }
4523 if (status == NO_ERROR) {
4524 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4525 keyValuePair.string());
4526 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004527 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004528 mStandby = true;
4529 mBytesWritten = 0;
4530 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4531 keyValuePair.string());
4532 }
4533 if (status == NO_ERROR && reconfig) {
4534 readOutputParameters_l();
4535 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4536 }
4537 }
4538
Eric Laurent81784c32012-11-19 14:55:58 -08004539 return reconfig;
4540}
4541
4542uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4543{
4544 uint32_t time;
4545 if (audio_is_linear_pcm(mFormat)) {
4546 time = PlaybackThread::activeSleepTimeUs();
4547 } else {
4548 time = 10000;
4549 }
4550 return time;
4551}
4552
4553uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4554{
4555 uint32_t time;
4556 if (audio_is_linear_pcm(mFormat)) {
4557 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4558 } else {
4559 time = 10000;
4560 }
4561 return time;
4562}
4563
4564uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4565{
4566 uint32_t time;
4567 if (audio_is_linear_pcm(mFormat)) {
4568 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4569 } else {
4570 time = 10000;
4571 }
4572 return time;
4573}
4574
4575void AudioFlinger::DirectOutputThread::cacheParameters_l()
4576{
4577 PlaybackThread::cacheParameters_l();
4578
4579 // use shorter standby delay as on normal output to release
4580 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004581 // no delay on outputs with HW A/V sync
4582 if (usesHwAvSync()) {
4583 standbyDelay = 0;
4584 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004585 standbyDelay = microseconds(activeSleepTime*2);
4586 } else {
4587 standbyDelay = kOffloadStandbyDelayNs;
4588 }
Eric Laurent81784c32012-11-19 14:55:58 -08004589}
4590
Eric Laurente659ef42014-09-29 13:06:46 -07004591void AudioFlinger::DirectOutputThread::flushHw_l()
4592{
Phil Burk062e67a2015-02-11 13:40:50 -08004593 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004594 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004595}
4596
Eric Laurent81784c32012-11-19 14:55:58 -08004597// ----------------------------------------------------------------------------
4598
Eric Laurentbfb1b832013-01-07 09:53:42 -08004599AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004600 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004601 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004602 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004603 mWriteAckSequence(0),
4604 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605{
4606}
4607
4608AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4609{
4610}
4611
4612void AudioFlinger::AsyncCallbackThread::onFirstRef()
4613{
4614 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4615}
4616
4617bool AudioFlinger::AsyncCallbackThread::threadLoop()
4618{
4619 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004620 uint32_t writeAckSequence;
4621 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622
4623 {
4624 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004625 while (!((mWriteAckSequence & 1) ||
4626 (mDrainSequence & 1) ||
4627 exitPending())) {
4628 mWaitWorkCV.wait(mLock);
4629 }
4630
Eric Laurentbfb1b832013-01-07 09:53:42 -08004631 if (exitPending()) {
4632 break;
4633 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004634 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4635 mWriteAckSequence, mDrainSequence);
4636 writeAckSequence = mWriteAckSequence;
4637 mWriteAckSequence &= ~1;
4638 drainSequence = mDrainSequence;
4639 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 }
4641 {
Eric Laurent4de95592013-09-26 15:28:21 -07004642 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4643 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004644 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004645 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004647 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004648 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 }
4650 }
4651 }
4652 }
4653 return false;
4654}
4655
4656void AudioFlinger::AsyncCallbackThread::exit()
4657{
4658 ALOGV("AsyncCallbackThread::exit");
4659 Mutex::Autolock _l(mLock);
4660 requestExit();
4661 mWaitWorkCV.broadcast();
4662}
4663
Eric Laurent3b4529e2013-09-05 18:09:19 -07004664void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665{
4666 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004667 // bit 0 is cleared
4668 mWriteAckSequence = sequence << 1;
4669}
4670
4671void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4672{
4673 Mutex::Autolock _l(mLock);
4674 // ignore unexpected callbacks
4675 if (mWriteAckSequence & 2) {
4676 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004677 mWaitWorkCV.signal();
4678 }
4679}
4680
Eric Laurent3b4529e2013-09-05 18:09:19 -07004681void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682{
4683 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004684 // bit 0 is cleared
4685 mDrainSequence = sequence << 1;
4686}
4687
4688void AudioFlinger::AsyncCallbackThread::resetDraining()
4689{
4690 Mutex::Autolock _l(mLock);
4691 // ignore unexpected callbacks
4692 if (mDrainSequence & 2) {
4693 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004694 mWaitWorkCV.signal();
4695 }
4696}
4697
4698
4699// ----------------------------------------------------------------------------
4700AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4701 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4702 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004703 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004704{
Eric Laurentfd477972013-10-25 18:10:40 -07004705 //FIXME: mStandby should be set to true by ThreadBase constructor
4706 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707}
4708
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709void AudioFlinger::OffloadThread::threadLoop_exit()
4710{
4711 if (mFlushPending || mHwPaused) {
4712 // If a flush is pending or track was paused, just discard buffered data
4713 flushHw_l();
4714 } else {
4715 mMixerStatus = MIXER_DRAIN_ALL;
4716 threadLoop_drain();
4717 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004718 if (mUseAsyncWrite) {
4719 ALOG_ASSERT(mCallbackThread != 0);
4720 mCallbackThread->exit();
4721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004722 PlaybackThread::threadLoop_exit();
4723}
4724
4725AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4726 Vector< sp<Track> > *tracksToRemove
4727)
4728{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729 size_t count = mActiveTracks.size();
4730
4731 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004732 bool doHwPause = false;
4733 bool doHwResume = false;
4734
Eric Laurentede6c3b2013-09-19 14:37:46 -07004735 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4736
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737 // find out which tracks need to be processed
4738 for (size_t i = 0; i < count; i++) {
4739 sp<Track> t = mActiveTracks[i].promote();
4740 // The track died recently
4741 if (t == 0) {
4742 continue;
4743 }
4744 Track* const track = t.get();
4745 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004746 // Only consider last track started for volume and mixer state control.
4747 // In theory an older track could underrun and restart after the new one starts
4748 // but as we only care about the transition phase between two tracks on a
4749 // direct output, it is not a problem to ignore the underrun case.
4750 sp<Track> l = mLatestActiveTrack.promote();
4751 bool last = l.get() == track;
4752
Haynes Mathew George7844f672014-01-15 12:32:55 -08004753 if (track->isInvalid()) {
4754 ALOGW("An invalidated track shouldn't be in active list");
4755 tracksToRemove->add(track);
4756 continue;
4757 }
4758
4759 if (track->mState == TrackBase::IDLE) {
4760 ALOGW("An idle track shouldn't be in active list");
4761 continue;
4762 }
4763
Eric Laurentbfb1b832013-01-07 09:53:42 -08004764 if (track->isPausing()) {
4765 track->setPaused();
4766 if (last) {
4767 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004768 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769 mHwPaused = true;
4770 }
4771 // If we were part way through writing the mixbuffer to
4772 // the HAL we must save this until we resume
4773 // BUG - this will be wrong if a different track is made active,
4774 // in that case we want to discard the pending data in the
4775 // mixbuffer and tell the client to present it again when the
4776 // track is resumed
4777 mPausedWriteLength = mCurrentWriteLength;
4778 mPausedBytesRemaining = mBytesRemaining;
4779 mBytesRemaining = 0; // stop writing
4780 }
4781 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004782 } else if (track->isFlushPending()) {
4783 track->flushAck();
4784 if (last) {
4785 mFlushPending = true;
4786 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004787 } else if (track->isResumePending()){
4788 track->resumeAck();
4789 if (last) {
4790 if (mPausedBytesRemaining) {
4791 // Need to continue write that was interrupted
4792 mCurrentWriteLength = mPausedWriteLength;
4793 mBytesRemaining = mPausedBytesRemaining;
4794 mPausedBytesRemaining = 0;
4795 }
4796 if (mHwPaused) {
4797 doHwResume = true;
4798 mHwPaused = false;
4799 // threadLoop_mix() will handle the case that we need to
4800 // resume an interrupted write
4801 }
4802 // enable write to audio HAL
4803 sleepTime = 0;
4804
4805 // Do not handle new data in this iteration even if track->framesReady()
4806 mixerStatus = MIXER_TRACKS_ENABLED;
4807 }
4808 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004809 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004810 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811 if (track->mFillingUpStatus == Track::FS_FILLED) {
4812 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004813 // make sure processVolume_l() will apply new volume even if 0
4814 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815 }
4816
4817 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004818 sp<Track> previousTrack = mPreviousTrack.promote();
4819 if (previousTrack != 0) {
4820 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004821 // Flush any data still being written from last track
4822 mBytesRemaining = 0;
4823 if (mPausedBytesRemaining) {
4824 // Last track was paused so we also need to flush saved
4825 // mixbuffer state and invalidate track so that it will
4826 // re-submit that unwritten data when it is next resumed
4827 mPausedBytesRemaining = 0;
4828 // Invalidate is a bit drastic - would be more efficient
4829 // to have a flag to tell client that some of the
4830 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004831 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004832 }
4833 // flush data already sent to the DSP if changing audio session as audio
4834 // comes from a different source. Also invalidate previous track to force a
4835 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004836 if (previousTrack->sessionId() != track->sessionId()) {
4837 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004838 }
4839 }
4840 }
4841 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004842 // reset retry count
4843 track->mRetryCount = kMaxTrackRetriesOffload;
4844 mActiveTrack = t;
4845 mixerStatus = MIXER_TRACKS_READY;
4846 }
4847 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004848 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 if (track->isStopping_1()) {
4850 // Hardware buffer can hold a large amount of audio so we must
4851 // wait for all current track's data to drain before we say
4852 // that the track is stopped.
4853 if (mBytesRemaining == 0) {
4854 // Only start draining when all data in mixbuffer
4855 // has been written
4856 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4857 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004858 // do not drain if no data was ever sent to HAL (mStandby == true)
4859 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004860 // do not modify drain sequence if we are already draining. This happens
4861 // when resuming from pause after drain.
4862 if ((mDrainSequence & 1) == 0) {
4863 sleepTime = 0;
4864 standbyTime = systemTime() + standbyDelay;
4865 mixerStatus = MIXER_DRAIN_TRACK;
4866 mDrainSequence += 2;
4867 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004868 if (mHwPaused) {
4869 // It is possible to move from PAUSED to STOPPING_1 without
4870 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004871 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004872 mHwPaused = false;
4873 }
4874 }
4875 }
4876 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004877 // Drain has completed or we are in standby, signal presentation complete
4878 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004879 track->mState = TrackBase::STOPPED;
4880 size_t audioHALFrames =
4881 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4882 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08004883 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884 track->presentationComplete(framesWritten, audioHALFrames);
4885 track->reset();
4886 tracksToRemove->add(track);
4887 }
4888 } else {
4889 // No buffers for this track. Give it a few chances to
4890 // fill a buffer, then remove it from active list.
4891 if (--(track->mRetryCount) <= 0) {
4892 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4893 track->name());
4894 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004895 // indicate to client process that the track was disabled because of underrun;
4896 // it will then automatically call start() when data is available
4897 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004898 } else if (last){
4899 mixerStatus = MIXER_TRACKS_ENABLED;
4900 }
4901 }
4902 }
4903 // compute volume for this track
4904 processVolume_l(track, last);
4905 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004906
Eric Laurentea0fade2013-10-04 16:23:48 -07004907 // make sure the pause/flush/resume sequence is executed in the right order.
4908 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4909 // before flush and then resume HW. This can happen in case of pause/flush/resume
4910 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004911 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004912 mOutput->stream->pause(mOutput->stream);
4913 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004914 if (mFlushPending) {
4915 flushHw_l();
4916 mFlushPending = false;
4917 }
Eric Laurentfd477972013-10-25 18:10:40 -07004918 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004919 mOutput->stream->resume(mOutput->stream);
4920 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004921
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922 // remove all the tracks that need to be...
4923 removeTracks_l(*tracksToRemove);
4924
4925 return mixerStatus;
4926}
4927
Eric Laurentbfb1b832013-01-07 09:53:42 -08004928// must be called with thread mutex locked
4929bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4930{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004931 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4932 mWriteAckSequence, mDrainSequence);
4933 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004934 return true;
4935 }
4936 return false;
4937}
4938
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4940{
4941 Mutex::Autolock _l(mLock);
4942 return waitingAsyncCallback_l();
4943}
4944
4945void AudioFlinger::OffloadThread::flushHw_l()
4946{
Eric Laurente659ef42014-09-29 13:06:46 -07004947 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 // Flush anything still waiting in the mixbuffer
4949 mCurrentWriteLength = 0;
4950 mBytesRemaining = 0;
4951 mPausedWriteLength = 0;
4952 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004953
Eric Laurentbfb1b832013-01-07 09:53:42 -08004954 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004955 // discard any pending drain or write ack by incrementing sequence
4956 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4957 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004959 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4960 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004961 }
4962}
4963
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004964void AudioFlinger::OffloadThread::onAddNewTrack_l()
4965{
4966 sp<Track> previousTrack = mPreviousTrack.promote();
4967 sp<Track> latestTrack = mLatestActiveTrack.promote();
4968
4969 if (previousTrack != 0 && latestTrack != 0 &&
4970 (previousTrack->sessionId() != latestTrack->sessionId())) {
4971 mFlushPending = true;
4972 }
4973 PlaybackThread::onAddNewTrack_l();
4974}
4975
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976// ----------------------------------------------------------------------------
4977
Eric Laurent81784c32012-11-19 14:55:58 -08004978AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4979 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4980 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4981 DUPLICATING),
4982 mWaitTimeMs(UINT_MAX)
4983{
4984 addOutputTrack(mainThread);
4985}
4986
4987AudioFlinger::DuplicatingThread::~DuplicatingThread()
4988{
4989 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4990 mOutputTracks[i]->destroy();
4991 }
4992}
4993
4994void AudioFlinger::DuplicatingThread::threadLoop_mix()
4995{
4996 // mix buffers...
4997 if (outputsReady(outputTracks)) {
4998 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4999 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005000 if (mMixerBufferValid) {
5001 memset(mMixerBuffer, 0, mMixerBufferSize);
5002 } else {
5003 memset(mSinkBuffer, 0, mSinkBufferSize);
5004 }
Eric Laurent81784c32012-11-19 14:55:58 -08005005 }
5006 sleepTime = 0;
5007 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005008 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005009 standbyTime = systemTime() + standbyDelay;
5010}
5011
5012void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5013{
5014 if (sleepTime == 0) {
5015 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5016 sleepTime = activeSleepTime;
5017 } else {
5018 sleepTime = idleSleepTime;
5019 }
5020 } else if (mBytesWritten != 0) {
5021 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5022 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005023 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005024 } else {
5025 // flush remaining overflow buffers in output tracks
5026 writeFrames = 0;
5027 }
5028 sleepTime = 0;
5029 }
5030}
5031
Eric Laurentbfb1b832013-01-07 09:53:42 -08005032ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005033{
5034 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005035 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005037 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005038 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005039}
5040
5041void AudioFlinger::DuplicatingThread::threadLoop_standby()
5042{
5043 // DuplicatingThread implements standby by stopping all tracks
5044 for (size_t i = 0; i < outputTracks.size(); i++) {
5045 outputTracks[i]->stop();
5046 }
5047}
5048
5049void AudioFlinger::DuplicatingThread::saveOutputTracks()
5050{
5051 outputTracks = mOutputTracks;
5052}
5053
5054void AudioFlinger::DuplicatingThread::clearOutputTracks()
5055{
5056 outputTracks.clear();
5057}
5058
5059void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5060{
5061 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005062 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5063 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5064 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5065 const size_t frameCount =
5066 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5067 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5068 // from different OutputTracks and their associated MixerThreads (e.g. one may
5069 // nearly empty and the other may be dropping data).
5070
5071 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005072 this,
5073 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005074 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005075 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005076 frameCount,
5077 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005078 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005079 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005080 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005081 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005082 updateWaitTime_l();
5083 }
5084}
5085
5086void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5087{
5088 Mutex::Autolock _l(mLock);
5089 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5090 if (mOutputTracks[i]->thread() == thread) {
5091 mOutputTracks[i]->destroy();
5092 mOutputTracks.removeAt(i);
5093 updateWaitTime_l();
5094 return;
5095 }
5096 }
5097 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5098}
5099
5100// caller must hold mLock
5101void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5102{
5103 mWaitTimeMs = UINT_MAX;
5104 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5105 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5106 if (strong != 0) {
5107 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5108 if (waitTimeMs < mWaitTimeMs) {
5109 mWaitTimeMs = waitTimeMs;
5110 }
5111 }
5112 }
5113}
5114
5115
5116bool AudioFlinger::DuplicatingThread::outputsReady(
5117 const SortedVector< sp<OutputTrack> > &outputTracks)
5118{
5119 for (size_t i = 0; i < outputTracks.size(); i++) {
5120 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5121 if (thread == 0) {
5122 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5123 outputTracks[i].get());
5124 return false;
5125 }
5126 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5127 // see note at standby() declaration
5128 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5129 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5130 thread.get());
5131 return false;
5132 }
5133 }
5134 return true;
5135}
5136
5137uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5138{
5139 return (mWaitTimeMs * 1000) / 2;
5140}
5141
5142void AudioFlinger::DuplicatingThread::cacheParameters_l()
5143{
5144 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5145 updateWaitTime_l();
5146
5147 MixerThread::cacheParameters_l();
5148}
5149
5150// ----------------------------------------------------------------------------
5151// Record
5152// ----------------------------------------------------------------------------
5153
5154AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5155 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005156 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005157 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005158 audio_devices_t inDevice
5159#ifdef TEE_SINK
5160 , const sp<NBAIO_Sink>& teeSink
5161#endif
5162 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005163 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005164 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005165 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005166 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005167#ifdef TEE_SINK
5168 , mTeeSink(teeSink)
5169#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005170 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5171 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005172 // mFastCapture below
5173 , mFastCaptureFutex(0)
5174 // mInputSource
5175 // mPipeSink
5176 // mPipeSource
5177 , mPipeFramesP2(0)
5178 // mPipeMemory
5179 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005180 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005181{
Glenn Kastend7dca052015-03-05 16:05:54 -08005182 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5183 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005184
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005185 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005186
5187 // create an NBAIO source for the HAL input stream, and negotiate
5188 mInputSource = new AudioStreamInSource(input->stream);
5189 size_t numCounterOffers = 0;
5190 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5191 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5192 ALOG_ASSERT(index == 0);
5193
5194 // initialize fast capture depending on configuration
5195 bool initFastCapture;
5196 switch (kUseFastCapture) {
5197 case FastCapture_Never:
5198 initFastCapture = false;
5199 break;
5200 case FastCapture_Always:
5201 initFastCapture = true;
5202 break;
5203 case FastCapture_Static:
5204 uint32_t primaryOutputSampleRate;
5205 {
5206 AutoMutex _l(audioFlinger->mHardwareLock);
5207 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5208 }
5209 initFastCapture =
5210 // either capture sample rate is same as (a reasonable) primary output sample rate
5211 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5212 (mSampleRate == primaryOutputSampleRate)) ||
5213 // or primary output sample rate is unknown, and capture sample rate is reasonable
5214 ((primaryOutputSampleRate == 0) &&
5215 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005216 // and the buffer size is < 12 ms
5217 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005218 break;
5219 // case FastCapture_Dynamic:
5220 }
5221
5222 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005223 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005224 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005225 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005226 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5227 void *pipeBuffer;
5228 const sp<MemoryDealer> roHeap(readOnlyHeap());
5229 sp<IMemory> pipeMemory;
5230 if ((roHeap == 0) ||
5231 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5232 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5233 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5234 goto failed;
5235 }
5236 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5237 memset(pipeBuffer, 0, pipeSize);
5238 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5239 const NBAIO_Format offers[1] = {format};
5240 size_t numCounterOffers = 0;
5241 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5242 ALOG_ASSERT(index == 0);
5243 mPipeSink = pipe;
5244 PipeReader *pipeReader = new PipeReader(*pipe);
5245 numCounterOffers = 0;
5246 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5247 ALOG_ASSERT(index == 0);
5248 mPipeSource = pipeReader;
5249 mPipeFramesP2 = pipeFramesP2;
5250 mPipeMemory = pipeMemory;
5251
5252 // create fast capture
5253 mFastCapture = new FastCapture();
5254 FastCaptureStateQueue *sq = mFastCapture->sq();
5255#ifdef STATE_QUEUE_DUMP
5256 // FIXME
5257#endif
5258 FastCaptureState *state = sq->begin();
5259 state->mCblk = NULL;
5260 state->mInputSource = mInputSource.get();
5261 state->mInputSourceGen++;
5262 state->mPipeSink = pipe;
5263 state->mPipeSinkGen++;
5264 state->mFrameCount = mFrameCount;
5265 state->mCommand = FastCaptureState::COLD_IDLE;
5266 // already done in constructor initialization list
5267 //mFastCaptureFutex = 0;
5268 state->mColdFutexAddr = &mFastCaptureFutex;
5269 state->mColdGen++;
5270 state->mDumpState = &mFastCaptureDumpState;
5271#ifdef TEE_SINK
5272 // FIXME
5273#endif
5274 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5275 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5276 sq->end();
5277 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5278
5279 // start the fast capture
5280 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5281 pid_t tid = mFastCapture->getTid();
5282 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5283 if (err != 0) {
5284 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5285 kPriorityFastCapture, getpid_cached, tid, err);
5286 }
5287
5288#ifdef AUDIO_WATCHDOG
5289 // FIXME
5290#endif
5291
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005292 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005293 }
5294failed: ;
5295
5296 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005297}
5298
Eric Laurent81784c32012-11-19 14:55:58 -08005299AudioFlinger::RecordThread::~RecordThread()
5300{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005301 if (mFastCapture != 0) {
5302 FastCaptureStateQueue *sq = mFastCapture->sq();
5303 FastCaptureState *state = sq->begin();
5304 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5305 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5306 if (old == -1) {
5307 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5308 }
5309 }
5310 state->mCommand = FastCaptureState::EXIT;
5311 sq->end();
5312 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5313 mFastCapture->join();
5314 mFastCapture.clear();
5315 }
5316 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005317 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005318 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005319}
5320
5321void AudioFlinger::RecordThread::onFirstRef()
5322{
Glenn Kastend7dca052015-03-05 16:05:54 -08005323 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005324}
5325
Eric Laurent81784c32012-11-19 14:55:58 -08005326bool AudioFlinger::RecordThread::threadLoop()
5327{
Eric Laurent81784c32012-11-19 14:55:58 -08005328 nsecs_t lastWarning = 0;
5329
5330 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005331
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005332reacquire_wakelock:
5333 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005334 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005335 {
5336 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005337 size_t size = mActiveTracks.size();
5338 activeTracksGen = mActiveTracksGen;
5339 if (size > 0) {
5340 // FIXME an arbitrary choice
5341 activeTrack = mActiveTracks[0];
5342 acquireWakeLock_l(activeTrack->uid());
5343 if (size > 1) {
5344 SortedVector<int> tmp;
5345 for (size_t i = 0; i < size; i++) {
5346 tmp.add(mActiveTracks[i]->uid());
5347 }
5348 updateWakeLockUids_l(tmp);
5349 }
5350 } else {
5351 acquireWakeLock_l(-1);
5352 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005353 }
5354
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005355 // used to request a deferred sleep, to be executed later while mutex is unlocked
5356 uint32_t sleepUs = 0;
5357
5358 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005359 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005360 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005361
Glenn Kasten5edadd42013-08-14 16:30:49 -07005362 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005363 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005364 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005365 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005366 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005367 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005368 }
5369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005370 // activeTracks accumulates a copy of a subset of mActiveTracks
5371 Vector< sp<RecordTrack> > activeTracks;
5372
Glenn Kasten735f45f2014-08-18 15:51:59 -07005373 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005374 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005375
Glenn Kasten735f45f2014-08-18 15:51:59 -07005376 // reference to a fast track which is about to be removed
5377 sp<RecordTrack> fastTrackToRemove;
5378
Eric Laurent81784c32012-11-19 14:55:58 -08005379 { // scope for mLock
5380 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005381
Eric Laurent021cf962014-05-13 10:18:14 -07005382 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005383
Eric Laurent000a4192014-01-29 15:17:32 -08005384 // check exitPending here because checkForNewParameters_l() and
5385 // checkForNewParameters_l() can temporarily release mLock
5386 if (exitPending()) {
5387 break;
5388 }
5389
Glenn Kasten2b806402013-11-20 16:37:38 -08005390 // if no active track(s), then standby and release wakelock
5391 size_t size = mActiveTracks.size();
5392 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005393 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005394 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005395 releaseWakeLock_l();
5396 ALOGV("RecordThread: loop stopping");
5397 // go to sleep
5398 mWaitWorkCV.wait(mLock);
5399 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005400 goto reacquire_wakelock;
5401 }
5402
Glenn Kasten2b806402013-11-20 16:37:38 -08005403 if (mActiveTracksGen != activeTracksGen) {
5404 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005405 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005406 for (size_t i = 0; i < size; i++) {
5407 tmp.add(mActiveTracks[i]->uid());
5408 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005409 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005410 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005411
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005412 bool doBroadcast = false;
5413 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005414
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005415 activeTrack = mActiveTracks[i];
5416 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005417 if (activeTrack->isFastTrack()) {
5418 ALOG_ASSERT(fastTrackToRemove == 0);
5419 fastTrackToRemove = activeTrack;
5420 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005422 mActiveTracks.remove(activeTrack);
5423 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005424 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005425 continue;
5426 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005427
5428 TrackBase::track_state activeTrackState = activeTrack->mState;
5429 switch (activeTrackState) {
5430
5431 case TrackBase::PAUSING:
5432 mActiveTracks.remove(activeTrack);
5433 mActiveTracksGen++;
5434 doBroadcast = true;
5435 size--;
5436 continue;
5437
5438 case TrackBase::STARTING_1:
5439 sleepUs = 10000;
5440 i++;
5441 continue;
5442
5443 case TrackBase::STARTING_2:
5444 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005445 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005446 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005447 break;
5448
5449 case TrackBase::ACTIVE:
5450 break;
5451
5452 case TrackBase::IDLE:
5453 i++;
5454 continue;
5455
5456 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005457 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005458 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005459
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 activeTracks.add(activeTrack);
5461 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005462
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005463 if (activeTrack->isFastTrack()) {
5464 ALOG_ASSERT(!mFastTrackAvail);
5465 ALOG_ASSERT(fastTrack == 0);
5466 fastTrack = activeTrack;
5467 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005468 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 if (doBroadcast) {
5470 mStartStopCond.broadcast();
5471 }
5472
5473 // sleep if there are no active tracks to process
5474 if (activeTracks.size() == 0) {
5475 if (sleepUs == 0) {
5476 sleepUs = kRecordThreadSleepUs;
5477 }
5478 continue;
5479 }
5480 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005481
Eric Laurent81784c32012-11-19 14:55:58 -08005482 lockEffectChains_l(effectChains);
5483 }
5484
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005485 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005486
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005487 size_t size = effectChains.size();
5488 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005489 // thread mutex is not locked, but effect chain is locked
5490 effectChains[i]->process_l();
5491 }
5492
Glenn Kasten735f45f2014-08-18 15:51:59 -07005493 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005494 if (mFastCapture != 0) {
5495 FastCaptureStateQueue *sq = mFastCapture->sq();
5496 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005497 bool didModify = false;
5498 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005499 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5500 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5501 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5502 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5503 if (old == -1) {
5504 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5505 }
5506 }
5507 state->mCommand = FastCaptureState::READ_WRITE;
5508#if 0 // FIXME
5509 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005510 FastThreadDumpState::kSamplingNforLowRamDevice :
5511 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005512#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005513 didModify = true;
5514 }
5515 audio_track_cblk_t *cblkOld = state->mCblk;
5516 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5517 if (cblkNew != cblkOld) {
5518 state->mCblk = cblkNew;
5519 // block until acked if removing a fast track
5520 if (cblkOld != NULL) {
5521 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5522 }
5523 didModify = true;
5524 }
5525 sq->end(didModify);
5526 if (didModify) {
5527 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005528#if 0
5529 if (kUseFastCapture == FastCapture_Dynamic) {
5530 mNormalSource = mPipeSource;
5531 }
5532#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005533 }
5534 }
5535
Glenn Kasten735f45f2014-08-18 15:51:59 -07005536 // now run the fast track destructor with thread mutex unlocked
5537 fastTrackToRemove.clear();
5538
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5540 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5541 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5542 // If destination is non-contiguous, first read past the nominal end of buffer, then
5543 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005544
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005545 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005546 ssize_t framesRead;
5547
5548 // If an NBAIO source is present, use it to read the normal capture's data
5549 if (mPipeSource != 0) {
5550 size_t framesToRead = mBufferSize / mFrameSize;
5551 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5552 framesToRead, AudioBufferProvider::kInvalidPTS);
5553 if (framesRead == 0) {
5554 // since pipe is non-blocking, simulate blocking input
5555 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5556 }
5557 // otherwise use the HAL / AudioStreamIn directly
5558 } else {
5559 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5560 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5561 if (bytesRead < 0) {
5562 framesRead = bytesRead;
5563 } else {
5564 framesRead = bytesRead / mFrameSize;
5565 }
5566 }
5567
5568 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5569 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005570 // Force input into standby so that it tries to recover at next read attempt
5571 inputStandBy();
5572 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005573 }
5574 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005575 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005576 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005577 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005578
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005579 if (mTeeSink != 0) {
5580 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5581 }
5582 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005583 {
5584 size_t part1 = mRsmpInFramesP2 - rear;
5585 if ((size_t) framesRead > part1) {
5586 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5587 (framesRead - part1) * mFrameSize);
5588 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005589 }
5590 rear = mRsmpInRear += framesRead;
5591
5592 size = activeTracks.size();
5593 // loop over each active track
5594 for (size_t i = 0; i < size; i++) {
5595 activeTrack = activeTracks[i];
5596
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005597 // skip fast tracks, as those are handled directly by FastCapture
5598 if (activeTrack->isFastTrack()) {
5599 continue;
5600 }
5601
Andy Hung73c02e42015-03-29 01:13:58 -07005602 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005603 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5604
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005605 enum {
5606 OVERRUN_UNKNOWN,
5607 OVERRUN_TRUE,
5608 OVERRUN_FALSE
5609 } overrun = OVERRUN_UNKNOWN;
5610
5611 // loop over getNextBuffer to handle circular sink
5612 for (;;) {
5613
5614 activeTrack->mSink.frameCount = ~0;
5615 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5616 size_t framesOut = activeTrack->mSink.frameCount;
5617 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5618
Andy Hung73c02e42015-03-29 01:13:58 -07005619 // check available frames and handle overrun conditions
5620 // if the record track isn't draining fast enough.
5621 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005622 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005623 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5624 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005625 overrun = OVERRUN_TRUE;
5626 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005627 if (framesOut == 0 || framesIn == 0) {
5628 break;
5629 }
5630
Andy Hung6770c6f2015-04-07 13:43:36 -07005631 // Don't allow framesOut to be larger than what is possible with resampling
5632 // from framesIn.
5633 // This isn't strictly necessary but helps limit buffer resizing in
5634 // RecordBufferConverter. TODO: remove when no longer needed.
5635 framesOut = min(framesOut,
5636 destinationFramesPossible(
5637 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005638 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5639 framesOut = activeTrack->mRecordBufferConverter->convert(
5640 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641
5642 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5643 overrun = OVERRUN_FALSE;
5644 }
5645
5646 if (activeTrack->mFramesToDrop == 0) {
5647 if (framesOut > 0) {
5648 activeTrack->mSink.frameCount = framesOut;
5649 activeTrack->releaseBuffer(&activeTrack->mSink);
5650 }
5651 } else {
5652 // FIXME could do a partial drop of framesOut
5653 if (activeTrack->mFramesToDrop > 0) {
5654 activeTrack->mFramesToDrop -= framesOut;
5655 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005656 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005657 }
5658 } else {
5659 activeTrack->mFramesToDrop += framesOut;
5660 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5661 activeTrack->mSyncStartEvent->isCancelled()) {
5662 ALOGW("Synced record %s, session %d, trigger session %d",
5663 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5664 activeTrack->sessionId(),
5665 (activeTrack->mSyncStartEvent != 0) ?
5666 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005667 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005668 }
5669 }
5670 }
5671
5672 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005673 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005674 }
5675 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005676
5677 switch (overrun) {
5678 case OVERRUN_TRUE:
5679 // client isn't retrieving buffers fast enough
5680 if (!activeTrack->setOverflow()) {
5681 nsecs_t now = systemTime();
5682 // FIXME should lastWarning per track?
5683 if ((now - lastWarning) > kWarningThrottleNs) {
5684 ALOGW("RecordThread: buffer overflow");
5685 lastWarning = now;
5686 }
5687 }
5688 break;
5689 case OVERRUN_FALSE:
5690 activeTrack->clearOverflow();
5691 break;
5692 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005693 break;
5694 }
5695
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005696 }
5697
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005698unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005699 // enable changes in effect chain
5700 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005701 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005702 }
5703
Glenn Kasten93e471f2013-08-19 08:40:07 -07005704 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005705
5706 {
5707 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005708 for (size_t i = 0; i < mTracks.size(); i++) {
5709 sp<RecordTrack> track = mTracks[i];
5710 track->invalidate();
5711 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005712 mActiveTracks.clear();
5713 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005714 mStartStopCond.broadcast();
5715 }
5716
5717 releaseWakeLock();
5718
5719 ALOGV("RecordThread %p exiting", this);
5720 return false;
5721}
5722
Glenn Kasten93e471f2013-08-19 08:40:07 -07005723void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005724{
5725 if (!mStandby) {
5726 inputStandBy();
5727 mStandby = true;
5728 }
5729}
5730
5731void AudioFlinger::RecordThread::inputStandBy()
5732{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005733 // Idle the fast capture if it's currently running
5734 if (mFastCapture != 0) {
5735 FastCaptureStateQueue *sq = mFastCapture->sq();
5736 FastCaptureState *state = sq->begin();
5737 if (!(state->mCommand & FastCaptureState::IDLE)) {
5738 state->mCommand = FastCaptureState::COLD_IDLE;
5739 state->mColdFutexAddr = &mFastCaptureFutex;
5740 state->mColdGen++;
5741 mFastCaptureFutex = 0;
5742 sq->end();
5743 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5744 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5745#if 0
5746 if (kUseFastCapture == FastCapture_Dynamic) {
5747 // FIXME
5748 }
5749#endif
5750#ifdef AUDIO_WATCHDOG
5751 // FIXME
5752#endif
5753 } else {
5754 sq->end(false /*didModify*/);
5755 }
5756 }
Eric Laurent81784c32012-11-19 14:55:58 -08005757 mInput->stream->common.standby(&mInput->stream->common);
5758}
5759
Glenn Kasten05997e22014-03-13 15:08:33 -07005760// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005761sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005762 const sp<AudioFlinger::Client>& client,
5763 uint32_t sampleRate,
5764 audio_format_t format,
5765 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005766 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005767 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005768 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005769 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005770 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005771 pid_t tid,
5772 status_t *status)
5773{
Glenn Kasten74935e42013-12-19 08:56:45 -08005774 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005775 sp<RecordTrack> track;
5776 status_t lStatus;
5777
Glenn Kasten90e58b12013-07-31 16:16:02 -07005778 // client expresses a preference for FAST, but we get the final say
5779 if (*flags & IAudioFlinger::TRACK_FAST) {
5780 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005781 // we formerly checked for a callback handler (non-0 tid),
5782 // but that is no longer required for TRANSFER_OBTAIN mode
5783 //
Glenn Kasten74105912014-07-03 12:28:53 -07005784 // frame count is not specified, or is exactly the pipe depth
5785 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005786 // PCM data
5787 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005788 // native format
5789 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005790 // native channel mask
5791 (channelMask == mChannelMask) &&
5792 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005793 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005794 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005795 hasFastCapture() &&
5796 // there are sufficient fast track slots available
5797 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005798 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005799 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005800 frameCount, mFrameCount);
5801 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005802 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5803 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005805 frameCount, mFrameCount, mPipeFramesP2,
5806 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5807 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005808 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005809 }
5810 }
5811
5812 // compute track buffer size in frames, and suggest the notification frame count
5813 if (*flags & IAudioFlinger::TRACK_FAST) {
5814 // fast track: frame count is exactly the pipe depth
5815 frameCount = mPipeFramesP2;
5816 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5817 *notificationFrames = mFrameCount;
5818 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005819 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5820 // or 20 ms if there is a fast capture
5821 // TODO This could be a roundupRatio inline, and const
5822 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5823 * sampleRate + mSampleRate - 1) / mSampleRate;
5824 // minimum number of notification periods is at least kMinNotifications,
5825 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5826 static const size_t kMinNotifications = 3;
5827 static const uint32_t kMinMs = 30;
5828 // TODO This could be a roundupRatio inline
5829 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5830 // TODO This could be a roundupRatio inline
5831 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5832 maxNotificationFrames;
5833 const size_t minFrameCount = maxNotificationFrames *
5834 max(kMinNotifications, minNotificationsByMs);
5835 frameCount = max(frameCount, minFrameCount);
5836 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5837 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005838 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005839 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005840 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005841
Glenn Kasten15e57982013-09-24 11:52:37 -07005842 lStatus = initCheck();
5843 if (lStatus != NO_ERROR) {
5844 ALOGE("createRecordTrack_l() audio driver not initialized");
5845 goto Exit;
5846 }
Eric Laurent81784c32012-11-19 14:55:58 -08005847
5848 { // scope for mLock
5849 Mutex::Autolock _l(mLock);
5850
5851 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005852 format, channelMask, frameCount, NULL, sessionId, uid,
5853 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005854
Glenn Kasten03003332013-08-06 15:40:54 -07005855 lStatus = track->initCheck();
5856 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005857 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005858 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005859 goto Exit;
5860 }
5861 mTracks.add(track);
5862
5863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5864 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5865 mAudioFlinger->btNrecIsOff();
5866 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5867 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005868
5869 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5870 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5871 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5872 // so ask activity manager to do this on our behalf
5873 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5874 }
Eric Laurent81784c32012-11-19 14:55:58 -08005875 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005876
Eric Laurent81784c32012-11-19 14:55:58 -08005877 lStatus = NO_ERROR;
5878
5879Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005880 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005881 return track;
5882}
5883
5884status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5885 AudioSystem::sync_event_t event,
5886 int triggerSession)
5887{
5888 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5889 sp<ThreadBase> strongMe = this;
5890 status_t status = NO_ERROR;
5891
5892 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005893 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005894 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005895 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005896 triggerSession,
5897 recordTrack->sessionId(),
5898 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005900 // Sync event can be cancelled by the trigger session if the track is not in a
5901 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005902 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005903 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005904 } else {
5905 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005906 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005907 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005908 }
5909 }
5910
5911 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005912 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005913 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5915 if (recordTrack->mState == TrackBase::PAUSING) {
5916 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005917 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005918 } else {
5919 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005920 }
5921 return status;
5922 }
5923
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005924 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5925 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5926 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005928 mActiveTracks.add(recordTrack);
5929 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005930 status_t status = NO_ERROR;
5931 if (recordTrack->isExternalTrack()) {
5932 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005933 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005934 mLock.lock();
5935 // FIXME should verify that recordTrack is still in mActiveTracks
5936 if (status != NO_ERROR) {
5937 mActiveTracks.remove(recordTrack);
5938 mActiveTracksGen++;
5939 recordTrack->clearSyncStartEvent();
5940 ALOGV("RecordThread::start error %d", status);
5941 return status;
5942 }
Eric Laurent81784c32012-11-19 14:55:58 -08005943 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 // Catch up with current buffer indices if thread is already running.
5945 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5946 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5947 // see previously buffered data before it called start(), but with greater risk of overrun.
5948
Andy Hung73c02e42015-03-29 01:13:58 -07005949 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07005950 // clear any converter state as new data will be discontinuous
5951 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005953 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005954 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005955 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005956 ALOGV("Record failed to start");
5957 status = BAD_VALUE;
5958 goto startError;
5959 }
Eric Laurent81784c32012-11-19 14:55:58 -08005960 return status;
5961 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005962
Eric Laurent81784c32012-11-19 14:55:58 -08005963startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005964 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005965 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005966 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005967 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005968 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005969 return status;
5970}
5971
Eric Laurent81784c32012-11-19 14:55:58 -08005972void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5973{
5974 sp<SyncEvent> strongEvent = event.promote();
5975
5976 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005977 sp<RefBase> ptr = strongEvent->cookie().promote();
5978 if (ptr != 0) {
5979 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5980 recordTrack->handleSyncStartEvent(strongEvent);
5981 }
Eric Laurent81784c32012-11-19 14:55:58 -08005982 }
5983}
5984
Glenn Kastena8356f62013-07-25 14:37:52 -07005985bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005986 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005987 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005988 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005989 return false;
5990 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005991 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005992 recordTrack->mState = TrackBase::PAUSING;
5993 // do not wait for mStartStopCond if exiting
5994 if (exitPending()) {
5995 return true;
5996 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005997 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005998 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005999 // if we have been restarted, recordTrack is in mActiveTracks here
6000 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006001 ALOGV("Record stopped OK");
6002 return true;
6003 }
6004 return false;
6005}
6006
Glenn Kasten0f11b512014-01-31 16:18:54 -08006007bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006008{
6009 return false;
6010}
6011
Glenn Kasten0f11b512014-01-31 16:18:54 -08006012status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006013{
6014#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6015 if (!isValidSyncEvent(event)) {
6016 return BAD_VALUE;
6017 }
6018
6019 int eventSession = event->triggerSession();
6020 status_t ret = NAME_NOT_FOUND;
6021
6022 Mutex::Autolock _l(mLock);
6023
6024 for (size_t i = 0; i < mTracks.size(); i++) {
6025 sp<RecordTrack> track = mTracks[i];
6026 if (eventSession == track->sessionId()) {
6027 (void) track->setSyncEvent(event);
6028 ret = NO_ERROR;
6029 }
6030 }
6031 return ret;
6032#else
6033 return BAD_VALUE;
6034#endif
6035}
6036
6037// destroyTrack_l() must be called with ThreadBase::mLock held
6038void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6039{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006040 track->terminate();
6041 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006042 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006043 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006044 removeTrack_l(track);
6045 }
6046}
6047
6048void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6049{
6050 mTracks.remove(track);
6051 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006052 if (track->isFastTrack()) {
6053 ALOG_ASSERT(!mFastTrackAvail);
6054 mFastTrackAvail = true;
6055 }
Eric Laurent81784c32012-11-19 14:55:58 -08006056}
6057
6058void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6059{
6060 dumpInternals(fd, args);
6061 dumpTracks(fd, args);
6062 dumpEffectChains(fd, args);
6063}
6064
6065void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6066{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006067 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006068
Glenn Kasten44182c22015-03-05 17:12:23 -08006069 dumpBase(fd, args);
6070
6071 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006072 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006074 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006076
6077 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6078 const FastCaptureDumpState copy(mFastCaptureDumpState);
6079 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006080}
6081
Glenn Kasten0f11b512014-01-31 16:18:54 -08006082void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006083{
6084 const size_t SIZE = 256;
6085 char buffer[SIZE];
6086 String8 result;
6087
Marco Nelissenb2208842014-02-07 14:00:50 -08006088 size_t numtracks = mTracks.size();
6089 size_t numactive = mActiveTracks.size();
6090 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006091 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006092 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006093 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006094 RecordTrack::appendDumpHeader(result);
6095 for (size_t i = 0; i < numtracks ; ++i) {
6096 sp<RecordTrack> track = mTracks[i];
6097 if (track != 0) {
6098 bool active = mActiveTracks.indexOf(track) >= 0;
6099 if (active) {
6100 numactiveseen++;
6101 }
6102 track->dump(buffer, SIZE, active);
6103 result.append(buffer);
6104 }
Eric Laurent81784c32012-11-19 14:55:58 -08006105 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006106 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006107 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006108 }
6109
Marco Nelissenb2208842014-02-07 14:00:50 -08006110 if (numactiveseen != numactive) {
6111 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6112 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006113 result.append(buffer);
6114 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006115 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006116 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006117 if (mTracks.indexOf(track) < 0) {
6118 track->dump(buffer, SIZE, true);
6119 result.append(buffer);
6120 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006121 }
Eric Laurent81784c32012-11-19 14:55:58 -08006122
6123 }
6124 write(fd, result.string(), result.size());
6125}
6126
Andy Hung73c02e42015-03-29 01:13:58 -07006127
6128void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6129{
6130 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6131 RecordThread *recordThread = (RecordThread *) threadBase.get();
6132 mRsmpInFront = recordThread->mRsmpInRear;
6133 mRsmpInUnrel = 0;
6134}
6135
6136void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6137 size_t *framesAvailable, bool *hasOverrun)
6138{
6139 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6140 RecordThread *recordThread = (RecordThread *) threadBase.get();
6141 const int32_t rear = recordThread->mRsmpInRear;
6142 const int32_t front = mRsmpInFront;
6143 const ssize_t filled = rear - front;
6144
6145 size_t framesIn;
6146 bool overrun = false;
6147 if (filled < 0) {
6148 // should not happen, but treat like a massive overrun and re-sync
6149 framesIn = 0;
6150 mRsmpInFront = rear;
6151 overrun = true;
6152 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6153 framesIn = (size_t) filled;
6154 } else {
6155 // client is not keeping up with server, but give it latest data
6156 framesIn = recordThread->mRsmpInFrames;
6157 mRsmpInFront = /* front = */ rear - framesIn;
6158 overrun = true;
6159 }
6160 if (framesAvailable != NULL) {
6161 *framesAvailable = framesIn;
6162 }
6163 if (hasOverrun != NULL) {
6164 *hasOverrun = overrun;
6165 }
6166}
6167
Eric Laurent81784c32012-11-19 14:55:58 -08006168// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006169status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6170 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006171{
Andy Hung73c02e42015-03-29 01:13:58 -07006172 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 if (threadBase == 0) {
6174 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006175 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 return NOT_ENOUGH_DATA;
6177 }
6178 RecordThread *recordThread = (RecordThread *) threadBase.get();
6179 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006180 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006181 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 // FIXME should not be P2 (don't want to increase latency)
6183 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006184 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006185 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 front &= recordThread->mRsmpInFramesP2 - 1;
6187 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006188 if (part1 > (size_t) filled) {
6189 part1 = filled;
6190 }
6191 size_t ask = buffer->frameCount;
6192 ALOG_ASSERT(ask > 0);
6193 if (part1 > ask) {
6194 part1 = ask;
6195 }
6196 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006197 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006198 buffer->raw = NULL;
6199 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006200 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006201 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
6203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006205 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006206 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006207 return NO_ERROR;
6208}
6209
6210// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006211void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6212 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006213{
Glenn Kasten85948432013-08-19 12:09:05 -07006214 size_t stepCount = buffer->frameCount;
6215 if (stepCount == 0) {
6216 return;
6217 }
Andy Hung73c02e42015-03-29 01:13:58 -07006218 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6219 mRsmpInUnrel -= stepCount;
6220 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006221 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006222 buffer->frameCount = 0;
6223}
6224
Andy Hung97a893e2015-03-29 01:03:07 -07006225AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6226 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6227 uint32_t srcSampleRate,
6228 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6229 uint32_t dstSampleRate) :
6230 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6231 // mSrcFormat
6232 // mSrcSampleRate
6233 // mDstChannelMask
6234 // mDstFormat
6235 // mDstSampleRate
6236 // mSrcChannelCount
6237 // mDstChannelCount
6238 // mDstFrameSize
6239 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6240 mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0)
6241{
6242 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6243 dstChannelMask, dstFormat, dstSampleRate);
6244}
6245
6246AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6247 free(mBuf);
6248 delete mResampler;
6249 free(mRsmpOutBuffer);
6250}
6251
6252size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6253 AudioBufferProvider *provider, size_t frames)
6254{
6255 if (mSrcSampleRate == mDstSampleRate) {
6256 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6257 mSrcSampleRate, mSrcFormat, mDstFormat);
6258
6259 AudioBufferProvider::Buffer buffer;
6260 for (size_t i = frames; i > 0; ) {
6261 buffer.frameCount = i;
6262 status_t status = provider->getNextBuffer(&buffer, 0);
6263 if (status != OK || buffer.frameCount == 0) {
6264 frames -= i; // cannot fill request.
6265 break;
6266 }
6267 // convert to destination buffer
6268 convert(dst, buffer.raw, buffer.frameCount);
6269
6270 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6271 i -= buffer.frameCount;
6272 provider->releaseBuffer(&buffer);
6273 }
6274 } else {
6275 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6276 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6277
6278 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
6279 if (mRsmpOutFrameCount < frames) {
6280 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
6281 free(mRsmpOutBuffer);
6282 // resampler always outputs stereo (FOR NOW)
6283 (void)posix_memalign(&mRsmpOutBuffer, 32, frames * FCC_2 * sizeof(int32_t) /*Q4.27*/);
6284 mRsmpOutFrameCount = frames;
6285 }
6286 // resampler accumulates, but we only have one source track
6287 memset(mRsmpOutBuffer, 0, frames * FCC_2 * sizeof(int32_t));
6288 frames = mResampler->resample((int32_t*)mRsmpOutBuffer, frames, provider);
6289
6290 // convert to destination buffer
6291 convert(dst, mRsmpOutBuffer, frames);
6292 }
6293 return frames;
6294}
6295
6296status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6297 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6298 uint32_t srcSampleRate,
6299 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6300 uint32_t dstSampleRate)
6301{
6302 // quick evaluation if there is any change.
6303 if (mSrcFormat == srcFormat
6304 && mSrcChannelMask == srcChannelMask
6305 && mSrcSampleRate == srcSampleRate
6306 && mDstFormat == dstFormat
6307 && mDstChannelMask == dstChannelMask
6308 && mDstSampleRate == dstSampleRate) {
6309 return NO_ERROR;
6310 }
6311
6312 const bool valid =
6313 audio_is_input_channel(srcChannelMask)
6314 && audio_is_input_channel(dstChannelMask)
6315 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6316 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6317 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6318 ; // no upsampling checks for now
6319 if (!valid) {
6320 return BAD_VALUE;
6321 }
6322
6323 mSrcFormat = srcFormat;
6324 mSrcChannelMask = srcChannelMask;
6325 mSrcSampleRate = srcSampleRate;
6326 mDstFormat = dstFormat;
6327 mDstChannelMask = dstChannelMask;
6328 mDstSampleRate = dstSampleRate;
6329
6330 // compute derived parameters
6331 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6332 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6333 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6334
6335 // do we need a format buffer?
6336 if (mSrcFormat != mDstFormat && mDstChannelCount != mSrcChannelCount) {
6337 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6338 } else {
6339 mBufFrameSize = 0;
6340 }
6341 mBufFrames = 0; // force the buffer to be resized.
6342
6343 // do we need to resample?
6344 if (mSrcSampleRate != mDstSampleRate) {
6345 if (mResampler != NULL) {
6346 delete mResampler;
6347 }
6348 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
6349 mSrcChannelCount, mDstSampleRate); // may seem confusing...
6350 mResampler->setSampleRate(mSrcSampleRate);
6351 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6352 }
6353 return NO_ERROR;
6354}
6355
6356void AudioFlinger::RecordThread::RecordBufferConverter::convert(
6357 void *dst, /*const*/ void *src, size_t frames)
6358{
6359 // check if a memcpy will do
6360 if (mResampler == NULL
6361 && mSrcChannelCount == mDstChannelCount
6362 && mSrcFormat == mDstFormat) {
6363 memcpy(dst, src,
6364 frames * mDstChannelCount * audio_bytes_per_sample(mDstFormat));
6365 return;
6366 }
6367 // reallocate buffer if needed
6368 if (mBufFrameSize != 0 && mBufFrames < frames) {
6369 free(mBuf);
6370 mBufFrames = frames;
6371 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6372 }
6373 // do processing
6374 if (mResampler != NULL) {
6375 // src channel count is always >= 2.
6376 void *dstBuf = mBuf != NULL ? mBuf : dst;
6377 // ditherAndClamp() works as long as all buffers returned by
6378 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
6379 if (mDstChannelCount == 1) {
6380 // the resampler always outputs stereo samples.
6381 // FIXME: this rewrites back into src
6382 ditherAndClamp((int32_t *)src, (const int32_t *)src, frames);
6383 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6384 (const int16_t *)src, frames);
6385 } else {
6386 ditherAndClamp((int32_t *)dstBuf, (const int32_t *)src, frames);
6387 }
6388 } else if (mSrcChannelCount != mDstChannelCount) {
6389 void *dstBuf = mBuf != NULL ? mBuf : dst;
6390 if (mSrcChannelCount == 1) {
6391 upmix_to_stereo_i16_from_mono_i16((int16_t *)dstBuf, (const int16_t *)src,
6392 frames);
6393 } else {
6394 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6395 (const int16_t *)src, frames);
6396 }
6397 }
6398 if (mSrcFormat != mDstFormat) {
6399 void *srcBuf = mBuf != NULL ? mBuf : src;
6400 memcpy_by_audio_format(dst, mDstFormat, srcBuf, mSrcFormat,
6401 frames * mDstChannelCount);
6402 }
6403}
6404
Eric Laurent10351942014-05-08 18:49:52 -07006405bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6406 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006407{
6408 bool reconfig = false;
6409
Eric Laurent10351942014-05-08 18:49:52 -07006410 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006411
Eric Laurent10351942014-05-08 18:49:52 -07006412 audio_format_t reqFormat = mFormat;
6413 uint32_t samplingRate = mSampleRate;
6414 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6415
6416 AudioParameter param = AudioParameter(keyValuePair);
6417 int value;
6418 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6419 // channel count change can be requested. Do we mandate the first client defines the
6420 // HAL sampling rate and channel count or do we allow changes on the fly?
6421 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6422 samplingRate = value;
6423 reconfig = true;
6424 }
6425 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006426 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006427 status = BAD_VALUE;
6428 } else {
6429 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006430 reconfig = true;
6431 }
Eric Laurent10351942014-05-08 18:49:52 -07006432 }
6433 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6434 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6435 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6436 status = BAD_VALUE;
6437 } else {
6438 channelMask = mask;
6439 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
Eric Laurent10351942014-05-08 18:49:52 -07006441 }
6442 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6443 // do not accept frame count changes if tracks are open as the track buffer
6444 // size depends on frame count and correct behavior would not be guaranteed
6445 // if frame count is changed after track creation
6446 if (mActiveTracks.size() > 0) {
6447 status = INVALID_OPERATION;
6448 } else {
6449 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006450 }
Eric Laurent10351942014-05-08 18:49:52 -07006451 }
6452 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6453 // forward device change to effects that have requested to be
6454 // aware of attached audio device.
6455 for (size_t i = 0; i < mEffectChains.size(); i++) {
6456 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006457 }
Eric Laurent81784c32012-11-19 14:55:58 -08006458
Eric Laurent10351942014-05-08 18:49:52 -07006459 // store input device and output device but do not forward output device to audio HAL.
6460 // Note that status is ignored by the caller for output device
6461 // (see AudioFlinger::setParameters()
6462 if (audio_is_output_devices(value)) {
6463 mOutDevice = value;
6464 status = BAD_VALUE;
6465 } else {
6466 mInDevice = value;
6467 // disable AEC and NS if the device is a BT SCO headset supporting those
6468 // pre processings
6469 if (mTracks.size() > 0) {
6470 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6471 mAudioFlinger->btNrecIsOff();
6472 for (size_t i = 0; i < mTracks.size(); i++) {
6473 sp<RecordTrack> track = mTracks[i];
6474 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6475 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006476 }
6477 }
6478 }
Eric Laurent10351942014-05-08 18:49:52 -07006479 }
6480 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6481 mAudioSource != (audio_source_t)value) {
6482 // forward device change to effects that have requested to be
6483 // aware of attached audio device.
6484 for (size_t i = 0; i < mEffectChains.size(); i++) {
6485 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006486 }
Eric Laurent10351942014-05-08 18:49:52 -07006487 mAudioSource = (audio_source_t)value;
6488 }
Glenn Kastene198c362013-08-13 09:13:36 -07006489
Eric Laurent10351942014-05-08 18:49:52 -07006490 if (status == NO_ERROR) {
6491 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6492 keyValuePair.string());
6493 if (status == INVALID_OPERATION) {
6494 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006495 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6496 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006497 }
6498 if (reconfig) {
6499 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006500 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6501 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006502 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006503 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006504 audio_channel_count_from_in_mask(
6505 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006506 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6507 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6508 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006509 }
Eric Laurent10351942014-05-08 18:49:52 -07006510 if (status == NO_ERROR) {
6511 readInputParameters_l();
6512 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006513 }
6514 }
Eric Laurent81784c32012-11-19 14:55:58 -08006515 }
Eric Laurent10351942014-05-08 18:49:52 -07006516
Eric Laurent81784c32012-11-19 14:55:58 -08006517 return reconfig;
6518}
6519
6520String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6521{
Eric Laurent81784c32012-11-19 14:55:58 -08006522 Mutex::Autolock _l(mLock);
6523 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006524 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006525 }
6526
Glenn Kastend8ea6992013-07-16 14:17:15 -07006527 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6528 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006529 free(s);
6530 return out_s8;
6531}
6532
Eric Laurent021cf962014-05-13 10:18:14 -07006533void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006534 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006535 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006536
6537 switch (event) {
6538 case AudioSystem::INPUT_OPENED:
6539 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006540 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006541 desc.samplingRate = mSampleRate;
6542 desc.format = mFormat;
6543 desc.frameCount = mFrameCount;
6544 desc.latency = 0;
6545 param2 = &desc;
6546 break;
6547
6548 case AudioSystem::INPUT_CLOSED:
6549 default:
6550 break;
6551 }
Eric Laurent021cf962014-05-13 10:18:14 -07006552 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006553}
6554
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006555void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006556{
Eric Laurent81784c32012-11-19 14:55:58 -08006557 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6558 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006559 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006560 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6561 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006562 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006563 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006564 }
Eric Laurent665470b2014-07-03 16:37:08 -07006565 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006566 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6567 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006568 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006569 // 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 -07006570 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006571 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006572 // A larger value should allow more old data to be read after a track calls start(),
6573 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006574 //
6575 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006576 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006577 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006578 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006579
6580 // TODO optimize audio capture buffer sizes ...
6581 // Here we calculate the size of the sliding buffer used as a source
6582 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6583 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6584 // be better to have it derived from the pipe depth in the long term.
6585 // The current value is higher than necessary. However it should not add to latency.
6586
Glenn Kasten85948432013-08-19 12:09:05 -07006587 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6588 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006589
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006590 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6591 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006592}
6593
Glenn Kasten5f972c02014-01-13 09:59:31 -08006594uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006595{
6596 Mutex::Autolock _l(mLock);
6597 if (initCheck() != NO_ERROR) {
6598 return 0;
6599 }
6600
6601 return mInput->stream->get_input_frames_lost(mInput->stream);
6602}
6603
6604uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6605{
6606 Mutex::Autolock _l(mLock);
6607 uint32_t result = 0;
6608 if (getEffectChain_l(sessionId) != 0) {
6609 result = EFFECT_SESSION;
6610 }
6611
6612 for (size_t i = 0; i < mTracks.size(); ++i) {
6613 if (sessionId == mTracks[i]->sessionId()) {
6614 result |= TRACK_SESSION;
6615 break;
6616 }
6617 }
6618
6619 return result;
6620}
6621
6622KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6623{
6624 KeyedVector<int, bool> ids;
6625 Mutex::Autolock _l(mLock);
6626 for (size_t j = 0; j < mTracks.size(); ++j) {
6627 sp<RecordThread::RecordTrack> track = mTracks[j];
6628 int sessionId = track->sessionId();
6629 if (ids.indexOfKey(sessionId) < 0) {
6630 ids.add(sessionId, true);
6631 }
6632 }
6633 return ids;
6634}
6635
6636AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6637{
6638 Mutex::Autolock _l(mLock);
6639 AudioStreamIn *input = mInput;
6640 mInput = NULL;
6641 return input;
6642}
6643
6644// this method must always be called either with ThreadBase mLock held or inside the thread loop
6645audio_stream_t* AudioFlinger::RecordThread::stream() const
6646{
6647 if (mInput == NULL) {
6648 return NULL;
6649 }
6650 return &mInput->stream->common;
6651}
6652
6653status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6654{
6655 // only one chain per input thread
6656 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006657 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006658 return INVALID_OPERATION;
6659 }
6660 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006661 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006662 chain->setInBuffer(NULL);
6663 chain->setOutBuffer(NULL);
6664
6665 checkSuspendOnAddEffectChain_l(chain);
6666
Eric Laurent1b928682014-10-02 19:41:47 -07006667 // make sure enabled pre processing effects state is communicated to the HAL as we
6668 // just moved them to a new input stream.
6669 chain->syncHalEffectsState();
6670
Eric Laurent81784c32012-11-19 14:55:58 -08006671 mEffectChains.add(chain);
6672
6673 return NO_ERROR;
6674}
6675
6676size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6677{
6678 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6679 ALOGW_IF(mEffectChains.size() != 1,
6680 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6681 chain.get(), mEffectChains.size(), this);
6682 if (mEffectChains.size() == 1) {
6683 mEffectChains.removeAt(0);
6684 }
6685 return 0;
6686}
6687
Eric Laurent1c333e22014-05-20 10:48:17 -07006688status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6689 audio_patch_handle_t *handle)
6690{
6691 status_t status = NO_ERROR;
6692 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6693 // store new device and send to effects
6694 mInDevice = patch->sources[0].ext.device.type;
6695 for (size_t i = 0; i < mEffectChains.size(); i++) {
6696 mEffectChains[i]->setDevice_l(mInDevice);
6697 }
6698
6699 // disable AEC and NS if the device is a BT SCO headset supporting those
6700 // pre processings
6701 if (mTracks.size() > 0) {
6702 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6703 mAudioFlinger->btNrecIsOff();
6704 for (size_t i = 0; i < mTracks.size(); i++) {
6705 sp<RecordTrack> track = mTracks[i];
6706 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6707 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6708 }
6709 }
6710
6711 // store new source and send to effects
6712 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6713 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6714 for (size_t i = 0; i < mEffectChains.size(); i++) {
6715 mEffectChains[i]->setAudioSource_l(mAudioSource);
6716 }
6717 }
6718
6719 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6720 status = hwDevice->create_audio_patch(hwDevice,
6721 patch->num_sources,
6722 patch->sources,
6723 patch->num_sinks,
6724 patch->sinks,
6725 handle);
6726 } else {
6727 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6728 }
6729 return status;
6730}
6731
6732status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6733{
6734 status_t status = NO_ERROR;
6735 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6736 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6737 status = hwDevice->release_audio_patch(hwDevice, handle);
6738 } else {
6739 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6740 }
6741 return status;
6742}
6743
Eric Laurent83b88082014-06-20 18:31:16 -07006744void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6745{
6746 Mutex::Autolock _l(mLock);
6747 mTracks.add(record);
6748}
6749
6750void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6751{
6752 Mutex::Autolock _l(mLock);
6753 destroyTrack_l(record);
6754}
6755
6756void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6757{
6758 ThreadBase::getAudioPortConfig(config);
6759 config->role = AUDIO_PORT_ROLE_SINK;
6760 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6761 config->ext.mix.usecase.source = mAudioSource;
6762}
Eric Laurent1c333e22014-05-20 10:48:17 -07006763
Glenn Kasten63238ef2015-03-02 15:50:29 -08006764} // namespace android