blob: b30fd20b5a9f01ad8b4b819cd9bf6168da2146e6 [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();
3602 float speed, pitch;
3603 track->mAudioTrackServerProxy->getPlaybackRate(&speed, &pitch);
3604
3605 desiredFrames = sourceFramesNeededWithTimestretch(
3606 sampleRate, mNormalFrameCount, mSampleRate, speed);
3607 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3608 // add frames already consumed but not yet released by the resampler
3609 // because mAudioTrackServerProxy->framesReady() will include these frames
3610 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3611
Eric Laurent81784c32012-11-19 14:55:58 -08003612 uint32_t minFrames = 1;
3613 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3614 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003615 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003616 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003617
3618 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003619 if (ATRACE_ENABLED()) {
3620 // I wish we had formatted trace names
3621 char traceName[16];
3622 strcpy(traceName, "nRdy");
3623 int name = track->name();
3624 if (AudioMixer::TRACK0 <= name &&
3625 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3626 name -= AudioMixer::TRACK0;
3627 traceName[4] = (name / 10) + '0';
3628 traceName[5] = (name % 10) + '0';
3629 } else {
3630 traceName[4] = '?';
3631 traceName[5] = '?';
3632 }
3633 traceName[6] = '\0';
3634 ATRACE_INT(traceName, framesReady);
3635 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003636 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003637 !track->isPaused() && !track->isTerminated())
3638 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003639 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003640
3641 mixedTracks++;
3642
Andy Hung69aed5f2014-02-25 17:24:40 -08003643 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3644 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003645 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003646 if (track->mainBuffer() != mSinkBuffer &&
3647 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003648 if (mEffectBufferEnabled) {
3649 mEffectBufferValid = true; // Later can set directly.
3650 }
Eric Laurent81784c32012-11-19 14:55:58 -08003651 chain = getEffectChain_l(track->sessionId());
3652 // Delegate volume control to effect in track effect chain if needed
3653 if (chain != 0) {
3654 tracksWithEffect++;
3655 } else {
3656 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3657 "session %d",
3658 name, track->sessionId());
3659 }
3660 }
3661
3662
3663 int param = AudioMixer::VOLUME;
3664 if (track->mFillingUpStatus == Track::FS_FILLED) {
3665 // no ramp for the first volume setting
3666 track->mFillingUpStatus = Track::FS_ACTIVE;
3667 if (track->mState == TrackBase::RESUMING) {
3668 track->mState = TrackBase::ACTIVE;
3669 param = AudioMixer::RAMP_VOLUME;
3670 }
3671 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003672 // FIXME should not make a decision based on mServer
3673 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003674 // If the track is stopped before the first frame was mixed,
3675 // do not apply ramp
3676 param = AudioMixer::RAMP_VOLUME;
3677 }
3678
3679 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003680 uint32_t vl, vr; // in U8.24 integer format
3681 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003682 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003683 vl = vr = 0;
3684 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003685 if (track->isPausing()) {
3686 track->setPaused();
3687 }
3688 } else {
3689
3690 // read original volumes with volume control
3691 float typeVolume = mStreamTypes[track->streamType()].volume;
3692 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003693 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003694 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003695 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3696 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003697 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003698 if (vlf > GAIN_FLOAT_UNITY) {
3699 ALOGV("Track left volume out of range: %.3g", vlf);
3700 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003701 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003702 if (vrf > GAIN_FLOAT_UNITY) {
3703 ALOGV("Track right volume out of range: %.3g", vrf);
3704 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003705 }
3706 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003707 vlf *= v;
3708 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003709 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003710 // then derive vl and vr as U8.24 versions for the effect chain
3711 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3712 vl = (uint32_t) (scaleto8_24 * vlf);
3713 vr = (uint32_t) (scaleto8_24 * vrf);
3714 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003715 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003716 // send level comes from shared memory and so may be corrupt
3717 if (sendLevel > MAX_GAIN_INT) {
3718 ALOGV("Track send level out of range: %04X", sendLevel);
3719 sendLevel = MAX_GAIN_INT;
3720 }
Andy Hung6be49402014-05-30 10:42:03 -07003721 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3722 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003724
Eric Laurent81784c32012-11-19 14:55:58 -08003725 // Delegate volume control to effect in track effect chain if needed
3726 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3727 // Do not ramp volume if volume is controlled by effect
3728 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003729 // Update remaining floating point volume levels
3730 vlf = (float)vl / (1 << 24);
3731 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003732 track->mHasVolumeController = true;
3733 } else {
3734 // force no volume ramp when volume controller was just disabled or removed
3735 // from effect chain to avoid volume spike
3736 if (track->mHasVolumeController) {
3737 param = AudioMixer::VOLUME;
3738 }
3739 track->mHasVolumeController = false;
3740 }
3741
Eric Laurent81784c32012-11-19 14:55:58 -08003742 // XXX: these things DON'T need to be done each time
3743 mAudioMixer->setBufferProvider(name, track);
3744 mAudioMixer->enable(name);
3745
Andy Hung6be49402014-05-30 10:42:03 -07003746 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3747 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3748 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003749 mAudioMixer->setParameter(
3750 name,
3751 AudioMixer::TRACK,
3752 AudioMixer::FORMAT, (void *)track->format());
3753 mAudioMixer->setParameter(
3754 name,
3755 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003756 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003757 mAudioMixer->setParameter(
3758 name,
3759 AudioMixer::TRACK,
3760 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003761 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003762 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003763 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003764 if (reqSampleRate == 0) {
3765 reqSampleRate = mSampleRate;
3766 } else if (reqSampleRate > maxSampleRate) {
3767 reqSampleRate = maxSampleRate;
3768 }
Eric Laurent81784c32012-11-19 14:55:58 -08003769 mAudioMixer->setParameter(
3770 name,
3771 AudioMixer::RESAMPLE,
3772 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003773 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003774
3775 // set the playback rate as an float array {speed, pitch}
3776 float playbackRate[2];
3777 track->mAudioTrackServerProxy->getPlaybackRate(
3778 &playbackRate[0] /*speed*/, &playbackRate[1] /*pitch*/);
3779 mAudioMixer->setParameter(
3780 name,
3781 AudioMixer::TIMESTRETCH,
3782 AudioMixer::PLAYBACK_RATE,
3783 playbackRate);
3784
Andy Hung69aed5f2014-02-25 17:24:40 -08003785 /*
3786 * Select the appropriate output buffer for the track.
3787 *
Andy Hung98ef9782014-03-04 14:46:50 -08003788 * Tracks with effects go into their own effects chain buffer
3789 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003790 *
3791 * Other tracks can use mMixerBuffer for higher precision
3792 * channel accumulation. If this buffer is enabled
3793 * (mMixerBufferEnabled true), then selected tracks will accumulate
3794 * into it.
3795 *
3796 */
3797 if (mMixerBufferEnabled
3798 && (track->mainBuffer() == mSinkBuffer
3799 || track->mainBuffer() == mMixerBuffer)) {
3800 mAudioMixer->setParameter(
3801 name,
3802 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003803 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003804 mAudioMixer->setParameter(
3805 name,
3806 AudioMixer::TRACK,
3807 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3808 // TODO: override track->mainBuffer()?
3809 mMixerBufferValid = true;
3810 } else {
3811 mAudioMixer->setParameter(
3812 name,
3813 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003814 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003815 mAudioMixer->setParameter(
3816 name,
3817 AudioMixer::TRACK,
3818 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3819 }
Eric Laurent81784c32012-11-19 14:55:58 -08003820 mAudioMixer->setParameter(
3821 name,
3822 AudioMixer::TRACK,
3823 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3824
3825 // reset retry count
3826 track->mRetryCount = kMaxTrackRetries;
3827
3828 // If one track is ready, set the mixer ready if:
3829 // - the mixer was not ready during previous round OR
3830 // - no other track is not ready
3831 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3832 mixerStatus != MIXER_TRACKS_ENABLED) {
3833 mixerStatus = MIXER_TRACKS_READY;
3834 }
3835 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003836 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003837 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003838 }
Eric Laurent81784c32012-11-19 14:55:58 -08003839 // clear effect chain input buffer if an active track underruns to avoid sending
3840 // previous audio buffer again to effects
3841 chain = getEffectChain_l(track->sessionId());
3842 if (chain != 0) {
3843 chain->clearInputBuffer();
3844 }
3845
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003846 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003847 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3848 track->isStopped() || track->isPaused()) {
3849 // We have consumed all the buffers of this track.
3850 // Remove it from the list of active tracks.
3851 // TODO: use actual buffer filling status instead of latency when available from
3852 // audio HAL
3853 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3854 size_t framesWritten = mBytesWritten / mFrameSize;
3855 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3856 if (track->isStopped()) {
3857 track->reset();
3858 }
3859 tracksToRemove->add(track);
3860 }
3861 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003862 // No buffers for this track. Give it a few chances to
3863 // fill a buffer, then remove it from active list.
3864 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003865 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003866 tracksToRemove->add(track);
3867 // indicate to client process that the track was disabled because of underrun;
3868 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003869 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003870 // If one track is not ready, mark the mixer also not ready if:
3871 // - the mixer was ready during previous round OR
3872 // - no other track is ready
3873 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3874 mixerStatus != MIXER_TRACKS_READY) {
3875 mixerStatus = MIXER_TRACKS_ENABLED;
3876 }
3877 }
3878 mAudioMixer->disable(name);
3879 }
3880
3881 } // local variable scope to avoid goto warning
3882track_is_ready: ;
3883
3884 }
3885
3886 // Push the new FastMixer state if necessary
3887 bool pauseAudioWatchdog = false;
3888 if (didModify) {
3889 state->mFastTracksGen++;
3890 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3891 if (kUseFastMixer == FastMixer_Dynamic &&
3892 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3893 state->mCommand = FastMixerState::COLD_IDLE;
3894 state->mColdFutexAddr = &mFastMixerFutex;
3895 state->mColdGen++;
3896 mFastMixerFutex = 0;
3897 if (kUseFastMixer == FastMixer_Dynamic) {
3898 mNormalSink = mOutputSink;
3899 }
3900 // If we go into cold idle, need to wait for acknowledgement
3901 // so that fast mixer stops doing I/O.
3902 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3903 pauseAudioWatchdog = true;
3904 }
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
3906 if (sq != NULL) {
3907 sq->end(didModify);
3908 sq->push(block);
3909 }
3910#ifdef AUDIO_WATCHDOG
3911 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3912 mAudioWatchdog->pause();
3913 }
3914#endif
3915
3916 // Now perform the deferred reset on fast tracks that have stopped
3917 while (resetMask != 0) {
3918 size_t i = __builtin_ctz(resetMask);
3919 ALOG_ASSERT(i < count);
3920 resetMask &= ~(1 << i);
3921 sp<Track> t = mActiveTracks[i].promote();
3922 if (t == 0) {
3923 continue;
3924 }
3925 Track* track = t.get();
3926 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3927 track->reset();
3928 }
3929
3930 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003932
Eric Laurent97d547d2014-09-02 14:45:53 -07003933 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3934 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003935 }
3936
3937 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003938 // as long as there are effects we should clear the effects buffer, to avoid
3939 // passing a non-clean buffer to the effect chain
3940 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003941 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003942 // sink or mix buffer must be cleared if all tracks are connected to an
3943 // effect chain as in this case the mixer will not write to the sink or mix buffer
3944 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3946 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003948 if (mMixerBufferValid) {
3949 memset(mMixerBuffer, 0, mMixerBufferSize);
3950 // TODO: In testing, mSinkBuffer below need not be cleared because
3951 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3952 // after mixing.
3953 //
3954 // To enforce this guarantee:
3955 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3956 // (mixedTracks == 0 && fastTracks > 0))
3957 // must imply MIXER_TRACKS_READY.
3958 // Later, we may clear buffers regardless, and skip much of this logic.
3959 }
Andy Hung98ef9782014-03-04 14:46:50 -08003960 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003961 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003962 }
3963
3964 // if any fast tracks, then status is ready
3965 mMixerStatusIgnoringFastTracks = mixerStatus;
3966 if (fastTracks > 0) {
3967 mixerStatus = MIXER_TRACKS_READY;
3968 }
3969 return mixerStatus;
3970}
3971
3972// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003973int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3974 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003975{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003976 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003977}
3978
3979// deleteTrackName_l() must be called with ThreadBase::mLock held
3980void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3981{
3982 ALOGV("remove track (%d) and delete from mixer", name);
3983 mAudioMixer->deleteTrackName(name);
3984}
3985
Eric Laurent10351942014-05-08 18:49:52 -07003986// checkForNewParameter_l() must be called with ThreadBase::mLock held
3987bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3988 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003989{
Eric Laurent81784c32012-11-19 14:55:58 -08003990 bool reconfig = false;
3991
Eric Laurent10351942014-05-08 18:49:52 -07003992 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003993
Eric Laurent10351942014-05-08 18:49:52 -07003994 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3995 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003996 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003997 FastMixerStateQueue *sq = mFastMixer->sq();
3998 FastMixerState *state = sq->begin();
3999 if (!(state->mCommand & FastMixerState::IDLE)) {
4000 previousCommand = state->mCommand;
4001 state->mCommand = FastMixerState::HOT_IDLE;
4002 sq->end();
4003 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4004 } else {
4005 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 }
Eric Laurent10351942014-05-08 18:49:52 -07004007 }
Eric Laurent81784c32012-11-19 14:55:58 -08004008
Eric Laurent10351942014-05-08 18:49:52 -07004009 AudioParameter param = AudioParameter(keyValuePair);
4010 int value;
4011 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4012 reconfig = true;
4013 }
4014 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004015 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004016 status = BAD_VALUE;
4017 } else {
4018 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004019 reconfig = true;
4020 }
Eric Laurent10351942014-05-08 18:49:52 -07004021 }
4022 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004023 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004024 status = BAD_VALUE;
4025 } else {
4026 // no need to save value, since it's constant
4027 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004028 }
Eric Laurent10351942014-05-08 18:49:52 -07004029 }
4030 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4031 // do not accept frame count changes if tracks are open as the track buffer
4032 // size depends on frame count and correct behavior would not be guaranteed
4033 // if frame count is changed after track creation
4034 if (!mTracks.isEmpty()) {
4035 status = INVALID_OPERATION;
4036 } else {
4037 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004038 }
Eric Laurent10351942014-05-08 18:49:52 -07004039 }
4040 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004041#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004042 // when changing the audio output device, call addBatteryData to notify
4043 // the change
4044 if (mOutDevice != value) {
4045 uint32_t params = 0;
4046 // check whether speaker is on
4047 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4048 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004049 }
Eric Laurent10351942014-05-08 18:49:52 -07004050
4051 audio_devices_t deviceWithoutSpeaker
4052 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4053 // check if any other device (except speaker) is on
4054 if (value & deviceWithoutSpeaker ) {
4055 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4056 }
4057
4058 if (params != 0) {
4059 addBatteryData(params);
4060 }
4061 }
Eric Laurent81784c32012-11-19 14:55:58 -08004062#endif
4063
Eric Laurent10351942014-05-08 18:49:52 -07004064 // forward device change to effects that have requested to be
4065 // aware of attached audio device.
4066 if (value != AUDIO_DEVICE_NONE) {
4067 mOutDevice = value;
4068 for (size_t i = 0; i < mEffectChains.size(); i++) {
4069 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004070 }
4071 }
Eric Laurent10351942014-05-08 18:49:52 -07004072 }
Eric Laurent81784c32012-11-19 14:55:58 -08004073
Eric Laurent10351942014-05-08 18:49:52 -07004074 if (status == NO_ERROR) {
4075 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4076 keyValuePair.string());
4077 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004078 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004079 mStandby = true;
4080 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004081 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004082 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004083 }
Eric Laurent10351942014-05-08 18:49:52 -07004084 if (status == NO_ERROR && reconfig) {
4085 readOutputParameters_l();
4086 delete mAudioMixer;
4087 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4088 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004089 int name = getTrackName_l(mTracks[i]->mChannelMask,
4090 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004091 if (name < 0) {
4092 break;
4093 }
4094 mTracks[i]->mName = name;
4095 }
4096 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4097 }
Eric Laurent81784c32012-11-19 14:55:58 -08004098 }
4099
4100 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004101 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004102 FastMixerStateQueue *sq = mFastMixer->sq();
4103 FastMixerState *state = sq->begin();
4104 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4105 state->mCommand = previousCommand;
4106 sq->end();
4107 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4108 }
4109
4110 return reconfig;
4111}
4112
4113
4114void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4115{
4116 const size_t SIZE = 256;
4117 char buffer[SIZE];
4118 String8 result;
4119
4120 PlaybackThread::dumpInternals(fd, args);
4121
Elliott Hughes87cebad2014-05-22 10:14:43 -07004122 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004123
4124 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004125 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004126 copy.dump(fd);
4127
4128#ifdef STATE_QUEUE_DUMP
4129 // Similar for state queue
4130 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4131 observerCopy.dump(fd);
4132 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4133 mutatorCopy.dump(fd);
4134#endif
4135
Glenn Kasten46909e72013-02-26 09:20:22 -08004136#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004137 // Write the tee output to a .wav file
4138 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004139#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004140
4141#ifdef AUDIO_WATCHDOG
4142 if (mAudioWatchdog != 0) {
4143 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4144 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4145 wdCopy.dump(fd);
4146 }
4147#endif
4148}
4149
4150uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4151{
4152 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4153}
4154
4155uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4156{
4157 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4158}
4159
4160void AudioFlinger::MixerThread::cacheParameters_l()
4161{
4162 PlaybackThread::cacheParameters_l();
4163
4164 // FIXME: Relaxed timing because of a certain device that can't meet latency
4165 // Should be reduced to 2x after the vendor fixes the driver issue
4166 // increase threshold again due to low power audio mode. The way this warning
4167 // threshold is calculated and its usefulness should be reconsidered anyway.
4168 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4169}
4170
4171// ----------------------------------------------------------------------------
4172
4173AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4174 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4175 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4176 // mLeftVolFloat, mRightVolFloat
4177{
4178}
4179
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4181 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4182 ThreadBase::type_t type)
4183 : PlaybackThread(audioFlinger, output, id, device, type)
4184 // mLeftVolFloat, mRightVolFloat
4185{
4186}
4187
Eric Laurent81784c32012-11-19 14:55:58 -08004188AudioFlinger::DirectOutputThread::~DirectOutputThread()
4189{
4190}
4191
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4193{
4194 audio_track_cblk_t* cblk = track->cblk();
4195 float left, right;
4196
4197 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4198 left = right = 0;
4199 } else {
4200 float typeVolume = mStreamTypes[track->streamType()].volume;
4201 float v = mMasterVolume * typeVolume;
4202 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004203 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4204 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4205 if (left > GAIN_FLOAT_UNITY) {
4206 left = GAIN_FLOAT_UNITY;
4207 }
4208 left *= v;
4209 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4210 if (right > GAIN_FLOAT_UNITY) {
4211 right = GAIN_FLOAT_UNITY;
4212 }
4213 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 }
4215
4216 if (lastTrack) {
4217 if (left != mLeftVolFloat || right != mRightVolFloat) {
4218 mLeftVolFloat = left;
4219 mRightVolFloat = right;
4220
4221 // Convert volumes from float to 8.24
4222 uint32_t vl = (uint32_t)(left * (1 << 24));
4223 uint32_t vr = (uint32_t)(right * (1 << 24));
4224
4225 // Delegate volume control to effect in track effect chain if needed
4226 // only one effect chain can be present on DirectOutputThread, so if
4227 // there is one, the track is connected to it
4228 if (!mEffectChains.isEmpty()) {
4229 mEffectChains[0]->setVolume_l(&vl, &vr);
4230 left = (float)vl / (1 << 24);
4231 right = (float)vr / (1 << 24);
4232 }
4233 if (mOutput->stream->set_volume) {
4234 mOutput->stream->set_volume(mOutput->stream, left, right);
4235 }
4236 }
4237 }
4238}
4239
4240
Eric Laurent81784c32012-11-19 14:55:58 -08004241AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4242 Vector< sp<Track> > *tracksToRemove
4243)
4244{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004245 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004246 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004247 bool doHwPause = false;
4248 bool doHwResume = false;
4249 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004250
4251 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004252 for (size_t i = 0; i < count; i++) {
4253 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004254 // The track died recently
4255 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004256 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004257 }
4258
4259 Track* const track = t.get();
4260 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004261 // Only consider last track started for volume and mixer state control.
4262 // In theory an older track could underrun and restart after the new one starts
4263 // but as we only care about the transition phase between two tracks on a
4264 // direct output, it is not a problem to ignore the underrun case.
4265 sp<Track> l = mLatestActiveTrack.promote();
4266 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004267
Eric Laurentd1f69b02014-12-15 14:33:13 -08004268 if (mHwSupportsPause && track->isPausing()) {
4269 track->setPaused();
4270 if (last && !mHwPaused) {
4271 doHwPause = true;
4272 mHwPaused = true;
4273 }
4274 tracksToRemove->add(track);
4275 } else if (track->isFlushPending()) {
4276 track->flushAck();
4277 if (last) {
4278 flushPending = true;
4279 }
4280 } else if (mHwSupportsPause && track->isResumePending()){
4281 track->resumeAck();
4282 if (last) {
4283 if (mHwPaused) {
4284 doHwResume = true;
4285 mHwPaused = false;
4286 }
4287 }
4288 }
4289
Eric Laurent81784c32012-11-19 14:55:58 -08004290 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004291 // for all its buffers to be filled before processing it.
4292 // Allow draining the buffer in case the client
4293 // app does not call stop() and relies on underrun to stop:
4294 // hence the test on (track->mRetryCount > 1).
4295 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004296 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004297 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4298 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004299 minFrames = mNormalFrameCount;
4300 } else {
4301 minFrames = 1;
4302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004303
Eric Laurentab5cdba2014-06-09 17:22:27 -07004304 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4305 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004306 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004307 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004308
4309 if (track->mFillingUpStatus == Track::FS_FILLED) {
4310 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004311 // make sure processVolume_l() will apply new volume even if 0
4312 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004313 if (!mHwSupportsPause) {
4314 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004315 }
4316 }
4317
4318 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004319 processVolume_l(track, last);
4320 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004321 // reset retry count
4322 track->mRetryCount = kMaxTrackRetriesDirect;
4323 mActiveTrack = t;
4324 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004325 if (usesHwAvSync() && mHwPaused) {
4326 doHwResume = true;
4327 mHwPaused = false;
4328 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004329 }
Eric Laurent81784c32012-11-19 14:55:58 -08004330 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004331 // clear effect chain input buffer if the last active track started underruns
4332 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004333 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004334 mEffectChains[0]->clearInputBuffer();
4335 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004336 if (track->isStopping_1()) {
4337 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004338 if (last && mHwPaused) {
4339 doHwResume = true;
4340 mHwPaused = false;
4341 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004342 }
4343 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4344 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004345 // We have consumed all the buffers of this track.
4346 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004347 size_t audioHALFrames;
4348 if (audio_is_linear_pcm(mFormat)) {
4349 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4350 } else {
4351 audioHALFrames = 0;
4352 }
4353
Eric Laurent81784c32012-11-19 14:55:58 -08004354 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004355 if (mStandby || !last ||
4356 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004357 if (track->isStopping_2()) {
4358 track->mState = TrackBase::STOPPED;
4359 }
Eric Laurent81784c32012-11-19 14:55:58 -08004360 if (track->isStopped()) {
4361 track->reset();
4362 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004363 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004364 }
4365 } else {
4366 // No buffers for this track. Give it a few chances to
4367 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004368 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004369 if (--(track->mRetryCount) <= 0) {
4370 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004371 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004372 // indicate to client process that the track was disabled because of underrun;
4373 // it will then automatically call start() when data is available
4374 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004376 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004377 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4378 doHwPause = true;
4379 mHwPaused = true;
4380 }
Eric Laurent81784c32012-11-19 14:55:58 -08004381 }
4382 }
4383 }
4384 }
4385
Eric Laurentd1f69b02014-12-15 14:33:13 -08004386 // if an active track did not command a flush, check for pending flush on stopped tracks
4387 if (!flushPending) {
4388 for (size_t i = 0; i < mTracks.size(); i++) {
4389 if (mTracks[i]->isFlushPending()) {
4390 mTracks[i]->flushAck();
4391 flushPending = true;
4392 }
4393 }
4394 }
4395
4396 // make sure the pause/flush/resume sequence is executed in the right order.
4397 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4398 // before flush and then resume HW. This can happen in case of pause/flush/resume
4399 // if resume is received before pause is executed.
4400 if (mHwSupportsPause && !mStandby &&
4401 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4402 mOutput->stream->pause(mOutput->stream);
4403 }
4404 if (flushPending) {
4405 flushHw_l();
4406 }
4407 if (mHwSupportsPause && !mStandby && doHwResume) {
4408 mOutput->stream->resume(mOutput->stream);
4409 }
Eric Laurent81784c32012-11-19 14:55:58 -08004410 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004411 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004412
4413 return mixerStatus;
4414}
4415
4416void AudioFlinger::DirectOutputThread::threadLoop_mix()
4417{
Eric Laurent81784c32012-11-19 14:55:58 -08004418 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004419 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004420 // output audio to hardware
4421 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004422 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004423 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004424 status_t status = mActiveTrack->getNextBuffer(&buffer);
4425 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004426 memset(curBuf, 0, frameCount * mFrameSize);
4427 break;
4428 }
4429 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4430 frameCount -= buffer.frameCount;
4431 curBuf += buffer.frameCount * mFrameSize;
4432 mActiveTrack->releaseBuffer(&buffer);
4433 }
Andy Hung2098f272014-02-27 14:00:06 -08004434 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004435 sleepTime = 0;
4436 standbyTime = systemTime() + standbyDelay;
4437 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004438}
4439
4440void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4441{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004442 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004443 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004444 sleepTime = idleSleepTime;
4445 return;
4446 }
Eric Laurent81784c32012-11-19 14:55:58 -08004447 if (sleepTime == 0) {
4448 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4449 sleepTime = activeSleepTime;
4450 } else {
4451 sleepTime = idleSleepTime;
4452 }
4453 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004454 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004455 sleepTime = 0;
4456 }
4457}
4458
Eric Laurentd1f69b02014-12-15 14:33:13 -08004459void AudioFlinger::DirectOutputThread::threadLoop_exit()
4460{
4461 {
4462 Mutex::Autolock _l(mLock);
4463 bool flushPending = false;
4464 for (size_t i = 0; i < mTracks.size(); i++) {
4465 if (mTracks[i]->isFlushPending()) {
4466 mTracks[i]->flushAck();
4467 flushPending = true;
4468 }
4469 }
4470 if (flushPending) {
4471 flushHw_l();
4472 }
4473 }
4474 PlaybackThread::threadLoop_exit();
4475}
4476
4477// must be called with thread mutex locked
4478bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4479{
4480 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004481 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004482
4483 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4484 // after a timeout and we will enter standby then.
4485 if (mTracks.size() > 0) {
4486 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004487 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4488 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004489 }
4490
Eric Laurentb369caf2015-03-30 20:51:47 -07004491 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004492}
4493
Eric Laurent81784c32012-11-19 14:55:58 -08004494// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004495int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004496 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004497{
4498 return 0;
4499}
4500
4501// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004502void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004503{
4504}
4505
Eric Laurent10351942014-05-08 18:49:52 -07004506// checkForNewParameter_l() must be called with ThreadBase::mLock held
4507bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4508 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004509{
4510 bool reconfig = false;
4511
Eric Laurent10351942014-05-08 18:49:52 -07004512 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004513
Eric Laurent10351942014-05-08 18:49:52 -07004514 AudioParameter param = AudioParameter(keyValuePair);
4515 int value;
4516 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4517 // forward device change to effects that have requested to be
4518 // aware of attached audio device.
4519 if (value != AUDIO_DEVICE_NONE) {
4520 mOutDevice = value;
4521 for (size_t i = 0; i < mEffectChains.size(); i++) {
4522 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004523 }
4524 }
Eric Laurent81784c32012-11-19 14:55:58 -08004525 }
Eric Laurent10351942014-05-08 18:49:52 -07004526 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4527 // do not accept frame count changes if tracks are open as the track buffer
4528 // size depends on frame count and correct behavior would not be garantied
4529 // if frame count is changed after track creation
4530 if (!mTracks.isEmpty()) {
4531 status = INVALID_OPERATION;
4532 } else {
4533 reconfig = true;
4534 }
4535 }
4536 if (status == NO_ERROR) {
4537 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4538 keyValuePair.string());
4539 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004540 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004541 mStandby = true;
4542 mBytesWritten = 0;
4543 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4544 keyValuePair.string());
4545 }
4546 if (status == NO_ERROR && reconfig) {
4547 readOutputParameters_l();
4548 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4549 }
4550 }
4551
Eric Laurent81784c32012-11-19 14:55:58 -08004552 return reconfig;
4553}
4554
4555uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4556{
4557 uint32_t time;
4558 if (audio_is_linear_pcm(mFormat)) {
4559 time = PlaybackThread::activeSleepTimeUs();
4560 } else {
4561 time = 10000;
4562 }
4563 return time;
4564}
4565
4566uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4567{
4568 uint32_t time;
4569 if (audio_is_linear_pcm(mFormat)) {
4570 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4571 } else {
4572 time = 10000;
4573 }
4574 return time;
4575}
4576
4577uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4578{
4579 uint32_t time;
4580 if (audio_is_linear_pcm(mFormat)) {
4581 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4582 } else {
4583 time = 10000;
4584 }
4585 return time;
4586}
4587
4588void AudioFlinger::DirectOutputThread::cacheParameters_l()
4589{
4590 PlaybackThread::cacheParameters_l();
4591
4592 // use shorter standby delay as on normal output to release
4593 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004594 // no delay on outputs with HW A/V sync
4595 if (usesHwAvSync()) {
4596 standbyDelay = 0;
4597 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004598 standbyDelay = microseconds(activeSleepTime*2);
4599 } else {
4600 standbyDelay = kOffloadStandbyDelayNs;
4601 }
Eric Laurent81784c32012-11-19 14:55:58 -08004602}
4603
Eric Laurente659ef42014-09-29 13:06:46 -07004604void AudioFlinger::DirectOutputThread::flushHw_l()
4605{
Phil Burk062e67a2015-02-11 13:40:50 -08004606 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004607 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004608}
4609
Eric Laurent81784c32012-11-19 14:55:58 -08004610// ----------------------------------------------------------------------------
4611
Eric Laurentbfb1b832013-01-07 09:53:42 -08004612AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004613 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004615 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004616 mWriteAckSequence(0),
4617 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618{
4619}
4620
4621AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4622{
4623}
4624
4625void AudioFlinger::AsyncCallbackThread::onFirstRef()
4626{
4627 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4628}
4629
4630bool AudioFlinger::AsyncCallbackThread::threadLoop()
4631{
4632 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004633 uint32_t writeAckSequence;
4634 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004635
4636 {
4637 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004638 while (!((mWriteAckSequence & 1) ||
4639 (mDrainSequence & 1) ||
4640 exitPending())) {
4641 mWaitWorkCV.wait(mLock);
4642 }
4643
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 if (exitPending()) {
4645 break;
4646 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004647 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4648 mWriteAckSequence, mDrainSequence);
4649 writeAckSequence = mWriteAckSequence;
4650 mWriteAckSequence &= ~1;
4651 drainSequence = mDrainSequence;
4652 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004653 }
4654 {
Eric Laurent4de95592013-09-26 15:28:21 -07004655 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4656 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004657 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004658 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004660 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004661 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004662 }
4663 }
4664 }
4665 }
4666 return false;
4667}
4668
4669void AudioFlinger::AsyncCallbackThread::exit()
4670{
4671 ALOGV("AsyncCallbackThread::exit");
4672 Mutex::Autolock _l(mLock);
4673 requestExit();
4674 mWaitWorkCV.broadcast();
4675}
4676
Eric Laurent3b4529e2013-09-05 18:09:19 -07004677void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004678{
4679 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004680 // bit 0 is cleared
4681 mWriteAckSequence = sequence << 1;
4682}
4683
4684void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4685{
4686 Mutex::Autolock _l(mLock);
4687 // ignore unexpected callbacks
4688 if (mWriteAckSequence & 2) {
4689 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004690 mWaitWorkCV.signal();
4691 }
4692}
4693
Eric Laurent3b4529e2013-09-05 18:09:19 -07004694void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695{
4696 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004697 // bit 0 is cleared
4698 mDrainSequence = sequence << 1;
4699}
4700
4701void AudioFlinger::AsyncCallbackThread::resetDraining()
4702{
4703 Mutex::Autolock _l(mLock);
4704 // ignore unexpected callbacks
4705 if (mDrainSequence & 2) {
4706 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707 mWaitWorkCV.signal();
4708 }
4709}
4710
4711
4712// ----------------------------------------------------------------------------
4713AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4714 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4715 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004716 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717{
Eric Laurentfd477972013-10-25 18:10:40 -07004718 //FIXME: mStandby should be set to true by ThreadBase constructor
4719 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004720}
4721
Eric Laurentbfb1b832013-01-07 09:53:42 -08004722void AudioFlinger::OffloadThread::threadLoop_exit()
4723{
4724 if (mFlushPending || mHwPaused) {
4725 // If a flush is pending or track was paused, just discard buffered data
4726 flushHw_l();
4727 } else {
4728 mMixerStatus = MIXER_DRAIN_ALL;
4729 threadLoop_drain();
4730 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004731 if (mUseAsyncWrite) {
4732 ALOG_ASSERT(mCallbackThread != 0);
4733 mCallbackThread->exit();
4734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 PlaybackThread::threadLoop_exit();
4736}
4737
4738AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4739 Vector< sp<Track> > *tracksToRemove
4740)
4741{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004742 size_t count = mActiveTracks.size();
4743
4744 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004745 bool doHwPause = false;
4746 bool doHwResume = false;
4747
Eric Laurentede6c3b2013-09-19 14:37:46 -07004748 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4749
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750 // find out which tracks need to be processed
4751 for (size_t i = 0; i < count; i++) {
4752 sp<Track> t = mActiveTracks[i].promote();
4753 // The track died recently
4754 if (t == 0) {
4755 continue;
4756 }
4757 Track* const track = t.get();
4758 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004759 // Only consider last track started for volume and mixer state control.
4760 // In theory an older track could underrun and restart after the new one starts
4761 // but as we only care about the transition phase between two tracks on a
4762 // direct output, it is not a problem to ignore the underrun case.
4763 sp<Track> l = mLatestActiveTrack.promote();
4764 bool last = l.get() == track;
4765
Haynes Mathew George7844f672014-01-15 12:32:55 -08004766 if (track->isInvalid()) {
4767 ALOGW("An invalidated track shouldn't be in active list");
4768 tracksToRemove->add(track);
4769 continue;
4770 }
4771
4772 if (track->mState == TrackBase::IDLE) {
4773 ALOGW("An idle track shouldn't be in active list");
4774 continue;
4775 }
4776
Eric Laurentbfb1b832013-01-07 09:53:42 -08004777 if (track->isPausing()) {
4778 track->setPaused();
4779 if (last) {
4780 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004781 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004782 mHwPaused = true;
4783 }
4784 // If we were part way through writing the mixbuffer to
4785 // the HAL we must save this until we resume
4786 // BUG - this will be wrong if a different track is made active,
4787 // in that case we want to discard the pending data in the
4788 // mixbuffer and tell the client to present it again when the
4789 // track is resumed
4790 mPausedWriteLength = mCurrentWriteLength;
4791 mPausedBytesRemaining = mBytesRemaining;
4792 mBytesRemaining = 0; // stop writing
4793 }
4794 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004795 } else if (track->isFlushPending()) {
4796 track->flushAck();
4797 if (last) {
4798 mFlushPending = true;
4799 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004800 } else if (track->isResumePending()){
4801 track->resumeAck();
4802 if (last) {
4803 if (mPausedBytesRemaining) {
4804 // Need to continue write that was interrupted
4805 mCurrentWriteLength = mPausedWriteLength;
4806 mBytesRemaining = mPausedBytesRemaining;
4807 mPausedBytesRemaining = 0;
4808 }
4809 if (mHwPaused) {
4810 doHwResume = true;
4811 mHwPaused = false;
4812 // threadLoop_mix() will handle the case that we need to
4813 // resume an interrupted write
4814 }
4815 // enable write to audio HAL
4816 sleepTime = 0;
4817
4818 // Do not handle new data in this iteration even if track->framesReady()
4819 mixerStatus = MIXER_TRACKS_ENABLED;
4820 }
4821 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004822 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004823 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824 if (track->mFillingUpStatus == Track::FS_FILLED) {
4825 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004826 // make sure processVolume_l() will apply new volume even if 0
4827 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 }
4829
4830 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004831 sp<Track> previousTrack = mPreviousTrack.promote();
4832 if (previousTrack != 0) {
4833 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004834 // Flush any data still being written from last track
4835 mBytesRemaining = 0;
4836 if (mPausedBytesRemaining) {
4837 // Last track was paused so we also need to flush saved
4838 // mixbuffer state and invalidate track so that it will
4839 // re-submit that unwritten data when it is next resumed
4840 mPausedBytesRemaining = 0;
4841 // Invalidate is a bit drastic - would be more efficient
4842 // to have a flag to tell client that some of the
4843 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004844 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004845 }
4846 // flush data already sent to the DSP if changing audio session as audio
4847 // comes from a different source. Also invalidate previous track to force a
4848 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004849 if (previousTrack->sessionId() != track->sessionId()) {
4850 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004851 }
4852 }
4853 }
4854 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855 // reset retry count
4856 track->mRetryCount = kMaxTrackRetriesOffload;
4857 mActiveTrack = t;
4858 mixerStatus = MIXER_TRACKS_READY;
4859 }
4860 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004861 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862 if (track->isStopping_1()) {
4863 // Hardware buffer can hold a large amount of audio so we must
4864 // wait for all current track's data to drain before we say
4865 // that the track is stopped.
4866 if (mBytesRemaining == 0) {
4867 // Only start draining when all data in mixbuffer
4868 // has been written
4869 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4870 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004871 // do not drain if no data was ever sent to HAL (mStandby == true)
4872 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004873 // do not modify drain sequence if we are already draining. This happens
4874 // when resuming from pause after drain.
4875 if ((mDrainSequence & 1) == 0) {
4876 sleepTime = 0;
4877 standbyTime = systemTime() + standbyDelay;
4878 mixerStatus = MIXER_DRAIN_TRACK;
4879 mDrainSequence += 2;
4880 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 if (mHwPaused) {
4882 // It is possible to move from PAUSED to STOPPING_1 without
4883 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004884 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004885 mHwPaused = false;
4886 }
4887 }
4888 }
4889 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004890 // Drain has completed or we are in standby, signal presentation complete
4891 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004892 track->mState = TrackBase::STOPPED;
4893 size_t audioHALFrames =
4894 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4895 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08004896 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004897 track->presentationComplete(framesWritten, audioHALFrames);
4898 track->reset();
4899 tracksToRemove->add(track);
4900 }
4901 } else {
4902 // No buffers for this track. Give it a few chances to
4903 // fill a buffer, then remove it from active list.
4904 if (--(track->mRetryCount) <= 0) {
4905 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4906 track->name());
4907 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004908 // indicate to client process that the track was disabled because of underrun;
4909 // it will then automatically call start() when data is available
4910 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 } else if (last){
4912 mixerStatus = MIXER_TRACKS_ENABLED;
4913 }
4914 }
4915 }
4916 // compute volume for this track
4917 processVolume_l(track, last);
4918 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004919
Eric Laurentea0fade2013-10-04 16:23:48 -07004920 // make sure the pause/flush/resume sequence is executed in the right order.
4921 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4922 // before flush and then resume HW. This can happen in case of pause/flush/resume
4923 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004924 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004925 mOutput->stream->pause(mOutput->stream);
4926 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004927 if (mFlushPending) {
4928 flushHw_l();
4929 mFlushPending = false;
4930 }
Eric Laurentfd477972013-10-25 18:10:40 -07004931 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004932 mOutput->stream->resume(mOutput->stream);
4933 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004934
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935 // remove all the tracks that need to be...
4936 removeTracks_l(*tracksToRemove);
4937
4938 return mixerStatus;
4939}
4940
Eric Laurentbfb1b832013-01-07 09:53:42 -08004941// must be called with thread mutex locked
4942bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4943{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004944 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4945 mWriteAckSequence, mDrainSequence);
4946 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004947 return true;
4948 }
4949 return false;
4950}
4951
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4953{
4954 Mutex::Autolock _l(mLock);
4955 return waitingAsyncCallback_l();
4956}
4957
4958void AudioFlinger::OffloadThread::flushHw_l()
4959{
Eric Laurente659ef42014-09-29 13:06:46 -07004960 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004961 // Flush anything still waiting in the mixbuffer
4962 mCurrentWriteLength = 0;
4963 mBytesRemaining = 0;
4964 mPausedWriteLength = 0;
4965 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004966
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004968 // discard any pending drain or write ack by incrementing sequence
4969 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4970 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004971 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004972 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4973 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004974 }
4975}
4976
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004977void AudioFlinger::OffloadThread::onAddNewTrack_l()
4978{
4979 sp<Track> previousTrack = mPreviousTrack.promote();
4980 sp<Track> latestTrack = mLatestActiveTrack.promote();
4981
4982 if (previousTrack != 0 && latestTrack != 0 &&
4983 (previousTrack->sessionId() != latestTrack->sessionId())) {
4984 mFlushPending = true;
4985 }
4986 PlaybackThread::onAddNewTrack_l();
4987}
4988
Eric Laurentbfb1b832013-01-07 09:53:42 -08004989// ----------------------------------------------------------------------------
4990
Eric Laurent81784c32012-11-19 14:55:58 -08004991AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4992 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4993 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4994 DUPLICATING),
4995 mWaitTimeMs(UINT_MAX)
4996{
4997 addOutputTrack(mainThread);
4998}
4999
5000AudioFlinger::DuplicatingThread::~DuplicatingThread()
5001{
5002 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5003 mOutputTracks[i]->destroy();
5004 }
5005}
5006
5007void AudioFlinger::DuplicatingThread::threadLoop_mix()
5008{
5009 // mix buffers...
5010 if (outputsReady(outputTracks)) {
5011 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5012 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005013 if (mMixerBufferValid) {
5014 memset(mMixerBuffer, 0, mMixerBufferSize);
5015 } else {
5016 memset(mSinkBuffer, 0, mSinkBufferSize);
5017 }
Eric Laurent81784c32012-11-19 14:55:58 -08005018 }
5019 sleepTime = 0;
5020 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005021 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 standbyTime = systemTime() + standbyDelay;
5023}
5024
5025void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5026{
5027 if (sleepTime == 0) {
5028 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5029 sleepTime = activeSleepTime;
5030 } else {
5031 sleepTime = idleSleepTime;
5032 }
5033 } else if (mBytesWritten != 0) {
5034 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5035 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005036 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005037 } else {
5038 // flush remaining overflow buffers in output tracks
5039 writeFrames = 0;
5040 }
5041 sleepTime = 0;
5042 }
5043}
5044
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005046{
5047 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005048 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005049 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005050 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005051 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005052}
5053
5054void AudioFlinger::DuplicatingThread::threadLoop_standby()
5055{
5056 // DuplicatingThread implements standby by stopping all tracks
5057 for (size_t i = 0; i < outputTracks.size(); i++) {
5058 outputTracks[i]->stop();
5059 }
5060}
5061
5062void AudioFlinger::DuplicatingThread::saveOutputTracks()
5063{
5064 outputTracks = mOutputTracks;
5065}
5066
5067void AudioFlinger::DuplicatingThread::clearOutputTracks()
5068{
5069 outputTracks.clear();
5070}
5071
5072void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5073{
5074 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005075 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5076 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5077 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5078 const size_t frameCount =
5079 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5080 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5081 // from different OutputTracks and their associated MixerThreads (e.g. one may
5082 // nearly empty and the other may be dropping data).
5083
5084 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005085 this,
5086 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005087 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005088 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005089 frameCount,
5090 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005091 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005092 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005093 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005094 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005095 updateWaitTime_l();
5096 }
5097}
5098
5099void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5100{
5101 Mutex::Autolock _l(mLock);
5102 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5103 if (mOutputTracks[i]->thread() == thread) {
5104 mOutputTracks[i]->destroy();
5105 mOutputTracks.removeAt(i);
5106 updateWaitTime_l();
5107 return;
5108 }
5109 }
5110 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5111}
5112
5113// caller must hold mLock
5114void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5115{
5116 mWaitTimeMs = UINT_MAX;
5117 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5118 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5119 if (strong != 0) {
5120 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5121 if (waitTimeMs < mWaitTimeMs) {
5122 mWaitTimeMs = waitTimeMs;
5123 }
5124 }
5125 }
5126}
5127
5128
5129bool AudioFlinger::DuplicatingThread::outputsReady(
5130 const SortedVector< sp<OutputTrack> > &outputTracks)
5131{
5132 for (size_t i = 0; i < outputTracks.size(); i++) {
5133 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5134 if (thread == 0) {
5135 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5136 outputTracks[i].get());
5137 return false;
5138 }
5139 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5140 // see note at standby() declaration
5141 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5142 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5143 thread.get());
5144 return false;
5145 }
5146 }
5147 return true;
5148}
5149
5150uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5151{
5152 return (mWaitTimeMs * 1000) / 2;
5153}
5154
5155void AudioFlinger::DuplicatingThread::cacheParameters_l()
5156{
5157 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5158 updateWaitTime_l();
5159
5160 MixerThread::cacheParameters_l();
5161}
5162
5163// ----------------------------------------------------------------------------
5164// Record
5165// ----------------------------------------------------------------------------
5166
5167AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5168 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005169 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005170 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005171 audio_devices_t inDevice
5172#ifdef TEE_SINK
5173 , const sp<NBAIO_Sink>& teeSink
5174#endif
5175 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005176 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005177 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005178 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005179 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005180#ifdef TEE_SINK
5181 , mTeeSink(teeSink)
5182#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005183 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5184 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005185 // mFastCapture below
5186 , mFastCaptureFutex(0)
5187 // mInputSource
5188 // mPipeSink
5189 // mPipeSource
5190 , mPipeFramesP2(0)
5191 // mPipeMemory
5192 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005193 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005194{
Glenn Kastend7dca052015-03-05 16:05:54 -08005195 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5196 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005197
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005198 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005199
5200 // create an NBAIO source for the HAL input stream, and negotiate
5201 mInputSource = new AudioStreamInSource(input->stream);
5202 size_t numCounterOffers = 0;
5203 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5204 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5205 ALOG_ASSERT(index == 0);
5206
5207 // initialize fast capture depending on configuration
5208 bool initFastCapture;
5209 switch (kUseFastCapture) {
5210 case FastCapture_Never:
5211 initFastCapture = false;
5212 break;
5213 case FastCapture_Always:
5214 initFastCapture = true;
5215 break;
5216 case FastCapture_Static:
5217 uint32_t primaryOutputSampleRate;
5218 {
5219 AutoMutex _l(audioFlinger->mHardwareLock);
5220 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5221 }
5222 initFastCapture =
5223 // either capture sample rate is same as (a reasonable) primary output sample rate
5224 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5225 (mSampleRate == primaryOutputSampleRate)) ||
5226 // or primary output sample rate is unknown, and capture sample rate is reasonable
5227 ((primaryOutputSampleRate == 0) &&
5228 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005229 // and the buffer size is < 12 ms
5230 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005231 break;
5232 // case FastCapture_Dynamic:
5233 }
5234
5235 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005236 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005237 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005238 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005239 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5240 void *pipeBuffer;
5241 const sp<MemoryDealer> roHeap(readOnlyHeap());
5242 sp<IMemory> pipeMemory;
5243 if ((roHeap == 0) ||
5244 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5245 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5246 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5247 goto failed;
5248 }
5249 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5250 memset(pipeBuffer, 0, pipeSize);
5251 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5252 const NBAIO_Format offers[1] = {format};
5253 size_t numCounterOffers = 0;
5254 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5255 ALOG_ASSERT(index == 0);
5256 mPipeSink = pipe;
5257 PipeReader *pipeReader = new PipeReader(*pipe);
5258 numCounterOffers = 0;
5259 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5260 ALOG_ASSERT(index == 0);
5261 mPipeSource = pipeReader;
5262 mPipeFramesP2 = pipeFramesP2;
5263 mPipeMemory = pipeMemory;
5264
5265 // create fast capture
5266 mFastCapture = new FastCapture();
5267 FastCaptureStateQueue *sq = mFastCapture->sq();
5268#ifdef STATE_QUEUE_DUMP
5269 // FIXME
5270#endif
5271 FastCaptureState *state = sq->begin();
5272 state->mCblk = NULL;
5273 state->mInputSource = mInputSource.get();
5274 state->mInputSourceGen++;
5275 state->mPipeSink = pipe;
5276 state->mPipeSinkGen++;
5277 state->mFrameCount = mFrameCount;
5278 state->mCommand = FastCaptureState::COLD_IDLE;
5279 // already done in constructor initialization list
5280 //mFastCaptureFutex = 0;
5281 state->mColdFutexAddr = &mFastCaptureFutex;
5282 state->mColdGen++;
5283 state->mDumpState = &mFastCaptureDumpState;
5284#ifdef TEE_SINK
5285 // FIXME
5286#endif
5287 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5288 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5289 sq->end();
5290 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5291
5292 // start the fast capture
5293 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5294 pid_t tid = mFastCapture->getTid();
5295 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5296 if (err != 0) {
5297 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5298 kPriorityFastCapture, getpid_cached, tid, err);
5299 }
5300
5301#ifdef AUDIO_WATCHDOG
5302 // FIXME
5303#endif
5304
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005305 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005306 }
5307failed: ;
5308
5309 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005310}
5311
Eric Laurent81784c32012-11-19 14:55:58 -08005312AudioFlinger::RecordThread::~RecordThread()
5313{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005314 if (mFastCapture != 0) {
5315 FastCaptureStateQueue *sq = mFastCapture->sq();
5316 FastCaptureState *state = sq->begin();
5317 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5318 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5319 if (old == -1) {
5320 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5321 }
5322 }
5323 state->mCommand = FastCaptureState::EXIT;
5324 sq->end();
5325 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5326 mFastCapture->join();
5327 mFastCapture.clear();
5328 }
5329 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005330 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005331 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005332}
5333
5334void AudioFlinger::RecordThread::onFirstRef()
5335{
Glenn Kastend7dca052015-03-05 16:05:54 -08005336 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005337}
5338
Eric Laurent81784c32012-11-19 14:55:58 -08005339bool AudioFlinger::RecordThread::threadLoop()
5340{
Eric Laurent81784c32012-11-19 14:55:58 -08005341 nsecs_t lastWarning = 0;
5342
5343 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005344
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005345reacquire_wakelock:
5346 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005347 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005348 {
5349 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005350 size_t size = mActiveTracks.size();
5351 activeTracksGen = mActiveTracksGen;
5352 if (size > 0) {
5353 // FIXME an arbitrary choice
5354 activeTrack = mActiveTracks[0];
5355 acquireWakeLock_l(activeTrack->uid());
5356 if (size > 1) {
5357 SortedVector<int> tmp;
5358 for (size_t i = 0; i < size; i++) {
5359 tmp.add(mActiveTracks[i]->uid());
5360 }
5361 updateWakeLockUids_l(tmp);
5362 }
5363 } else {
5364 acquireWakeLock_l(-1);
5365 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005366 }
5367
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005368 // used to request a deferred sleep, to be executed later while mutex is unlocked
5369 uint32_t sleepUs = 0;
5370
5371 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005372 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005373 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005374
Glenn Kasten5edadd42013-08-14 16:30:49 -07005375 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005376 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005377 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005378 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005379 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005380 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005381 }
5382
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005383 // activeTracks accumulates a copy of a subset of mActiveTracks
5384 Vector< sp<RecordTrack> > activeTracks;
5385
Glenn Kasten735f45f2014-08-18 15:51:59 -07005386 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005387 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005388
Glenn Kasten735f45f2014-08-18 15:51:59 -07005389 // reference to a fast track which is about to be removed
5390 sp<RecordTrack> fastTrackToRemove;
5391
Eric Laurent81784c32012-11-19 14:55:58 -08005392 { // scope for mLock
5393 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005394
Eric Laurent021cf962014-05-13 10:18:14 -07005395 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005396
Eric Laurent000a4192014-01-29 15:17:32 -08005397 // check exitPending here because checkForNewParameters_l() and
5398 // checkForNewParameters_l() can temporarily release mLock
5399 if (exitPending()) {
5400 break;
5401 }
5402
Glenn Kasten2b806402013-11-20 16:37:38 -08005403 // if no active track(s), then standby and release wakelock
5404 size_t size = mActiveTracks.size();
5405 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005406 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005407 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005408 releaseWakeLock_l();
5409 ALOGV("RecordThread: loop stopping");
5410 // go to sleep
5411 mWaitWorkCV.wait(mLock);
5412 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005413 goto reacquire_wakelock;
5414 }
5415
Glenn Kasten2b806402013-11-20 16:37:38 -08005416 if (mActiveTracksGen != activeTracksGen) {
5417 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005418 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005419 for (size_t i = 0; i < size; i++) {
5420 tmp.add(mActiveTracks[i]->uid());
5421 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005422 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005423 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005424
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005425 bool doBroadcast = false;
5426 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005427
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005428 activeTrack = mActiveTracks[i];
5429 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005430 if (activeTrack->isFastTrack()) {
5431 ALOG_ASSERT(fastTrackToRemove == 0);
5432 fastTrackToRemove = activeTrack;
5433 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005434 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005435 mActiveTracks.remove(activeTrack);
5436 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005437 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005438 continue;
5439 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005440
5441 TrackBase::track_state activeTrackState = activeTrack->mState;
5442 switch (activeTrackState) {
5443
5444 case TrackBase::PAUSING:
5445 mActiveTracks.remove(activeTrack);
5446 mActiveTracksGen++;
5447 doBroadcast = true;
5448 size--;
5449 continue;
5450
5451 case TrackBase::STARTING_1:
5452 sleepUs = 10000;
5453 i++;
5454 continue;
5455
5456 case TrackBase::STARTING_2:
5457 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005459 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 break;
5461
5462 case TrackBase::ACTIVE:
5463 break;
5464
5465 case TrackBase::IDLE:
5466 i++;
5467 continue;
5468
5469 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005470 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005471 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005472
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 activeTracks.add(activeTrack);
5474 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005475
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005476 if (activeTrack->isFastTrack()) {
5477 ALOG_ASSERT(!mFastTrackAvail);
5478 ALOG_ASSERT(fastTrack == 0);
5479 fastTrack = activeTrack;
5480 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005481 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005482 if (doBroadcast) {
5483 mStartStopCond.broadcast();
5484 }
5485
5486 // sleep if there are no active tracks to process
5487 if (activeTracks.size() == 0) {
5488 if (sleepUs == 0) {
5489 sleepUs = kRecordThreadSleepUs;
5490 }
5491 continue;
5492 }
5493 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005494
Eric Laurent81784c32012-11-19 14:55:58 -08005495 lockEffectChains_l(effectChains);
5496 }
5497
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005498 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005499
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005500 size_t size = effectChains.size();
5501 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005502 // thread mutex is not locked, but effect chain is locked
5503 effectChains[i]->process_l();
5504 }
5505
Glenn Kasten735f45f2014-08-18 15:51:59 -07005506 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005507 if (mFastCapture != 0) {
5508 FastCaptureStateQueue *sq = mFastCapture->sq();
5509 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005510 bool didModify = false;
5511 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005512 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5513 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5514 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5515 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5516 if (old == -1) {
5517 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5518 }
5519 }
5520 state->mCommand = FastCaptureState::READ_WRITE;
5521#if 0 // FIXME
5522 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005523 FastThreadDumpState::kSamplingNforLowRamDevice :
5524 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005525#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005526 didModify = true;
5527 }
5528 audio_track_cblk_t *cblkOld = state->mCblk;
5529 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5530 if (cblkNew != cblkOld) {
5531 state->mCblk = cblkNew;
5532 // block until acked if removing a fast track
5533 if (cblkOld != NULL) {
5534 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5535 }
5536 didModify = true;
5537 }
5538 sq->end(didModify);
5539 if (didModify) {
5540 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005541#if 0
5542 if (kUseFastCapture == FastCapture_Dynamic) {
5543 mNormalSource = mPipeSource;
5544 }
5545#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005546 }
5547 }
5548
Glenn Kasten735f45f2014-08-18 15:51:59 -07005549 // now run the fast track destructor with thread mutex unlocked
5550 fastTrackToRemove.clear();
5551
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005552 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5553 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5554 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5555 // If destination is non-contiguous, first read past the nominal end of buffer, then
5556 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005557
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005558 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005559 ssize_t framesRead;
5560
5561 // If an NBAIO source is present, use it to read the normal capture's data
5562 if (mPipeSource != 0) {
5563 size_t framesToRead = mBufferSize / mFrameSize;
5564 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5565 framesToRead, AudioBufferProvider::kInvalidPTS);
5566 if (framesRead == 0) {
5567 // since pipe is non-blocking, simulate blocking input
5568 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5569 }
5570 // otherwise use the HAL / AudioStreamIn directly
5571 } else {
5572 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5573 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5574 if (bytesRead < 0) {
5575 framesRead = bytesRead;
5576 } else {
5577 framesRead = bytesRead / mFrameSize;
5578 }
5579 }
5580
5581 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5582 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005583 // Force input into standby so that it tries to recover at next read attempt
5584 inputStandBy();
5585 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005586 }
5587 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005588 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005589 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005590 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005591
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005592 if (mTeeSink != 0) {
5593 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5594 }
5595 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005596 {
5597 size_t part1 = mRsmpInFramesP2 - rear;
5598 if ((size_t) framesRead > part1) {
5599 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5600 (framesRead - part1) * mFrameSize);
5601 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005602 }
5603 rear = mRsmpInRear += framesRead;
5604
5605 size = activeTracks.size();
5606 // loop over each active track
5607 for (size_t i = 0; i < size; i++) {
5608 activeTrack = activeTracks[i];
5609
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005610 // skip fast tracks, as those are handled directly by FastCapture
5611 if (activeTrack->isFastTrack()) {
5612 continue;
5613 }
5614
Andy Hung73c02e42015-03-29 01:13:58 -07005615 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005616 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5617
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005618 enum {
5619 OVERRUN_UNKNOWN,
5620 OVERRUN_TRUE,
5621 OVERRUN_FALSE
5622 } overrun = OVERRUN_UNKNOWN;
5623
5624 // loop over getNextBuffer to handle circular sink
5625 for (;;) {
5626
5627 activeTrack->mSink.frameCount = ~0;
5628 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5629 size_t framesOut = activeTrack->mSink.frameCount;
5630 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5631
Andy Hung73c02e42015-03-29 01:13:58 -07005632 // check available frames and handle overrun conditions
5633 // if the record track isn't draining fast enough.
5634 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005635 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005636 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5637 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 overrun = OVERRUN_TRUE;
5639 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005640 if (framesOut == 0 || framesIn == 0) {
5641 break;
5642 }
5643
Andy Hung6770c6f2015-04-07 13:43:36 -07005644 // Don't allow framesOut to be larger than what is possible with resampling
5645 // from framesIn.
5646 // This isn't strictly necessary but helps limit buffer resizing in
5647 // RecordBufferConverter. TODO: remove when no longer needed.
5648 framesOut = min(framesOut,
5649 destinationFramesPossible(
5650 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005651 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5652 framesOut = activeTrack->mRecordBufferConverter->convert(
5653 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005654
5655 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5656 overrun = OVERRUN_FALSE;
5657 }
5658
5659 if (activeTrack->mFramesToDrop == 0) {
5660 if (framesOut > 0) {
5661 activeTrack->mSink.frameCount = framesOut;
5662 activeTrack->releaseBuffer(&activeTrack->mSink);
5663 }
5664 } else {
5665 // FIXME could do a partial drop of framesOut
5666 if (activeTrack->mFramesToDrop > 0) {
5667 activeTrack->mFramesToDrop -= framesOut;
5668 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005669 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 }
5671 } else {
5672 activeTrack->mFramesToDrop += framesOut;
5673 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5674 activeTrack->mSyncStartEvent->isCancelled()) {
5675 ALOGW("Synced record %s, session %d, trigger session %d",
5676 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5677 activeTrack->sessionId(),
5678 (activeTrack->mSyncStartEvent != 0) ?
5679 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005680 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005681 }
5682 }
5683 }
5684
5685 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005686 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005687 }
5688 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005689
5690 switch (overrun) {
5691 case OVERRUN_TRUE:
5692 // client isn't retrieving buffers fast enough
5693 if (!activeTrack->setOverflow()) {
5694 nsecs_t now = systemTime();
5695 // FIXME should lastWarning per track?
5696 if ((now - lastWarning) > kWarningThrottleNs) {
5697 ALOGW("RecordThread: buffer overflow");
5698 lastWarning = now;
5699 }
5700 }
5701 break;
5702 case OVERRUN_FALSE:
5703 activeTrack->clearOverflow();
5704 break;
5705 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005706 break;
5707 }
5708
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005709 }
5710
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005711unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005712 // enable changes in effect chain
5713 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005714 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716
Glenn Kasten93e471f2013-08-19 08:40:07 -07005717 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005718
5719 {
5720 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005721 for (size_t i = 0; i < mTracks.size(); i++) {
5722 sp<RecordTrack> track = mTracks[i];
5723 track->invalidate();
5724 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005725 mActiveTracks.clear();
5726 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005727 mStartStopCond.broadcast();
5728 }
5729
5730 releaseWakeLock();
5731
5732 ALOGV("RecordThread %p exiting", this);
5733 return false;
5734}
5735
Glenn Kasten93e471f2013-08-19 08:40:07 -07005736void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005737{
5738 if (!mStandby) {
5739 inputStandBy();
5740 mStandby = true;
5741 }
5742}
5743
5744void AudioFlinger::RecordThread::inputStandBy()
5745{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005746 // Idle the fast capture if it's currently running
5747 if (mFastCapture != 0) {
5748 FastCaptureStateQueue *sq = mFastCapture->sq();
5749 FastCaptureState *state = sq->begin();
5750 if (!(state->mCommand & FastCaptureState::IDLE)) {
5751 state->mCommand = FastCaptureState::COLD_IDLE;
5752 state->mColdFutexAddr = &mFastCaptureFutex;
5753 state->mColdGen++;
5754 mFastCaptureFutex = 0;
5755 sq->end();
5756 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5757 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5758#if 0
5759 if (kUseFastCapture == FastCapture_Dynamic) {
5760 // FIXME
5761 }
5762#endif
5763#ifdef AUDIO_WATCHDOG
5764 // FIXME
5765#endif
5766 } else {
5767 sq->end(false /*didModify*/);
5768 }
5769 }
Eric Laurent81784c32012-11-19 14:55:58 -08005770 mInput->stream->common.standby(&mInput->stream->common);
5771}
5772
Glenn Kasten05997e22014-03-13 15:08:33 -07005773// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005774sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005775 const sp<AudioFlinger::Client>& client,
5776 uint32_t sampleRate,
5777 audio_format_t format,
5778 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005779 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005780 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005781 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005782 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005783 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005784 pid_t tid,
5785 status_t *status)
5786{
Glenn Kasten74935e42013-12-19 08:56:45 -08005787 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005788 sp<RecordTrack> track;
5789 status_t lStatus;
5790
Glenn Kasten90e58b12013-07-31 16:16:02 -07005791 // client expresses a preference for FAST, but we get the final say
5792 if (*flags & IAudioFlinger::TRACK_FAST) {
5793 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005794 // we formerly checked for a callback handler (non-0 tid),
5795 // but that is no longer required for TRANSFER_OBTAIN mode
5796 //
Glenn Kasten74105912014-07-03 12:28:53 -07005797 // frame count is not specified, or is exactly the pipe depth
5798 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005799 // PCM data
5800 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005801 // native format
5802 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005803 // native channel mask
5804 (channelMask == mChannelMask) &&
5805 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005806 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005807 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005808 hasFastCapture() &&
5809 // there are sufficient fast track slots available
5810 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005811 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005812 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005813 frameCount, mFrameCount);
5814 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005815 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5816 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005817 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005818 frameCount, mFrameCount, mPipeFramesP2,
5819 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5820 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005821 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005822 }
5823 }
5824
5825 // compute track buffer size in frames, and suggest the notification frame count
5826 if (*flags & IAudioFlinger::TRACK_FAST) {
5827 // fast track: frame count is exactly the pipe depth
5828 frameCount = mPipeFramesP2;
5829 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5830 *notificationFrames = mFrameCount;
5831 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005832 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5833 // or 20 ms if there is a fast capture
5834 // TODO This could be a roundupRatio inline, and const
5835 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5836 * sampleRate + mSampleRate - 1) / mSampleRate;
5837 // minimum number of notification periods is at least kMinNotifications,
5838 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5839 static const size_t kMinNotifications = 3;
5840 static const uint32_t kMinMs = 30;
5841 // TODO This could be a roundupRatio inline
5842 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5843 // TODO This could be a roundupRatio inline
5844 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5845 maxNotificationFrames;
5846 const size_t minFrameCount = maxNotificationFrames *
5847 max(kMinNotifications, minNotificationsByMs);
5848 frameCount = max(frameCount, minFrameCount);
5849 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5850 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005851 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005852 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005853 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005854
Glenn Kasten15e57982013-09-24 11:52:37 -07005855 lStatus = initCheck();
5856 if (lStatus != NO_ERROR) {
5857 ALOGE("createRecordTrack_l() audio driver not initialized");
5858 goto Exit;
5859 }
Eric Laurent81784c32012-11-19 14:55:58 -08005860
5861 { // scope for mLock
5862 Mutex::Autolock _l(mLock);
5863
5864 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005865 format, channelMask, frameCount, NULL, sessionId, uid,
5866 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005867
Glenn Kasten03003332013-08-06 15:40:54 -07005868 lStatus = track->initCheck();
5869 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005870 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005871 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005872 goto Exit;
5873 }
5874 mTracks.add(track);
5875
5876 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5877 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5878 mAudioFlinger->btNrecIsOff();
5879 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5880 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005881
5882 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5883 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5884 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5885 // so ask activity manager to do this on our behalf
5886 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5887 }
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005889
Eric Laurent81784c32012-11-19 14:55:58 -08005890 lStatus = NO_ERROR;
5891
5892Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005893 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005894 return track;
5895}
5896
5897status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5898 AudioSystem::sync_event_t event,
5899 int triggerSession)
5900{
5901 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5902 sp<ThreadBase> strongMe = this;
5903 status_t status = NO_ERROR;
5904
5905 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005906 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005907 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005908 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005909 triggerSession,
5910 recordTrack->sessionId(),
5911 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005913 // Sync event can be cancelled by the trigger session if the track is not in a
5914 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005915 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005916 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005917 } else {
5918 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005919 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005920 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005921 }
5922 }
5923
5924 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005925 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005926 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5928 if (recordTrack->mState == TrackBase::PAUSING) {
5929 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005930 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931 } else {
5932 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005933 }
5934 return status;
5935 }
5936
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005937 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5938 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5939 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005940 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005941 mActiveTracks.add(recordTrack);
5942 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005943 status_t status = NO_ERROR;
5944 if (recordTrack->isExternalTrack()) {
5945 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005946 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005947 mLock.lock();
5948 // FIXME should verify that recordTrack is still in mActiveTracks
5949 if (status != NO_ERROR) {
5950 mActiveTracks.remove(recordTrack);
5951 mActiveTracksGen++;
5952 recordTrack->clearSyncStartEvent();
5953 ALOGV("RecordThread::start error %d", status);
5954 return status;
5955 }
Eric Laurent81784c32012-11-19 14:55:58 -08005956 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005957 // Catch up with current buffer indices if thread is already running.
5958 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5959 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5960 // see previously buffered data before it called start(), but with greater risk of overrun.
5961
Andy Hung73c02e42015-03-29 01:13:58 -07005962 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07005963 // clear any converter state as new data will be discontinuous
5964 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005965 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005966 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005967 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005968 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005969 ALOGV("Record failed to start");
5970 status = BAD_VALUE;
5971 goto startError;
5972 }
Eric Laurent81784c32012-11-19 14:55:58 -08005973 return status;
5974 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005975
Eric Laurent81784c32012-11-19 14:55:58 -08005976startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005977 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005978 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005979 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005980 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005981 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005982 return status;
5983}
5984
Eric Laurent81784c32012-11-19 14:55:58 -08005985void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5986{
5987 sp<SyncEvent> strongEvent = event.promote();
5988
5989 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005990 sp<RefBase> ptr = strongEvent->cookie().promote();
5991 if (ptr != 0) {
5992 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5993 recordTrack->handleSyncStartEvent(strongEvent);
5994 }
Eric Laurent81784c32012-11-19 14:55:58 -08005995 }
5996}
5997
Glenn Kastena8356f62013-07-25 14:37:52 -07005998bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005999 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006000 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006001 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006002 return false;
6003 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006004 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006005 recordTrack->mState = TrackBase::PAUSING;
6006 // do not wait for mStartStopCond if exiting
6007 if (exitPending()) {
6008 return true;
6009 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006010 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006011 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006012 // if we have been restarted, recordTrack is in mActiveTracks here
6013 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006014 ALOGV("Record stopped OK");
6015 return true;
6016 }
6017 return false;
6018}
6019
Glenn Kasten0f11b512014-01-31 16:18:54 -08006020bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006021{
6022 return false;
6023}
6024
Glenn Kasten0f11b512014-01-31 16:18:54 -08006025status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006026{
6027#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6028 if (!isValidSyncEvent(event)) {
6029 return BAD_VALUE;
6030 }
6031
6032 int eventSession = event->triggerSession();
6033 status_t ret = NAME_NOT_FOUND;
6034
6035 Mutex::Autolock _l(mLock);
6036
6037 for (size_t i = 0; i < mTracks.size(); i++) {
6038 sp<RecordTrack> track = mTracks[i];
6039 if (eventSession == track->sessionId()) {
6040 (void) track->setSyncEvent(event);
6041 ret = NO_ERROR;
6042 }
6043 }
6044 return ret;
6045#else
6046 return BAD_VALUE;
6047#endif
6048}
6049
6050// destroyTrack_l() must be called with ThreadBase::mLock held
6051void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6052{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006053 track->terminate();
6054 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006055 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006056 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006057 removeTrack_l(track);
6058 }
6059}
6060
6061void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6062{
6063 mTracks.remove(track);
6064 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006065 if (track->isFastTrack()) {
6066 ALOG_ASSERT(!mFastTrackAvail);
6067 mFastTrackAvail = true;
6068 }
Eric Laurent81784c32012-11-19 14:55:58 -08006069}
6070
6071void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6072{
6073 dumpInternals(fd, args);
6074 dumpTracks(fd, args);
6075 dumpEffectChains(fd, args);
6076}
6077
6078void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6079{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006080 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006081
Glenn Kasten44182c22015-03-05 17:12:23 -08006082 dumpBase(fd, args);
6083
6084 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006085 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006087 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006088 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006089
6090 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6091 const FastCaptureDumpState copy(mFastCaptureDumpState);
6092 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006093}
6094
Glenn Kasten0f11b512014-01-31 16:18:54 -08006095void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006096{
6097 const size_t SIZE = 256;
6098 char buffer[SIZE];
6099 String8 result;
6100
Marco Nelissenb2208842014-02-07 14:00:50 -08006101 size_t numtracks = mTracks.size();
6102 size_t numactive = mActiveTracks.size();
6103 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006104 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006105 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006106 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006107 RecordTrack::appendDumpHeader(result);
6108 for (size_t i = 0; i < numtracks ; ++i) {
6109 sp<RecordTrack> track = mTracks[i];
6110 if (track != 0) {
6111 bool active = mActiveTracks.indexOf(track) >= 0;
6112 if (active) {
6113 numactiveseen++;
6114 }
6115 track->dump(buffer, SIZE, active);
6116 result.append(buffer);
6117 }
Eric Laurent81784c32012-11-19 14:55:58 -08006118 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006119 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006120 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006121 }
6122
Marco Nelissenb2208842014-02-07 14:00:50 -08006123 if (numactiveseen != numactive) {
6124 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6125 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006126 result.append(buffer);
6127 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006128 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006129 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006130 if (mTracks.indexOf(track) < 0) {
6131 track->dump(buffer, SIZE, true);
6132 result.append(buffer);
6133 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 }
Eric Laurent81784c32012-11-19 14:55:58 -08006135
6136 }
6137 write(fd, result.string(), result.size());
6138}
6139
Andy Hung73c02e42015-03-29 01:13:58 -07006140
6141void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6142{
6143 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6144 RecordThread *recordThread = (RecordThread *) threadBase.get();
6145 mRsmpInFront = recordThread->mRsmpInRear;
6146 mRsmpInUnrel = 0;
6147}
6148
6149void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6150 size_t *framesAvailable, bool *hasOverrun)
6151{
6152 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6153 RecordThread *recordThread = (RecordThread *) threadBase.get();
6154 const int32_t rear = recordThread->mRsmpInRear;
6155 const int32_t front = mRsmpInFront;
6156 const ssize_t filled = rear - front;
6157
6158 size_t framesIn;
6159 bool overrun = false;
6160 if (filled < 0) {
6161 // should not happen, but treat like a massive overrun and re-sync
6162 framesIn = 0;
6163 mRsmpInFront = rear;
6164 overrun = true;
6165 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6166 framesIn = (size_t) filled;
6167 } else {
6168 // client is not keeping up with server, but give it latest data
6169 framesIn = recordThread->mRsmpInFrames;
6170 mRsmpInFront = /* front = */ rear - framesIn;
6171 overrun = true;
6172 }
6173 if (framesAvailable != NULL) {
6174 *framesAvailable = framesIn;
6175 }
6176 if (hasOverrun != NULL) {
6177 *hasOverrun = overrun;
6178 }
6179}
6180
Eric Laurent81784c32012-11-19 14:55:58 -08006181// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6183 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006184{
Andy Hung73c02e42015-03-29 01:13:58 -07006185 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 if (threadBase == 0) {
6187 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006188 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 return NOT_ENOUGH_DATA;
6190 }
6191 RecordThread *recordThread = (RecordThread *) threadBase.get();
6192 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006193 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006194 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 // FIXME should not be P2 (don't want to increase latency)
6196 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006197 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006198 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006199 front &= recordThread->mRsmpInFramesP2 - 1;
6200 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006201 if (part1 > (size_t) filled) {
6202 part1 = filled;
6203 }
6204 size_t ask = buffer->frameCount;
6205 ALOG_ASSERT(ask > 0);
6206 if (part1 > ask) {
6207 part1 = ask;
6208 }
6209 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006210 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006211 buffer->raw = NULL;
6212 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006213 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006214 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006215 }
6216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006218 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006219 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006220 return NO_ERROR;
6221}
6222
6223// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6225 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006226{
Glenn Kasten85948432013-08-19 12:09:05 -07006227 size_t stepCount = buffer->frameCount;
6228 if (stepCount == 0) {
6229 return;
6230 }
Andy Hung73c02e42015-03-29 01:13:58 -07006231 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6232 mRsmpInUnrel -= stepCount;
6233 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006234 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006235 buffer->frameCount = 0;
6236}
6237
Andy Hung97a893e2015-03-29 01:03:07 -07006238AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6239 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6240 uint32_t srcSampleRate,
6241 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6242 uint32_t dstSampleRate) :
6243 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6244 // mSrcFormat
6245 // mSrcSampleRate
6246 // mDstChannelMask
6247 // mDstFormat
6248 // mDstSampleRate
6249 // mSrcChannelCount
6250 // mDstChannelCount
6251 // mDstFrameSize
6252 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6253 mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0)
6254{
6255 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6256 dstChannelMask, dstFormat, dstSampleRate);
6257}
6258
6259AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6260 free(mBuf);
6261 delete mResampler;
6262 free(mRsmpOutBuffer);
6263}
6264
6265size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6266 AudioBufferProvider *provider, size_t frames)
6267{
6268 if (mSrcSampleRate == mDstSampleRate) {
6269 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6270 mSrcSampleRate, mSrcFormat, mDstFormat);
6271
6272 AudioBufferProvider::Buffer buffer;
6273 for (size_t i = frames; i > 0; ) {
6274 buffer.frameCount = i;
6275 status_t status = provider->getNextBuffer(&buffer, 0);
6276 if (status != OK || buffer.frameCount == 0) {
6277 frames -= i; // cannot fill request.
6278 break;
6279 }
6280 // convert to destination buffer
6281 convert(dst, buffer.raw, buffer.frameCount);
6282
6283 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6284 i -= buffer.frameCount;
6285 provider->releaseBuffer(&buffer);
6286 }
6287 } else {
6288 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6289 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6290
6291 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
6292 if (mRsmpOutFrameCount < frames) {
6293 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
6294 free(mRsmpOutBuffer);
6295 // resampler always outputs stereo (FOR NOW)
6296 (void)posix_memalign(&mRsmpOutBuffer, 32, frames * FCC_2 * sizeof(int32_t) /*Q4.27*/);
6297 mRsmpOutFrameCount = frames;
6298 }
6299 // resampler accumulates, but we only have one source track
6300 memset(mRsmpOutBuffer, 0, frames * FCC_2 * sizeof(int32_t));
6301 frames = mResampler->resample((int32_t*)mRsmpOutBuffer, frames, provider);
6302
6303 // convert to destination buffer
6304 convert(dst, mRsmpOutBuffer, frames);
6305 }
6306 return frames;
6307}
6308
6309status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6310 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6311 uint32_t srcSampleRate,
6312 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6313 uint32_t dstSampleRate)
6314{
6315 // quick evaluation if there is any change.
6316 if (mSrcFormat == srcFormat
6317 && mSrcChannelMask == srcChannelMask
6318 && mSrcSampleRate == srcSampleRate
6319 && mDstFormat == dstFormat
6320 && mDstChannelMask == dstChannelMask
6321 && mDstSampleRate == dstSampleRate) {
6322 return NO_ERROR;
6323 }
6324
6325 const bool valid =
6326 audio_is_input_channel(srcChannelMask)
6327 && audio_is_input_channel(dstChannelMask)
6328 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6329 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6330 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6331 ; // no upsampling checks for now
6332 if (!valid) {
6333 return BAD_VALUE;
6334 }
6335
6336 mSrcFormat = srcFormat;
6337 mSrcChannelMask = srcChannelMask;
6338 mSrcSampleRate = srcSampleRate;
6339 mDstFormat = dstFormat;
6340 mDstChannelMask = dstChannelMask;
6341 mDstSampleRate = dstSampleRate;
6342
6343 // compute derived parameters
6344 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6345 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6346 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6347
6348 // do we need a format buffer?
6349 if (mSrcFormat != mDstFormat && mDstChannelCount != mSrcChannelCount) {
6350 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6351 } else {
6352 mBufFrameSize = 0;
6353 }
6354 mBufFrames = 0; // force the buffer to be resized.
6355
6356 // do we need to resample?
6357 if (mSrcSampleRate != mDstSampleRate) {
6358 if (mResampler != NULL) {
6359 delete mResampler;
6360 }
6361 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
6362 mSrcChannelCount, mDstSampleRate); // may seem confusing...
6363 mResampler->setSampleRate(mSrcSampleRate);
6364 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6365 }
6366 return NO_ERROR;
6367}
6368
6369void AudioFlinger::RecordThread::RecordBufferConverter::convert(
6370 void *dst, /*const*/ void *src, size_t frames)
6371{
6372 // check if a memcpy will do
6373 if (mResampler == NULL
6374 && mSrcChannelCount == mDstChannelCount
6375 && mSrcFormat == mDstFormat) {
6376 memcpy(dst, src,
6377 frames * mDstChannelCount * audio_bytes_per_sample(mDstFormat));
6378 return;
6379 }
6380 // reallocate buffer if needed
6381 if (mBufFrameSize != 0 && mBufFrames < frames) {
6382 free(mBuf);
6383 mBufFrames = frames;
6384 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6385 }
6386 // do processing
6387 if (mResampler != NULL) {
6388 // src channel count is always >= 2.
6389 void *dstBuf = mBuf != NULL ? mBuf : dst;
6390 // ditherAndClamp() works as long as all buffers returned by
6391 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
6392 if (mDstChannelCount == 1) {
6393 // the resampler always outputs stereo samples.
6394 // FIXME: this rewrites back into src
6395 ditherAndClamp((int32_t *)src, (const int32_t *)src, frames);
6396 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6397 (const int16_t *)src, frames);
6398 } else {
6399 ditherAndClamp((int32_t *)dstBuf, (const int32_t *)src, frames);
6400 }
6401 } else if (mSrcChannelCount != mDstChannelCount) {
6402 void *dstBuf = mBuf != NULL ? mBuf : dst;
6403 if (mSrcChannelCount == 1) {
6404 upmix_to_stereo_i16_from_mono_i16((int16_t *)dstBuf, (const int16_t *)src,
6405 frames);
6406 } else {
6407 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6408 (const int16_t *)src, frames);
6409 }
6410 }
6411 if (mSrcFormat != mDstFormat) {
6412 void *srcBuf = mBuf != NULL ? mBuf : src;
6413 memcpy_by_audio_format(dst, mDstFormat, srcBuf, mSrcFormat,
6414 frames * mDstChannelCount);
6415 }
6416}
6417
Eric Laurent10351942014-05-08 18:49:52 -07006418bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6419 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006420{
6421 bool reconfig = false;
6422
Eric Laurent10351942014-05-08 18:49:52 -07006423 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006424
Eric Laurent10351942014-05-08 18:49:52 -07006425 audio_format_t reqFormat = mFormat;
6426 uint32_t samplingRate = mSampleRate;
6427 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6428
6429 AudioParameter param = AudioParameter(keyValuePair);
6430 int value;
6431 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6432 // channel count change can be requested. Do we mandate the first client defines the
6433 // HAL sampling rate and channel count or do we allow changes on the fly?
6434 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6435 samplingRate = value;
6436 reconfig = true;
6437 }
6438 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006439 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006440 status = BAD_VALUE;
6441 } else {
6442 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006443 reconfig = true;
6444 }
Eric Laurent10351942014-05-08 18:49:52 -07006445 }
6446 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6447 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6448 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6449 status = BAD_VALUE;
6450 } else {
6451 channelMask = mask;
6452 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006453 }
Eric Laurent10351942014-05-08 18:49:52 -07006454 }
6455 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6456 // do not accept frame count changes if tracks are open as the track buffer
6457 // size depends on frame count and correct behavior would not be guaranteed
6458 // if frame count is changed after track creation
6459 if (mActiveTracks.size() > 0) {
6460 status = INVALID_OPERATION;
6461 } else {
6462 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006463 }
Eric Laurent10351942014-05-08 18:49:52 -07006464 }
6465 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6466 // forward device change to effects that have requested to be
6467 // aware of attached audio device.
6468 for (size_t i = 0; i < mEffectChains.size(); i++) {
6469 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006470 }
Eric Laurent81784c32012-11-19 14:55:58 -08006471
Eric Laurent10351942014-05-08 18:49:52 -07006472 // store input device and output device but do not forward output device to audio HAL.
6473 // Note that status is ignored by the caller for output device
6474 // (see AudioFlinger::setParameters()
6475 if (audio_is_output_devices(value)) {
6476 mOutDevice = value;
6477 status = BAD_VALUE;
6478 } else {
6479 mInDevice = value;
6480 // disable AEC and NS if the device is a BT SCO headset supporting those
6481 // pre processings
6482 if (mTracks.size() > 0) {
6483 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6484 mAudioFlinger->btNrecIsOff();
6485 for (size_t i = 0; i < mTracks.size(); i++) {
6486 sp<RecordTrack> track = mTracks[i];
6487 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6488 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006489 }
6490 }
6491 }
Eric Laurent10351942014-05-08 18:49:52 -07006492 }
6493 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6494 mAudioSource != (audio_source_t)value) {
6495 // forward device change to effects that have requested to be
6496 // aware of attached audio device.
6497 for (size_t i = 0; i < mEffectChains.size(); i++) {
6498 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006499 }
Eric Laurent10351942014-05-08 18:49:52 -07006500 mAudioSource = (audio_source_t)value;
6501 }
Glenn Kastene198c362013-08-13 09:13:36 -07006502
Eric Laurent10351942014-05-08 18:49:52 -07006503 if (status == NO_ERROR) {
6504 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6505 keyValuePair.string());
6506 if (status == INVALID_OPERATION) {
6507 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006508 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6509 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006510 }
6511 if (reconfig) {
6512 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006513 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6514 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006515 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006516 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006517 audio_channel_count_from_in_mask(
6518 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006519 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6520 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6521 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006522 }
Eric Laurent10351942014-05-08 18:49:52 -07006523 if (status == NO_ERROR) {
6524 readInputParameters_l();
6525 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006526 }
6527 }
Eric Laurent81784c32012-11-19 14:55:58 -08006528 }
Eric Laurent10351942014-05-08 18:49:52 -07006529
Eric Laurent81784c32012-11-19 14:55:58 -08006530 return reconfig;
6531}
6532
6533String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6534{
Eric Laurent81784c32012-11-19 14:55:58 -08006535 Mutex::Autolock _l(mLock);
6536 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006537 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006538 }
6539
Glenn Kastend8ea6992013-07-16 14:17:15 -07006540 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6541 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006542 free(s);
6543 return out_s8;
6544}
6545
Eric Laurent021cf962014-05-13 10:18:14 -07006546void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006547 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006548 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006549
6550 switch (event) {
6551 case AudioSystem::INPUT_OPENED:
6552 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006553 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006554 desc.samplingRate = mSampleRate;
6555 desc.format = mFormat;
6556 desc.frameCount = mFrameCount;
6557 desc.latency = 0;
6558 param2 = &desc;
6559 break;
6560
6561 case AudioSystem::INPUT_CLOSED:
6562 default:
6563 break;
6564 }
Eric Laurent021cf962014-05-13 10:18:14 -07006565 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006566}
6567
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006568void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006569{
Eric Laurent81784c32012-11-19 14:55:58 -08006570 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6571 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006572 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006573 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6574 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006575 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006576 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006577 }
Eric Laurent665470b2014-07-03 16:37:08 -07006578 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006579 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6580 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006581 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006582 // 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 -07006583 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006584 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006585 // A larger value should allow more old data to be read after a track calls start(),
6586 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006587 //
6588 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006589 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006590 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006591 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006592
6593 // TODO optimize audio capture buffer sizes ...
6594 // Here we calculate the size of the sliding buffer used as a source
6595 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6596 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6597 // be better to have it derived from the pipe depth in the long term.
6598 // The current value is higher than necessary. However it should not add to latency.
6599
Glenn Kasten85948432013-08-19 12:09:05 -07006600 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6601 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006602
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006603 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6604 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006605}
6606
Glenn Kasten5f972c02014-01-13 09:59:31 -08006607uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006608{
6609 Mutex::Autolock _l(mLock);
6610 if (initCheck() != NO_ERROR) {
6611 return 0;
6612 }
6613
6614 return mInput->stream->get_input_frames_lost(mInput->stream);
6615}
6616
6617uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6618{
6619 Mutex::Autolock _l(mLock);
6620 uint32_t result = 0;
6621 if (getEffectChain_l(sessionId) != 0) {
6622 result = EFFECT_SESSION;
6623 }
6624
6625 for (size_t i = 0; i < mTracks.size(); ++i) {
6626 if (sessionId == mTracks[i]->sessionId()) {
6627 result |= TRACK_SESSION;
6628 break;
6629 }
6630 }
6631
6632 return result;
6633}
6634
6635KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6636{
6637 KeyedVector<int, bool> ids;
6638 Mutex::Autolock _l(mLock);
6639 for (size_t j = 0; j < mTracks.size(); ++j) {
6640 sp<RecordThread::RecordTrack> track = mTracks[j];
6641 int sessionId = track->sessionId();
6642 if (ids.indexOfKey(sessionId) < 0) {
6643 ids.add(sessionId, true);
6644 }
6645 }
6646 return ids;
6647}
6648
6649AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6650{
6651 Mutex::Autolock _l(mLock);
6652 AudioStreamIn *input = mInput;
6653 mInput = NULL;
6654 return input;
6655}
6656
6657// this method must always be called either with ThreadBase mLock held or inside the thread loop
6658audio_stream_t* AudioFlinger::RecordThread::stream() const
6659{
6660 if (mInput == NULL) {
6661 return NULL;
6662 }
6663 return &mInput->stream->common;
6664}
6665
6666status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6667{
6668 // only one chain per input thread
6669 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006670 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006671 return INVALID_OPERATION;
6672 }
6673 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006674 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006675 chain->setInBuffer(NULL);
6676 chain->setOutBuffer(NULL);
6677
6678 checkSuspendOnAddEffectChain_l(chain);
6679
Eric Laurent1b928682014-10-02 19:41:47 -07006680 // make sure enabled pre processing effects state is communicated to the HAL as we
6681 // just moved them to a new input stream.
6682 chain->syncHalEffectsState();
6683
Eric Laurent81784c32012-11-19 14:55:58 -08006684 mEffectChains.add(chain);
6685
6686 return NO_ERROR;
6687}
6688
6689size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6690{
6691 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6692 ALOGW_IF(mEffectChains.size() != 1,
6693 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6694 chain.get(), mEffectChains.size(), this);
6695 if (mEffectChains.size() == 1) {
6696 mEffectChains.removeAt(0);
6697 }
6698 return 0;
6699}
6700
Eric Laurent1c333e22014-05-20 10:48:17 -07006701status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6702 audio_patch_handle_t *handle)
6703{
6704 status_t status = NO_ERROR;
6705 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6706 // store new device and send to effects
6707 mInDevice = patch->sources[0].ext.device.type;
6708 for (size_t i = 0; i < mEffectChains.size(); i++) {
6709 mEffectChains[i]->setDevice_l(mInDevice);
6710 }
6711
6712 // disable AEC and NS if the device is a BT SCO headset supporting those
6713 // pre processings
6714 if (mTracks.size() > 0) {
6715 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6716 mAudioFlinger->btNrecIsOff();
6717 for (size_t i = 0; i < mTracks.size(); i++) {
6718 sp<RecordTrack> track = mTracks[i];
6719 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6720 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6721 }
6722 }
6723
6724 // store new source and send to effects
6725 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6726 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6727 for (size_t i = 0; i < mEffectChains.size(); i++) {
6728 mEffectChains[i]->setAudioSource_l(mAudioSource);
6729 }
6730 }
6731
6732 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6733 status = hwDevice->create_audio_patch(hwDevice,
6734 patch->num_sources,
6735 patch->sources,
6736 patch->num_sinks,
6737 patch->sinks,
6738 handle);
6739 } else {
6740 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6741 }
6742 return status;
6743}
6744
6745status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6746{
6747 status_t status = NO_ERROR;
6748 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6749 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6750 status = hwDevice->release_audio_patch(hwDevice, handle);
6751 } else {
6752 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6753 }
6754 return status;
6755}
6756
Eric Laurent83b88082014-06-20 18:31:16 -07006757void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6758{
6759 Mutex::Autolock _l(mLock);
6760 mTracks.add(record);
6761}
6762
6763void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6764{
6765 Mutex::Autolock _l(mLock);
6766 destroyTrack_l(record);
6767}
6768
6769void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6770{
6771 ThreadBase::getAudioPortConfig(config);
6772 config->role = AUDIO_PORT_ROLE_SINK;
6773 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6774 config->ext.mix.usecase.source = mAudioSource;
6775}
Eric Laurent1c333e22014-05-20 10:48:17 -07006776
Glenn Kasten63238ef2015-03-02 15:50:29 -08006777} // namespace android