blob: 4eaeda30239cd331319d74491658a088f65b7e65 [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) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001611 // this must match AudioTrack.cpp calculateMinFrameCount().
1612 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001613 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1614 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1615 if (minBufCount < 2) {
1616 minBufCount = 2;
1617 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001618 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1619 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001620 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001621 minBufCount * sourceFramesNeededWithTimestretch(
1622 sampleRate, mNormalFrameCount,
1623 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001624 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001625 frameCount = minFrameCount;
1626 }
Eric Laurent81784c32012-11-19 14:55:58 -08001627 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001628 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001629
Glenn Kastenc3df8382014-03-13 15:05:25 -07001630 switch (mType) {
1631
1632 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001633 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001634 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001635 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1636 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001637 sampleRate, format, channelMask, mOutput, mFormat);
1638 lStatus = BAD_VALUE;
1639 goto Exit;
1640 }
1641 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001642 break;
1643
1644 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001646 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1647 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001648 sampleRate, format, channelMask, mOutput, mFormat);
1649 lStatus = BAD_VALUE;
1650 goto Exit;
1651 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001652 break;
1653
1654 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001655 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001656 ALOGE("createTrack_l() Bad parameter: format %#x \""
1657 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658 format, mOutput, mFormat);
1659 lStatus = BAD_VALUE;
1660 goto Exit;
1661 }
Andy Hungcd044842014-08-07 11:04:34 -07001662 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001663 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1664 lStatus = BAD_VALUE;
1665 goto Exit;
1666 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001667 break;
1668
Eric Laurent81784c32012-11-19 14:55:58 -08001669 }
1670
1671 lStatus = initCheck();
1672 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001673 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001674 goto Exit;
1675 }
1676
1677 { // scope for mLock
1678 Mutex::Autolock _l(mLock);
1679
1680 // all tracks in same audio session must share the same routing strategy otherwise
1681 // conflicts will happen when tracks are moved from one output to another by audio policy
1682 // manager
1683 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1684 for (size_t i = 0; i < mTracks.size(); ++i) {
1685 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001686 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001687 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1688 if (sessionId == t->sessionId() && strategy != actual) {
1689 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1690 strategy, actual);
1691 lStatus = BAD_VALUE;
1692 goto Exit;
1693 }
1694 }
1695 }
1696
1697 if (!isTimed) {
1698 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001699 channelMask, frameCount, NULL, sharedBuffer,
1700 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001701 } else {
1702 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001703 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001704 }
Glenn Kasten03003332013-08-06 15:40:54 -07001705
1706 // new Track always returns non-NULL,
1707 // but TimedTrack::create() is a factory that could fail by returning NULL
1708 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1709 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001710 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001711 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001712 goto Exit;
1713 }
1714 mTracks.add(track);
1715
1716 sp<EffectChain> chain = getEffectChain_l(sessionId);
1717 if (chain != 0) {
1718 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1719 track->setMainBuffer(chain->inBuffer());
1720 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1721 chain->incTrackCnt();
1722 }
1723
1724 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1725 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1726 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1727 // so ask activity manager to do this on our behalf
1728 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1729 }
1730 }
1731
1732 lStatus = NO_ERROR;
1733
1734Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001735 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001736 return track;
1737}
1738
1739uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1740{
1741 return latency;
1742}
1743
1744uint32_t AudioFlinger::PlaybackThread::latency() const
1745{
1746 Mutex::Autolock _l(mLock);
1747 return latency_l();
1748}
1749uint32_t AudioFlinger::PlaybackThread::latency_l() const
1750{
1751 if (initCheck() == NO_ERROR) {
1752 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1753 } else {
1754 return 0;
1755 }
1756}
1757
1758void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1759{
1760 Mutex::Autolock _l(mLock);
1761 // Don't apply master volume in SW if our HAL can do it for us.
1762 if (mOutput && mOutput->audioHwDev &&
1763 mOutput->audioHwDev->canSetMasterVolume()) {
1764 mMasterVolume = 1.0;
1765 } else {
1766 mMasterVolume = value;
1767 }
1768}
1769
1770void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1771{
1772 Mutex::Autolock _l(mLock);
1773 // Don't apply master mute in SW if our HAL can do it for us.
1774 if (mOutput && mOutput->audioHwDev &&
1775 mOutput->audioHwDev->canSetMasterMute()) {
1776 mMasterMute = false;
1777 } else {
1778 mMasterMute = muted;
1779 }
1780}
1781
1782void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1783{
1784 Mutex::Autolock _l(mLock);
1785 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001786 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001787}
1788
1789void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1790{
1791 Mutex::Autolock _l(mLock);
1792 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001793 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001794}
1795
1796float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1797{
1798 Mutex::Autolock _l(mLock);
1799 return mStreamTypes[stream].volume;
1800}
1801
1802// addTrack_l() must be called with ThreadBase::mLock held
1803status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1804{
1805 status_t status = ALREADY_EXISTS;
1806
1807 // set retry count for buffer fill
1808 track->mRetryCount = kMaxTrackStartupRetries;
1809 if (mActiveTracks.indexOf(track) < 0) {
1810 // the track is newly added, make sure it fills up all its
1811 // buffers before playing. This is to ensure the client will
1812 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001813 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001814 TrackBase::track_state state = track->mState;
1815 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001816 status = AudioSystem::startOutput(mId, track->streamType(),
1817 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001818 mLock.lock();
1819 // abort track was stopped/paused while we released the lock
1820 if (state != track->mState) {
1821 if (status == NO_ERROR) {
1822 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001823 AudioSystem::stopOutput(mId, track->streamType(),
1824 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001825 mLock.lock();
1826 }
1827 return INVALID_OPERATION;
1828 }
1829 // abort if start is rejected by audio policy manager
1830 if (status != NO_ERROR) {
1831 return PERMISSION_DENIED;
1832 }
1833#ifdef ADD_BATTERY_DATA
1834 // to track the speaker usage
1835 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1836#endif
1837 }
1838
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001839 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001840 track->mResetDone = false;
1841 track->mPresentationCompleteFrames = 0;
1842 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001843 mWakeLockUids.add(track->uid());
1844 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001845 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001846 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1847 if (chain != 0) {
1848 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1849 track->sessionId());
1850 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001851 }
1852
1853 status = NO_ERROR;
1854 }
1855
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001856 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001857 return status;
1858}
1859
Eric Laurentbfb1b832013-01-07 09:53:42 -08001860bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001861{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001863 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001864 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1865 track->mState = TrackBase::STOPPED;
1866 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001867 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001868 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001871
1872 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001873}
1874
1875void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1876{
1877 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1878 mTracks.remove(track);
1879 deleteTrackName_l(track->name());
1880 // redundant as track is about to be destroyed, for dumpsys only
1881 track->mName = -1;
1882 if (track->isFastTrack()) {
1883 int index = track->mFastIndex;
1884 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1885 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1886 mFastTrackAvailMask |= 1 << index;
1887 // redundant as track is about to be destroyed, for dumpsys only
1888 track->mFastIndex = -1;
1889 }
1890 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1891 if (chain != 0) {
1892 chain->decTrackCnt();
1893 }
1894}
1895
Eric Laurentede6c3b2013-09-19 14:37:46 -07001896void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001897{
1898 // Thread could be blocked waiting for async
1899 // so signal it to handle state changes immediately
1900 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1901 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1902 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001903 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001904}
1905
Eric Laurent81784c32012-11-19 14:55:58 -08001906String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1907{
Eric Laurent81784c32012-11-19 14:55:58 -08001908 Mutex::Autolock _l(mLock);
1909 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001910 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001911 }
1912
Glenn Kastend8ea6992013-07-16 14:17:15 -07001913 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1914 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001915 free(s);
1916 return out_s8;
1917}
1918
Eric Laurent021cf962014-05-13 10:18:14 -07001919void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001920 AudioSystem::OutputDescriptor desc;
1921 void *param2 = NULL;
1922
Eric Laurent021cf962014-05-13 10:18:14 -07001923 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001924 param);
1925
1926 switch (event) {
1927 case AudioSystem::OUTPUT_OPENED:
1928 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001929 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001930 desc.samplingRate = mSampleRate;
1931 desc.format = mFormat;
1932 desc.frameCount = mNormalFrameCount; // FIXME see
1933 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001934 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001935 param2 = &desc;
1936 break;
1937
1938 case AudioSystem::STREAM_CONFIG_CHANGED:
1939 param2 = &param;
1940 case AudioSystem::OUTPUT_CLOSED:
1941 default:
1942 break;
1943 }
Eric Laurent021cf962014-05-13 10:18:14 -07001944 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001945}
1946
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947void AudioFlinger::PlaybackThread::writeCallback()
1948{
1949 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951}
1952
1953void AudioFlinger::PlaybackThread::drainCallback()
1954{
1955 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001956 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957}
1958
Eric Laurent3b4529e2013-09-05 18:09:19 -07001959void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960{
1961 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001962 // reject out of sequence requests
1963 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1964 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965 mWaitWorkCV.signal();
1966 }
1967}
1968
Eric Laurent3b4529e2013-09-05 18:09:19 -07001969void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970{
1971 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001972 // reject out of sequence requests
1973 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1974 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 mWaitWorkCV.signal();
1976 }
1977}
1978
1979// static
1980int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001981 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001982 void *cookie)
1983{
1984 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1985 ALOGV("asyncCallback() event %d", event);
1986 switch (event) {
1987 case STREAM_CBK_EVENT_WRITE_READY:
1988 me->writeCallback();
1989 break;
1990 case STREAM_CBK_EVENT_DRAIN_READY:
1991 me->drainCallback();
1992 break;
1993 default:
1994 ALOGW("asyncCallback() unknown event %d", event);
1995 break;
1996 }
1997 return 0;
1998}
1999
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002000void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002001{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002002 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002003 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2004 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002005 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002006 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002007 }
Andy Hung9a592762014-07-21 21:56:01 -07002008 if ((mType == MIXER || mType == DUPLICATING)
2009 && !isValidPcmSinkChannelMask(mChannelMask)) {
2010 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2011 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002012 }
Andy Hunge5412692014-05-16 11:25:07 -07002013 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002014 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2015 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002016 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002017 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002018 }
Andy Hung6146c082014-03-18 11:56:15 -07002019 if ((mType == MIXER || mType == DUPLICATING)
2020 && !isValidPcmSinkFormat(mFormat)) {
2021 LOG_FATAL("HAL format %#x not supported for mixed output",
2022 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002023 }
Phil Burk062e67a2015-02-11 13:40:50 -08002024 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002025 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2026 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002027 if (mFrameCount & 15) {
2028 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2029 mFrameCount);
2030 }
2031
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2033 (mOutput->stream->set_callback != NULL)) {
2034 if (mOutput->stream->set_callback(mOutput->stream,
2035 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2036 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002037 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038 }
2039 }
2040
Eric Laurentd1f69b02014-12-15 14:33:13 -08002041 mHwSupportsPause = false;
2042 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2043 if (mOutput->stream->pause != NULL) {
2044 if (mOutput->stream->resume != NULL) {
2045 mHwSupportsPause = true;
2046 } else {
2047 ALOGW("direct output implements pause but not resume");
2048 }
2049 } else if (mOutput->stream->resume != NULL) {
2050 ALOGW("direct output implements resume but not pause");
2051 }
2052 }
2053
Andy Hungfbfc3952015-01-15 13:33:51 -08002054 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2055 // For best precision, we use float instead of the associated output
2056 // device format (typically PCM 16 bit).
2057
2058 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2059 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2060 mBufferSize = mFrameSize * mFrameCount;
2061
2062 // TODO: We currently use the associated output device channel mask and sample rate.
2063 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2064 // (if a valid mask) to avoid premature downmix.
2065 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2066 // instead of the output device sample rate to avoid loss of high frequency information.
2067 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2068 }
2069
Andy Hung09a50072014-02-27 14:30:47 -08002070 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002071 double multiplier = 1.0;
2072 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2073 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002074 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2075 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002076 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2077 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2078 maxNormalFrameCount = maxNormalFrameCount & ~15;
2079 if (maxNormalFrameCount < minNormalFrameCount) {
2080 maxNormalFrameCount = minNormalFrameCount;
2081 }
2082 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2083 if (multiplier <= 1.0) {
2084 multiplier = 1.0;
2085 } else if (multiplier <= 2.0) {
2086 if (2 * mFrameCount <= maxNormalFrameCount) {
2087 multiplier = 2.0;
2088 } else {
2089 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2090 }
2091 } else {
2092 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002093 // 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 -08002094 // track, but we sometimes have to do this to satisfy the maximum frame count
2095 // constraint)
2096 // FIXME this rounding up should not be done if no HAL SRC
2097 uint32_t truncMult = (uint32_t) multiplier;
2098 if ((truncMult & 1)) {
2099 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2100 ++truncMult;
2101 }
2102 }
2103 multiplier = (double) truncMult;
2104 }
2105 }
2106 mNormalFrameCount = multiplier * mFrameCount;
2107 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002108 if (mType == MIXER || mType == DUPLICATING) {
2109 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2110 }
Andy Hung09a50072014-02-27 14:30:47 -08002111 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002112 mNormalFrameCount);
2113
Andy Hung010a1a12014-03-13 13:57:33 -07002114 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2115 // Originally this was int16_t[] array, need to remove legacy implications.
2116 free(mSinkBuffer);
2117 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002118 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2119 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2120 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002121 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002122
Andy Hung69aed5f2014-02-25 17:24:40 -08002123 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2124 // drives the output.
2125 free(mMixerBuffer);
2126 mMixerBuffer = NULL;
2127 if (mMixerBufferEnabled) {
2128 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2129 mMixerBufferSize = mNormalFrameCount * mChannelCount
2130 * audio_bytes_per_sample(mMixerBufferFormat);
2131 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2132 }
Andy Hung98ef9782014-03-04 14:46:50 -08002133 free(mEffectBuffer);
2134 mEffectBuffer = NULL;
2135 if (mEffectBufferEnabled) {
2136 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2137 mEffectBufferSize = mNormalFrameCount * mChannelCount
2138 * audio_bytes_per_sample(mEffectBufferFormat);
2139 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2140 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002141
Eric Laurent81784c32012-11-19 14:55:58 -08002142 // force reconfiguration of effect chains and engines to take new buffer size and audio
2143 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002144 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002145 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2146 // matter.
2147 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2148 Vector< sp<EffectChain> > effectChains = mEffectChains;
2149 for (size_t i = 0; i < effectChains.size(); i ++) {
2150 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2151 }
2152}
2153
2154
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002155status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002156{
2157 if (halFrames == NULL || dspFrames == NULL) {
2158 return BAD_VALUE;
2159 }
2160 Mutex::Autolock _l(mLock);
2161 if (initCheck() != NO_ERROR) {
2162 return INVALID_OPERATION;
2163 }
2164 size_t framesWritten = mBytesWritten / mFrameSize;
2165 *halFrames = framesWritten;
2166
2167 if (isSuspended()) {
2168 // return an estimation of rendered frames when the output is suspended
2169 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2170 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2171 return NO_ERROR;
2172 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002173 status_t status;
2174 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002175 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002176 *dspFrames = (size_t)frames;
2177 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002178 }
2179}
2180
2181uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2182{
2183 Mutex::Autolock _l(mLock);
2184 uint32_t result = 0;
2185 if (getEffectChain_l(sessionId) != 0) {
2186 result = EFFECT_SESSION;
2187 }
2188
2189 for (size_t i = 0; i < mTracks.size(); ++i) {
2190 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002191 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002192 result |= TRACK_SESSION;
2193 break;
2194 }
2195 }
2196
2197 return result;
2198}
2199
2200uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2201{
2202 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2203 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2204 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2205 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2206 }
2207 for (size_t i = 0; i < mTracks.size(); i++) {
2208 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002209 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002210 return AudioSystem::getStrategyForStream(track->streamType());
2211 }
2212 }
2213 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2214}
2215
2216
Phil Burk062e67a2015-02-11 13:40:50 -08002217AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
2219 Mutex::Autolock _l(mLock);
2220 return mOutput;
2221}
2222
Phil Burk062e67a2015-02-11 13:40:50 -08002223AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002224{
2225 Mutex::Autolock _l(mLock);
2226 AudioStreamOut *output = mOutput;
2227 mOutput = NULL;
2228 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2229 // must push a NULL and wait for ack
2230 mOutputSink.clear();
2231 mPipeSink.clear();
2232 mNormalSink.clear();
2233 return output;
2234}
2235
2236// this method must always be called either with ThreadBase mLock held or inside the thread loop
2237audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2238{
2239 if (mOutput == NULL) {
2240 return NULL;
2241 }
2242 return &mOutput->stream->common;
2243}
2244
2245uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2246{
2247 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2248}
2249
2250status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2251{
2252 if (!isValidSyncEvent(event)) {
2253 return BAD_VALUE;
2254 }
2255
2256 Mutex::Autolock _l(mLock);
2257
2258 for (size_t i = 0; i < mTracks.size(); ++i) {
2259 sp<Track> track = mTracks[i];
2260 if (event->triggerSession() == track->sessionId()) {
2261 (void) track->setSyncEvent(event);
2262 return NO_ERROR;
2263 }
2264 }
2265
2266 return NAME_NOT_FOUND;
2267}
2268
2269bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2270{
2271 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2272}
2273
2274void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2275 const Vector< sp<Track> >& tracksToRemove)
2276{
2277 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002278 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002279 for (size_t i = 0 ; i < count ; i++) {
2280 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002281 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002282 AudioSystem::stopOutput(mId, track->streamType(),
2283 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284#ifdef ADD_BATTERY_DATA
2285 // to track the speaker usage
2286 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2287#endif
2288 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002289 AudioSystem::releaseOutput(mId, track->streamType(),
2290 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291 }
Eric Laurent81784c32012-11-19 14:55:58 -08002292 }
2293 }
2294 }
Eric Laurent81784c32012-11-19 14:55:58 -08002295}
2296
2297void AudioFlinger::PlaybackThread::checkSilentMode_l()
2298{
2299 if (!mMasterMute) {
2300 char value[PROPERTY_VALUE_MAX];
2301 if (property_get("ro.audio.silent", value, "0") > 0) {
2302 char *endptr;
2303 unsigned long ul = strtoul(value, &endptr, 0);
2304 if (*endptr == '\0' && ul != 0) {
2305 ALOGD("Silence is golden");
2306 // The setprop command will not allow a property to be changed after
2307 // the first time it is set, so we don't have to worry about un-muting.
2308 setMasterMute_l(true);
2309 }
2310 }
2311 }
2312}
2313
2314// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002316{
2317 // FIXME rewrite to reduce number of system calls
2318 mLastWriteTime = systemTime();
2319 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002321 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002322
2323 // If an NBAIO sink is present, use it to write the normal mixer's submix
2324 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002325
Andy Hung010a1a12014-03-13 13:57:33 -07002326 const size_t count = mBytesRemaining / mFrameSize;
2327
Simon Wilson2d590962012-11-29 15:18:50 -08002328 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002329 // update the setpoint when AudioFlinger::mScreenState changes
2330 uint32_t screenState = AudioFlinger::mScreenState;
2331 if (screenState != mScreenState) {
2332 mScreenState = screenState;
2333 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2334 if (pipe != NULL) {
2335 pipe->setAvgFrames((mScreenState & 1) ?
2336 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2337 }
2338 }
Andy Hung010a1a12014-03-13 13:57:33 -07002339 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002340 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002341 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002342 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002343 } else {
2344 bytesWritten = framesWritten;
2345 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002346 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002347 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002348 if (status == NO_ERROR) {
2349 size_t totalFramesWritten = mNormalSink->framesWritten();
2350 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2351 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002352 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002353 mLatchDValid = true;
2354 }
2355 }
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // otherwise use the HAL / AudioStreamOut directly
2357 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002358 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002359
Eric Laurentbfb1b832013-01-07 09:53:42 -08002360 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002361 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2362 mWriteAckSequence += 2;
2363 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002365 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002367 // FIXME We should have an implementation of timestamps for direct output threads.
2368 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002369 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 if (mUseAsyncWrite &&
2371 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2372 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002373 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002375 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377 }
2378
Eric Laurent81784c32012-11-19 14:55:58 -08002379 mNumWrites++;
2380 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002381 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 return bytesWritten;
2383}
2384
2385void AudioFlinger::PlaybackThread::threadLoop_drain()
2386{
2387 if (mOutput->stream->drain) {
2388 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2389 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002390 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2391 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002392 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002393 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002394 }
2395 mOutput->stream->drain(mOutput->stream,
2396 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2397 : AUDIO_DRAIN_ALL);
2398 }
2399}
2400
2401void AudioFlinger::PlaybackThread::threadLoop_exit()
2402{
Eric Laurent275e8e92014-11-30 15:14:47 -08002403 {
2404 Mutex::Autolock _l(mLock);
2405 for (size_t i = 0; i < mTracks.size(); i++) {
2406 sp<Track> track = mTracks[i];
2407 track->invalidate();
2408 }
2409 }
Eric Laurent81784c32012-11-19 14:55:58 -08002410}
2411
2412/*
2413The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002414 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002415 - activeSleepTime from activeSleepTimeUs()
2416 - idleSleepTime from idleSleepTimeUs()
2417 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2418 - maxPeriod from frame count and sample rate (MIXER only)
2419
2420The parameters that affect these derived values are:
2421 - frame count
2422 - frame size
2423 - sample rate
2424 - device type: A2DP or not
2425 - device latency
2426 - format: PCM or not
2427 - active sleep time
2428 - idle sleep time
2429*/
2430
2431void AudioFlinger::PlaybackThread::cacheParameters_l()
2432{
Andy Hung25c2dac2014-02-27 14:56:00 -08002433 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002434 activeSleepTime = activeSleepTimeUs();
2435 idleSleepTime = idleSleepTimeUs();
2436}
2437
2438void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2439{
Glenn Kasten7c027242012-12-26 14:43:16 -08002440 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002441 this, streamType, mTracks.size());
2442 Mutex::Autolock _l(mLock);
2443
2444 size_t size = mTracks.size();
2445 for (size_t i = 0; i < size; i++) {
2446 sp<Track> t = mTracks[i];
2447 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002448 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002449 }
2450 }
2451}
2452
2453status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2454{
2455 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002456 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2457 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002458 bool ownsBuffer = false;
2459
2460 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2461 if (session > 0) {
2462 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002463 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002464 if (mType != DIRECT) {
2465 size_t numSamples = mNormalFrameCount * mChannelCount;
2466 buffer = new int16_t[numSamples];
2467 memset(buffer, 0, numSamples * sizeof(int16_t));
2468 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2469 ownsBuffer = true;
2470 }
2471
2472 // Attach all tracks with same session ID to this chain.
2473 for (size_t i = 0; i < mTracks.size(); ++i) {
2474 sp<Track> track = mTracks[i];
2475 if (session == track->sessionId()) {
2476 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2477 buffer);
2478 track->setMainBuffer(buffer);
2479 chain->incTrackCnt();
2480 }
2481 }
2482
2483 // indicate all active tracks in the chain
2484 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2485 sp<Track> track = mActiveTracks[i].promote();
2486 if (track == 0) {
2487 continue;
2488 }
2489 if (session == track->sessionId()) {
2490 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2491 chain->incActiveTrackCnt();
2492 }
2493 }
2494 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002495 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002496 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002497 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2498 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002499 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2500 // chains list in order to be processed last as it contains output stage effects
2501 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2502 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2503 // after track specific effects and before output stage
2504 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2505 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2506 // Effect chain for other sessions are inserted at beginning of effect
2507 // chains list to be processed before output mix effects. Relative order between other
2508 // sessions is not important
2509 size_t size = mEffectChains.size();
2510 size_t i = 0;
2511 for (i = 0; i < size; i++) {
2512 if (mEffectChains[i]->sessionId() < session) {
2513 break;
2514 }
2515 }
2516 mEffectChains.insertAt(chain, i);
2517 checkSuspendOnAddEffectChain_l(chain);
2518
2519 return NO_ERROR;
2520}
2521
2522size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2523{
2524 int session = chain->sessionId();
2525
2526 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2527
2528 for (size_t i = 0; i < mEffectChains.size(); i++) {
2529 if (chain == mEffectChains[i]) {
2530 mEffectChains.removeAt(i);
2531 // detach all active tracks from the chain
2532 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2533 sp<Track> track = mActiveTracks[i].promote();
2534 if (track == 0) {
2535 continue;
2536 }
2537 if (session == track->sessionId()) {
2538 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2539 chain.get(), session);
2540 chain->decActiveTrackCnt();
2541 }
2542 }
2543
2544 // detach all tracks with same session ID from this chain
2545 for (size_t i = 0; i < mTracks.size(); ++i) {
2546 sp<Track> track = mTracks[i];
2547 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002548 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002549 chain->decTrackCnt();
2550 }
2551 }
2552 break;
2553 }
2554 }
2555 return mEffectChains.size();
2556}
2557
2558status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2559 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2560{
2561 Mutex::Autolock _l(mLock);
2562 return attachAuxEffect_l(track, EffectId);
2563}
2564
2565status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2566 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2567{
2568 status_t status = NO_ERROR;
2569
2570 if (EffectId == 0) {
2571 track->setAuxBuffer(0, NULL);
2572 } else {
2573 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2574 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2575 if (effect != 0) {
2576 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2577 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2578 } else {
2579 status = INVALID_OPERATION;
2580 }
2581 } else {
2582 status = BAD_VALUE;
2583 }
2584 }
2585 return status;
2586}
2587
2588void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2589{
2590 for (size_t i = 0; i < mTracks.size(); ++i) {
2591 sp<Track> track = mTracks[i];
2592 if (track->auxEffectId() == effectId) {
2593 attachAuxEffect_l(track, 0);
2594 }
2595 }
2596}
2597
2598bool AudioFlinger::PlaybackThread::threadLoop()
2599{
2600 Vector< sp<Track> > tracksToRemove;
2601
2602 standbyTime = systemTime();
2603
2604 // MIXER
2605 nsecs_t lastWarning = 0;
2606
2607 // DUPLICATING
2608 // FIXME could this be made local to while loop?
2609 writeFrames = 0;
2610
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002611 int lastGeneration = 0;
2612
Eric Laurent81784c32012-11-19 14:55:58 -08002613 cacheParameters_l();
2614 sleepTime = idleSleepTime;
2615
2616 if (mType == MIXER) {
2617 sleepTimeShift = 0;
2618 }
2619
2620 CpuStats cpuStats;
2621 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2622
2623 acquireWakeLock();
2624
Glenn Kasten9e58b552013-01-18 15:09:48 -08002625 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2626 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2627 // and then that string will be logged at the next convenient opportunity.
2628 const char *logString = NULL;
2629
Eric Laurent664539d2013-09-23 18:24:31 -07002630 checkSilentMode_l();
2631
Eric Laurent81784c32012-11-19 14:55:58 -08002632 while (!exitPending())
2633 {
2634 cpuStats.sample(myName);
2635
2636 Vector< sp<EffectChain> > effectChains;
2637
Eric Laurent81784c32012-11-19 14:55:58 -08002638 { // scope for mLock
2639
2640 Mutex::Autolock _l(mLock);
2641
Eric Laurent021cf962014-05-13 10:18:14 -07002642 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002643
Glenn Kasten9e58b552013-01-18 15:09:48 -08002644 if (logString != NULL) {
2645 mNBLogWriter->logTimestamp();
2646 mNBLogWriter->log(logString);
2647 logString = NULL;
2648 }
2649
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002650 // Gather the framesReleased counters for all active tracks,
2651 // and latch them atomically with the timestamp.
2652 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2653 mLatchD.mFramesReleased.clear();
2654 size_t size = mActiveTracks.size();
2655 for (size_t i = 0; i < size; i++) {
2656 sp<Track> t = mActiveTracks[i].promote();
2657 if (t != 0) {
2658 mLatchD.mFramesReleased.add(t.get(),
2659 t->mAudioTrackServerProxy->framesReleased());
2660 }
2661 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002662 if (mLatchDValid) {
2663 mLatchQ = mLatchD;
2664 mLatchDValid = false;
2665 mLatchQValid = true;
2666 }
2667
Eric Laurent81784c32012-11-19 14:55:58 -08002668 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 if (mSignalPending) {
2670 // A signal was raised while we were unlocked
2671 mSignalPending = false;
2672 } else if (waitingAsyncCallback_l()) {
2673 if (exitPending()) {
2674 break;
2675 }
2676 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002677 mWakeLockUids.clear();
2678 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 ALOGV("wait async completion");
2680 mWaitWorkCV.wait(mLock);
2681 ALOGV("async completion/wake");
2682 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002683 standbyTime = systemTime() + standbyDelay;
2684 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002685
2686 continue;
2687 }
2688 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 isSuspended()) {
2690 // put audio hardware into standby after short delay
2691 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002692
2693 threadLoop_standby();
2694
2695 mStandby = true;
2696 }
2697
2698 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2699 // we're about to wait, flush the binder command buffer
2700 IPCThreadState::self()->flushCommands();
2701
2702 clearOutputTracks();
2703
2704 if (exitPending()) {
2705 break;
2706 }
2707
2708 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002709 mWakeLockUids.clear();
2710 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002711 // wait until we have something to do...
2712 ALOGV("%s going to sleep", myName.string());
2713 mWaitWorkCV.wait(mLock);
2714 ALOGV("%s waking up", myName.string());
2715 acquireWakeLock_l();
2716
2717 mMixerStatus = MIXER_IDLE;
2718 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2719 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002721 checkSilentMode_l();
2722
2723 standbyTime = systemTime() + standbyDelay;
2724 sleepTime = idleSleepTime;
2725 if (mType == MIXER) {
2726 sleepTimeShift = 0;
2727 }
2728
2729 continue;
2730 }
2731 }
Eric Laurent81784c32012-11-19 14:55:58 -08002732 // mMixerStatusIgnoringFastTracks is also updated internally
2733 mMixerStatus = prepareTracks_l(&tracksToRemove);
2734
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002735 // compare with previously applied list
2736 if (lastGeneration != mActiveTracksGeneration) {
2737 // update wakelock
2738 updateWakeLockUids_l(mWakeLockUids);
2739 lastGeneration = mActiveTracksGeneration;
2740 }
2741
Eric Laurent81784c32012-11-19 14:55:58 -08002742 // prevent any changes in effect chain list and in each effect chain
2743 // during mixing and effect process as the audio buffers could be deleted
2744 // or modified if an effect is created or deleted
2745 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002746 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002747
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 if (mBytesRemaining == 0) {
2749 mCurrentWriteLength = 0;
2750 if (mMixerStatus == MIXER_TRACKS_READY) {
2751 // threadLoop_mix() sets mCurrentWriteLength
2752 threadLoop_mix();
2753 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2754 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2755 // threadLoop_sleepTime sets sleepTime to 0 if data
2756 // must be written to HAL
2757 threadLoop_sleepTime();
2758 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002759 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 }
2761 }
Andy Hung98ef9782014-03-04 14:46:50 -08002762 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2763 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2764 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2765 // or mSinkBuffer (if there are no effects).
2766 //
2767 // This is done pre-effects computation; if effects change to
2768 // support higher precision, this needs to move.
2769 //
2770 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2771 // TODO use sleepTime == 0 as an additional condition.
2772 if (mMixerBufferValid) {
2773 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2774 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2775
2776 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2777 mNormalFrameCount * mChannelCount);
2778 }
2779
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 mBytesRemaining = mCurrentWriteLength;
2781 if (isSuspended()) {
2782 sleepTime = suspendSleepTimeUs();
2783 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002784 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 mBytesRemaining = 0;
2786 }
Eric Laurent81784c32012-11-19 14:55:58 -08002787
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002789 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002790 for (size_t i = 0; i < effectChains.size(); i ++) {
2791 effectChains[i]->process_l();
2792 }
Eric Laurent81784c32012-11-19 14:55:58 -08002793 }
2794 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002795 // Process effect chains for offloaded thread even if no audio
2796 // was read from audio track: process only updates effect state
2797 // and thus does have to be synchronized with audio writes but may have
2798 // to be called while waiting for async write callback
2799 if (mType == OFFLOAD) {
2800 for (size_t i = 0; i < effectChains.size(); i ++) {
2801 effectChains[i]->process_l();
2802 }
2803 }
Eric Laurent81784c32012-11-19 14:55:58 -08002804
Andy Hung98ef9782014-03-04 14:46:50 -08002805 // Only if the Effects buffer is enabled and there is data in the
2806 // Effects buffer (buffer valid), we need to
2807 // copy into the sink buffer.
2808 // TODO use sleepTime == 0 as an additional condition.
2809 if (mEffectBufferValid) {
2810 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2811 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2812 mNormalFrameCount * mChannelCount);
2813 }
2814
Eric Laurent81784c32012-11-19 14:55:58 -08002815 // enable changes in effect chain
2816 unlockEffectChains(effectChains);
2817
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 if (!waitingAsyncCallback()) {
2819 // sleepTime == 0 means we must write to audio hardware
2820 if (sleepTime == 0) {
2821 if (mBytesRemaining) {
2822 ssize_t ret = threadLoop_write();
2823 if (ret < 0) {
2824 mBytesRemaining = 0;
2825 } else {
2826 mBytesWritten += ret;
2827 mBytesRemaining -= ret;
2828 }
2829 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2830 (mMixerStatus == MIXER_DRAIN_ALL)) {
2831 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002832 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002833 if (mType == MIXER) {
2834 // write blocked detection
2835 nsecs_t now = systemTime();
2836 nsecs_t delta = now - mLastWriteTime;
2837 if (!mStandby && delta > maxPeriod) {
2838 mNumDelayedWrites++;
2839 if ((now - lastWarning) > kWarningThrottleNs) {
2840 ATRACE_NAME("underrun");
2841 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2842 ns2ms(delta), mNumDelayedWrites, this);
2843 lastWarning = now;
2844 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002845 }
2846 }
Eric Laurent81784c32012-11-19 14:55:58 -08002847
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002849 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002851 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852 }
Eric Laurent81784c32012-11-19 14:55:58 -08002853 }
2854
2855 // Finally let go of removed track(s), without the lock held
2856 // since we can't guarantee the destructors won't acquire that
2857 // same lock. This will also mutate and push a new fast mixer state.
2858 threadLoop_removeTracks(tracksToRemove);
2859 tracksToRemove.clear();
2860
2861 // FIXME I don't understand the need for this here;
2862 // it was in the original code but maybe the
2863 // assignment in saveOutputTracks() makes this unnecessary?
2864 clearOutputTracks();
2865
2866 // Effect chains will be actually deleted here if they were removed from
2867 // mEffectChains list during mixing or effects processing
2868 effectChains.clear();
2869
2870 // FIXME Note that the above .clear() is no longer necessary since effectChains
2871 // is now local to this block, but will keep it for now (at least until merge done).
2872 }
2873
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 threadLoop_exit();
2875
Eric Laurentcf817a22014-08-04 20:36:31 -07002876 if (!mStandby) {
2877 threadLoop_standby();
2878 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002879 }
2880
2881 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002882 mWakeLockUids.clear();
2883 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002884
2885 ALOGV("Thread %p type %d exiting", this, mType);
2886 return false;
2887}
2888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889// removeTracks_l() must be called with ThreadBase::mLock held
2890void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2891{
2892 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002893 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 for (size_t i=0 ; i<count ; i++) {
2895 const sp<Track>& track = tracksToRemove.itemAt(i);
2896 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002897 mWakeLockUids.remove(track->uid());
2898 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2900 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2901 if (chain != 0) {
2902 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2903 track->sessionId());
2904 chain->decActiveTrackCnt();
2905 }
2906 if (track->isTerminated()) {
2907 removeTrack_l(track);
2908 }
2909 }
2910 }
2911
2912}
Eric Laurent81784c32012-11-19 14:55:58 -08002913
Eric Laurentaccc1472013-09-20 09:36:34 -07002914status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2915{
2916 if (mNormalSink != 0) {
2917 return mNormalSink->getTimestamp(timestamp);
2918 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002919 if ((mType == OFFLOAD || mType == DIRECT)
2920 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002921 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002922 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002923 if (ret == 0) {
2924 timestamp.mPosition = (uint32_t)position64;
2925 return NO_ERROR;
2926 }
2927 }
2928 return INVALID_OPERATION;
2929}
Eric Laurent1c333e22014-05-20 10:48:17 -07002930
2931status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2932 audio_patch_handle_t *handle)
2933{
2934 status_t status = NO_ERROR;
2935 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2936 // store new device and send to effects
2937 audio_devices_t type = AUDIO_DEVICE_NONE;
2938 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2939 type |= patch->sinks[i].ext.device.type;
2940 }
2941 mOutDevice = type;
2942 for (size_t i = 0; i < mEffectChains.size(); i++) {
2943 mEffectChains[i]->setDevice_l(mOutDevice);
2944 }
2945
2946 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2947 status = hwDevice->create_audio_patch(hwDevice,
2948 patch->num_sources,
2949 patch->sources,
2950 patch->num_sinks,
2951 patch->sinks,
2952 handle);
2953 } else {
2954 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2955 }
2956 return status;
2957}
2958
2959status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2960{
2961 status_t status = NO_ERROR;
2962 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2963 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2964 status = hwDevice->release_audio_patch(hwDevice, handle);
2965 } else {
2966 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2967 }
2968 return status;
2969}
2970
Eric Laurent83b88082014-06-20 18:31:16 -07002971void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2972{
2973 Mutex::Autolock _l(mLock);
2974 mTracks.add(track);
2975}
2976
2977void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2978{
2979 Mutex::Autolock _l(mLock);
2980 destroyTrack_l(track);
2981}
2982
2983void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2984{
2985 ThreadBase::getAudioPortConfig(config);
2986 config->role = AUDIO_PORT_ROLE_SOURCE;
2987 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2988 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2989}
2990
Eric Laurent81784c32012-11-19 14:55:58 -08002991// ----------------------------------------------------------------------------
2992
2993AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2994 audio_io_handle_t id, audio_devices_t device, type_t type)
2995 : PlaybackThread(audioFlinger, output, id, device, type),
2996 // mAudioMixer below
2997 // mFastMixer below
2998 mFastMixerFutex(0)
2999 // mOutputSink below
3000 // mPipeSink below
3001 // mNormalSink below
3002{
3003 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003004 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003005 "mFrameCount=%d, mNormalFrameCount=%d",
3006 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3007 mNormalFrameCount);
3008 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3009
Andy Hungfbfc3952015-01-15 13:33:51 -08003010 if (type == DUPLICATING) {
3011 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3012 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3013 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3014 return;
3015 }
Eric Laurent81784c32012-11-19 14:55:58 -08003016 // create an NBAIO sink for the HAL output stream, and negotiate
3017 mOutputSink = new AudioStreamOutSink(output->stream);
3018 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003019 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003020 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3021 ALOG_ASSERT(index == 0);
3022
3023 // initialize fast mixer depending on configuration
3024 bool initFastMixer;
3025 switch (kUseFastMixer) {
3026 case FastMixer_Never:
3027 initFastMixer = false;
3028 break;
3029 case FastMixer_Always:
3030 initFastMixer = true;
3031 break;
3032 case FastMixer_Static:
3033 case FastMixer_Dynamic:
3034 initFastMixer = mFrameCount < mNormalFrameCount;
3035 break;
3036 }
3037 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003038 audio_format_t fastMixerFormat;
3039 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3040 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3041 } else {
3042 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3043 }
3044 if (mFormat != fastMixerFormat) {
3045 // change our Sink format to accept our intermediate precision
3046 mFormat = fastMixerFormat;
3047 free(mSinkBuffer);
3048 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3049 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3050 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3051 }
Eric Laurent81784c32012-11-19 14:55:58 -08003052
3053 // create a MonoPipe to connect our submix to FastMixer
3054 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003055 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003056 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003057 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003058 format.mFormat = fastMixerFormat;
3059 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3060
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3062 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3063 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3064 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3065 const NBAIO_Format offers[1] = {format};
3066 size_t numCounterOffers = 0;
3067 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3068 ALOG_ASSERT(index == 0);
3069 monoPipe->setAvgFrames((mScreenState & 1) ?
3070 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3071 mPipeSink = monoPipe;
3072
Glenn Kasten46909e72013-02-26 09:20:22 -08003073#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003074 if (mTeeSinkOutputEnabled) {
3075 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003076 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3077 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003078 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003079 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003080 ALOG_ASSERT(index == 0);
3081 mTeeSink = teeSink;
3082 PipeReader *teeSource = new PipeReader(*teeSink);
3083 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003084 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003085 ALOG_ASSERT(index == 0);
3086 mTeeSource = teeSource;
3087 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003088#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003089
3090 // create fast mixer and configure it initially with just one fast track for our submix
3091 mFastMixer = new FastMixer();
3092 FastMixerStateQueue *sq = mFastMixer->sq();
3093#ifdef STATE_QUEUE_DUMP
3094 sq->setObserverDump(&mStateQueueObserverDump);
3095 sq->setMutatorDump(&mStateQueueMutatorDump);
3096#endif
3097 FastMixerState *state = sq->begin();
3098 FastTrack *fastTrack = &state->mFastTracks[0];
3099 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3100 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3101 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003102 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3103 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003104 fastTrack->mGeneration++;
3105 state->mFastTracksGen++;
3106 state->mTrackMask = 1;
3107 // fast mixer will use the HAL output sink
3108 state->mOutputSink = mOutputSink.get();
3109 state->mOutputSinkGen++;
3110 state->mFrameCount = mFrameCount;
3111 state->mCommand = FastMixerState::COLD_IDLE;
3112 // already done in constructor initialization list
3113 //mFastMixerFutex = 0;
3114 state->mColdFutexAddr = &mFastMixerFutex;
3115 state->mColdGen++;
3116 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003117#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003118 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003119#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003120 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3121 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003122 sq->end();
3123 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3124
3125 // start the fast mixer
3126 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3127 pid_t tid = mFastMixer->getTid();
3128 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3129 if (err != 0) {
3130 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3131 kPriorityFastMixer, getpid_cached, tid, err);
3132 }
3133
3134#ifdef AUDIO_WATCHDOG
3135 // create and start the watchdog
3136 mAudioWatchdog = new AudioWatchdog();
3137 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3138 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3139 tid = mAudioWatchdog->getTid();
3140 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3141 if (err != 0) {
3142 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3143 kPriorityFastMixer, getpid_cached, tid, err);
3144 }
3145#endif
3146
Eric Laurent81784c32012-11-19 14:55:58 -08003147 }
3148
3149 switch (kUseFastMixer) {
3150 case FastMixer_Never:
3151 case FastMixer_Dynamic:
3152 mNormalSink = mOutputSink;
3153 break;
3154 case FastMixer_Always:
3155 mNormalSink = mPipeSink;
3156 break;
3157 case FastMixer_Static:
3158 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3159 break;
3160 }
3161}
3162
3163AudioFlinger::MixerThread::~MixerThread()
3164{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003165 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003166 FastMixerStateQueue *sq = mFastMixer->sq();
3167 FastMixerState *state = sq->begin();
3168 if (state->mCommand == FastMixerState::COLD_IDLE) {
3169 int32_t old = android_atomic_inc(&mFastMixerFutex);
3170 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003171 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003172 }
3173 }
3174 state->mCommand = FastMixerState::EXIT;
3175 sq->end();
3176 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3177 mFastMixer->join();
3178 // Though the fast mixer thread has exited, it's state queue is still valid.
3179 // We'll use that extract the final state which contains one remaining fast track
3180 // corresponding to our sub-mix.
3181 state = sq->begin();
3182 ALOG_ASSERT(state->mTrackMask == 1);
3183 FastTrack *fastTrack = &state->mFastTracks[0];
3184 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3185 delete fastTrack->mBufferProvider;
3186 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003187 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003188#ifdef AUDIO_WATCHDOG
3189 if (mAudioWatchdog != 0) {
3190 mAudioWatchdog->requestExit();
3191 mAudioWatchdog->requestExitAndWait();
3192 mAudioWatchdog.clear();
3193 }
3194#endif
3195 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003196 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003197 delete mAudioMixer;
3198}
3199
3200
3201uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3202{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003204 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3205 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3206 }
3207 return latency;
3208}
3209
3210
3211void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3212{
3213 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3214}
3215
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003217{
3218 // FIXME we should only do one push per cycle; confirm this is true
3219 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003220 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003221 FastMixerStateQueue *sq = mFastMixer->sq();
3222 FastMixerState *state = sq->begin();
3223 if (state->mCommand != FastMixerState::MIX_WRITE &&
3224 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3225 if (state->mCommand == FastMixerState::COLD_IDLE) {
3226 int32_t old = android_atomic_inc(&mFastMixerFutex);
3227 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003228 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003229 }
3230#ifdef AUDIO_WATCHDOG
3231 if (mAudioWatchdog != 0) {
3232 mAudioWatchdog->resume();
3233 }
3234#endif
3235 }
3236 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003237#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003238 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003239 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003240#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003241 sq->end();
3242 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3243 if (kUseFastMixer == FastMixer_Dynamic) {
3244 mNormalSink = mPipeSink;
3245 }
3246 } else {
3247 sq->end(false /*didModify*/);
3248 }
3249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003251}
3252
3253void AudioFlinger::MixerThread::threadLoop_standby()
3254{
3255 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003256 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003257 FastMixerStateQueue *sq = mFastMixer->sq();
3258 FastMixerState *state = sq->begin();
3259 if (!(state->mCommand & FastMixerState::IDLE)) {
3260 state->mCommand = FastMixerState::COLD_IDLE;
3261 state->mColdFutexAddr = &mFastMixerFutex;
3262 state->mColdGen++;
3263 mFastMixerFutex = 0;
3264 sq->end();
3265 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3266 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3267 if (kUseFastMixer == FastMixer_Dynamic) {
3268 mNormalSink = mOutputSink;
3269 }
3270#ifdef AUDIO_WATCHDOG
3271 if (mAudioWatchdog != 0) {
3272 mAudioWatchdog->pause();
3273 }
3274#endif
3275 } else {
3276 sq->end(false /*didModify*/);
3277 }
3278 }
3279 PlaybackThread::threadLoop_standby();
3280}
3281
Eric Laurentbfb1b832013-01-07 09:53:42 -08003282bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3283{
3284 return false;
3285}
3286
3287bool AudioFlinger::PlaybackThread::shouldStandby_l()
3288{
3289 return !mStandby;
3290}
3291
3292bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3293{
3294 Mutex::Autolock _l(mLock);
3295 return waitingAsyncCallback_l();
3296}
3297
Eric Laurent81784c32012-11-19 14:55:58 -08003298// shared by MIXER and DIRECT, overridden by DUPLICATING
3299void AudioFlinger::PlaybackThread::threadLoop_standby()
3300{
3301 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003302 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003304 // discard any pending drain or write ack by incrementing sequence
3305 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3306 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003307 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003308 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3309 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003311 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003312}
3313
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003314void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3315{
3316 ALOGV("signal playback thread");
3317 broadcast_l();
3318}
3319
Eric Laurent81784c32012-11-19 14:55:58 -08003320void AudioFlinger::MixerThread::threadLoop_mix()
3321{
3322 // obtain the presentation timestamp of the next output buffer
3323 int64_t pts;
3324 status_t status = INVALID_OPERATION;
3325
3326 if (mNormalSink != 0) {
3327 status = mNormalSink->getNextWriteTimestamp(&pts);
3328 } else {
3329 status = mOutputSink->getNextWriteTimestamp(&pts);
3330 }
3331
3332 if (status != NO_ERROR) {
3333 pts = AudioBufferProvider::kInvalidPTS;
3334 }
3335
3336 // mix buffers...
3337 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003338 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // increase sleep time progressively when application underrun condition clears.
3340 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3341 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3342 // such that we would underrun the audio HAL.
3343 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3344 sleepTimeShift--;
3345 }
3346 sleepTime = 0;
3347 standbyTime = systemTime() + standbyDelay;
3348 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003349
Eric Laurent81784c32012-11-19 14:55:58 -08003350}
3351
3352void AudioFlinger::MixerThread::threadLoop_sleepTime()
3353{
3354 // If no tracks are ready, sleep once for the duration of an output
3355 // buffer size, then write 0s to the output
3356 if (sleepTime == 0) {
3357 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3358 sleepTime = activeSleepTime >> sleepTimeShift;
3359 if (sleepTime < kMinThreadSleepTimeUs) {
3360 sleepTime = kMinThreadSleepTimeUs;
3361 }
3362 // reduce sleep time in case of consecutive application underruns to avoid
3363 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3364 // duration we would end up writing less data than needed by the audio HAL if
3365 // the condition persists.
3366 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3367 sleepTimeShift++;
3368 }
3369 } else {
3370 sleepTime = idleSleepTime;
3371 }
3372 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003373 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3374 // before effects processing or output.
3375 if (mMixerBufferValid) {
3376 memset(mMixerBuffer, 0, mMixerBufferSize);
3377 } else {
3378 memset(mSinkBuffer, 0, mSinkBufferSize);
3379 }
Eric Laurent81784c32012-11-19 14:55:58 -08003380 sleepTime = 0;
3381 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3382 "anticipated start");
3383 }
3384 // TODO add standby time extension fct of effect tail
3385}
3386
3387// prepareTracks_l() must be called with ThreadBase::mLock held
3388AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3389 Vector< sp<Track> > *tracksToRemove)
3390{
3391
3392 mixer_state mixerStatus = MIXER_IDLE;
3393 // find out which tracks need to be processed
3394 size_t count = mActiveTracks.size();
3395 size_t mixedTracks = 0;
3396 size_t tracksWithEffect = 0;
3397 // counts only _active_ fast tracks
3398 size_t fastTracks = 0;
3399 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3400
3401 float masterVolume = mMasterVolume;
3402 bool masterMute = mMasterMute;
3403
3404 if (masterMute) {
3405 masterVolume = 0;
3406 }
3407 // Delegate master volume control to effect in output mix effect chain if needed
3408 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3409 if (chain != 0) {
3410 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3411 chain->setVolume_l(&v, &v);
3412 masterVolume = (float)((v + (1 << 23)) >> 24);
3413 chain.clear();
3414 }
3415
3416 // prepare a new state to push
3417 FastMixerStateQueue *sq = NULL;
3418 FastMixerState *state = NULL;
3419 bool didModify = false;
3420 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003421 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003422 sq = mFastMixer->sq();
3423 state = sq->begin();
3424 }
3425
Andy Hung69aed5f2014-02-25 17:24:40 -08003426 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003427 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003428
Eric Laurent81784c32012-11-19 14:55:58 -08003429 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003430 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003431 if (t == 0) {
3432 continue;
3433 }
3434
3435 // this const just means the local variable doesn't change
3436 Track* const track = t.get();
3437
3438 // process fast tracks
3439 if (track->isFastTrack()) {
3440
3441 // It's theoretically possible (though unlikely) for a fast track to be created
3442 // and then removed within the same normal mix cycle. This is not a problem, as
3443 // the track never becomes active so it's fast mixer slot is never touched.
3444 // The converse, of removing an (active) track and then creating a new track
3445 // at the identical fast mixer slot within the same normal mix cycle,
3446 // is impossible because the slot isn't marked available until the end of each cycle.
3447 int j = track->mFastIndex;
3448 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3449 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3450 FastTrack *fastTrack = &state->mFastTracks[j];
3451
3452 // Determine whether the track is currently in underrun condition,
3453 // and whether it had a recent underrun.
3454 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3455 FastTrackUnderruns underruns = ftDump->mUnderruns;
3456 uint32_t recentFull = (underruns.mBitFields.mFull -
3457 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3458 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3459 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3460 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3461 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3462 uint32_t recentUnderruns = recentPartial + recentEmpty;
3463 track->mObservedUnderruns = underruns;
3464 // don't count underruns that occur while stopping or pausing
3465 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003466 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3467 recentUnderruns > 0) {
3468 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3469 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003470 }
3471
3472 // This is similar to the state machine for normal tracks,
3473 // with a few modifications for fast tracks.
3474 bool isActive = true;
3475 switch (track->mState) {
3476 case TrackBase::STOPPING_1:
3477 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003479 track->mState = TrackBase::STOPPING_2;
3480 }
3481 break;
3482 case TrackBase::PAUSING:
3483 // ramp down is not yet implemented
3484 track->setPaused();
3485 break;
3486 case TrackBase::RESUMING:
3487 // ramp up is not yet implemented
3488 track->mState = TrackBase::ACTIVE;
3489 break;
3490 case TrackBase::ACTIVE:
3491 if (recentFull > 0 || recentPartial > 0) {
3492 // track has provided at least some frames recently: reset retry count
3493 track->mRetryCount = kMaxTrackRetries;
3494 }
3495 if (recentUnderruns == 0) {
3496 // no recent underruns: stay active
3497 break;
3498 }
3499 // there has recently been an underrun of some kind
3500 if (track->sharedBuffer() == 0) {
3501 // were any of the recent underruns "empty" (no frames available)?
3502 if (recentEmpty == 0) {
3503 // no, then ignore the partial underruns as they are allowed indefinitely
3504 break;
3505 }
3506 // there has recently been an "empty" underrun: decrement the retry counter
3507 if (--(track->mRetryCount) > 0) {
3508 break;
3509 }
3510 // indicate to client process that the track was disabled because of underrun;
3511 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003512 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003513 // remove from active list, but state remains ACTIVE [confusing but true]
3514 isActive = false;
3515 break;
3516 }
3517 // fall through
3518 case TrackBase::STOPPING_2:
3519 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003520 case TrackBase::STOPPED:
3521 case TrackBase::FLUSHED: // flush() while active
3522 // Check for presentation complete if track is inactive
3523 // We have consumed all the buffers of this track.
3524 // This would be incomplete if we auto-paused on underrun
3525 {
3526 size_t audioHALFrames =
3527 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3528 size_t framesWritten = mBytesWritten / mFrameSize;
3529 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3530 // track stays in active list until presentation is complete
3531 break;
3532 }
3533 }
3534 if (track->isStopping_2()) {
3535 track->mState = TrackBase::STOPPED;
3536 }
3537 if (track->isStopped()) {
3538 // Can't reset directly, as fast mixer is still polling this track
3539 // track->reset();
3540 // So instead mark this track as needing to be reset after push with ack
3541 resetMask |= 1 << i;
3542 }
3543 isActive = false;
3544 break;
3545 case TrackBase::IDLE:
3546 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003547 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003548 }
3549
3550 if (isActive) {
3551 // was it previously inactive?
3552 if (!(state->mTrackMask & (1 << j))) {
3553 ExtendedAudioBufferProvider *eabp = track;
3554 VolumeProvider *vp = track;
3555 fastTrack->mBufferProvider = eabp;
3556 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003557 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003558 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003559 fastTrack->mGeneration++;
3560 state->mTrackMask |= 1 << j;
3561 didModify = true;
3562 // no acknowledgement required for newly active tracks
3563 }
3564 // cache the combined master volume and stream type volume for fast mixer; this
3565 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003566 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003567 ++fastTracks;
3568 } else {
3569 // was it previously active?
3570 if (state->mTrackMask & (1 << j)) {
3571 fastTrack->mBufferProvider = NULL;
3572 fastTrack->mGeneration++;
3573 state->mTrackMask &= ~(1 << j);
3574 didModify = true;
3575 // If any fast tracks were removed, we must wait for acknowledgement
3576 // because we're about to decrement the last sp<> on those tracks.
3577 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3578 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003579 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003580 }
3581 tracksToRemove->add(track);
3582 // Avoids a misleading display in dumpsys
3583 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3584 }
3585 continue;
3586 }
3587
3588 { // local variable scope to avoid goto warning
3589
3590 audio_track_cblk_t* cblk = track->cblk();
3591
3592 // The first time a track is added we wait
3593 // for all its buffers to be filled before processing it
3594 int name = track->name();
3595 // make sure that we have enough frames to mix one full buffer.
3596 // enforce this condition only once to enable draining the buffer in case the client
3597 // app does not call stop() and relies on underrun to stop:
3598 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3599 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003600 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003601 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003602 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003603
3604 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003605 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003606 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3607 // add frames already consumed but not yet released by the resampler
3608 // because mAudioTrackServerProxy->framesReady() will include these frames
3609 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3610
Eric Laurent81784c32012-11-19 14:55:58 -08003611 uint32_t minFrames = 1;
3612 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3613 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003614 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003615 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003616
3617 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003618 if (ATRACE_ENABLED()) {
3619 // I wish we had formatted trace names
3620 char traceName[16];
3621 strcpy(traceName, "nRdy");
3622 int name = track->name();
3623 if (AudioMixer::TRACK0 <= name &&
3624 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3625 name -= AudioMixer::TRACK0;
3626 traceName[4] = (name / 10) + '0';
3627 traceName[5] = (name % 10) + '0';
3628 } else {
3629 traceName[4] = '?';
3630 traceName[5] = '?';
3631 }
3632 traceName[6] = '\0';
3633 ATRACE_INT(traceName, framesReady);
3634 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003635 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003636 !track->isPaused() && !track->isTerminated())
3637 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003638 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003639
3640 mixedTracks++;
3641
Andy Hung69aed5f2014-02-25 17:24:40 -08003642 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3643 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003644 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003645 if (track->mainBuffer() != mSinkBuffer &&
3646 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003647 if (mEffectBufferEnabled) {
3648 mEffectBufferValid = true; // Later can set directly.
3649 }
Eric Laurent81784c32012-11-19 14:55:58 -08003650 chain = getEffectChain_l(track->sessionId());
3651 // Delegate volume control to effect in track effect chain if needed
3652 if (chain != 0) {
3653 tracksWithEffect++;
3654 } else {
3655 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3656 "session %d",
3657 name, track->sessionId());
3658 }
3659 }
3660
3661
3662 int param = AudioMixer::VOLUME;
3663 if (track->mFillingUpStatus == Track::FS_FILLED) {
3664 // no ramp for the first volume setting
3665 track->mFillingUpStatus = Track::FS_ACTIVE;
3666 if (track->mState == TrackBase::RESUMING) {
3667 track->mState = TrackBase::ACTIVE;
3668 param = AudioMixer::RAMP_VOLUME;
3669 }
3670 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003671 // FIXME should not make a decision based on mServer
3672 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003673 // If the track is stopped before the first frame was mixed,
3674 // do not apply ramp
3675 param = AudioMixer::RAMP_VOLUME;
3676 }
3677
3678 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003679 uint32_t vl, vr; // in U8.24 integer format
3680 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003681 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003682 vl = vr = 0;
3683 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003684 if (track->isPausing()) {
3685 track->setPaused();
3686 }
3687 } else {
3688
3689 // read original volumes with volume control
3690 float typeVolume = mStreamTypes[track->streamType()].volume;
3691 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003692 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003693 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003694 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3695 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003696 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003697 if (vlf > GAIN_FLOAT_UNITY) {
3698 ALOGV("Track left volume out of range: %.3g", vlf);
3699 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003700 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003701 if (vrf > GAIN_FLOAT_UNITY) {
3702 ALOGV("Track right volume out of range: %.3g", vrf);
3703 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003704 }
3705 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003706 vlf *= v;
3707 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003708 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003709 // then derive vl and vr as U8.24 versions for the effect chain
3710 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3711 vl = (uint32_t) (scaleto8_24 * vlf);
3712 vr = (uint32_t) (scaleto8_24 * vrf);
3713 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003714 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003715 // send level comes from shared memory and so may be corrupt
3716 if (sendLevel > MAX_GAIN_INT) {
3717 ALOGV("Track send level out of range: %04X", sendLevel);
3718 sendLevel = MAX_GAIN_INT;
3719 }
Andy Hung6be49402014-05-30 10:42:03 -07003720 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3721 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003722 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003723
Eric Laurent81784c32012-11-19 14:55:58 -08003724 // Delegate volume control to effect in track effect chain if needed
3725 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3726 // Do not ramp volume if volume is controlled by effect
3727 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003728 // Update remaining floating point volume levels
3729 vlf = (float)vl / (1 << 24);
3730 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003731 track->mHasVolumeController = true;
3732 } else {
3733 // force no volume ramp when volume controller was just disabled or removed
3734 // from effect chain to avoid volume spike
3735 if (track->mHasVolumeController) {
3736 param = AudioMixer::VOLUME;
3737 }
3738 track->mHasVolumeController = false;
3739 }
3740
Eric Laurent81784c32012-11-19 14:55:58 -08003741 // XXX: these things DON'T need to be done each time
3742 mAudioMixer->setBufferProvider(name, track);
3743 mAudioMixer->enable(name);
3744
Andy Hung6be49402014-05-30 10:42:03 -07003745 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3746 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3747 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003748 mAudioMixer->setParameter(
3749 name,
3750 AudioMixer::TRACK,
3751 AudioMixer::FORMAT, (void *)track->format());
3752 mAudioMixer->setParameter(
3753 name,
3754 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003755 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003756 mAudioMixer->setParameter(
3757 name,
3758 AudioMixer::TRACK,
3759 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003760 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003761 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003762 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003763 if (reqSampleRate == 0) {
3764 reqSampleRate = mSampleRate;
3765 } else if (reqSampleRate > maxSampleRate) {
3766 reqSampleRate = maxSampleRate;
3767 }
Eric Laurent81784c32012-11-19 14:55:58 -08003768 mAudioMixer->setParameter(
3769 name,
3770 AudioMixer::RESAMPLE,
3771 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003772 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003773
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003774 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003775 mAudioMixer->setParameter(
3776 name,
3777 AudioMixer::TIMESTRETCH,
3778 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003779 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003780
Andy Hung69aed5f2014-02-25 17:24:40 -08003781 /*
3782 * Select the appropriate output buffer for the track.
3783 *
Andy Hung98ef9782014-03-04 14:46:50 -08003784 * Tracks with effects go into their own effects chain buffer
3785 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003786 *
3787 * Other tracks can use mMixerBuffer for higher precision
3788 * channel accumulation. If this buffer is enabled
3789 * (mMixerBufferEnabled true), then selected tracks will accumulate
3790 * into it.
3791 *
3792 */
3793 if (mMixerBufferEnabled
3794 && (track->mainBuffer() == mSinkBuffer
3795 || track->mainBuffer() == mMixerBuffer)) {
3796 mAudioMixer->setParameter(
3797 name,
3798 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003799 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003800 mAudioMixer->setParameter(
3801 name,
3802 AudioMixer::TRACK,
3803 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3804 // TODO: override track->mainBuffer()?
3805 mMixerBufferValid = true;
3806 } else {
3807 mAudioMixer->setParameter(
3808 name,
3809 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003810 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003811 mAudioMixer->setParameter(
3812 name,
3813 AudioMixer::TRACK,
3814 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3815 }
Eric Laurent81784c32012-11-19 14:55:58 -08003816 mAudioMixer->setParameter(
3817 name,
3818 AudioMixer::TRACK,
3819 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3820
3821 // reset retry count
3822 track->mRetryCount = kMaxTrackRetries;
3823
3824 // If one track is ready, set the mixer ready if:
3825 // - the mixer was not ready during previous round OR
3826 // - no other track is not ready
3827 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3828 mixerStatus != MIXER_TRACKS_ENABLED) {
3829 mixerStatus = MIXER_TRACKS_READY;
3830 }
3831 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003832 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003833 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003834 }
Eric Laurent81784c32012-11-19 14:55:58 -08003835 // clear effect chain input buffer if an active track underruns to avoid sending
3836 // previous audio buffer again to effects
3837 chain = getEffectChain_l(track->sessionId());
3838 if (chain != 0) {
3839 chain->clearInputBuffer();
3840 }
3841
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003842 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003843 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3844 track->isStopped() || track->isPaused()) {
3845 // We have consumed all the buffers of this track.
3846 // Remove it from the list of active tracks.
3847 // TODO: use actual buffer filling status instead of latency when available from
3848 // audio HAL
3849 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3850 size_t framesWritten = mBytesWritten / mFrameSize;
3851 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3852 if (track->isStopped()) {
3853 track->reset();
3854 }
3855 tracksToRemove->add(track);
3856 }
3857 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003858 // No buffers for this track. Give it a few chances to
3859 // fill a buffer, then remove it from active list.
3860 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003861 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 tracksToRemove->add(track);
3863 // indicate to client process that the track was disabled because of underrun;
3864 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003865 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003866 // If one track is not ready, mark the mixer also not ready if:
3867 // - the mixer was ready during previous round OR
3868 // - no other track is ready
3869 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3870 mixerStatus != MIXER_TRACKS_READY) {
3871 mixerStatus = MIXER_TRACKS_ENABLED;
3872 }
3873 }
3874 mAudioMixer->disable(name);
3875 }
3876
3877 } // local variable scope to avoid goto warning
3878track_is_ready: ;
3879
3880 }
3881
3882 // Push the new FastMixer state if necessary
3883 bool pauseAudioWatchdog = false;
3884 if (didModify) {
3885 state->mFastTracksGen++;
3886 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3887 if (kUseFastMixer == FastMixer_Dynamic &&
3888 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3889 state->mCommand = FastMixerState::COLD_IDLE;
3890 state->mColdFutexAddr = &mFastMixerFutex;
3891 state->mColdGen++;
3892 mFastMixerFutex = 0;
3893 if (kUseFastMixer == FastMixer_Dynamic) {
3894 mNormalSink = mOutputSink;
3895 }
3896 // If we go into cold idle, need to wait for acknowledgement
3897 // so that fast mixer stops doing I/O.
3898 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3899 pauseAudioWatchdog = true;
3900 }
Eric Laurent81784c32012-11-19 14:55:58 -08003901 }
3902 if (sq != NULL) {
3903 sq->end(didModify);
3904 sq->push(block);
3905 }
3906#ifdef AUDIO_WATCHDOG
3907 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3908 mAudioWatchdog->pause();
3909 }
3910#endif
3911
3912 // Now perform the deferred reset on fast tracks that have stopped
3913 while (resetMask != 0) {
3914 size_t i = __builtin_ctz(resetMask);
3915 ALOG_ASSERT(i < count);
3916 resetMask &= ~(1 << i);
3917 sp<Track> t = mActiveTracks[i].promote();
3918 if (t == 0) {
3919 continue;
3920 }
3921 Track* track = t.get();
3922 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3923 track->reset();
3924 }
3925
3926 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003927 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003928
Eric Laurent97d547d2014-09-02 14:45:53 -07003929 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3930 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003931 }
3932
3933 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003934 // as long as there are effects we should clear the effects buffer, to avoid
3935 // passing a non-clean buffer to the effect chain
3936 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003937 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003938 // sink or mix buffer must be cleared if all tracks are connected to an
3939 // effect chain as in this case the mixer will not write to the sink or mix buffer
3940 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3942 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003943 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003944 if (mMixerBufferValid) {
3945 memset(mMixerBuffer, 0, mMixerBufferSize);
3946 // TODO: In testing, mSinkBuffer below need not be cleared because
3947 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3948 // after mixing.
3949 //
3950 // To enforce this guarantee:
3951 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3952 // (mixedTracks == 0 && fastTracks > 0))
3953 // must imply MIXER_TRACKS_READY.
3954 // Later, we may clear buffers regardless, and skip much of this logic.
3955 }
Andy Hung98ef9782014-03-04 14:46:50 -08003956 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003957 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003958 }
3959
3960 // if any fast tracks, then status is ready
3961 mMixerStatusIgnoringFastTracks = mixerStatus;
3962 if (fastTracks > 0) {
3963 mixerStatus = MIXER_TRACKS_READY;
3964 }
3965 return mixerStatus;
3966}
3967
3968// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003969int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3970 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003971{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003972 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003973}
3974
3975// deleteTrackName_l() must be called with ThreadBase::mLock held
3976void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3977{
3978 ALOGV("remove track (%d) and delete from mixer", name);
3979 mAudioMixer->deleteTrackName(name);
3980}
3981
Eric Laurent10351942014-05-08 18:49:52 -07003982// checkForNewParameter_l() must be called with ThreadBase::mLock held
3983bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3984 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003985{
Eric Laurent81784c32012-11-19 14:55:58 -08003986 bool reconfig = false;
3987
Eric Laurent10351942014-05-08 18:49:52 -07003988 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003989
Eric Laurent10351942014-05-08 18:49:52 -07003990 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3991 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003992 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003993 FastMixerStateQueue *sq = mFastMixer->sq();
3994 FastMixerState *state = sq->begin();
3995 if (!(state->mCommand & FastMixerState::IDLE)) {
3996 previousCommand = state->mCommand;
3997 state->mCommand = FastMixerState::HOT_IDLE;
3998 sq->end();
3999 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4000 } else {
4001 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004002 }
Eric Laurent10351942014-05-08 18:49:52 -07004003 }
Eric Laurent81784c32012-11-19 14:55:58 -08004004
Eric Laurent10351942014-05-08 18:49:52 -07004005 AudioParameter param = AudioParameter(keyValuePair);
4006 int value;
4007 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4008 reconfig = true;
4009 }
4010 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004011 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004012 status = BAD_VALUE;
4013 } else {
4014 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004015 reconfig = true;
4016 }
Eric Laurent10351942014-05-08 18:49:52 -07004017 }
4018 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004019 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004020 status = BAD_VALUE;
4021 } else {
4022 // no need to save value, since it's constant
4023 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004024 }
Eric Laurent10351942014-05-08 18:49:52 -07004025 }
4026 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4027 // do not accept frame count changes if tracks are open as the track buffer
4028 // size depends on frame count and correct behavior would not be guaranteed
4029 // if frame count is changed after track creation
4030 if (!mTracks.isEmpty()) {
4031 status = INVALID_OPERATION;
4032 } else {
4033 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
Eric Laurent10351942014-05-08 18:49:52 -07004035 }
4036 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004037#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004038 // when changing the audio output device, call addBatteryData to notify
4039 // the change
4040 if (mOutDevice != value) {
4041 uint32_t params = 0;
4042 // check whether speaker is on
4043 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4044 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004045 }
Eric Laurent10351942014-05-08 18:49:52 -07004046
4047 audio_devices_t deviceWithoutSpeaker
4048 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4049 // check if any other device (except speaker) is on
4050 if (value & deviceWithoutSpeaker ) {
4051 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4052 }
4053
4054 if (params != 0) {
4055 addBatteryData(params);
4056 }
4057 }
Eric Laurent81784c32012-11-19 14:55:58 -08004058#endif
4059
Eric Laurent10351942014-05-08 18:49:52 -07004060 // forward device change to effects that have requested to be
4061 // aware of attached audio device.
4062 if (value != AUDIO_DEVICE_NONE) {
4063 mOutDevice = value;
4064 for (size_t i = 0; i < mEffectChains.size(); i++) {
4065 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004066 }
4067 }
Eric Laurent10351942014-05-08 18:49:52 -07004068 }
Eric Laurent81784c32012-11-19 14:55:58 -08004069
Eric Laurent10351942014-05-08 18:49:52 -07004070 if (status == NO_ERROR) {
4071 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4072 keyValuePair.string());
4073 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004074 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004075 mStandby = true;
4076 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004077 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004078 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
Eric Laurent10351942014-05-08 18:49:52 -07004080 if (status == NO_ERROR && reconfig) {
4081 readOutputParameters_l();
4082 delete mAudioMixer;
4083 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4084 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004085 int name = getTrackName_l(mTracks[i]->mChannelMask,
4086 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004087 if (name < 0) {
4088 break;
4089 }
4090 mTracks[i]->mName = name;
4091 }
4092 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4093 }
Eric Laurent81784c32012-11-19 14:55:58 -08004094 }
4095
4096 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004097 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004098 FastMixerStateQueue *sq = mFastMixer->sq();
4099 FastMixerState *state = sq->begin();
4100 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4101 state->mCommand = previousCommand;
4102 sq->end();
4103 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4104 }
4105
4106 return reconfig;
4107}
4108
4109
4110void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4111{
4112 const size_t SIZE = 256;
4113 char buffer[SIZE];
4114 String8 result;
4115
4116 PlaybackThread::dumpInternals(fd, args);
4117
Elliott Hughes87cebad2014-05-22 10:14:43 -07004118 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004119
4120 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004121 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004122 copy.dump(fd);
4123
4124#ifdef STATE_QUEUE_DUMP
4125 // Similar for state queue
4126 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4127 observerCopy.dump(fd);
4128 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4129 mutatorCopy.dump(fd);
4130#endif
4131
Glenn Kasten46909e72013-02-26 09:20:22 -08004132#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004133 // Write the tee output to a .wav file
4134 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004135#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004136
4137#ifdef AUDIO_WATCHDOG
4138 if (mAudioWatchdog != 0) {
4139 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4140 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4141 wdCopy.dump(fd);
4142 }
4143#endif
4144}
4145
4146uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4147{
4148 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4149}
4150
4151uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4152{
4153 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4154}
4155
4156void AudioFlinger::MixerThread::cacheParameters_l()
4157{
4158 PlaybackThread::cacheParameters_l();
4159
4160 // FIXME: Relaxed timing because of a certain device that can't meet latency
4161 // Should be reduced to 2x after the vendor fixes the driver issue
4162 // increase threshold again due to low power audio mode. The way this warning
4163 // threshold is calculated and its usefulness should be reconsidered anyway.
4164 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4165}
4166
4167// ----------------------------------------------------------------------------
4168
4169AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4170 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4171 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4172 // mLeftVolFloat, mRightVolFloat
4173{
4174}
4175
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4177 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4178 ThreadBase::type_t type)
4179 : PlaybackThread(audioFlinger, output, id, device, type)
4180 // mLeftVolFloat, mRightVolFloat
4181{
4182}
4183
Eric Laurent81784c32012-11-19 14:55:58 -08004184AudioFlinger::DirectOutputThread::~DirectOutputThread()
4185{
4186}
4187
Eric Laurentbfb1b832013-01-07 09:53:42 -08004188void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4189{
4190 audio_track_cblk_t* cblk = track->cblk();
4191 float left, right;
4192
4193 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4194 left = right = 0;
4195 } else {
4196 float typeVolume = mStreamTypes[track->streamType()].volume;
4197 float v = mMasterVolume * typeVolume;
4198 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004199 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4200 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4201 if (left > GAIN_FLOAT_UNITY) {
4202 left = GAIN_FLOAT_UNITY;
4203 }
4204 left *= v;
4205 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4206 if (right > GAIN_FLOAT_UNITY) {
4207 right = GAIN_FLOAT_UNITY;
4208 }
4209 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004210 }
4211
4212 if (lastTrack) {
4213 if (left != mLeftVolFloat || right != mRightVolFloat) {
4214 mLeftVolFloat = left;
4215 mRightVolFloat = right;
4216
4217 // Convert volumes from float to 8.24
4218 uint32_t vl = (uint32_t)(left * (1 << 24));
4219 uint32_t vr = (uint32_t)(right * (1 << 24));
4220
4221 // Delegate volume control to effect in track effect chain if needed
4222 // only one effect chain can be present on DirectOutputThread, so if
4223 // there is one, the track is connected to it
4224 if (!mEffectChains.isEmpty()) {
4225 mEffectChains[0]->setVolume_l(&vl, &vr);
4226 left = (float)vl / (1 << 24);
4227 right = (float)vr / (1 << 24);
4228 }
4229 if (mOutput->stream->set_volume) {
4230 mOutput->stream->set_volume(mOutput->stream, left, right);
4231 }
4232 }
4233 }
4234}
4235
4236
Eric Laurent81784c32012-11-19 14:55:58 -08004237AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4238 Vector< sp<Track> > *tracksToRemove
4239)
4240{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004241 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004242 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004243 bool doHwPause = false;
4244 bool doHwResume = false;
4245 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004246
4247 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004248 for (size_t i = 0; i < count; i++) {
4249 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004250 // The track died recently
4251 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004252 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004253 }
4254
4255 Track* const track = t.get();
4256 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004257 // Only consider last track started for volume and mixer state control.
4258 // In theory an older track could underrun and restart after the new one starts
4259 // but as we only care about the transition phase between two tracks on a
4260 // direct output, it is not a problem to ignore the underrun case.
4261 sp<Track> l = mLatestActiveTrack.promote();
4262 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004263
Eric Laurentd1f69b02014-12-15 14:33:13 -08004264 if (mHwSupportsPause && track->isPausing()) {
4265 track->setPaused();
4266 if (last && !mHwPaused) {
4267 doHwPause = true;
4268 mHwPaused = true;
4269 }
4270 tracksToRemove->add(track);
4271 } else if (track->isFlushPending()) {
4272 track->flushAck();
4273 if (last) {
4274 flushPending = true;
4275 }
4276 } else if (mHwSupportsPause && track->isResumePending()){
4277 track->resumeAck();
4278 if (last) {
4279 if (mHwPaused) {
4280 doHwResume = true;
4281 mHwPaused = false;
4282 }
4283 }
4284 }
4285
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004287 // for all its buffers to be filled before processing it.
4288 // Allow draining the buffer in case the client
4289 // app does not call stop() and relies on underrun to stop:
4290 // hence the test on (track->mRetryCount > 1).
4291 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004292 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004293 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4294 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004295 minFrames = mNormalFrameCount;
4296 } else {
4297 minFrames = 1;
4298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299
Eric Laurentab5cdba2014-06-09 17:22:27 -07004300 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4301 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004302 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004303 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004304
4305 if (track->mFillingUpStatus == Track::FS_FILLED) {
4306 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004307 // make sure processVolume_l() will apply new volume even if 0
4308 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004309 if (!mHwSupportsPause) {
4310 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004311 }
4312 }
4313
4314 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315 processVolume_l(track, last);
4316 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004317 // reset retry count
4318 track->mRetryCount = kMaxTrackRetriesDirect;
4319 mActiveTrack = t;
4320 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004321 if (usesHwAvSync() && mHwPaused) {
4322 doHwResume = true;
4323 mHwPaused = false;
4324 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004325 }
Eric Laurent81784c32012-11-19 14:55:58 -08004326 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004327 // clear effect chain input buffer if the last active track started underruns
4328 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004329 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004330 mEffectChains[0]->clearInputBuffer();
4331 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004332 if (track->isStopping_1()) {
4333 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004334 if (last && mHwPaused) {
4335 doHwResume = true;
4336 mHwPaused = false;
4337 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004338 }
4339 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4340 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004341 // We have consumed all the buffers of this track.
4342 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004343 size_t audioHALFrames;
4344 if (audio_is_linear_pcm(mFormat)) {
4345 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4346 } else {
4347 audioHALFrames = 0;
4348 }
4349
Eric Laurent81784c32012-11-19 14:55:58 -08004350 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004351 if (mStandby || !last ||
4352 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004353 if (track->isStopping_2()) {
4354 track->mState = TrackBase::STOPPED;
4355 }
Eric Laurent81784c32012-11-19 14:55:58 -08004356 if (track->isStopped()) {
4357 track->reset();
4358 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004359 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004360 }
4361 } else {
4362 // No buffers for this track. Give it a few chances to
4363 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004364 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004365 if (--(track->mRetryCount) <= 0) {
4366 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004367 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004368 // indicate to client process that the track was disabled because of underrun;
4369 // it will then automatically call start() when data is available
4370 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004371 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004372 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004373 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4374 doHwPause = true;
4375 mHwPaused = true;
4376 }
Eric Laurent81784c32012-11-19 14:55:58 -08004377 }
4378 }
4379 }
4380 }
4381
Eric Laurentd1f69b02014-12-15 14:33:13 -08004382 // if an active track did not command a flush, check for pending flush on stopped tracks
4383 if (!flushPending) {
4384 for (size_t i = 0; i < mTracks.size(); i++) {
4385 if (mTracks[i]->isFlushPending()) {
4386 mTracks[i]->flushAck();
4387 flushPending = true;
4388 }
4389 }
4390 }
4391
4392 // make sure the pause/flush/resume sequence is executed in the right order.
4393 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4394 // before flush and then resume HW. This can happen in case of pause/flush/resume
4395 // if resume is received before pause is executed.
4396 if (mHwSupportsPause && !mStandby &&
4397 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4398 mOutput->stream->pause(mOutput->stream);
4399 }
4400 if (flushPending) {
4401 flushHw_l();
4402 }
4403 if (mHwSupportsPause && !mStandby && doHwResume) {
4404 mOutput->stream->resume(mOutput->stream);
4405 }
Eric Laurent81784c32012-11-19 14:55:58 -08004406 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004407 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004408
4409 return mixerStatus;
4410}
4411
4412void AudioFlinger::DirectOutputThread::threadLoop_mix()
4413{
Eric Laurent81784c32012-11-19 14:55:58 -08004414 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004415 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004416 // output audio to hardware
4417 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004418 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004419 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004420 status_t status = mActiveTrack->getNextBuffer(&buffer);
4421 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004422 memset(curBuf, 0, frameCount * mFrameSize);
4423 break;
4424 }
4425 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4426 frameCount -= buffer.frameCount;
4427 curBuf += buffer.frameCount * mFrameSize;
4428 mActiveTrack->releaseBuffer(&buffer);
4429 }
Andy Hung2098f272014-02-27 14:00:06 -08004430 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004431 sleepTime = 0;
4432 standbyTime = systemTime() + standbyDelay;
4433 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004434}
4435
4436void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4437{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004438 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004439 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004440 sleepTime = idleSleepTime;
4441 return;
4442 }
Eric Laurent81784c32012-11-19 14:55:58 -08004443 if (sleepTime == 0) {
4444 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4445 sleepTime = activeSleepTime;
4446 } else {
4447 sleepTime = idleSleepTime;
4448 }
4449 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004450 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004451 sleepTime = 0;
4452 }
4453}
4454
Eric Laurentd1f69b02014-12-15 14:33:13 -08004455void AudioFlinger::DirectOutputThread::threadLoop_exit()
4456{
4457 {
4458 Mutex::Autolock _l(mLock);
4459 bool flushPending = false;
4460 for (size_t i = 0; i < mTracks.size(); i++) {
4461 if (mTracks[i]->isFlushPending()) {
4462 mTracks[i]->flushAck();
4463 flushPending = true;
4464 }
4465 }
4466 if (flushPending) {
4467 flushHw_l();
4468 }
4469 }
4470 PlaybackThread::threadLoop_exit();
4471}
4472
4473// must be called with thread mutex locked
4474bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4475{
4476 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004477 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004478
4479 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4480 // after a timeout and we will enter standby then.
4481 if (mTracks.size() > 0) {
4482 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004483 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4484 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004485 }
4486
Eric Laurentb369caf2015-03-30 20:51:47 -07004487 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004488}
4489
Eric Laurent81784c32012-11-19 14:55:58 -08004490// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004491int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004492 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004493{
4494 return 0;
4495}
4496
4497// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004498void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004499{
4500}
4501
Eric Laurent10351942014-05-08 18:49:52 -07004502// checkForNewParameter_l() must be called with ThreadBase::mLock held
4503bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4504 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004505{
4506 bool reconfig = false;
4507
Eric Laurent10351942014-05-08 18:49:52 -07004508 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004509
Eric Laurent10351942014-05-08 18:49:52 -07004510 AudioParameter param = AudioParameter(keyValuePair);
4511 int value;
4512 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4513 // forward device change to effects that have requested to be
4514 // aware of attached audio device.
4515 if (value != AUDIO_DEVICE_NONE) {
4516 mOutDevice = value;
4517 for (size_t i = 0; i < mEffectChains.size(); i++) {
4518 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004519 }
4520 }
Eric Laurent81784c32012-11-19 14:55:58 -08004521 }
Eric Laurent10351942014-05-08 18:49:52 -07004522 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4523 // do not accept frame count changes if tracks are open as the track buffer
4524 // size depends on frame count and correct behavior would not be garantied
4525 // if frame count is changed after track creation
4526 if (!mTracks.isEmpty()) {
4527 status = INVALID_OPERATION;
4528 } else {
4529 reconfig = true;
4530 }
4531 }
4532 if (status == NO_ERROR) {
4533 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4534 keyValuePair.string());
4535 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004536 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004537 mStandby = true;
4538 mBytesWritten = 0;
4539 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4540 keyValuePair.string());
4541 }
4542 if (status == NO_ERROR && reconfig) {
4543 readOutputParameters_l();
4544 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4545 }
4546 }
4547
Eric Laurent81784c32012-11-19 14:55:58 -08004548 return reconfig;
4549}
4550
4551uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4552{
4553 uint32_t time;
4554 if (audio_is_linear_pcm(mFormat)) {
4555 time = PlaybackThread::activeSleepTimeUs();
4556 } else {
4557 time = 10000;
4558 }
4559 return time;
4560}
4561
4562uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4563{
4564 uint32_t time;
4565 if (audio_is_linear_pcm(mFormat)) {
4566 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4567 } else {
4568 time = 10000;
4569 }
4570 return time;
4571}
4572
4573uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4574{
4575 uint32_t time;
4576 if (audio_is_linear_pcm(mFormat)) {
4577 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4578 } else {
4579 time = 10000;
4580 }
4581 return time;
4582}
4583
4584void AudioFlinger::DirectOutputThread::cacheParameters_l()
4585{
4586 PlaybackThread::cacheParameters_l();
4587
4588 // use shorter standby delay as on normal output to release
4589 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004590 // no delay on outputs with HW A/V sync
4591 if (usesHwAvSync()) {
4592 standbyDelay = 0;
4593 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004594 standbyDelay = microseconds(activeSleepTime*2);
4595 } else {
4596 standbyDelay = kOffloadStandbyDelayNs;
4597 }
Eric Laurent81784c32012-11-19 14:55:58 -08004598}
4599
Eric Laurente659ef42014-09-29 13:06:46 -07004600void AudioFlinger::DirectOutputThread::flushHw_l()
4601{
Phil Burk062e67a2015-02-11 13:40:50 -08004602 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004603 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004604}
4605
Eric Laurent81784c32012-11-19 14:55:58 -08004606// ----------------------------------------------------------------------------
4607
Eric Laurentbfb1b832013-01-07 09:53:42 -08004608AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004609 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004611 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004612 mWriteAckSequence(0),
4613 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614{
4615}
4616
4617AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4618{
4619}
4620
4621void AudioFlinger::AsyncCallbackThread::onFirstRef()
4622{
4623 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4624}
4625
4626bool AudioFlinger::AsyncCallbackThread::threadLoop()
4627{
4628 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004629 uint32_t writeAckSequence;
4630 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004631
4632 {
4633 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004634 while (!((mWriteAckSequence & 1) ||
4635 (mDrainSequence & 1) ||
4636 exitPending())) {
4637 mWaitWorkCV.wait(mLock);
4638 }
4639
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 if (exitPending()) {
4641 break;
4642 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004643 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4644 mWriteAckSequence, mDrainSequence);
4645 writeAckSequence = mWriteAckSequence;
4646 mWriteAckSequence &= ~1;
4647 drainSequence = mDrainSequence;
4648 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 }
4650 {
Eric Laurent4de95592013-09-26 15:28:21 -07004651 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4652 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004653 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004654 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004656 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004657 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 }
4659 }
4660 }
4661 }
4662 return false;
4663}
4664
4665void AudioFlinger::AsyncCallbackThread::exit()
4666{
4667 ALOGV("AsyncCallbackThread::exit");
4668 Mutex::Autolock _l(mLock);
4669 requestExit();
4670 mWaitWorkCV.broadcast();
4671}
4672
Eric Laurent3b4529e2013-09-05 18:09:19 -07004673void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004674{
4675 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004676 // bit 0 is cleared
4677 mWriteAckSequence = sequence << 1;
4678}
4679
4680void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4681{
4682 Mutex::Autolock _l(mLock);
4683 // ignore unexpected callbacks
4684 if (mWriteAckSequence & 2) {
4685 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004686 mWaitWorkCV.signal();
4687 }
4688}
4689
Eric Laurent3b4529e2013-09-05 18:09:19 -07004690void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004691{
4692 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004693 // bit 0 is cleared
4694 mDrainSequence = sequence << 1;
4695}
4696
4697void AudioFlinger::AsyncCallbackThread::resetDraining()
4698{
4699 Mutex::Autolock _l(mLock);
4700 // ignore unexpected callbacks
4701 if (mDrainSequence & 2) {
4702 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703 mWaitWorkCV.signal();
4704 }
4705}
4706
4707
4708// ----------------------------------------------------------------------------
4709AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4710 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4711 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004712 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713{
Eric Laurentfd477972013-10-25 18:10:40 -07004714 //FIXME: mStandby should be set to true by ThreadBase constructor
4715 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716}
4717
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718void AudioFlinger::OffloadThread::threadLoop_exit()
4719{
4720 if (mFlushPending || mHwPaused) {
4721 // If a flush is pending or track was paused, just discard buffered data
4722 flushHw_l();
4723 } else {
4724 mMixerStatus = MIXER_DRAIN_ALL;
4725 threadLoop_drain();
4726 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004727 if (mUseAsyncWrite) {
4728 ALOG_ASSERT(mCallbackThread != 0);
4729 mCallbackThread->exit();
4730 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004731 PlaybackThread::threadLoop_exit();
4732}
4733
4734AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4735 Vector< sp<Track> > *tracksToRemove
4736)
4737{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 size_t count = mActiveTracks.size();
4739
4740 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004741 bool doHwPause = false;
4742 bool doHwResume = false;
4743
Eric Laurentede6c3b2013-09-19 14:37:46 -07004744 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4745
Eric Laurentbfb1b832013-01-07 09:53:42 -08004746 // find out which tracks need to be processed
4747 for (size_t i = 0; i < count; i++) {
4748 sp<Track> t = mActiveTracks[i].promote();
4749 // The track died recently
4750 if (t == 0) {
4751 continue;
4752 }
4753 Track* const track = t.get();
4754 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004755 // Only consider last track started for volume and mixer state control.
4756 // In theory an older track could underrun and restart after the new one starts
4757 // but as we only care about the transition phase between two tracks on a
4758 // direct output, it is not a problem to ignore the underrun case.
4759 sp<Track> l = mLatestActiveTrack.promote();
4760 bool last = l.get() == track;
4761
Haynes Mathew George7844f672014-01-15 12:32:55 -08004762 if (track->isInvalid()) {
4763 ALOGW("An invalidated track shouldn't be in active list");
4764 tracksToRemove->add(track);
4765 continue;
4766 }
4767
4768 if (track->mState == TrackBase::IDLE) {
4769 ALOGW("An idle track shouldn't be in active list");
4770 continue;
4771 }
4772
Eric Laurentbfb1b832013-01-07 09:53:42 -08004773 if (track->isPausing()) {
4774 track->setPaused();
4775 if (last) {
4776 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004777 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 mHwPaused = true;
4779 }
4780 // If we were part way through writing the mixbuffer to
4781 // the HAL we must save this until we resume
4782 // BUG - this will be wrong if a different track is made active,
4783 // in that case we want to discard the pending data in the
4784 // mixbuffer and tell the client to present it again when the
4785 // track is resumed
4786 mPausedWriteLength = mCurrentWriteLength;
4787 mPausedBytesRemaining = mBytesRemaining;
4788 mBytesRemaining = 0; // stop writing
4789 }
4790 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004791 } else if (track->isFlushPending()) {
4792 track->flushAck();
4793 if (last) {
4794 mFlushPending = true;
4795 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004796 } else if (track->isResumePending()){
4797 track->resumeAck();
4798 if (last) {
4799 if (mPausedBytesRemaining) {
4800 // Need to continue write that was interrupted
4801 mCurrentWriteLength = mPausedWriteLength;
4802 mBytesRemaining = mPausedBytesRemaining;
4803 mPausedBytesRemaining = 0;
4804 }
4805 if (mHwPaused) {
4806 doHwResume = true;
4807 mHwPaused = false;
4808 // threadLoop_mix() will handle the case that we need to
4809 // resume an interrupted write
4810 }
4811 // enable write to audio HAL
4812 sleepTime = 0;
4813
4814 // Do not handle new data in this iteration even if track->framesReady()
4815 mixerStatus = MIXER_TRACKS_ENABLED;
4816 }
4817 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004818 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004819 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 if (track->mFillingUpStatus == Track::FS_FILLED) {
4821 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004822 // make sure processVolume_l() will apply new volume even if 0
4823 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824 }
4825
4826 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004827 sp<Track> previousTrack = mPreviousTrack.promote();
4828 if (previousTrack != 0) {
4829 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004830 // Flush any data still being written from last track
4831 mBytesRemaining = 0;
4832 if (mPausedBytesRemaining) {
4833 // Last track was paused so we also need to flush saved
4834 // mixbuffer state and invalidate track so that it will
4835 // re-submit that unwritten data when it is next resumed
4836 mPausedBytesRemaining = 0;
4837 // Invalidate is a bit drastic - would be more efficient
4838 // to have a flag to tell client that some of the
4839 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004840 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004841 }
4842 // flush data already sent to the DSP if changing audio session as audio
4843 // comes from a different source. Also invalidate previous track to force a
4844 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004845 if (previousTrack->sessionId() != track->sessionId()) {
4846 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004847 }
4848 }
4849 }
4850 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004851 // reset retry count
4852 track->mRetryCount = kMaxTrackRetriesOffload;
4853 mActiveTrack = t;
4854 mixerStatus = MIXER_TRACKS_READY;
4855 }
4856 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004857 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004858 if (track->isStopping_1()) {
4859 // Hardware buffer can hold a large amount of audio so we must
4860 // wait for all current track's data to drain before we say
4861 // that the track is stopped.
4862 if (mBytesRemaining == 0) {
4863 // Only start draining when all data in mixbuffer
4864 // has been written
4865 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4866 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004867 // do not drain if no data was ever sent to HAL (mStandby == true)
4868 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004869 // do not modify drain sequence if we are already draining. This happens
4870 // when resuming from pause after drain.
4871 if ((mDrainSequence & 1) == 0) {
4872 sleepTime = 0;
4873 standbyTime = systemTime() + standbyDelay;
4874 mixerStatus = MIXER_DRAIN_TRACK;
4875 mDrainSequence += 2;
4876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004877 if (mHwPaused) {
4878 // It is possible to move from PAUSED to STOPPING_1 without
4879 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004880 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 mHwPaused = false;
4882 }
4883 }
4884 }
4885 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004886 // Drain has completed or we are in standby, signal presentation complete
4887 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 track->mState = TrackBase::STOPPED;
4889 size_t audioHALFrames =
4890 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4891 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08004892 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004893 track->presentationComplete(framesWritten, audioHALFrames);
4894 track->reset();
4895 tracksToRemove->add(track);
4896 }
4897 } else {
4898 // No buffers for this track. Give it a few chances to
4899 // fill a buffer, then remove it from active list.
4900 if (--(track->mRetryCount) <= 0) {
4901 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4902 track->name());
4903 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004904 // indicate to client process that the track was disabled because of underrun;
4905 // it will then automatically call start() when data is available
4906 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004907 } else if (last){
4908 mixerStatus = MIXER_TRACKS_ENABLED;
4909 }
4910 }
4911 }
4912 // compute volume for this track
4913 processVolume_l(track, last);
4914 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004915
Eric Laurentea0fade2013-10-04 16:23:48 -07004916 // make sure the pause/flush/resume sequence is executed in the right order.
4917 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4918 // before flush and then resume HW. This can happen in case of pause/flush/resume
4919 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004920 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004921 mOutput->stream->pause(mOutput->stream);
4922 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004923 if (mFlushPending) {
4924 flushHw_l();
4925 mFlushPending = false;
4926 }
Eric Laurentfd477972013-10-25 18:10:40 -07004927 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004928 mOutput->stream->resume(mOutput->stream);
4929 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004930
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 // remove all the tracks that need to be...
4932 removeTracks_l(*tracksToRemove);
4933
4934 return mixerStatus;
4935}
4936
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937// must be called with thread mutex locked
4938bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4939{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004940 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4941 mWriteAckSequence, mDrainSequence);
4942 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004943 return true;
4944 }
4945 return false;
4946}
4947
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4949{
4950 Mutex::Autolock _l(mLock);
4951 return waitingAsyncCallback_l();
4952}
4953
4954void AudioFlinger::OffloadThread::flushHw_l()
4955{
Eric Laurente659ef42014-09-29 13:06:46 -07004956 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004957 // Flush anything still waiting in the mixbuffer
4958 mCurrentWriteLength = 0;
4959 mBytesRemaining = 0;
4960 mPausedWriteLength = 0;
4961 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004962
Eric Laurentbfb1b832013-01-07 09:53:42 -08004963 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004964 // discard any pending drain or write ack by incrementing sequence
4965 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4966 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004968 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4969 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004970 }
4971}
4972
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004973void AudioFlinger::OffloadThread::onAddNewTrack_l()
4974{
4975 sp<Track> previousTrack = mPreviousTrack.promote();
4976 sp<Track> latestTrack = mLatestActiveTrack.promote();
4977
4978 if (previousTrack != 0 && latestTrack != 0 &&
4979 (previousTrack->sessionId() != latestTrack->sessionId())) {
4980 mFlushPending = true;
4981 }
4982 PlaybackThread::onAddNewTrack_l();
4983}
4984
Eric Laurentbfb1b832013-01-07 09:53:42 -08004985// ----------------------------------------------------------------------------
4986
Eric Laurent81784c32012-11-19 14:55:58 -08004987AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4988 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4989 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4990 DUPLICATING),
4991 mWaitTimeMs(UINT_MAX)
4992{
4993 addOutputTrack(mainThread);
4994}
4995
4996AudioFlinger::DuplicatingThread::~DuplicatingThread()
4997{
4998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4999 mOutputTracks[i]->destroy();
5000 }
5001}
5002
5003void AudioFlinger::DuplicatingThread::threadLoop_mix()
5004{
5005 // mix buffers...
5006 if (outputsReady(outputTracks)) {
5007 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5008 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005009 if (mMixerBufferValid) {
5010 memset(mMixerBuffer, 0, mMixerBufferSize);
5011 } else {
5012 memset(mSinkBuffer, 0, mSinkBufferSize);
5013 }
Eric Laurent81784c32012-11-19 14:55:58 -08005014 }
5015 sleepTime = 0;
5016 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005017 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005018 standbyTime = systemTime() + standbyDelay;
5019}
5020
5021void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5022{
5023 if (sleepTime == 0) {
5024 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5025 sleepTime = activeSleepTime;
5026 } else {
5027 sleepTime = idleSleepTime;
5028 }
5029 } else if (mBytesWritten != 0) {
5030 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5031 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005032 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005033 } else {
5034 // flush remaining overflow buffers in output tracks
5035 writeFrames = 0;
5036 }
5037 sleepTime = 0;
5038 }
5039}
5040
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005042{
5043 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005044 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005045 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005046 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005047 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005048}
5049
5050void AudioFlinger::DuplicatingThread::threadLoop_standby()
5051{
5052 // DuplicatingThread implements standby by stopping all tracks
5053 for (size_t i = 0; i < outputTracks.size(); i++) {
5054 outputTracks[i]->stop();
5055 }
5056}
5057
5058void AudioFlinger::DuplicatingThread::saveOutputTracks()
5059{
5060 outputTracks = mOutputTracks;
5061}
5062
5063void AudioFlinger::DuplicatingThread::clearOutputTracks()
5064{
5065 outputTracks.clear();
5066}
5067
5068void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5069{
5070 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005071 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5072 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5073 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5074 const size_t frameCount =
5075 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5076 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5077 // from different OutputTracks and their associated MixerThreads (e.g. one may
5078 // nearly empty and the other may be dropping data).
5079
5080 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005081 this,
5082 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005083 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005084 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005085 frameCount,
5086 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005087 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005088 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005089 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005090 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005091 updateWaitTime_l();
5092 }
5093}
5094
5095void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5096{
5097 Mutex::Autolock _l(mLock);
5098 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5099 if (mOutputTracks[i]->thread() == thread) {
5100 mOutputTracks[i]->destroy();
5101 mOutputTracks.removeAt(i);
5102 updateWaitTime_l();
5103 return;
5104 }
5105 }
5106 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5107}
5108
5109// caller must hold mLock
5110void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5111{
5112 mWaitTimeMs = UINT_MAX;
5113 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5114 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5115 if (strong != 0) {
5116 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5117 if (waitTimeMs < mWaitTimeMs) {
5118 mWaitTimeMs = waitTimeMs;
5119 }
5120 }
5121 }
5122}
5123
5124
5125bool AudioFlinger::DuplicatingThread::outputsReady(
5126 const SortedVector< sp<OutputTrack> > &outputTracks)
5127{
5128 for (size_t i = 0; i < outputTracks.size(); i++) {
5129 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5130 if (thread == 0) {
5131 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5132 outputTracks[i].get());
5133 return false;
5134 }
5135 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5136 // see note at standby() declaration
5137 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5138 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5139 thread.get());
5140 return false;
5141 }
5142 }
5143 return true;
5144}
5145
5146uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5147{
5148 return (mWaitTimeMs * 1000) / 2;
5149}
5150
5151void AudioFlinger::DuplicatingThread::cacheParameters_l()
5152{
5153 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5154 updateWaitTime_l();
5155
5156 MixerThread::cacheParameters_l();
5157}
5158
5159// ----------------------------------------------------------------------------
5160// Record
5161// ----------------------------------------------------------------------------
5162
5163AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5164 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005165 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005166 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005167 audio_devices_t inDevice
5168#ifdef TEE_SINK
5169 , const sp<NBAIO_Sink>& teeSink
5170#endif
5171 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005172 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005173 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005174 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005175 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005176#ifdef TEE_SINK
5177 , mTeeSink(teeSink)
5178#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005179 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5180 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005181 // mFastCapture below
5182 , mFastCaptureFutex(0)
5183 // mInputSource
5184 // mPipeSink
5185 // mPipeSource
5186 , mPipeFramesP2(0)
5187 // mPipeMemory
5188 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005189 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005190{
Glenn Kastend7dca052015-03-05 16:05:54 -08005191 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5192 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005193
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005194 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005195
5196 // create an NBAIO source for the HAL input stream, and negotiate
5197 mInputSource = new AudioStreamInSource(input->stream);
5198 size_t numCounterOffers = 0;
5199 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5200 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5201 ALOG_ASSERT(index == 0);
5202
5203 // initialize fast capture depending on configuration
5204 bool initFastCapture;
5205 switch (kUseFastCapture) {
5206 case FastCapture_Never:
5207 initFastCapture = false;
5208 break;
5209 case FastCapture_Always:
5210 initFastCapture = true;
5211 break;
5212 case FastCapture_Static:
5213 uint32_t primaryOutputSampleRate;
5214 {
5215 AutoMutex _l(audioFlinger->mHardwareLock);
5216 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5217 }
5218 initFastCapture =
5219 // either capture sample rate is same as (a reasonable) primary output sample rate
5220 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5221 (mSampleRate == primaryOutputSampleRate)) ||
5222 // or primary output sample rate is unknown, and capture sample rate is reasonable
5223 ((primaryOutputSampleRate == 0) &&
5224 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005225 // and the buffer size is < 12 ms
5226 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005227 break;
5228 // case FastCapture_Dynamic:
5229 }
5230
5231 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005232 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005233 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005234 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005235 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5236 void *pipeBuffer;
5237 const sp<MemoryDealer> roHeap(readOnlyHeap());
5238 sp<IMemory> pipeMemory;
5239 if ((roHeap == 0) ||
5240 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5241 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5242 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5243 goto failed;
5244 }
5245 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5246 memset(pipeBuffer, 0, pipeSize);
5247 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5248 const NBAIO_Format offers[1] = {format};
5249 size_t numCounterOffers = 0;
5250 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5251 ALOG_ASSERT(index == 0);
5252 mPipeSink = pipe;
5253 PipeReader *pipeReader = new PipeReader(*pipe);
5254 numCounterOffers = 0;
5255 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5256 ALOG_ASSERT(index == 0);
5257 mPipeSource = pipeReader;
5258 mPipeFramesP2 = pipeFramesP2;
5259 mPipeMemory = pipeMemory;
5260
5261 // create fast capture
5262 mFastCapture = new FastCapture();
5263 FastCaptureStateQueue *sq = mFastCapture->sq();
5264#ifdef STATE_QUEUE_DUMP
5265 // FIXME
5266#endif
5267 FastCaptureState *state = sq->begin();
5268 state->mCblk = NULL;
5269 state->mInputSource = mInputSource.get();
5270 state->mInputSourceGen++;
5271 state->mPipeSink = pipe;
5272 state->mPipeSinkGen++;
5273 state->mFrameCount = mFrameCount;
5274 state->mCommand = FastCaptureState::COLD_IDLE;
5275 // already done in constructor initialization list
5276 //mFastCaptureFutex = 0;
5277 state->mColdFutexAddr = &mFastCaptureFutex;
5278 state->mColdGen++;
5279 state->mDumpState = &mFastCaptureDumpState;
5280#ifdef TEE_SINK
5281 // FIXME
5282#endif
5283 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5284 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5285 sq->end();
5286 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5287
5288 // start the fast capture
5289 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5290 pid_t tid = mFastCapture->getTid();
5291 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5292 if (err != 0) {
5293 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5294 kPriorityFastCapture, getpid_cached, tid, err);
5295 }
5296
5297#ifdef AUDIO_WATCHDOG
5298 // FIXME
5299#endif
5300
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005301 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005302 }
5303failed: ;
5304
5305 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005306}
5307
Eric Laurent81784c32012-11-19 14:55:58 -08005308AudioFlinger::RecordThread::~RecordThread()
5309{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005310 if (mFastCapture != 0) {
5311 FastCaptureStateQueue *sq = mFastCapture->sq();
5312 FastCaptureState *state = sq->begin();
5313 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5314 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5315 if (old == -1) {
5316 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5317 }
5318 }
5319 state->mCommand = FastCaptureState::EXIT;
5320 sq->end();
5321 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5322 mFastCapture->join();
5323 mFastCapture.clear();
5324 }
5325 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005326 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005327 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005328}
5329
5330void AudioFlinger::RecordThread::onFirstRef()
5331{
Glenn Kastend7dca052015-03-05 16:05:54 -08005332 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005333}
5334
Eric Laurent81784c32012-11-19 14:55:58 -08005335bool AudioFlinger::RecordThread::threadLoop()
5336{
Eric Laurent81784c32012-11-19 14:55:58 -08005337 nsecs_t lastWarning = 0;
5338
5339 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005340
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005341reacquire_wakelock:
5342 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005343 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005344 {
5345 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005346 size_t size = mActiveTracks.size();
5347 activeTracksGen = mActiveTracksGen;
5348 if (size > 0) {
5349 // FIXME an arbitrary choice
5350 activeTrack = mActiveTracks[0];
5351 acquireWakeLock_l(activeTrack->uid());
5352 if (size > 1) {
5353 SortedVector<int> tmp;
5354 for (size_t i = 0; i < size; i++) {
5355 tmp.add(mActiveTracks[i]->uid());
5356 }
5357 updateWakeLockUids_l(tmp);
5358 }
5359 } else {
5360 acquireWakeLock_l(-1);
5361 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005362 }
5363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005364 // used to request a deferred sleep, to be executed later while mutex is unlocked
5365 uint32_t sleepUs = 0;
5366
5367 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005368 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005369 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005370
Glenn Kasten5edadd42013-08-14 16:30:49 -07005371 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005372 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005373 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005374 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005375 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005376 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005377 }
5378
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005379 // activeTracks accumulates a copy of a subset of mActiveTracks
5380 Vector< sp<RecordTrack> > activeTracks;
5381
Glenn Kasten735f45f2014-08-18 15:51:59 -07005382 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005383 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005384
Glenn Kasten735f45f2014-08-18 15:51:59 -07005385 // reference to a fast track which is about to be removed
5386 sp<RecordTrack> fastTrackToRemove;
5387
Eric Laurent81784c32012-11-19 14:55:58 -08005388 { // scope for mLock
5389 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005390
Eric Laurent021cf962014-05-13 10:18:14 -07005391 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005392
Eric Laurent000a4192014-01-29 15:17:32 -08005393 // check exitPending here because checkForNewParameters_l() and
5394 // checkForNewParameters_l() can temporarily release mLock
5395 if (exitPending()) {
5396 break;
5397 }
5398
Glenn Kasten2b806402013-11-20 16:37:38 -08005399 // if no active track(s), then standby and release wakelock
5400 size_t size = mActiveTracks.size();
5401 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005402 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005403 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005404 releaseWakeLock_l();
5405 ALOGV("RecordThread: loop stopping");
5406 // go to sleep
5407 mWaitWorkCV.wait(mLock);
5408 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005409 goto reacquire_wakelock;
5410 }
5411
Glenn Kasten2b806402013-11-20 16:37:38 -08005412 if (mActiveTracksGen != activeTracksGen) {
5413 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005414 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005415 for (size_t i = 0; i < size; i++) {
5416 tmp.add(mActiveTracks[i]->uid());
5417 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005418 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005419 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005420
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421 bool doBroadcast = false;
5422 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005423
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005424 activeTrack = mActiveTracks[i];
5425 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005426 if (activeTrack->isFastTrack()) {
5427 ALOG_ASSERT(fastTrackToRemove == 0);
5428 fastTrackToRemove = activeTrack;
5429 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005430 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005431 mActiveTracks.remove(activeTrack);
5432 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005433 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005434 continue;
5435 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005436
5437 TrackBase::track_state activeTrackState = activeTrack->mState;
5438 switch (activeTrackState) {
5439
5440 case TrackBase::PAUSING:
5441 mActiveTracks.remove(activeTrack);
5442 mActiveTracksGen++;
5443 doBroadcast = true;
5444 size--;
5445 continue;
5446
5447 case TrackBase::STARTING_1:
5448 sleepUs = 10000;
5449 i++;
5450 continue;
5451
5452 case TrackBase::STARTING_2:
5453 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005455 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005456 break;
5457
5458 case TrackBase::ACTIVE:
5459 break;
5460
5461 case TrackBase::IDLE:
5462 i++;
5463 continue;
5464
5465 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005466 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005467 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 activeTracks.add(activeTrack);
5470 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005471
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005472 if (activeTrack->isFastTrack()) {
5473 ALOG_ASSERT(!mFastTrackAvail);
5474 ALOG_ASSERT(fastTrack == 0);
5475 fastTrack = activeTrack;
5476 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005477 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005478 if (doBroadcast) {
5479 mStartStopCond.broadcast();
5480 }
5481
5482 // sleep if there are no active tracks to process
5483 if (activeTracks.size() == 0) {
5484 if (sleepUs == 0) {
5485 sleepUs = kRecordThreadSleepUs;
5486 }
5487 continue;
5488 }
5489 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005490
Eric Laurent81784c32012-11-19 14:55:58 -08005491 lockEffectChains_l(effectChains);
5492 }
5493
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005494 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005495
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005496 size_t size = effectChains.size();
5497 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005498 // thread mutex is not locked, but effect chain is locked
5499 effectChains[i]->process_l();
5500 }
5501
Glenn Kasten735f45f2014-08-18 15:51:59 -07005502 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005503 if (mFastCapture != 0) {
5504 FastCaptureStateQueue *sq = mFastCapture->sq();
5505 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005506 bool didModify = false;
5507 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005508 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5509 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5510 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5511 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5512 if (old == -1) {
5513 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5514 }
5515 }
5516 state->mCommand = FastCaptureState::READ_WRITE;
5517#if 0 // FIXME
5518 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005519 FastThreadDumpState::kSamplingNforLowRamDevice :
5520 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005521#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005522 didModify = true;
5523 }
5524 audio_track_cblk_t *cblkOld = state->mCblk;
5525 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5526 if (cblkNew != cblkOld) {
5527 state->mCblk = cblkNew;
5528 // block until acked if removing a fast track
5529 if (cblkOld != NULL) {
5530 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5531 }
5532 didModify = true;
5533 }
5534 sq->end(didModify);
5535 if (didModify) {
5536 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005537#if 0
5538 if (kUseFastCapture == FastCapture_Dynamic) {
5539 mNormalSource = mPipeSource;
5540 }
5541#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005542 }
5543 }
5544
Glenn Kasten735f45f2014-08-18 15:51:59 -07005545 // now run the fast track destructor with thread mutex unlocked
5546 fastTrackToRemove.clear();
5547
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005548 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5549 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5550 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5551 // If destination is non-contiguous, first read past the nominal end of buffer, then
5552 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005554 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005555 ssize_t framesRead;
5556
5557 // If an NBAIO source is present, use it to read the normal capture's data
5558 if (mPipeSource != 0) {
5559 size_t framesToRead = mBufferSize / mFrameSize;
5560 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5561 framesToRead, AudioBufferProvider::kInvalidPTS);
5562 if (framesRead == 0) {
5563 // since pipe is non-blocking, simulate blocking input
5564 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5565 }
5566 // otherwise use the HAL / AudioStreamIn directly
5567 } else {
5568 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5569 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5570 if (bytesRead < 0) {
5571 framesRead = bytesRead;
5572 } else {
5573 framesRead = bytesRead / mFrameSize;
5574 }
5575 }
5576
5577 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5578 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005579 // Force input into standby so that it tries to recover at next read attempt
5580 inputStandBy();
5581 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005582 }
5583 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005584 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005585 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005587
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005588 if (mTeeSink != 0) {
5589 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5590 }
5591 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005592 {
5593 size_t part1 = mRsmpInFramesP2 - rear;
5594 if ((size_t) framesRead > part1) {
5595 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5596 (framesRead - part1) * mFrameSize);
5597 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005598 }
5599 rear = mRsmpInRear += framesRead;
5600
5601 size = activeTracks.size();
5602 // loop over each active track
5603 for (size_t i = 0; i < size; i++) {
5604 activeTrack = activeTracks[i];
5605
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005606 // skip fast tracks, as those are handled directly by FastCapture
5607 if (activeTrack->isFastTrack()) {
5608 continue;
5609 }
5610
Andy Hung73c02e42015-03-29 01:13:58 -07005611 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005612 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5613
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005614 enum {
5615 OVERRUN_UNKNOWN,
5616 OVERRUN_TRUE,
5617 OVERRUN_FALSE
5618 } overrun = OVERRUN_UNKNOWN;
5619
5620 // loop over getNextBuffer to handle circular sink
5621 for (;;) {
5622
5623 activeTrack->mSink.frameCount = ~0;
5624 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5625 size_t framesOut = activeTrack->mSink.frameCount;
5626 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5627
Andy Hung73c02e42015-03-29 01:13:58 -07005628 // check available frames and handle overrun conditions
5629 // if the record track isn't draining fast enough.
5630 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005631 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005632 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5633 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 overrun = OVERRUN_TRUE;
5635 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005636 if (framesOut == 0 || framesIn == 0) {
5637 break;
5638 }
5639
Andy Hung6770c6f2015-04-07 13:43:36 -07005640 // Don't allow framesOut to be larger than what is possible with resampling
5641 // from framesIn.
5642 // This isn't strictly necessary but helps limit buffer resizing in
5643 // RecordBufferConverter. TODO: remove when no longer needed.
5644 framesOut = min(framesOut,
5645 destinationFramesPossible(
5646 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005647 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5648 framesOut = activeTrack->mRecordBufferConverter->convert(
5649 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650
5651 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5652 overrun = OVERRUN_FALSE;
5653 }
5654
5655 if (activeTrack->mFramesToDrop == 0) {
5656 if (framesOut > 0) {
5657 activeTrack->mSink.frameCount = framesOut;
5658 activeTrack->releaseBuffer(&activeTrack->mSink);
5659 }
5660 } else {
5661 // FIXME could do a partial drop of framesOut
5662 if (activeTrack->mFramesToDrop > 0) {
5663 activeTrack->mFramesToDrop -= framesOut;
5664 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005665 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005666 }
5667 } else {
5668 activeTrack->mFramesToDrop += framesOut;
5669 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5670 activeTrack->mSyncStartEvent->isCancelled()) {
5671 ALOGW("Synced record %s, session %d, trigger session %d",
5672 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5673 activeTrack->sessionId(),
5674 (activeTrack->mSyncStartEvent != 0) ?
5675 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005676 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005677 }
5678 }
5679 }
5680
5681 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005682 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005683 }
5684 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005685
5686 switch (overrun) {
5687 case OVERRUN_TRUE:
5688 // client isn't retrieving buffers fast enough
5689 if (!activeTrack->setOverflow()) {
5690 nsecs_t now = systemTime();
5691 // FIXME should lastWarning per track?
5692 if ((now - lastWarning) > kWarningThrottleNs) {
5693 ALOGW("RecordThread: buffer overflow");
5694 lastWarning = now;
5695 }
5696 }
5697 break;
5698 case OVERRUN_FALSE:
5699 activeTrack->clearOverflow();
5700 break;
5701 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005702 break;
5703 }
5704
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005705 }
5706
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005707unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005708 // enable changes in effect chain
5709 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005710 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
5712
Glenn Kasten93e471f2013-08-19 08:40:07 -07005713 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005714
5715 {
5716 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005717 for (size_t i = 0; i < mTracks.size(); i++) {
5718 sp<RecordTrack> track = mTracks[i];
5719 track->invalidate();
5720 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005721 mActiveTracks.clear();
5722 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 mStartStopCond.broadcast();
5724 }
5725
5726 releaseWakeLock();
5727
5728 ALOGV("RecordThread %p exiting", this);
5729 return false;
5730}
5731
Glenn Kasten93e471f2013-08-19 08:40:07 -07005732void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005733{
5734 if (!mStandby) {
5735 inputStandBy();
5736 mStandby = true;
5737 }
5738}
5739
5740void AudioFlinger::RecordThread::inputStandBy()
5741{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005742 // Idle the fast capture if it's currently running
5743 if (mFastCapture != 0) {
5744 FastCaptureStateQueue *sq = mFastCapture->sq();
5745 FastCaptureState *state = sq->begin();
5746 if (!(state->mCommand & FastCaptureState::IDLE)) {
5747 state->mCommand = FastCaptureState::COLD_IDLE;
5748 state->mColdFutexAddr = &mFastCaptureFutex;
5749 state->mColdGen++;
5750 mFastCaptureFutex = 0;
5751 sq->end();
5752 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5753 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5754#if 0
5755 if (kUseFastCapture == FastCapture_Dynamic) {
5756 // FIXME
5757 }
5758#endif
5759#ifdef AUDIO_WATCHDOG
5760 // FIXME
5761#endif
5762 } else {
5763 sq->end(false /*didModify*/);
5764 }
5765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766 mInput->stream->common.standby(&mInput->stream->common);
5767}
5768
Glenn Kasten05997e22014-03-13 15:08:33 -07005769// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005770sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005771 const sp<AudioFlinger::Client>& client,
5772 uint32_t sampleRate,
5773 audio_format_t format,
5774 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005775 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005776 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005777 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005778 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005779 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005780 pid_t tid,
5781 status_t *status)
5782{
Glenn Kasten74935e42013-12-19 08:56:45 -08005783 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005784 sp<RecordTrack> track;
5785 status_t lStatus;
5786
Glenn Kasten90e58b12013-07-31 16:16:02 -07005787 // client expresses a preference for FAST, but we get the final say
5788 if (*flags & IAudioFlinger::TRACK_FAST) {
5789 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005790 // we formerly checked for a callback handler (non-0 tid),
5791 // but that is no longer required for TRANSFER_OBTAIN mode
5792 //
Glenn Kasten74105912014-07-03 12:28:53 -07005793 // frame count is not specified, or is exactly the pipe depth
5794 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005795 // PCM data
5796 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005797 // native format
5798 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005799 // native channel mask
5800 (channelMask == mChannelMask) &&
5801 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005802 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005803 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804 hasFastCapture() &&
5805 // there are sufficient fast track slots available
5806 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005807 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005808 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005809 frameCount, mFrameCount);
5810 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005811 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5812 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005813 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005814 frameCount, mFrameCount, mPipeFramesP2,
5815 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5816 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005817 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005818 }
5819 }
5820
5821 // compute track buffer size in frames, and suggest the notification frame count
5822 if (*flags & IAudioFlinger::TRACK_FAST) {
5823 // fast track: frame count is exactly the pipe depth
5824 frameCount = mPipeFramesP2;
5825 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5826 *notificationFrames = mFrameCount;
5827 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005828 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5829 // or 20 ms if there is a fast capture
5830 // TODO This could be a roundupRatio inline, and const
5831 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5832 * sampleRate + mSampleRate - 1) / mSampleRate;
5833 // minimum number of notification periods is at least kMinNotifications,
5834 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5835 static const size_t kMinNotifications = 3;
5836 static const uint32_t kMinMs = 30;
5837 // TODO This could be a roundupRatio inline
5838 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5839 // TODO This could be a roundupRatio inline
5840 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5841 maxNotificationFrames;
5842 const size_t minFrameCount = maxNotificationFrames *
5843 max(kMinNotifications, minNotificationsByMs);
5844 frameCount = max(frameCount, minFrameCount);
5845 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5846 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005847 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005848 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005849 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005850
Glenn Kasten15e57982013-09-24 11:52:37 -07005851 lStatus = initCheck();
5852 if (lStatus != NO_ERROR) {
5853 ALOGE("createRecordTrack_l() audio driver not initialized");
5854 goto Exit;
5855 }
Eric Laurent81784c32012-11-19 14:55:58 -08005856
5857 { // scope for mLock
5858 Mutex::Autolock _l(mLock);
5859
5860 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005861 format, channelMask, frameCount, NULL, sessionId, uid,
5862 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005863
Glenn Kasten03003332013-08-06 15:40:54 -07005864 lStatus = track->initCheck();
5865 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005866 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005867 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005868 goto Exit;
5869 }
5870 mTracks.add(track);
5871
5872 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5873 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5874 mAudioFlinger->btNrecIsOff();
5875 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5876 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005877
5878 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5879 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5880 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5881 // so ask activity manager to do this on our behalf
5882 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5883 }
Eric Laurent81784c32012-11-19 14:55:58 -08005884 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005885
Eric Laurent81784c32012-11-19 14:55:58 -08005886 lStatus = NO_ERROR;
5887
5888Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005889 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005890 return track;
5891}
5892
5893status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5894 AudioSystem::sync_event_t event,
5895 int triggerSession)
5896{
5897 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5898 sp<ThreadBase> strongMe = this;
5899 status_t status = NO_ERROR;
5900
5901 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005902 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005903 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005905 triggerSession,
5906 recordTrack->sessionId(),
5907 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005908 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005909 // Sync event can be cancelled by the trigger session if the track is not in a
5910 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005911 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005912 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005913 } else {
5914 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005915 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005916 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005917 }
5918 }
5919
5920 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005921 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005922 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005923 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5924 if (recordTrack->mState == TrackBase::PAUSING) {
5925 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005926 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 } else {
5928 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
5930 return status;
5931 }
5932
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005933 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5934 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5935 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005937 mActiveTracks.add(recordTrack);
5938 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005939 status_t status = NO_ERROR;
5940 if (recordTrack->isExternalTrack()) {
5941 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005942 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005943 mLock.lock();
5944 // FIXME should verify that recordTrack is still in mActiveTracks
5945 if (status != NO_ERROR) {
5946 mActiveTracks.remove(recordTrack);
5947 mActiveTracksGen++;
5948 recordTrack->clearSyncStartEvent();
5949 ALOGV("RecordThread::start error %d", status);
5950 return status;
5951 }
Eric Laurent81784c32012-11-19 14:55:58 -08005952 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005953 // Catch up with current buffer indices if thread is already running.
5954 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5955 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5956 // see previously buffered data before it called start(), but with greater risk of overrun.
5957
Andy Hung73c02e42015-03-29 01:13:58 -07005958 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07005959 // clear any converter state as new data will be discontinuous
5960 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005962 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005963 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005964 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005965 ALOGV("Record failed to start");
5966 status = BAD_VALUE;
5967 goto startError;
5968 }
Eric Laurent81784c32012-11-19 14:55:58 -08005969 return status;
5970 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005971
Eric Laurent81784c32012-11-19 14:55:58 -08005972startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005973 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005974 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005975 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005976 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005977 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005978 return status;
5979}
5980
Eric Laurent81784c32012-11-19 14:55:58 -08005981void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5982{
5983 sp<SyncEvent> strongEvent = event.promote();
5984
5985 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005986 sp<RefBase> ptr = strongEvent->cookie().promote();
5987 if (ptr != 0) {
5988 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5989 recordTrack->handleSyncStartEvent(strongEvent);
5990 }
Eric Laurent81784c32012-11-19 14:55:58 -08005991 }
5992}
5993
Glenn Kastena8356f62013-07-25 14:37:52 -07005994bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005995 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005996 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005997 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005998 return false;
5999 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006000 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006001 recordTrack->mState = TrackBase::PAUSING;
6002 // do not wait for mStartStopCond if exiting
6003 if (exitPending()) {
6004 return true;
6005 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006006 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006007 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006008 // if we have been restarted, recordTrack is in mActiveTracks here
6009 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006010 ALOGV("Record stopped OK");
6011 return true;
6012 }
6013 return false;
6014}
6015
Glenn Kasten0f11b512014-01-31 16:18:54 -08006016bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006017{
6018 return false;
6019}
6020
Glenn Kasten0f11b512014-01-31 16:18:54 -08006021status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006022{
6023#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6024 if (!isValidSyncEvent(event)) {
6025 return BAD_VALUE;
6026 }
6027
6028 int eventSession = event->triggerSession();
6029 status_t ret = NAME_NOT_FOUND;
6030
6031 Mutex::Autolock _l(mLock);
6032
6033 for (size_t i = 0; i < mTracks.size(); i++) {
6034 sp<RecordTrack> track = mTracks[i];
6035 if (eventSession == track->sessionId()) {
6036 (void) track->setSyncEvent(event);
6037 ret = NO_ERROR;
6038 }
6039 }
6040 return ret;
6041#else
6042 return BAD_VALUE;
6043#endif
6044}
6045
6046// destroyTrack_l() must be called with ThreadBase::mLock held
6047void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6048{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006049 track->terminate();
6050 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006052 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006053 removeTrack_l(track);
6054 }
6055}
6056
6057void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6058{
6059 mTracks.remove(track);
6060 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006061 if (track->isFastTrack()) {
6062 ALOG_ASSERT(!mFastTrackAvail);
6063 mFastTrackAvail = true;
6064 }
Eric Laurent81784c32012-11-19 14:55:58 -08006065}
6066
6067void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6068{
6069 dumpInternals(fd, args);
6070 dumpTracks(fd, args);
6071 dumpEffectChains(fd, args);
6072}
6073
6074void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6075{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006076 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006077
Glenn Kasten44182c22015-03-05 17:12:23 -08006078 dumpBase(fd, args);
6079
6080 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006081 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006082 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006083 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006084 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006085
6086 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6087 const FastCaptureDumpState copy(mFastCaptureDumpState);
6088 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006089}
6090
Glenn Kasten0f11b512014-01-31 16:18:54 -08006091void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006092{
6093 const size_t SIZE = 256;
6094 char buffer[SIZE];
6095 String8 result;
6096
Marco Nelissenb2208842014-02-07 14:00:50 -08006097 size_t numtracks = mTracks.size();
6098 size_t numactive = mActiveTracks.size();
6099 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006100 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006101 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006102 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006103 RecordTrack::appendDumpHeader(result);
6104 for (size_t i = 0; i < numtracks ; ++i) {
6105 sp<RecordTrack> track = mTracks[i];
6106 if (track != 0) {
6107 bool active = mActiveTracks.indexOf(track) >= 0;
6108 if (active) {
6109 numactiveseen++;
6110 }
6111 track->dump(buffer, SIZE, active);
6112 result.append(buffer);
6113 }
Eric Laurent81784c32012-11-19 14:55:58 -08006114 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006115 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006116 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006117 }
6118
Marco Nelissenb2208842014-02-07 14:00:50 -08006119 if (numactiveseen != numactive) {
6120 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6121 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006122 result.append(buffer);
6123 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006124 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006125 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006126 if (mTracks.indexOf(track) < 0) {
6127 track->dump(buffer, SIZE, true);
6128 result.append(buffer);
6129 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006130 }
Eric Laurent81784c32012-11-19 14:55:58 -08006131
6132 }
6133 write(fd, result.string(), result.size());
6134}
6135
Andy Hung73c02e42015-03-29 01:13:58 -07006136
6137void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6138{
6139 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6140 RecordThread *recordThread = (RecordThread *) threadBase.get();
6141 mRsmpInFront = recordThread->mRsmpInRear;
6142 mRsmpInUnrel = 0;
6143}
6144
6145void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6146 size_t *framesAvailable, bool *hasOverrun)
6147{
6148 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6149 RecordThread *recordThread = (RecordThread *) threadBase.get();
6150 const int32_t rear = recordThread->mRsmpInRear;
6151 const int32_t front = mRsmpInFront;
6152 const ssize_t filled = rear - front;
6153
6154 size_t framesIn;
6155 bool overrun = false;
6156 if (filled < 0) {
6157 // should not happen, but treat like a massive overrun and re-sync
6158 framesIn = 0;
6159 mRsmpInFront = rear;
6160 overrun = true;
6161 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6162 framesIn = (size_t) filled;
6163 } else {
6164 // client is not keeping up with server, but give it latest data
6165 framesIn = recordThread->mRsmpInFrames;
6166 mRsmpInFront = /* front = */ rear - framesIn;
6167 overrun = true;
6168 }
6169 if (framesAvailable != NULL) {
6170 *framesAvailable = framesIn;
6171 }
6172 if (hasOverrun != NULL) {
6173 *hasOverrun = overrun;
6174 }
6175}
6176
Eric Laurent81784c32012-11-19 14:55:58 -08006177// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6179 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006180{
Andy Hung73c02e42015-03-29 01:13:58 -07006181 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 if (threadBase == 0) {
6183 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006184 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 return NOT_ENOUGH_DATA;
6186 }
6187 RecordThread *recordThread = (RecordThread *) threadBase.get();
6188 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006189 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006190 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 // FIXME should not be P2 (don't want to increase latency)
6192 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006193 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006194 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 front &= recordThread->mRsmpInFramesP2 - 1;
6196 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006197 if (part1 > (size_t) filled) {
6198 part1 = filled;
6199 }
6200 size_t ask = buffer->frameCount;
6201 ALOG_ASSERT(ask > 0);
6202 if (part1 > ask) {
6203 part1 = ask;
6204 }
6205 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006206 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006207 buffer->raw = NULL;
6208 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006209 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006210 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
6212
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006213 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006214 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006215 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 return NO_ERROR;
6217}
6218
6219// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6221 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006222{
Glenn Kasten85948432013-08-19 12:09:05 -07006223 size_t stepCount = buffer->frameCount;
6224 if (stepCount == 0) {
6225 return;
6226 }
Andy Hung73c02e42015-03-29 01:13:58 -07006227 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6228 mRsmpInUnrel -= stepCount;
6229 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006230 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006231 buffer->frameCount = 0;
6232}
6233
Andy Hung97a893e2015-03-29 01:03:07 -07006234AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6235 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6236 uint32_t srcSampleRate,
6237 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6238 uint32_t dstSampleRate) :
6239 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6240 // mSrcFormat
6241 // mSrcSampleRate
6242 // mDstChannelMask
6243 // mDstFormat
6244 // mDstSampleRate
6245 // mSrcChannelCount
6246 // mDstChannelCount
6247 // mDstFrameSize
6248 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6249 mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0)
6250{
6251 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6252 dstChannelMask, dstFormat, dstSampleRate);
6253}
6254
6255AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6256 free(mBuf);
6257 delete mResampler;
6258 free(mRsmpOutBuffer);
6259}
6260
6261size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6262 AudioBufferProvider *provider, size_t frames)
6263{
6264 if (mSrcSampleRate == mDstSampleRate) {
6265 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6266 mSrcSampleRate, mSrcFormat, mDstFormat);
6267
6268 AudioBufferProvider::Buffer buffer;
6269 for (size_t i = frames; i > 0; ) {
6270 buffer.frameCount = i;
6271 status_t status = provider->getNextBuffer(&buffer, 0);
6272 if (status != OK || buffer.frameCount == 0) {
6273 frames -= i; // cannot fill request.
6274 break;
6275 }
6276 // convert to destination buffer
6277 convert(dst, buffer.raw, buffer.frameCount);
6278
6279 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6280 i -= buffer.frameCount;
6281 provider->releaseBuffer(&buffer);
6282 }
6283 } else {
6284 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6285 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6286
6287 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
6288 if (mRsmpOutFrameCount < frames) {
6289 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
6290 free(mRsmpOutBuffer);
6291 // resampler always outputs stereo (FOR NOW)
6292 (void)posix_memalign(&mRsmpOutBuffer, 32, frames * FCC_2 * sizeof(int32_t) /*Q4.27*/);
6293 mRsmpOutFrameCount = frames;
6294 }
6295 // resampler accumulates, but we only have one source track
6296 memset(mRsmpOutBuffer, 0, frames * FCC_2 * sizeof(int32_t));
6297 frames = mResampler->resample((int32_t*)mRsmpOutBuffer, frames, provider);
6298
6299 // convert to destination buffer
6300 convert(dst, mRsmpOutBuffer, frames);
6301 }
6302 return frames;
6303}
6304
6305status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6306 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6307 uint32_t srcSampleRate,
6308 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6309 uint32_t dstSampleRate)
6310{
6311 // quick evaluation if there is any change.
6312 if (mSrcFormat == srcFormat
6313 && mSrcChannelMask == srcChannelMask
6314 && mSrcSampleRate == srcSampleRate
6315 && mDstFormat == dstFormat
6316 && mDstChannelMask == dstChannelMask
6317 && mDstSampleRate == dstSampleRate) {
6318 return NO_ERROR;
6319 }
6320
6321 const bool valid =
6322 audio_is_input_channel(srcChannelMask)
6323 && audio_is_input_channel(dstChannelMask)
6324 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6325 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6326 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6327 ; // no upsampling checks for now
6328 if (!valid) {
6329 return BAD_VALUE;
6330 }
6331
6332 mSrcFormat = srcFormat;
6333 mSrcChannelMask = srcChannelMask;
6334 mSrcSampleRate = srcSampleRate;
6335 mDstFormat = dstFormat;
6336 mDstChannelMask = dstChannelMask;
6337 mDstSampleRate = dstSampleRate;
6338
6339 // compute derived parameters
6340 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6341 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6342 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6343
6344 // do we need a format buffer?
6345 if (mSrcFormat != mDstFormat && mDstChannelCount != mSrcChannelCount) {
6346 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6347 } else {
6348 mBufFrameSize = 0;
6349 }
6350 mBufFrames = 0; // force the buffer to be resized.
6351
6352 // do we need to resample?
6353 if (mSrcSampleRate != mDstSampleRate) {
6354 if (mResampler != NULL) {
6355 delete mResampler;
6356 }
6357 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
6358 mSrcChannelCount, mDstSampleRate); // may seem confusing...
6359 mResampler->setSampleRate(mSrcSampleRate);
6360 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6361 }
6362 return NO_ERROR;
6363}
6364
6365void AudioFlinger::RecordThread::RecordBufferConverter::convert(
6366 void *dst, /*const*/ void *src, size_t frames)
6367{
6368 // check if a memcpy will do
6369 if (mResampler == NULL
6370 && mSrcChannelCount == mDstChannelCount
6371 && mSrcFormat == mDstFormat) {
6372 memcpy(dst, src,
6373 frames * mDstChannelCount * audio_bytes_per_sample(mDstFormat));
6374 return;
6375 }
6376 // reallocate buffer if needed
6377 if (mBufFrameSize != 0 && mBufFrames < frames) {
6378 free(mBuf);
6379 mBufFrames = frames;
6380 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6381 }
6382 // do processing
6383 if (mResampler != NULL) {
6384 // src channel count is always >= 2.
6385 void *dstBuf = mBuf != NULL ? mBuf : dst;
6386 // ditherAndClamp() works as long as all buffers returned by
6387 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
6388 if (mDstChannelCount == 1) {
6389 // the resampler always outputs stereo samples.
6390 // FIXME: this rewrites back into src
6391 ditherAndClamp((int32_t *)src, (const int32_t *)src, frames);
6392 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6393 (const int16_t *)src, frames);
6394 } else {
6395 ditherAndClamp((int32_t *)dstBuf, (const int32_t *)src, frames);
6396 }
6397 } else if (mSrcChannelCount != mDstChannelCount) {
6398 void *dstBuf = mBuf != NULL ? mBuf : dst;
6399 if (mSrcChannelCount == 1) {
6400 upmix_to_stereo_i16_from_mono_i16((int16_t *)dstBuf, (const int16_t *)src,
6401 frames);
6402 } else {
6403 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6404 (const int16_t *)src, frames);
6405 }
6406 }
6407 if (mSrcFormat != mDstFormat) {
6408 void *srcBuf = mBuf != NULL ? mBuf : src;
6409 memcpy_by_audio_format(dst, mDstFormat, srcBuf, mSrcFormat,
6410 frames * mDstChannelCount);
6411 }
6412}
6413
Eric Laurent10351942014-05-08 18:49:52 -07006414bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6415 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006416{
6417 bool reconfig = false;
6418
Eric Laurent10351942014-05-08 18:49:52 -07006419 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006420
Eric Laurent10351942014-05-08 18:49:52 -07006421 audio_format_t reqFormat = mFormat;
6422 uint32_t samplingRate = mSampleRate;
6423 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6424
6425 AudioParameter param = AudioParameter(keyValuePair);
6426 int value;
6427 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6428 // channel count change can be requested. Do we mandate the first client defines the
6429 // HAL sampling rate and channel count or do we allow changes on the fly?
6430 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6431 samplingRate = value;
6432 reconfig = true;
6433 }
6434 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006435 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006436 status = BAD_VALUE;
6437 } else {
6438 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006439 reconfig = true;
6440 }
Eric Laurent10351942014-05-08 18:49:52 -07006441 }
6442 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6443 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6444 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6445 status = BAD_VALUE;
6446 } else {
6447 channelMask = mask;
6448 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006449 }
Eric Laurent10351942014-05-08 18:49:52 -07006450 }
6451 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6452 // do not accept frame count changes if tracks are open as the track buffer
6453 // size depends on frame count and correct behavior would not be guaranteed
6454 // if frame count is changed after track creation
6455 if (mActiveTracks.size() > 0) {
6456 status = INVALID_OPERATION;
6457 } else {
6458 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006459 }
Eric Laurent10351942014-05-08 18:49:52 -07006460 }
6461 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6462 // forward device change to effects that have requested to be
6463 // aware of attached audio device.
6464 for (size_t i = 0; i < mEffectChains.size(); i++) {
6465 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006466 }
Eric Laurent81784c32012-11-19 14:55:58 -08006467
Eric Laurent10351942014-05-08 18:49:52 -07006468 // store input device and output device but do not forward output device to audio HAL.
6469 // Note that status is ignored by the caller for output device
6470 // (see AudioFlinger::setParameters()
6471 if (audio_is_output_devices(value)) {
6472 mOutDevice = value;
6473 status = BAD_VALUE;
6474 } else {
6475 mInDevice = value;
6476 // disable AEC and NS if the device is a BT SCO headset supporting those
6477 // pre processings
6478 if (mTracks.size() > 0) {
6479 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6480 mAudioFlinger->btNrecIsOff();
6481 for (size_t i = 0; i < mTracks.size(); i++) {
6482 sp<RecordTrack> track = mTracks[i];
6483 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6484 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006485 }
6486 }
6487 }
Eric Laurent10351942014-05-08 18:49:52 -07006488 }
6489 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6490 mAudioSource != (audio_source_t)value) {
6491 // forward device change to effects that have requested to be
6492 // aware of attached audio device.
6493 for (size_t i = 0; i < mEffectChains.size(); i++) {
6494 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006495 }
Eric Laurent10351942014-05-08 18:49:52 -07006496 mAudioSource = (audio_source_t)value;
6497 }
Glenn Kastene198c362013-08-13 09:13:36 -07006498
Eric Laurent10351942014-05-08 18:49:52 -07006499 if (status == NO_ERROR) {
6500 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6501 keyValuePair.string());
6502 if (status == INVALID_OPERATION) {
6503 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006504 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6505 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006506 }
6507 if (reconfig) {
6508 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006509 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6510 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006511 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006512 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006513 audio_channel_count_from_in_mask(
6514 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006515 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6516 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6517 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006518 }
Eric Laurent10351942014-05-08 18:49:52 -07006519 if (status == NO_ERROR) {
6520 readInputParameters_l();
6521 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006522 }
6523 }
Eric Laurent81784c32012-11-19 14:55:58 -08006524 }
Eric Laurent10351942014-05-08 18:49:52 -07006525
Eric Laurent81784c32012-11-19 14:55:58 -08006526 return reconfig;
6527}
6528
6529String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6530{
Eric Laurent81784c32012-11-19 14:55:58 -08006531 Mutex::Autolock _l(mLock);
6532 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006533 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006534 }
6535
Glenn Kastend8ea6992013-07-16 14:17:15 -07006536 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6537 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006538 free(s);
6539 return out_s8;
6540}
6541
Eric Laurent021cf962014-05-13 10:18:14 -07006542void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006543 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006544 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006545
6546 switch (event) {
6547 case AudioSystem::INPUT_OPENED:
6548 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006549 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006550 desc.samplingRate = mSampleRate;
6551 desc.format = mFormat;
6552 desc.frameCount = mFrameCount;
6553 desc.latency = 0;
6554 param2 = &desc;
6555 break;
6556
6557 case AudioSystem::INPUT_CLOSED:
6558 default:
6559 break;
6560 }
Eric Laurent021cf962014-05-13 10:18:14 -07006561 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006562}
6563
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006564void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006565{
Eric Laurent81784c32012-11-19 14:55:58 -08006566 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6567 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006568 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006569 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6570 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006571 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006572 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006573 }
Eric Laurent665470b2014-07-03 16:37:08 -07006574 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006575 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6576 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006577 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006578 // 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 -07006579 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006580 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006581 // A larger value should allow more old data to be read after a track calls start(),
6582 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006583 //
6584 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006585 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006586 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006587 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006588
6589 // TODO optimize audio capture buffer sizes ...
6590 // Here we calculate the size of the sliding buffer used as a source
6591 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6592 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6593 // be better to have it derived from the pipe depth in the long term.
6594 // The current value is higher than necessary. However it should not add to latency.
6595
Glenn Kasten85948432013-08-19 12:09:05 -07006596 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6597 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006598
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006599 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6600 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006601}
6602
Glenn Kasten5f972c02014-01-13 09:59:31 -08006603uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006604{
6605 Mutex::Autolock _l(mLock);
6606 if (initCheck() != NO_ERROR) {
6607 return 0;
6608 }
6609
6610 return mInput->stream->get_input_frames_lost(mInput->stream);
6611}
6612
6613uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6614{
6615 Mutex::Autolock _l(mLock);
6616 uint32_t result = 0;
6617 if (getEffectChain_l(sessionId) != 0) {
6618 result = EFFECT_SESSION;
6619 }
6620
6621 for (size_t i = 0; i < mTracks.size(); ++i) {
6622 if (sessionId == mTracks[i]->sessionId()) {
6623 result |= TRACK_SESSION;
6624 break;
6625 }
6626 }
6627
6628 return result;
6629}
6630
6631KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6632{
6633 KeyedVector<int, bool> ids;
6634 Mutex::Autolock _l(mLock);
6635 for (size_t j = 0; j < mTracks.size(); ++j) {
6636 sp<RecordThread::RecordTrack> track = mTracks[j];
6637 int sessionId = track->sessionId();
6638 if (ids.indexOfKey(sessionId) < 0) {
6639 ids.add(sessionId, true);
6640 }
6641 }
6642 return ids;
6643}
6644
6645AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6646{
6647 Mutex::Autolock _l(mLock);
6648 AudioStreamIn *input = mInput;
6649 mInput = NULL;
6650 return input;
6651}
6652
6653// this method must always be called either with ThreadBase mLock held or inside the thread loop
6654audio_stream_t* AudioFlinger::RecordThread::stream() const
6655{
6656 if (mInput == NULL) {
6657 return NULL;
6658 }
6659 return &mInput->stream->common;
6660}
6661
6662status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6663{
6664 // only one chain per input thread
6665 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006666 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006667 return INVALID_OPERATION;
6668 }
6669 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006670 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006671 chain->setInBuffer(NULL);
6672 chain->setOutBuffer(NULL);
6673
6674 checkSuspendOnAddEffectChain_l(chain);
6675
Eric Laurent1b928682014-10-02 19:41:47 -07006676 // make sure enabled pre processing effects state is communicated to the HAL as we
6677 // just moved them to a new input stream.
6678 chain->syncHalEffectsState();
6679
Eric Laurent81784c32012-11-19 14:55:58 -08006680 mEffectChains.add(chain);
6681
6682 return NO_ERROR;
6683}
6684
6685size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6686{
6687 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6688 ALOGW_IF(mEffectChains.size() != 1,
6689 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6690 chain.get(), mEffectChains.size(), this);
6691 if (mEffectChains.size() == 1) {
6692 mEffectChains.removeAt(0);
6693 }
6694 return 0;
6695}
6696
Eric Laurent1c333e22014-05-20 10:48:17 -07006697status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6698 audio_patch_handle_t *handle)
6699{
6700 status_t status = NO_ERROR;
6701 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6702 // store new device and send to effects
6703 mInDevice = patch->sources[0].ext.device.type;
6704 for (size_t i = 0; i < mEffectChains.size(); i++) {
6705 mEffectChains[i]->setDevice_l(mInDevice);
6706 }
6707
6708 // disable AEC and NS if the device is a BT SCO headset supporting those
6709 // pre processings
6710 if (mTracks.size() > 0) {
6711 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6712 mAudioFlinger->btNrecIsOff();
6713 for (size_t i = 0; i < mTracks.size(); i++) {
6714 sp<RecordTrack> track = mTracks[i];
6715 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6716 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6717 }
6718 }
6719
6720 // store new source and send to effects
6721 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6722 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6723 for (size_t i = 0; i < mEffectChains.size(); i++) {
6724 mEffectChains[i]->setAudioSource_l(mAudioSource);
6725 }
6726 }
6727
6728 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6729 status = hwDevice->create_audio_patch(hwDevice,
6730 patch->num_sources,
6731 patch->sources,
6732 patch->num_sinks,
6733 patch->sinks,
6734 handle);
6735 } else {
6736 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6737 }
6738 return status;
6739}
6740
6741status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6742{
6743 status_t status = NO_ERROR;
6744 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6745 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6746 status = hwDevice->release_audio_patch(hwDevice, handle);
6747 } else {
6748 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6749 }
6750 return status;
6751}
6752
Eric Laurent83b88082014-06-20 18:31:16 -07006753void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6754{
6755 Mutex::Autolock _l(mLock);
6756 mTracks.add(record);
6757}
6758
6759void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6760{
6761 Mutex::Autolock _l(mLock);
6762 destroyTrack_l(record);
6763}
6764
6765void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6766{
6767 ThreadBase::getAudioPortConfig(config);
6768 config->role = AUDIO_PORT_ROLE_SINK;
6769 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6770 config->ext.mix.usecase.source = mAudioSource;
6771}
Eric Laurent1c333e22014-05-20 10:48:17 -07006772
Glenn Kasten63238ef2015-03-02 15:50:29 -08006773} // namespace android